]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_request.cc
Reverted XFF unhiding changes
[thirdparty/squid.git] / src / client_side_request.cc
CommitLineData
edce4d98 1
2/*
ae45c4de 3 * DEBUG: section 85 Client-side Request Routines
4 * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c)
26ac0430 5 *
edce4d98 6 * SQUID Web Proxy Cache http://www.squid-cache.org/
7 * ----------------------------------------------------------
0a9297f6 8 *
9 * Squid is the result of efforts by numerous individuals from
10 * the Internet community; see the CONTRIBUTORS file for full
11 * details. Many organizations have provided support for Squid's
12 * development; see the SPONSORS file for full details. Squid is
13 * Copyrighted (C) 2001 by the Regents of the University of
14 * California; see the COPYRIGHT file for full details. Squid
15 * incorporates software developed and/or copyrighted by other
16 * sources; see the CREDITS file for full details.
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
22 *
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program; if not, write to the Free Software
30 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
31 *
edce4d98 32 */
33
69660be0 34/*
35 * General logic of request processing:
26ac0430 36 *
69660be0 37 * We run a series of tests to determine if access will be permitted, and to do
38 * any redirection. Then we call into the result clientStream to retrieve data.
39 * From that point on it's up to reply management.
edce4d98 40 */
41
582c2af2 42#include "squid.h"
c0941a6a
AR
43#include "acl/FilledChecklist.h"
44#include "acl/Gadgets.h"
65d448bc 45#include "anyp/PortCfg.h"
582c2af2 46#include "ClientRequestContext.h"
27bc2077
AJ
47#include "client_side.h"
48#include "client_side_reply.h"
49#include "client_side_request.h"
582c2af2 50#include "clientStream.h"
5c336a3b 51#include "comm/Connection.h"
ec41b64c 52#include "comm/Write.h"
27bc2077 53#include "compat/inet_pton.h"
582c2af2 54#include "err_detail_type.h"
2bd84e5f 55#include "errorpage.h"
c4ad1349 56#include "fd.h"
27bc2077 57#include "fde.h"
31971e6a 58#include "format/Token.h"
d05c079c 59#include "gopher.h"
5c0c642e 60#include "http.h"
ce394734 61#include "HttpHdrCc.h"
27bc2077
AJ
62#include "HttpReply.h"
63#include "HttpRequest.h"
582c2af2 64#include "ipcache.h"
425de4c8 65#include "ip/QosConfig.h"
1c7ae5ff 66#include "log/access_log.h"
27bc2077 67#include "MemObject.h"
8a01b99e 68#include "Parsing.h"
582c2af2 69#include "profiler/Profiler.h"
4d5904f7 70#include "SquidConfig.h"
27bc2077 71#include "SquidTime.h"
582c2af2 72#include "Store.h"
28204b3b 73#include "StrList.h"
685c6ff5 74#include "tools.h"
b1bd952a 75#include "URL.h"
27bc2077 76#include "wordlist.h"
582c2af2
FC
77#if USE_AUTH
78#include "auth/UserRequest.h"
79#endif
80#if USE_ADAPTATION
81#include "adaptation/AccessCheck.h"
82#include "adaptation/Answer.h"
83#include "adaptation/Iterator.h"
84#include "adaptation/Service.h"
85#if ICAP_CLIENT
86#include "adaptation/icap/History.h"
87#endif
88#endif
4db984be
CT
89#if USE_SSL
90#include "ssl/support.h"
2bd84e5f 91#include "ssl/ServerBump.h"
4db984be 92#endif
3ff65596 93
edce4d98 94#if LINGERING_CLOSE
95#define comm_close comm_lingering_close
96#endif
97
98static const char *const crlf = "\r\n";
99
609c620a 100#if FOLLOW_X_FORWARDED_FOR
2efeb0b7 101static void clientFollowXForwardedForCheck(allow_t answer, void *data);
609c620a 102#endif /* FOLLOW_X_FORWARDED_FOR */
3d674977 103
2bd84e5f
CT
104extern ErrorState *clientBuildError(err_type, http_status, char const *url, Ip::Address &, HttpRequest *);
105
8e2745f4 106CBDATA_CLASS_INIT(ClientRequestContext);
107
108void *
109ClientRequestContext::operator new (size_t size)
110{
111 assert (size == sizeof(ClientRequestContext));
112 CBDATA_INIT_TYPE(ClientRequestContext);
113 ClientRequestContext *result = cbdataAlloc(ClientRequestContext);
aa625860 114 return result;
8e2745f4 115}
62e76326 116
8e2745f4 117void
118ClientRequestContext::operator delete (void *address)
119{
120 ClientRequestContext *t = static_cast<ClientRequestContext *>(address);
aa625860 121 cbdataFree(t);
8e2745f4 122}
123
edce4d98 124/* Local functions */
edce4d98 125/* other */
2efeb0b7 126static void clientAccessCheckDoneWrapper(allow_t, void *);
e0c0d54c 127#if USE_SSL
2efeb0b7 128static void sslBumpAccessCheckDoneWrapper(allow_t, void *);
e0c0d54c 129#endif
59a1efb2 130static int clientHierarchical(ClientHttpRequest * http);
131static void clientInterpretRequestHeaders(ClientHttpRequest * http);
de31d06f 132static RH clientRedirectDoneWrapper;
2efeb0b7 133static void checkNoCacheDoneWrapper(allow_t, void *);
e6ccf245 134extern "C" CSR clientGetMoreData;
135extern "C" CSS clientReplyStatus;
136extern "C" CSD clientReplyDetach;
528b2c61 137static void checkFailureRatio(err_type, hier_code);
edce4d98 138
8e2745f4 139ClientRequestContext::~ClientRequestContext()
140{
de31d06f 141 /*
a546b04b 142 * Release our "lock" on our parent, ClientHttpRequest, if we
143 * still have one
de31d06f 144 */
a546b04b 145
146 if (http)
147 cbdataReferenceDone(http);
62e76326 148
2bd84e5f 149 delete error;
5f8252d2 150 debugs(85,3, HERE << this << " ClientRequestContext destructed");
8e2745f4 151}
152
2bd84e5f 153ClientRequestContext::ClientRequestContext(ClientHttpRequest *anHttp) : http(cbdataReference(anHttp)), acl_checklist (NULL), redirect_state (REDIRECT_NONE), error(NULL), readNextRequest(false)
edce4d98 154{
57abaac0 155 http_access_done = false;
156 redirect_done = false;
157 no_cache_done = false;
158 interpreted_req_hdrs = false;
e0c0d54c
CT
159#if USE_SSL
160 sslBumpCheckDone = false;
161#endif
0b86805b 162 debugs(85,3, HERE << this << " ClientRequestContext constructed");
edce4d98 163}
164
528b2c61 165CBDATA_CLASS_INIT(ClientHttpRequest);
8e2745f4 166
528b2c61 167void *
168ClientHttpRequest::operator new (size_t size)
169{
170 assert (size == sizeof (ClientHttpRequest));
171 CBDATA_INIT_TYPE(ClientHttpRequest);
172 ClientHttpRequest *result = cbdataAlloc(ClientHttpRequest);
aa625860 173 return result;
528b2c61 174}
175
62e76326 176void
528b2c61 177ClientHttpRequest::operator delete (void *address)
178{
aa625860 179 ClientHttpRequest *t = static_cast<ClientHttpRequest *>(address);
180 cbdataFree(t);
528b2c61 181}
182
26ac0430 183ClientHttpRequest::ClientHttpRequest(ConnStateData * aConn) :
a83c6ed6 184#if USE_ADAPTATION
26ac0430 185 AsyncJob("ClientHttpRequest"),
1cf238db 186#endif
26ac0430 187 loggingEntry_(NULL)
528b2c61 188{
1cf238db 189 start_time = current_time;
a0355e95 190 setConn(aConn);
41ebd397
CT
191 al = new AccessLogEntry;
192 al->tcpClient = clientConnection = aConn->clientConnection;
f4698e0b
CT
193#if USE_SSL
194 if (aConn->clientConnection != NULL && aConn->clientConnection->isOpen()) {
195 if (SSL *ssl = fd_table[aConn->clientConnection->fd].ssl)
196 al->cache.sslClientCert.reset(SSL_get_peer_certificate(ssl));
197 }
198#endif
a0355e95 199 dlinkAdd(this, &active, &ClientActiveRequests);
a83c6ed6 200#if USE_ADAPTATION
b044675d 201 request_satisfaction_mode = false;
202#endif
e0c0d54c 203#if USE_SSL
08097970 204 sslBumpNeed_ = Ssl::bumpEnd;
e0c0d54c 205#endif
528b2c61 206}
207
0655fa4d 208/*
209 * returns true if client specified that the object must come from the cache
210 * without contacting origin server
211 */
212bool
213ClientHttpRequest::onlyIfCached()const
214{
215 assert(request);
216 return request->cache_control &&
4ce6e3b5 217 request->cache_control->onlyIfCached();
0655fa4d 218}
219
77aacca5 220/**
528b2c61 221 * This function is designed to serve a fairly specific purpose.
222 * Occasionally our vBNS-connected caches can talk to each other, but not
223 * the rest of the world. Here we try to detect frequent failures which
224 * make the cache unusable (e.g. DNS lookup and connect() failures). If
225 * the failure:success ratio goes above 1.0 then we go into "hit only"
226 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
227 * will only fetch HITs from us if they are using the ICP protocol. We
228 * stay in this mode for 5 minutes.
26ac0430 229 *
528b2c61 230 * Duane W., Sept 16, 1996
231 */
528b2c61 232static void
233checkFailureRatio(err_type etype, hier_code hcode)
234{
77aacca5
AJ
235 // Can be set at compile time with -D compiler flag
236#ifndef FAILURE_MODE_TIME
237#define FAILURE_MODE_TIME 300
238#endif
239
8d74a311
AJ
240 if (hcode == HIER_NONE)
241 return;
242
243 // don't bother when ICP is disabled.
244 if (Config.Port.icp <= 0)
245 return;
246
528b2c61 247 static double magic_factor = 100.0;
248 double n_good;
249 double n_bad;
62e76326 250
528b2c61 251 n_good = magic_factor / (1.0 + request_failure_ratio);
62e76326 252
528b2c61 253 n_bad = magic_factor - n_good;
62e76326 254
528b2c61 255 switch (etype) {
62e76326 256
528b2c61 257 case ERR_DNS_FAIL:
62e76326 258
528b2c61 259 case ERR_CONNECT_FAIL:
3712be3f 260 case ERR_SECURE_CONNECT_FAIL:
62e76326 261
528b2c61 262 case ERR_READ_ERROR:
5086523e 263 ++n_bad;
62e76326 264 break;
265
528b2c61 266 default:
5086523e 267 ++n_good;
528b2c61 268 }
62e76326 269
528b2c61 270 request_failure_ratio = n_bad / n_good;
62e76326 271
528b2c61 272 if (hit_only_mode_until > squid_curtime)
62e76326 273 return;
274
528b2c61 275 if (request_failure_ratio < 1.0)
62e76326 276 return;
277
77aacca5 278 debugs(33, DBG_CRITICAL, "WARNING: Failure Ratio at "<< std::setw(4)<<
bf8fe701 279 std::setprecision(3) << request_failure_ratio);
62e76326 280
8d74a311 281 debugs(33, DBG_CRITICAL, "WARNING: ICP going into HIT-only mode for " <<
bf8fe701 282 FAILURE_MODE_TIME / 60 << " minutes...");
62e76326 283
528b2c61 284 hit_only_mode_until = squid_curtime + FAILURE_MODE_TIME;
62e76326 285
528b2c61 286 request_failure_ratio = 0.8; /* reset to something less than 1.0 */
287}
288
289ClientHttpRequest::~ClientHttpRequest()
290{
bf8fe701 291 debugs(33, 3, "httpRequestFree: " << uri);
72bdee4c 292 PROF_start(httpRequestFree);
62e76326 293
5f8252d2 294 // Even though freeResources() below may destroy the request,
295 // we no longer set request->body_pipe to NULL here
296 // because we did not initiate that pipe (ConnStateData did)
62e76326 297
528b2c61 298 /* the ICP check here was erroneous
26ac0430 299 * - StoreEntry::releaseRequest was always called if entry was valid
528b2c61 300 */
301 assert(logType < LOG_TYPE_MAX);
9ce7856a 302
528b2c61 303 logRequest();
9ce7856a 304
0976f8db 305 loggingEntry(NULL);
306
528b2c61 307 if (request)
41ebd397 308 checkFailureRatio(request->errType, al->hier.code);
62e76326 309
528b2c61 310 freeResources();
62e76326 311
a83c6ed6
AR
312#if USE_ADAPTATION
313 announceInitiatorAbort(virginHeadSource);
9d4d7c5e 314
a83c6ed6
AR
315 if (adaptedBodySource != NULL)
316 stopConsumingFrom(adaptedBodySource);
de31d06f 317#endif
9ce7856a 318
de31d06f 319 if (calloutContext)
320 delete calloutContext;
321
be364179
AJ
322 clientConnection = NULL;
323
26ac0430
AJ
324 if (conn_)
325 cbdataReferenceDone(conn_);
1cf238db 326
528b2c61 327 /* moving to the next connection is handled by the context free */
328 dlinkDelete(&active, &ClientActiveRequests);
9ce7856a 329
72bdee4c 330 PROF_stop(httpRequestFree);
528b2c61 331}
62e76326 332
11992b6f
AJ
333/**
334 * Create a request and kick it off
335 *
336 * \retval 0 success
337 * \retval -1 failure
338 *
69660be0 339 * TODO: Pass in the buffers to be used in the inital Read request, as they are
340 * determined by the user
edce4d98 341 */
11992b6f 342int
60745f24 343clientBeginRequest(const HttpRequestMethod& method, char const *url, CSCB * streamcallback,
0655fa4d 344 CSD * streamdetach, ClientStreamData streamdata, HttpHeader const *header,
62e76326 345 char *tailbuf, size_t taillen)
edce4d98 346{
347 size_t url_sz;
a0355e95 348 ClientHttpRequest *http = new ClientHttpRequest(NULL);
190154cf 349 HttpRequest *request;
528b2c61 350 StoreIOBuffer tempBuffer;
1cf238db 351 http->start_time = current_time;
edce4d98 352 /* this is only used to adjust the connection offset in client_side.c */
353 http->req_sz = 0;
c8be6d7b 354 tempBuffer.length = taillen;
355 tempBuffer.data = tailbuf;
edce4d98 356 /* client stream setup */
357 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
0655fa4d 358 clientReplyStatus, new clientReplyContext(http), streamcallback,
62e76326 359 streamdetach, streamdata, tempBuffer);
edce4d98 360 /* make it visible in the 'current acctive requests list' */
edce4d98 361 /* Set flags */
a46d2c0e 362 /* internal requests only makes sense in an
363 * accelerator today. TODO: accept flags ? */
364 http->flags.accel = 1;
edce4d98 365 /* allow size for url rewriting */
366 url_sz = strlen(url) + Config.appendDomainLen + 5;
e6ccf245 367 http->uri = (char *)xcalloc(url_sz, 1);
edce4d98 368 strcpy(http->uri, url);
369
c21ad0f5 370 if ((request = HttpRequest::CreateFromUrlAndMethod(http->uri, method)) == NULL) {
bf8fe701 371 debugs(85, 5, "Invalid URL: " << http->uri);
62e76326 372 return -1;
edce4d98 373 }
62e76326 374
69660be0 375 /*
11992b6f 376 * now update the headers in request with our supplied headers. urlParse
69660be0 377 * should return a blank header set, but we use Update to be sure of
378 * correctness.
edce4d98 379 */
380 if (header)
a9925b40 381 request->header.update(header, NULL);
62e76326 382
edce4d98 383 http->log_uri = xstrdup(urlCanonicalClean(request));
62e76326 384
edce4d98 385 /* http struct now ready */
386
69660be0 387 /*
388 * build new header list *? TODO
edce4d98 389 */
c2552223
FC
390 if (http->flags.accel)
391 request->flags.markAccelerated();
62e76326 392
b6433ffc 393 request->flags.setInternalClient();
a46d2c0e 394
395 /* this is an internally created
396 * request, not subject to acceleration
397 * target overrides */
69660be0 398 /*
399 * FIXME? Do we want to detect and handle internal requests of internal
400 * objects ?
401 */
edce4d98 402
403 /* Internally created requests cannot have bodies today */
404 request->content_length = 0;
62e76326 405
cc192b50 406 request->client_addr.SetNoAddr();
62e76326 407
3d674977
AJ
408#if FOLLOW_X_FORWARDED_FOR
409 request->indirect_client_addr.SetNoAddr();
410#endif /* FOLLOW_X_FORWARDED_FOR */
26ac0430 411
cc192b50 412 request->my_addr.SetNoAddr(); /* undefined for internal requests */
62e76326 413
cc192b50 414 request->my_addr.SetPort(0);
62e76326 415
3872be7c
AJ
416 /* Our version is HTTP/1.1 */
417 HttpVersion http_ver(1,1);
edce4d98 418 request->http_ver = http_ver;
62e76326 419
6dd9f4bd 420 http->request = HTTPMSGLOCK(request);
edce4d98 421
422 /* optional - skip the access check ? */
de31d06f 423 http->calloutContext = new ClientRequestContext(http);
424
57abaac0 425 http->calloutContext->http_access_done = false;
de31d06f 426
57abaac0 427 http->calloutContext->redirect_done = true;
de31d06f 428
57abaac0 429 http->calloutContext->no_cache_done = true;
de31d06f 430
431 http->doCallouts();
62e76326 432
edce4d98 433 return 0;
434}
435
de31d06f 436bool
437ClientRequestContext::httpStateIsValid()
438{
439 ClientHttpRequest *http_ = http;
440
441 if (cbdataReferenceValid(http_))
442 return true;
443
444 http = NULL;
445
446 cbdataReferenceDone(http_);
447
448 return false;
449}
450
3d674977
AJ
451#if FOLLOW_X_FORWARDED_FOR
452/**
a9044668 453 * clientFollowXForwardedForCheck() checks the content of X-Forwarded-For:
3d674977
AJ
454 * against the followXFF ACL, or cleans up and passes control to
455 * clientAccessCheck().
d096ace1
AJ
456 *
457 * The trust model here is a little ambiguous. So to clarify the logic:
458 * - we may always use the direct client address as the client IP.
a9044668 459 * - these trust tests merey tell whether we trust given IP enough to believe the
d096ace1
AJ
460 * IP string which it appended to the X-Forwarded-For: header.
461 * - if at any point we don't trust what an IP adds we stop looking.
462 * - at that point the current contents of indirect_client_addr are the value set
463 * by the last previously trusted IP.
464 * ++ indirect_client_addr contains the remote direct client from the trusted peers viewpoint.
3d674977 465 */
3d674977 466static void
2efeb0b7 467clientFollowXForwardedForCheck(allow_t answer, void *data)
3d674977
AJ
468{
469 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
3d674977
AJ
470
471 if (!calloutContext->httpStateIsValid())
472 return;
473
d096ace1
AJ
474 ClientHttpRequest *http = calloutContext->http;
475 HttpRequest *request = http->request;
476
3d674977
AJ
477 /*
478 * answer should be be ACCESS_ALLOWED or ACCESS_DENIED if we are
479 * called as a result of ACL checks, or -1 if we are called when
480 * there's nothing left to do.
481 */
482 if (answer == ACCESS_ALLOWED &&
26ac0430 483 request->x_forwarded_for_iterator.size () != 0) {
d096ace1 484
3d674977 485 /*
d096ace1
AJ
486 * Remove the last comma-delimited element from the
487 * x_forwarded_for_iterator and use it to repeat the cycle.
488 */
3d674977
AJ
489 const char *p;
490 const char *asciiaddr;
491 int l;
b7ac5457 492 Ip::Address addr;
bb790702 493 p = request->x_forwarded_for_iterator.termedBuf();
3d674977
AJ
494 l = request->x_forwarded_for_iterator.size();
495
496 /*
497 * XXX x_forwarded_for_iterator should really be a list of
498 * IP addresses, but it's a String instead. We have to
499 * walk backwards through the String, biting off the last
500 * comma-delimited part each time. As long as the data is in
501 * a String, we should probably implement and use a variant of
502 * strListGetItem() that walks backwards instead of forwards
503 * through a comma-separated list. But we don't even do that;
504 * we just do the work in-line here.
505 */
506 /* skip trailing space and commas */
507 while (l > 0 && (p[l-1] == ',' || xisspace(p[l-1])))
5e263176 508 --l;
3d674977
AJ
509 request->x_forwarded_for_iterator.cut(l);
510 /* look for start of last item in list */
511 while (l > 0 && ! (p[l-1] == ',' || xisspace(p[l-1])))
5e263176 512 --l;
3d674977 513 asciiaddr = p+l;
fafd0efa 514 if ((addr = asciiaddr)) {
3d674977
AJ
515 request->indirect_client_addr = addr;
516 request->x_forwarded_for_iterator.cut(l);
d096ace1
AJ
517 calloutContext->acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
518 if (!Config.onoff.acl_uses_indirect_client) {
519 /* override the default src_addr tested if we have to go deeper than one level into XFF */
520 Filled(calloutContext->acl_checklist)->src_addr = request->indirect_client_addr;
3d674977 521 }
d096ace1 522 calloutContext->acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, data);
3d674977
AJ
523 return;
524 }
525 } /*if (answer == ACCESS_ALLOWED &&
526 request->x_forwarded_for_iterator.size () != 0)*/
527
528 /* clean up, and pass control to clientAccessCheck */
26ac0430 529 if (Config.onoff.log_uses_indirect_client) {
3d674977
AJ
530 /*
531 * Ensure that the access log shows the indirect client
532 * instead of the direct client.
533 */
534 ConnStateData *conn = http->getConn();
535 conn->log_addr = request->indirect_client_addr;
536 }
537 request->x_forwarded_for_iterator.clean();
823e6f98 538 request->flags.setDoneFollowXFF();
3d674977 539
d096ace1
AJ
540 if (answer != ACCESS_ALLOWED && answer != ACCESS_DENIED) {
541 debugs(28, DBG_CRITICAL, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request->indirect_client_addr );
493d3865
AJ
542 }
543
544 /* process actual access ACL as normal. */
545 calloutContext->clientAccessCheck();
3d674977
AJ
546}
547#endif /* FOLLOW_X_FORWARDED_FOR */
548
fe97983f
AJ
549static void
550hostHeaderIpVerifyWrapper(const ipcache_addrs* ia, const DnsLookupDetails &dns, void *data)
551{
552 ClientRequestContext *c = static_cast<ClientRequestContext*>(data);
553 c->hostHeaderIpVerify(ia, dns);
554}
555
556void
557ClientRequestContext::hostHeaderIpVerify(const ipcache_addrs* ia, const DnsLookupDetails &dns)
558{
559 Comm::ConnectionPointer clientConn = http->getConn()->clientConnection;
560
561 // note the DNS details for the transaction stats.
562 http->request->recordLookup(dns);
563
564 if (ia != NULL && ia->count > 0) {
565 // Is the NAT destination IP in DNS?
5086523e 566 for (int i = 0; i < ia->count; ++i) {
fe97983f
AJ
567 if (clientConn->local.matchIPAddr(ia->in_addrs[i]) == 0) {
568 debugs(85, 3, HERE << "validate IP " << clientConn->local << " possible from Host:");
b58b5f77 569 http->request->flags.markHostVerified();
fe97983f
AJ
570 http->doCallouts();
571 return;
572 }
573 debugs(85, 3, HERE << "validate IP " << clientConn->local << " non-match from Host: IP " << ia->in_addrs[i]);
574 }
575 }
576 debugs(85, 3, HERE << "FAIL: validate IP " << clientConn->local << " possible from Host:");
05b28f84 577 hostHeaderVerifyFailed("local IP", "any domain IP");
fe97983f
AJ
578}
579
580void
05b28f84 581ClientRequestContext::hostHeaderVerifyFailed(const char *A, const char *B)
fe97983f 582{
2962f8b8
AJ
583 // IP address validation for Host: failed. Admin wants to ignore them.
584 // NP: we do not yet handle CONNECT tunnels well, so ignore for them
585 if (!Config.onoff.hostStrictVerify && http->request->method != METHOD_CONNECT) {
586 debugs(85, 3, "SECURITY ALERT: Host header forgery detected on " << http->getConn()->clientConnection <<
587 " (" << A << " does not match " << B << ") on URL: " << urlCanonical(http->request));
588
589 // NP: it is tempting to use 'flags.nocache' but that is all about READing cache data.
590 // The problems here are about WRITE for new cache content, which means flags.cachable
29615259 591 http->request->flags.setNotCachable(); // MUST NOT cache (for now)
2962f8b8 592 // XXX: when we have updated the cache key to base on raw-IP + URI this cacheable limit can go.
29615259 593 http->request->flags.clearHierarchical(); // MUST NOT pass to peers (for now)
2962f8b8 594 // XXX: when we have sorted out the best way to relay requests properly to peers this hierarchical limit can go.
567fe088 595 http->doCallouts();
2962f8b8
AJ
596 return;
597 }
598
8f489ad7
AJ
599 debugs(85, DBG_IMPORTANT, "SECURITY ALERT: Host header forgery detected on " <<
600 http->getConn()->clientConnection << " (" << A << " does not match " << B << ")");
601 debugs(85, DBG_IMPORTANT, "SECURITY ALERT: By user agent: " << http->request->header.getStr(HDR_USER_AGENT));
602 debugs(85, DBG_IMPORTANT, "SECURITY ALERT: on URL: " << urlCanonical(http->request));
fe97983f
AJ
603
604 // IP address validation for Host: failed. reject the connection.
605 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
606 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
607 assert (repContext);
2962f8b8 608 repContext->setReplyToError(ERR_CONFLICT_HOST, HTTP_CONFLICT,
fe97983f
AJ
609 http->request->method, NULL,
610 http->getConn()->clientConnection->remote,
611 http->request,
612 NULL,
613#if USE_AUTH
614 http->getConn() != NULL && http->getConn()->auth_user_request != NULL ?
615 http->getConn()->auth_user_request : http->request->auth_user_request);
616#else
617 NULL);
618#endif
619 node = (clientStreamNode *)http->client_stream.tail->data;
620 clientStreamRead(node, http, node->readBuffer);
621}
622
623void
624ClientRequestContext::hostHeaderVerify()
625{
626 // Require a Host: header.
627 const char *host = http->request->header.getStr(HDR_HOST);
fe97983f
AJ
628
629 if (!host) {
630 // TODO: dump out the HTTP/1.1 error about missing host header.
631 // otherwise this is fine, can't forge a header value when its not even set.
632 debugs(85, 3, HERE << "validate skipped with no Host: header present.");
633 http->doCallouts();
634 return;
635 }
636
b58b5f77 637 if (http->request->flags.isInternal()) {
8f489ad7
AJ
638 // TODO: kill this when URL handling allows partial URLs out of accel mode
639 // and we no longer screw with the URL just to add our internal host there
640 debugs(85, 6, HERE << "validate skipped due to internal composite URL.");
641 http->doCallouts();
642 return;
643 }
644
fe97983f
AJ
645 // Locate if there is a port attached, strip ready for IP lookup
646 char *portStr = NULL;
91663dce
AJ
647 char *hostB = xstrdup(host);
648 host = hostB;
fe97983f
AJ
649 if (host[0] == '[') {
650 // IPv6 literal.
fe97983f 651 portStr = strchr(hostB, ']');
91663dce
AJ
652 if (portStr && *(++portStr) != ':') {
653 portStr = NULL;
fe97983f 654 }
91663dce 655 } else {
fe97983f 656 // Domain or IPv4 literal with port
fe97983f 657 portStr = strrchr(hostB, ':');
91663dce
AJ
658 }
659
660 uint16_t port = 0;
661 if (portStr) {
662 *portStr = '\0'; // strip the ':'
663 if (*(++portStr) != '\0')
664 port = xatoi(portStr);
fe97983f
AJ
665 }
666
667 debugs(85, 3, HERE << "validate host=" << host << ", port=" << port << ", portStr=" << (portStr?portStr:"NULL"));
b58b5f77 668 if (http->request->flags.intercepted() || http->request->flags.spoofClientIp()) {
ba4d9da0 669 // verify the Host: port (if any) matches the apparent destination
fe97983f 670 if (portStr && port != http->getConn()->clientConnection->local.GetPort()) {
05b28f84
AJ
671 debugs(85, 3, HERE << "FAIL on validate port " << http->getConn()->clientConnection->local.GetPort() <<
672 " matches Host: port " << port << " (" << portStr << ")");
673 hostHeaderVerifyFailed("intercepted port", portStr);
ba4d9da0
AJ
674 } else {
675 // XXX: match the scheme default port against the apparent destination
fe97983f 676
ba4d9da0
AJ
677 // verify the destination DNS is one of the Host: headers IPs
678 ipcache_nbgethostbyname(host, hostHeaderIpVerifyWrapper, this);
679 }
06059513 680 } else if (!Config.onoff.hostStrictVerify) {
90529125
AJ
681 debugs(85, 3, HERE << "validate skipped.");
682 http->doCallouts();
8f489ad7
AJ
683 } else if (strlen(host) != strlen(http->request->GetHost())) {
684 // Verify forward-proxy requested URL domain matches the Host: header
685 debugs(85, 3, HERE << "FAIL on validate URL domain length " << http->request->GetHost() << " matches Host: " << host);
686 hostHeaderVerifyFailed(host, http->request->GetHost());
687 } else if (matchDomainName(host, http->request->GetHost()) != 0) {
ba4d9da0 688 // Verify forward-proxy requested URL domain matches the Host: header
fe97983f 689 debugs(85, 3, HERE << "FAIL on validate URL domain " << http->request->GetHost() << " matches Host: " << host);
05b28f84 690 hostHeaderVerifyFailed(host, http->request->GetHost());
ba4d9da0
AJ
691 } else if (portStr && port != http->request->port) {
692 // Verify forward-proxy requested URL domain matches the Host: header
693 debugs(85, 3, HERE << "FAIL on validate URL port " << http->request->port << " matches Host: port " << portStr);
694 hostHeaderVerifyFailed("URL port", portStr);
65d2fdbf 695 } else if (!portStr && http->request->method != METHOD_CONNECT && http->request->port != urlDefaultPort(http->request->protocol)) {
ba4d9da0 696 // Verify forward-proxy requested URL domain matches the Host: header
65d2fdbf 697 // Special case: we don't have a default-port to check for CONNECT. Assume URL is correct.
ba4d9da0
AJ
698 debugs(85, 3, HERE << "FAIL on validate URL port " << http->request->port << " matches Host: default port " << urlDefaultPort(http->request->protocol));
699 hostHeaderVerifyFailed("URL port", "default port");
700 } else {
701 // Okay no problem.
702 debugs(85, 3, HERE << "validate passed.");
b58b5f77 703 http->request->flags.markHostVerified();
ba4d9da0 704 http->doCallouts();
fe97983f 705 }
ba4d9da0 706 safe_free(hostB);
fe97983f
AJ
707}
708
edce4d98 709/* This is the entry point for external users of the client_side routines */
710void
de31d06f 711ClientRequestContext::clientAccessCheck()
edce4d98 712{
823e6f98
FC
713 /* NOP if !FOLLOW_X_FORWARDED_FOR */
714 if (FOLLOW_X_FORWARDED_FOR &&
715 !http->request->flags.doneFollowXFF() &&
26ac0430
AJ
716 Config.accessList.followXFF &&
717 http->request->header.has(HDR_X_FORWARDED_FOR)) {
d096ace1
AJ
718
719 /* we always trust the direct client address for actual use */
720 http->request->indirect_client_addr = http->request->client_addr;
fafd0efa 721 http->request->indirect_client_addr.SetPort(0);
d096ace1
AJ
722
723 /* setup the XFF iterator for processing */
724 http->request->x_forwarded_for_iterator = http->request->header.getList(HDR_X_FORWARDED_FOR);
725
726 /* begin by checking to see if we trust direct client enough to walk XFF */
727 acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
728 acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, this);
3d674977
AJ
729 return;
730 }
493d3865 731
b50e327b
AJ
732 if (Config.accessList.http) {
733 acl_checklist = clientAclChecklistCreate(Config.accessList.http, http);
734 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
735 } else {
736 debugs(0, DBG_CRITICAL, "No http_access configuration found. This will block ALL traffic");
737 clientAccessCheckDone(ACCESS_DENIED);
738 }
edce4d98 739}
740
533493da
AJ
741/**
742 * Identical in operation to clientAccessCheck() but performed later using different configured ACL list.
743 * The default here is to allow all. Since the earlier http_access should do a default deny all.
744 * This check is just for a last-minute denial based on adapted request headers.
745 */
746void
747ClientRequestContext::clientAccessCheck2()
748{
749 if (Config.accessList.adapted_http) {
750 acl_checklist = clientAclChecklistCreate(Config.accessList.adapted_http, http);
751 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
752 } else {
327e2131 753 debugs(85, 2, HERE << "No adapted_http_access configuration. default: ALLOW");
533493da
AJ
754 clientAccessCheckDone(ACCESS_ALLOWED);
755 }
756}
757
edce4d98 758void
2efeb0b7 759clientAccessCheckDoneWrapper(allow_t answer, void *data)
edce4d98 760{
de31d06f 761 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
fbade053 762
de31d06f 763 if (!calloutContext->httpStateIsValid())
62e76326 764 return;
62e76326 765
de31d06f 766 calloutContext->clientAccessCheckDone(answer);
767}
768
9d5e7196
AJ
769void
770ClientRequestContext::clientAccessCheckDone(const allow_t &answer)
de31d06f 771{
772 acl_checklist = NULL;
edce4d98 773 err_type page_id;
774 http_status status;
9d5e7196
AJ
775 debugs(85, 2, "The request " <<
776 RequestMethodStr(http->request->method) << " " <<
777 http->uri << " is " << answer <<
778 ", because it matched '" <<
779 (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" );
f5691f9c 780
2f1431ea
AJ
781#if USE_AUTH
782 char const *proxy_auth_msg = "<null>";
94a396a3 783 if (http->getConn() != NULL && http->getConn()->auth_user_request != NULL)
f5691f9c 784 proxy_auth_msg = http->getConn()->auth_user_request->denyMessage("<null>");
785 else if (http->request->auth_user_request != NULL)
786 proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
2f1431ea 787#endif
62e76326 788
dd332b92 789 if (answer != ACCESS_ALLOWED) {
9d5e7196 790 // auth has a grace period where credentials can be expired but okay not to challenge.
309347ef 791
9d5e7196
AJ
792 /* Send an auth challenge or error */
793 // XXX: do we still need aclIsProxyAuth() ?
dd332b92 794 bool auth_challenge = (answer == ACCESS_AUTH_REQUIRED || aclIsProxyAuth(AclMatchedName));
9d5e7196
AJ
795 debugs(85, 5, "Access Denied: " << http->uri);
796 debugs(85, 5, "AclMatchedName = " << (AclMatchedName ? AclMatchedName : "<null>"));
2f1431ea 797#if USE_AUTH
9d5e7196
AJ
798 if (auth_challenge)
799 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg ? proxy_auth_msg : "<null>"));
2f1431ea 800#endif
9ce7856a 801
9d5e7196
AJ
802 /*
803 * NOTE: get page_id here, based on AclMatchedName because if
804 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
805 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
806 * <pribeiro@isel.pt>
807 */
808 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, answer != ACCESS_AUTH_REQUIRED);
9ce7856a 809
9d5e7196 810 http->logType = LOG_TCP_DENIED;
62e76326 811
9d5e7196 812 if (auth_challenge) {
2f1431ea 813#if USE_AUTH
823e6f98 814 if (http->request->flags.sslBumped()) {
9d5e7196
AJ
815 /*SSL Bumped request, authentication is not possible*/
816 status = HTTP_FORBIDDEN;
817 } else if (!http->flags.accel) {
818 /* Proxy authorisation needed */
819 status = HTTP_PROXY_AUTHENTICATION_REQUIRED;
820 } else {
821 /* WWW authorisation needed */
822 status = HTTP_UNAUTHORIZED;
823 }
ed6163ef 824#else
9d5e7196
AJ
825 // need auth, but not possible to do.
826 status = HTTP_FORBIDDEN;
ed6163ef 827#endif
9d5e7196
AJ
828 if (page_id == ERR_NONE)
829 page_id = ERR_CACHE_ACCESS_DENIED;
830 } else {
831 status = HTTP_FORBIDDEN;
ed6163ef 832
9d5e7196
AJ
833 if (page_id == ERR_NONE)
834 page_id = ERR_ACCESS_DENIED;
835 }
62e76326 836
9d5e7196
AJ
837 Ip::Address tmpnoaddr;
838 tmpnoaddr.SetNoAddr();
87f237a9 839 error = clientBuildError(page_id, status,
68715527
CT
840 NULL,
841 http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmpnoaddr,
842 http->request
87f237a9 843 );
68715527 844
2f1431ea 845#if USE_AUTH
87f237a9 846 error->auth_user_request =
68715527
CT
847 http->getConn() != NULL && http->getConn()->auth_user_request != NULL ?
848 http->getConn()->auth_user_request : http->request->auth_user_request;
2f1431ea 849#endif
68715527
CT
850
851 readNextRequest = true;
9d5e7196 852 }
de31d06f 853
dd332b92 854 /* ACCESS_ALLOWED continues here ... */
de31d06f 855 safe_free(http->uri);
856
857 http->uri = xstrdup(urlCanonical(http->request));
858
859 http->doCallouts();
860}
861
a83c6ed6 862#if USE_ADAPTATION
de31d06f 863void
79628299 864ClientHttpRequest::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer g)
de31d06f 865{
a83c6ed6 866 debugs(93,3,HERE << this << " adaptationAclCheckDone called");
6ec67de9 867
e1381638 868#if ICAP_CLIENT
79628299 869 Adaptation::Icap::History::Pointer ih = request->icapHistory();
e1381638 870 if (ih != NULL) {
79628299
CT
871 if (getConn() != NULL) {
872 ih->rfc931 = getConn()->clientConnection->rfc931;
e1381638 873#if USE_SSL
79628299
CT
874 assert(getConn()->clientConnection != NULL);
875 ih->ssluser = sslGetUserEmail(fd_table[getConn()->clientConnection->fd].ssl);
e1381638 876#endif
3ff65596 877 }
79628299
CT
878 ih->log_uri = log_uri;
879 ih->req_sz = req_sz;
3ff65596
AR
880 }
881#endif
882
a22e6cd3
AR
883 if (!g) {
884 debugs(85,3, HERE << "no adaptation needed");
79628299 885 doCallouts();
5f8252d2 886 return;
887 }
de31d06f 888
79628299 889 startAdaptation(g);
edce4d98 890}
891
de31d06f 892#endif
893
14cc8559 894static void
2efeb0b7 895clientRedirectAccessCheckDone(allow_t answer, void *data)
14cc8559 896{
897 ClientRequestContext *context = (ClientRequestContext *)data;
9d5e7196
AJ
898 ClientHttpRequest *http = context->http;
899 context->acl_checklist = NULL;
14cc8559 900
901 if (answer == ACCESS_ALLOWED)
9d5e7196 902 redirectStart(http, clientRedirectDoneWrapper, context);
14cc8559 903 else
de31d06f 904 context->clientRedirectDone(NULL);
14cc8559 905}
906
de31d06f 907void
908ClientRequestContext::clientRedirectStart()
14cc8559 909{
48e7baac 910 debugs(33, 5, HERE << "'" << http->uri << "'");
14cc8559 911
14cc8559 912 if (Config.accessList.redirector) {
de31d06f 913 acl_checklist = clientAclChecklistCreate(Config.accessList.redirector, http);
914 acl_checklist->nonBlockingCheck(clientRedirectAccessCheckDone, this);
14cc8559 915 } else
de31d06f 916 redirectStart(http, clientRedirectDoneWrapper, this);
14cc8559 917}
918
edce4d98 919static int
59a1efb2 920clientHierarchical(ClientHttpRequest * http)
edce4d98 921{
922 const char *url = http->uri;
190154cf 923 HttpRequest *request = http->request;
60745f24 924 HttpRequestMethod method = request->method;
edce4d98 925 const wordlist *p = NULL;
926
2962f8b8 927 // intercepted requests MUST NOT (yet) be sent to peers unless verified
b58b5f77 928 if (!request->flags.hostVerified() && (request->flags.intercepted() || request->flags.spoofClientIp()))
2962f8b8
AJ
929 return 0;
930
69660be0 931 /*
932 * IMS needs a private key, so we can use the hierarchy for IMS only if our
933 * neighbors support private keys
934 */
62e76326 935
29615259 936 if (request->flags.hasIMS() && !neighbors_do_private_keys)
62e76326 937 return 0;
938
69660be0 939 /*
940 * This is incorrect: authenticating requests can be sent via a hierarchy
06b97e72 941 * (they can even be cached if the correct headers are set on the reply)
edce4d98 942 */
29615259 943 if (request->flags.hasAuth())
62e76326 944 return 0;
945
edce4d98 946 if (method == METHOD_TRACE)
62e76326 947 return 1;
948
edce4d98 949 if (method != METHOD_GET)
62e76326 950 return 0;
951
edce4d98 952 /* scan hierarchy_stoplist */
953 for (p = Config.hierarchy_stoplist; p; p = p->next)
62e76326 954 if (strstr(url, p->key))
955 return 0;
956
d60a166f 957 if (request->flags.loopDetect())
62e76326 958 return 0;
959
0c3d3f65 960 if (request->protocol == AnyP::PROTO_HTTP)
62e76326 961 return httpCachable(method);
962
0c3d3f65 963 if (request->protocol == AnyP::PROTO_GOPHER)
62e76326 964 return gopherCachable(request);
965
39a19cb7 966 if (request->protocol == AnyP::PROTO_CACHE_OBJECT)
62e76326 967 return 0;
968
edce4d98 969 return 1;
970}
971
46a1f562
HN
972static void
973clientCheckPinning(ClientHttpRequest * http)
974{
975 HttpRequest *request = http->request;
976 HttpHeader *req_hdr = &request->header;
977 ConnStateData *http_conn = http->getConn();
978
979 /* Internal requests such as those from ESI includes may be without
980 * a client connection
981 */
982 if (!http_conn)
f54f527e 983 return;
46a1f562 984
b6433ffc
FC
985 if (http_conn->port->connection_auth_disabled)
986 request->flags.disableConnectionAuth();
987 if (!request->flags.connectionAuthDisabled()) {
73c36fd9 988 if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) {
46a1f562 989 if (http_conn->pinning.auth) {
b6433ffc 990 request->flags.wantConnectionAuth();
29615259 991 request->flags.markAuth();
46a1f562 992 } else {
b6433ffc 993 request->flags.requestConnectionProxyAuth();
46a1f562 994 }
b1cf2350
AJ
995 // These should already be linked correctly.
996 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
997 }
998 }
999
1000 /* check if connection auth is used, and flag as candidate for pinning
b6433ffc 1001 * in such case.;
46a1f562
HN
1002 * Note: we may need to set flags.connection_auth even if the connection
1003 * is already pinned if it was pinned earlier due to proxy auth
1004 */
b6433ffc 1005 if (!request->flags.connectionAuthWanted()) {
46a1f562
HN
1006 if (req_hdr->has(HDR_AUTHORIZATION) || req_hdr->has(HDR_PROXY_AUTHORIZATION)) {
1007 HttpHeaderPos pos = HttpHeaderInitPos;
1008 HttpHeaderEntry *e;
1009 int may_pin = 0;
1010 while ((e = req_hdr->getEntry(&pos))) {
1011 if (e->id == HDR_AUTHORIZATION || e->id == HDR_PROXY_AUTHORIZATION) {
1012 const char *value = e->value.rawBuf();
1013 if (strncasecmp(value, "NTLM ", 5) == 0
1014 ||
1015 strncasecmp(value, "Negotiate ", 10) == 0
1016 ||
1017 strncasecmp(value, "Kerberos ", 9) == 0) {
1018 if (e->id == HDR_AUTHORIZATION) {
b6433ffc 1019 request->flags.wantConnectionAuth();
46a1f562
HN
1020 may_pin = 1;
1021 } else {
b6433ffc 1022 request->flags.requestConnectionProxyAuth();
46a1f562
HN
1023 may_pin = 1;
1024 }
1025 }
1026 }
1027 }
1028 if (may_pin && !request->pinnedConnection()) {
b1cf2350
AJ
1029 // These should already be linked correctly. Just need the ServerConnection to pinn.
1030 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
1031 }
1032 }
1033 }
1034}
1035
edce4d98 1036static void
59a1efb2 1037clientInterpretRequestHeaders(ClientHttpRequest * http)
edce4d98 1038{
190154cf 1039 HttpRequest *request = http->request;
0ef77270 1040 HttpHeader *req_hdr = &request->header;
5086523e 1041 bool no_cache = false;
edce4d98 1042 const char *str;
62e76326 1043
edce4d98 1044 request->imslen = -1;
a9925b40 1045 request->ims = req_hdr->getTime(HDR_IF_MODIFIED_SINCE);
62e76326 1046
edce4d98 1047 if (request->ims > 0)
29615259 1048 request->flags.setIMS();
62e76326 1049
b58b5f77 1050 if (!request->flags.ignoringCacheControl()) {
432bc83c
HN
1051 if (req_hdr->has(HDR_PRAGMA)) {
1052 String s = req_hdr->getList(HDR_PRAGMA);
62e76326 1053
432bc83c 1054 if (strListIsMember(&s, "no-cache", ','))
5086523e 1055 no_cache=true;
30abd221 1056
432bc83c
HN
1057 s.clean();
1058 }
62e76326 1059
432bc83c 1060 if (request->cache_control)
4ce6e3b5 1061 if (request->cache_control->noCache())
5086523e 1062 no_cache=true;
62e76326 1063
432bc83c
HN
1064 /*
1065 * Work around for supporting the Reload button in IE browsers when Squid
1066 * is used as an accelerator or transparent proxy, by turning accelerated
1067 * IMS request to no-cache requests. Now knows about IE 5.5 fix (is
1068 * actually only fixed in SP1, but we can't tell whether we are talking to
1069 * SP1 or not so all 5.5 versions are treated 'normally').
1070 */
1071 if (Config.onoff.ie_refresh) {
29615259 1072 if (http->flags.accel && request->flags.hasIMS()) {
432bc83c
HN
1073 if ((str = req_hdr->getStr(HDR_USER_AGENT))) {
1074 if (strstr(str, "MSIE 5.01") != NULL)
5086523e 1075 no_cache=true;
432bc83c 1076 else if (strstr(str, "MSIE 5.0") != NULL)
5086523e 1077 no_cache=true;
432bc83c 1078 else if (strstr(str, "MSIE 4.") != NULL)
5086523e 1079 no_cache=true;
432bc83c 1080 else if (strstr(str, "MSIE 3.") != NULL)
5086523e 1081 no_cache=true;
432bc83c 1082 }
62e76326 1083 }
1084 }
edce4d98 1085 }
914b89a2 1086
1087 if (request->method == METHOD_OTHER) {
5086523e 1088 no_cache=true;
60745f24 1089 }
62e76326 1090
edce4d98 1091 if (no_cache) {
626096be 1092#if USE_HTTP_VIOLATIONS
62e76326 1093
1094 if (Config.onoff.reload_into_ims)
c2552223 1095 request->flags.hackNocache();
62e76326 1096 else if (refresh_nocache_hack)
c2552223 1097 request->flags.hackNocache();
62e76326 1098 else
edce4d98 1099#endif
62e76326 1100
29615259 1101 request->flags.setNocache();
edce4d98 1102 }
62e76326 1103
0ef77270 1104 /* ignore range header in non-GETs or non-HEADs */
1105 if (request->method == METHOD_GET || request->method == METHOD_HEAD) {
56713d9a
AR
1106 // XXX: initialize if we got here without HttpRequest::parseHeader()
1107 if (!request->range)
1108 request->range = req_hdr->getRange();
62e76326 1109
1110 if (request->range) {
f206b652 1111 request->flags.setRanged();
62e76326 1112 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
1113 /* XXX: This is suboptimal. We should give the stream the range set,
1114 * and thereby let the top of the stream set the offset when the
26ac0430 1115 * size becomes known. As it is, we will end up requesting from 0
62e76326 1116 * for evey -X range specification.
1117 * RBC - this may be somewhat wrong. We should probably set the range
1118 * iter up at this point.
1119 */
1120 node->readBuffer.offset = request->range->lowestOffset(0);
1121 http->range_iter.pos = request->range->begin();
1122 http->range_iter.valid = true;
1123 }
edce4d98 1124 }
62e76326 1125
0ef77270 1126 /* Only HEAD and GET requests permit a Range or Request-Range header.
1127 * If these headers appear on any other type of request, delete them now.
1128 */
1129 else {
1130 req_hdr->delById(HDR_RANGE);
1131 req_hdr->delById(HDR_REQUEST_RANGE);
56713d9a 1132 delete request->range;
0ef77270 1133 request->range = NULL;
1134 }
1135
a9925b40 1136 if (req_hdr->has(HDR_AUTHORIZATION))
29615259 1137 request->flags.markAuth();
62e76326 1138
46a1f562 1139 clientCheckPinning(http);
d67acb4e 1140
edce4d98 1141 if (request->login[0] != '\0')
29615259 1142 request->flags.markAuth();
62e76326 1143
a9925b40 1144 if (req_hdr->has(HDR_VIA)) {
30abd221 1145 String s = req_hdr->getList(HDR_VIA);
62e76326 1146 /*
3c4fcf0f 1147 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
62e76326 1148 * Note ThisCache2 has a space prepended to the hostname so we don't
1149 * accidentally match super-domains.
1150 */
1151
1152 if (strListIsSubstr(&s, ThisCache2, ',')) {
1153 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
1154 request, (ObjPackMethod) & httpRequestPack);
d60a166f 1155 request->flags.setLoopDetect();
62e76326 1156 }
1157
21f6708d 1158#if USE_FORW_VIA_DB
bb790702 1159 fvdbCountVia(s.termedBuf());
62e76326 1160
edce4d98 1161#endif
62e76326 1162
30abd221 1163 s.clean();
edce4d98 1164 }
62e76326 1165
21f6708d 1166#if USE_FORW_VIA_DB
62e76326 1167
a9925b40 1168 if (req_hdr->has(HDR_X_FORWARDED_FOR)) {
30abd221 1169 String s = req_hdr->getList(HDR_X_FORWARDED_FOR);
bb790702 1170 fvdbCountForw(s.termedBuf());
30abd221 1171 s.clean();
edce4d98 1172 }
62e76326 1173
edce4d98 1174#endif
62e76326 1175
29615259 1176 request->flags.setCachable(http->request->cacheable());
62e76326 1177
edce4d98 1178 if (clientHierarchical(http))
29615259 1179 request->flags.setHierarchical();
62e76326 1180
bf8fe701 1181 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
29615259 1182 (request->flags.noCache() ? "SET" : "NOT SET"));
bf8fe701 1183 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
29615259 1184 (request->flags.isCachable() ? "SET" : "NOT SET"));
bf8fe701 1185 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
29615259 1186 (request->flags.hierarchical() ? "SET" : "NOT SET"));
62e76326 1187
edce4d98 1188}
1189
1190void
de31d06f 1191clientRedirectDoneWrapper(void *data, char *result)
edce4d98 1192{
de31d06f 1193 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
db02222f 1194
de31d06f 1195 if (!calloutContext->httpStateIsValid())
62e76326 1196 return;
62e76326 1197
de31d06f 1198 calloutContext->clientRedirectDone(result);
1199}
1200
1201void
1202ClientRequestContext::clientRedirectDone(char *result)
1203{
190154cf 1204 HttpRequest *old_request = http->request;
bf8fe701 1205 debugs(85, 5, "clientRedirectDone: '" << http->uri << "' result=" << (result ? result : "NULL"));
de31d06f 1206 assert(redirect_state == REDIRECT_PENDING);
1207 redirect_state = REDIRECT_DONE;
62e76326 1208
edce4d98 1209 if (result) {
62e76326 1210 http_status status = (http_status) atoi(result);
1211
1212 if (status == HTTP_MOVED_PERMANENTLY
1213 || status == HTTP_MOVED_TEMPORARILY
1214 || status == HTTP_SEE_OTHER
6bc67152 1215 || status == HTTP_PERMANENT_REDIRECT
62e76326 1216 || status == HTTP_TEMPORARY_REDIRECT) {
1217 char *t = result;
1218
1219 if ((t = strchr(result, ':')) != NULL) {
1220 http->redirect.status = status;
1221 http->redirect.location = xstrdup(t + 1);
e5b677f0 1222 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
62e76326 1223 } else {
6bc67152 1224 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid " << status << " redirect Location: " << result);
62e76326 1225 }
e5b677f0 1226 } else if (strcmp(result, http->uri)) {
9be14530
AJ
1227 // XXX: validate the URL properly *without* generating a whole new request object right here.
1228 // XXX: the clone() should be done only AFTER we know the new URL is valid.
1229 HttpRequest *new_request = old_request->clone();
1230 if (urlParse(old_request->method, result, new_request)) {
1231 debugs(61,2, HERE << "URL-rewriter diverts URL from " << urlCanonical(old_request) << " to " << urlCanonical(new_request));
1232
1233 // update the new request to flag the re-writing was done on it
944b0569 1234 new_request->flags.markRedirected();
9be14530
AJ
1235
1236 // unlink bodypipe from the old request. Not needed there any longer.
1237 if (old_request->body_pipe != NULL) {
1238 old_request->body_pipe = NULL;
1239 debugs(61,2, HERE << "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
1240 " from request " << old_request << " to " << new_request);
1241 }
1242
1243 // update the current working ClientHttpRequest fields
1244 safe_free(http->uri);
1245 http->uri = xstrdup(urlCanonical(new_request));
1246 HTTPMSGUNLOCK(old_request);
1247 http->request = HTTPMSGLOCK(new_request);
1248 } else {
e5b677f0 1249 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " <<
c9fd01b4 1250 old_request->method << " " << result << " " << old_request->http_ver);
9be14530
AJ
1251 delete new_request;
1252 }
74b48915 1253 }
edce4d98 1254 }
62e76326 1255
edce4d98 1256 /* FIXME PIPELINE: This is innacurate during pipelining */
62e76326 1257
73c36fd9
AJ
1258 if (http->getConn() != NULL && Comm::IsConnOpen(http->getConn()->clientConnection))
1259 fd_note(http->getConn()->clientConnection->fd, http->uri);
62e76326 1260
c8be6d7b 1261 assert(http->uri);
62e76326 1262
de31d06f 1263 http->doCallouts();
edce4d98 1264}
1265
b50e327b
AJ
1266/** Test cache allow/deny configuration
1267 * Sets flags.cachable=1 if caching is not denied.
1268 */
edce4d98 1269void
8e2745f4 1270ClientRequestContext::checkNoCache()
edce4d98 1271{
b50e327b
AJ
1272 if (Config.accessList.noCache) {
1273 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1274 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1275 } else {
1276 /* unless otherwise specified, we try to cache. */
2efeb0b7 1277 checkNoCacheDone(ACCESS_ALLOWED);
b50e327b 1278 }
edce4d98 1279}
1280
de31d06f 1281static void
2efeb0b7 1282checkNoCacheDoneWrapper(allow_t answer, void *data)
edce4d98 1283{
de31d06f 1284 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
e4a67a80 1285
de31d06f 1286 if (!calloutContext->httpStateIsValid())
1287 return;
1288
1289 calloutContext->checkNoCacheDone(answer);
8e2745f4 1290}
4fb35c3c 1291
8e2745f4 1292void
2efeb0b7 1293ClientRequestContext::checkNoCacheDone(const allow_t &answer)
62e76326 1294{
8e2745f4 1295 acl_checklist = NULL;
29615259
FC
1296 if (answer == ACCESS_ALLOWED)
1297 http->request->flags.setCachable();
de31d06f 1298 http->doCallouts();
edce4d98 1299}
1300
e0c0d54c
CT
1301#if USE_SSL
1302bool
1303ClientRequestContext::sslBumpAccessCheck()
1304{
08097970
AR
1305 // If SSL connection tunneling or bumping decision has been made, obey it.
1306 const Ssl::BumpMode bumpMode = http->getConn()->sslBumpMode;
1307 if (bumpMode != Ssl::bumpEnd) {
1308 debugs(85, 5, HERE << "SslBump already decided (" << bumpMode <<
1309 "), " << "ignoring ssl_bump for " << http->getConn());
71cae389 1310 http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
08097970
AR
1311 return false;
1312 }
e0c0d54c 1313
08097970
AR
1314 // If we have not decided yet, decide whether to bump now.
1315
1316 // Bumping here can only start with a CONNECT request on a bumping port
1317 // (bumping of intercepted SSL conns is decided before we get 1st request).
1318 // We also do not bump redirected CONNECT requests.
1319 if (http->request->method != METHOD_CONNECT || http->redirect.status ||
87f237a9 1320 !Config.accessList.ssl_bump || !http->getConn()->port->sslBump) {
71cae389 1321 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
08097970 1322 debugs(85, 5, HERE << "cannot SslBump this request");
e0c0d54c
CT
1323 return false;
1324 }
08097970
AR
1325
1326 // Do not bump during authentication: clients would not proxy-authenticate
1327 // if we delay a 407 response and respond with 200 OK to CONNECT.
1328 if (error && error->httpStatus == HTTP_PROXY_AUTHENTICATION_REQUIRED) {
71cae389 1329 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
08097970
AR
1330 debugs(85, 5, HERE << "no SslBump during proxy authentication");
1331 return false;
1332 }
1333
1334 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1335
1336 ACLFilledChecklist *acl_checklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http);
1337 acl_checklist->nonBlockingCheck(sslBumpAccessCheckDoneWrapper, this);
1338 return true;
e0c0d54c
CT
1339}
1340
f8901ea9 1341/**
e0c0d54c
CT
1342 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1343 * as ACLFilledChecklist callback
1344 */
1345static void
2efeb0b7 1346sslBumpAccessCheckDoneWrapper(allow_t answer, void *data)
e0c0d54c
CT
1347{
1348 ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data);
9d5e7196
AJ
1349
1350 if (!calloutContext->httpStateIsValid())
1351 return;
ed6163ef 1352 calloutContext->sslBumpAccessCheckDone(answer);
e0c0d54c
CT
1353}
1354
1355void
ed6163ef 1356ClientRequestContext::sslBumpAccessCheckDone(const allow_t &answer)
e0c0d54c 1357{
ed6163ef
AJ
1358 if (!httpStateIsValid())
1359 return;
1360
08097970 1361 const Ssl::BumpMode bumpMode = answer == ACCESS_ALLOWED ?
87f237a9 1362 static_cast<Ssl::BumpMode>(answer.kind) : Ssl::bumpNone;
08097970 1363 http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed
71cae389 1364 http->al->ssl.bumpMode = bumpMode; // for logging
caf3666d 1365
e0c0d54c
CT
1366 http->doCallouts();
1367}
1368#endif
1369
69660be0 1370/*
1371 * Identify requests that do not go through the store and client side stream
1372 * and forward them to the appropriate location. All other requests, request
1373 * them.
edce4d98 1374 */
1375void
8e2745f4 1376ClientHttpRequest::processRequest()
edce4d98 1377{
60745f24 1378 debugs(85, 4, "clientProcessRequest: " << RequestMethodStr(request->method) << " '" << uri << "'");
62e76326 1379
31281814 1380 if (request->method == METHOD_CONNECT && !redirect.status) {
3712be3f 1381#if USE_SSL
31281814
AJ
1382 if (sslBumpNeeded()) {
1383 sslBumpStart();
1384 return;
1385 }
3712be3f 1386#endif
62e76326 1387 logType = LOG_TCP_MISS;
f84dd7eb 1388 getConn()->stopReading(); // tunnels read for themselves
41ebd397 1389 tunnelStart(this, &out.size, &al->http.code);
62e76326 1390 return;
edce4d98 1391 }
62e76326 1392
8e2745f4 1393 httpStart();
1394}
1395
1396void
1397ClientHttpRequest::httpStart()
1398{
559da936 1399 PROF_start(httpStart);
8e2745f4 1400 logType = LOG_TAG_NONE;
38e16f92 1401 debugs(85, 4, "ClientHttpRequest::httpStart: " << Format::log_tags[logType] << " for '" << uri << "'");
bf8fe701 1402
edce4d98 1403 /* no one should have touched this */
8e2745f4 1404 assert(out.offset == 0);
edce4d98 1405 /* Use the Stream Luke */
8e2745f4 1406 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1407 clientStreamRead(node, this, node->readBuffer);
559da936 1408 PROF_stop(httpStart);
edce4d98 1409}
0655fa4d 1410
3712be3f 1411#if USE_SSL
1412
e0c0d54c 1413void
08097970 1414ClientHttpRequest::sslBumpNeed(Ssl::BumpMode mode)
e0c0d54c 1415{
caf3666d 1416 debugs(83, 3, HERE << "sslBump required: "<< Ssl::bumpMode(mode));
08097970 1417 sslBumpNeed_ = mode;
3712be3f 1418}
1419
1420// called when comm_write has completed
1421static void
e0d28505 1422SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, comm_err_t errflag, int, void *data)
3712be3f 1423{
1424 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1425 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1426
1427 assert(r && cbdataReferenceValid(r));
1428 r->sslBumpEstablish(errflag);
1429}
1430
1431void
1432ClientHttpRequest::sslBumpEstablish(comm_err_t errflag)
1433{
1434 // Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up
1435 if (errflag == COMM_ERR_CLOSING)
1436 return;
1437
1438 if (errflag) {
1fa35be8 1439 debugs(85, 3, HERE << "CONNECT response failure in SslBump: " << errflag);
bbc83914 1440 getConn()->clientConnection->close();
3712be3f 1441 return;
1442 }
1443
40d8be97
AR
1444 // We lack HttpReply which logRequest() uses to log the status code.
1445 // TODO: Use HttpReply instead of the "200 Connection established" string.
71cae389 1446 al->http.code = 200;
40d8be97 1447
21512911
CT
1448#if USE_AUTH
1449 // Preserve authentication info for the ssl-bumped request
1450 if (request->auth_user_request != NULL)
1451 getConn()->auth_user_request = request->auth_user_request;
1452#endif
03f00a11 1453
08097970
AR
1454 assert(sslBumpNeeded());
1455 getConn()->switchToHttps(request, sslBumpNeed_);
3712be3f 1456}
1457
1458void
1459ClientHttpRequest::sslBumpStart()
1460{
08097970
AR
1461 debugs(85, 5, HERE << "Confirming " << Ssl::bumpMode(sslBumpNeed_) <<
1462 "-bumped CONNECT tunnel on FD " << getConn()->clientConnection);
1463 getConn()->sslBumpMode = sslBumpNeed_;
3712be3f 1464
08097970 1465 // send an HTTP 200 response to kick client SSL negotiation
3712be3f 1466 // TODO: Unify with tunnel.cc and add a Server(?) header
b0388924 1467 static const char *const conn_established = "HTTP/1.1 200 Connection established\r\n\r\n";
ec41b64c
AJ
1468 AsyncCall::Pointer call = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1469 CommIoCbPtrFun(&SslBumpEstablish, this));
73c36fd9 1470 Comm::Write(getConn()->clientConnection, conn_established, strlen(conn_established), call, NULL);
3712be3f 1471}
1472
1473#endif
1474
0655fa4d 1475bool
1476ClientHttpRequest::gotEnough() const
1477{
86a2f789 1478 /** TODO: should be querying the stream. */
7173d5b0 1479 int64_t contentLength =
06a5ae20 1480 memObject()->getReply()->bodySize(request->method);
0655fa4d 1481 assert(contentLength >= 0);
1482
1483 if (out.offset < contentLength)
1484 return false;
1485
1486 return true;
1487}
1488
86a2f789 1489void
1490ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1491{
1492 entry_ = newEntry;
1493}
1494
0976f8db 1495void
1496ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1497{
1498 if (loggingEntry_)
97b5e68f 1499 loggingEntry_->unlock();
0976f8db 1500
1501 loggingEntry_ = newEntry;
1502
1503 if (loggingEntry_)
3d0ac046 1504 loggingEntry_->lock();
0976f8db 1505}
86a2f789 1506
de31d06f 1507/*
1508 * doCallouts() - This function controls the order of "callout"
1509 * executions, including non-blocking access control checks, the
1510 * redirector, and ICAP. Previously, these callouts were chained
1511 * together such that "clientAccessCheckDone()" would call
1512 * "clientRedirectStart()" and so on.
1513 *
1514 * The ClientRequestContext (aka calloutContext) class holds certain
1515 * state data for the callout/callback operations. Previously
1516 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1517 * for a short time. ClientRequestContext would then delete itself
1518 * and pass control back to ClientHttpRequest when all callouts
1519 * were finished.
1520 *
1521 * This caused some problems for ICAP because we want to make the
1522 * ICAP callout after checking ACLs, but before checking the no_cache
1523 * list. We can't stuff the ICAP state into the ClientRequestContext
1524 * class because we still need the ICAP state after ClientRequestContext
1525 * goes away.
1526 *
1527 * Note that ClientRequestContext is created before the first call
1528 * to doCallouts().
1529 *
1530 * If one of the callouts notices that ClientHttpRequest is no
1531 * longer valid, it should call cbdataReferenceDone() so that
1532 * ClientHttpRequest's reference count goes to zero and it will get
1533 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1534 *
1535 * Note that we set the _done flags here before actually starting
1536 * the callout. This is strictly for convenience.
1537 */
1538
425de4c8
AJ
1539extern tos_t aclMapTOS (acl_tos * head, ACLChecklist * ch);
1540extern nfmark_t aclMapNfmark (acl_nfmark * head, ACLChecklist * ch);
057f5854 1541
de31d06f 1542void
1543ClientHttpRequest::doCallouts()
1544{
1545 assert(calloutContext);
1546
6fca33e0 1547 /*Save the original request for logging purposes*/
41ebd397
CT
1548 if (!calloutContext->http->al->request)
1549 calloutContext->http->al->request = HTTPMSGLOCK(request);
6fca33e0 1550
38450a50 1551 if (!calloutContext->error) {
87f237a9 1552 // CVE-2009-0801: verify the Host: header is consistent with other known details.
38450a50
CT
1553 if (!calloutContext->host_header_verify_done) {
1554 debugs(83, 3, HERE << "Doing calloutContext->hostHeaderVerify()");
1555 calloutContext->host_header_verify_done = true;
1556 calloutContext->hostHeaderVerify();
1557 return;
1558 }
fe97983f 1559
38450a50
CT
1560 if (!calloutContext->http_access_done) {
1561 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()");
1562 calloutContext->http_access_done = true;
1563 calloutContext->clientAccessCheck();
1564 return;
1565 }
de31d06f 1566
a83c6ed6 1567#if USE_ADAPTATION
38450a50
CT
1568 if (!calloutContext->adaptation_acl_check_done) {
1569 calloutContext->adaptation_acl_check_done = true;
1570 if (Adaptation::AccessCheck::Start(
87f237a9
A
1571 Adaptation::methodReqmod, Adaptation::pointPreCache,
1572 request, NULL, this))
38450a50
CT
1573 return; // will call callback
1574 }
de31d06f 1575#endif
1576
38450a50
CT
1577 if (!calloutContext->redirect_done) {
1578 calloutContext->redirect_done = true;
1579 assert(calloutContext->redirect_state == REDIRECT_NONE);
de31d06f 1580
38450a50
CT
1581 if (Config.Program.redirect) {
1582 debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()");
1583 calloutContext->redirect_state = REDIRECT_PENDING;
1584 calloutContext->clientRedirectStart();
1585 return;
1586 }
de31d06f 1587 }
de31d06f 1588
38450a50
CT
1589 if (!calloutContext->adapted_http_access_done) {
1590 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()");
1591 calloutContext->adapted_http_access_done = true;
1592 calloutContext->clientAccessCheck2();
1593 return;
1594 }
533493da 1595
38450a50
CT
1596 if (!calloutContext->interpreted_req_hdrs) {
1597 debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()");
1598 calloutContext->interpreted_req_hdrs = 1;
1599 clientInterpretRequestHeaders(this);
1600 }
57abaac0 1601
38450a50
CT
1602 if (!calloutContext->no_cache_done) {
1603 calloutContext->no_cache_done = true;
de31d06f 1604
29615259 1605 if (Config.accessList.noCache && request->flags.isCachable()) {
38450a50
CT
1606 debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()");
1607 calloutContext->checkNoCache();
1608 return;
1609 }
de31d06f 1610 }
38450a50 1611 } // if !calloutContext->error
de31d06f 1612
425de4c8
AJ
1613 if (!calloutContext->tosToClientDone) {
1614 calloutContext->tosToClientDone = true;
73c36fd9 1615 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
c0941a6a 1616 ACLFilledChecklist ch(NULL, request, NULL);
057f5854 1617 ch.src_addr = request->client_addr;
1618 ch.my_addr = request->my_addr;
425de4c8 1619 tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch);
3712be3f 1620 if (tos)
73c36fd9 1621 Ip::Qos::setSockTos(getConn()->clientConnection, tos);
425de4c8
AJ
1622 }
1623 }
1624
1625 if (!calloutContext->nfmarkToClientDone) {
1626 calloutContext->nfmarkToClientDone = true;
73c36fd9 1627 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
425de4c8
AJ
1628 ACLFilledChecklist ch(NULL, request, NULL);
1629 ch.src_addr = request->client_addr;
1630 ch.my_addr = request->my_addr;
1631 nfmark_t mark = aclMapNfmark(Ip::Qos::TheConfig.nfmarkToClient, &ch);
1632 if (mark)
73c36fd9 1633 Ip::Qos::setSockNfmark(getConn()->clientConnection, mark);
3712be3f 1634 }
057f5854 1635 }
1636
d2565320 1637#if USE_SSL
7a957a93
AR
1638 // We need to check for SslBump even if the calloutContext->error is set
1639 // because bumping may require delaying the error until after CONNECT.
e0c0d54c
CT
1640 if (!calloutContext->sslBumpCheckDone) {
1641 calloutContext->sslBumpCheckDone = true;
1642 if (calloutContext->sslBumpAccessCheck())
1643 return;
1644 /* else no ssl bump required*/
1645 }
d2565320 1646#endif
e0c0d54c 1647
2bd84e5f
CT
1648 if (calloutContext->error) {
1649 const char *uri = urlCanonical(request);
1650 StoreEntry *e= storeCreateEntry(uri, uri, request->flags, request->method);
1651#if USE_SSL
08097970 1652 if (sslBumpNeeded()) {
2bd84e5f
CT
1653 // set final error but delay sending until we bump
1654 Ssl::ServerBump *srvBump = new Ssl::ServerBump(request, e);
1655 errorAppendEntry(e, calloutContext->error);
1656 calloutContext->error = NULL;
1657 getConn()->setServerBump(srvBump);
1658 e->unlock();
87f237a9 1659 } else
2bd84e5f
CT
1660#endif
1661 {
7a957a93 1662 // send the error to the client now
2bd84e5f
CT
1663 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1664 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1665 assert (repContext);
1666 repContext->setReplyToStoreEntry(e);
1667 errorAppendEntry(e, calloutContext->error);
1668 calloutContext->error = NULL;
1669 if (calloutContext->readNextRequest)
1670 getConn()->flags.readMore = true; // resume any pipeline reads.
1671 node = (clientStreamNode *)client_stream.tail->data;
1672 clientStreamRead(node, this, node->readBuffer);
1673 e->unlock();
2bd84e5f
CT
1674 return;
1675 }
1676 }
1677
de31d06f 1678 cbdataReferenceDone(calloutContext->http);
1679 delete calloutContext;
1680 calloutContext = NULL;
de31d06f 1681#if HEADERS_LOG
1682
1683 headersLog(0, 1, request->method, request);
1684#endif
1685
58d7150d 1686 debugs(83, 3, HERE << "calling processRequest()");
de31d06f 1687 processRequest();
3ff65596
AR
1688
1689#if ICAP_CLIENT
1690 Adaptation::Icap::History::Pointer ih = request->icapHistory();
1691 if (ih != NULL)
1692 ih->logType = logType;
1693#endif
de31d06f 1694}
1695
32d002cb 1696#if !_USE_INLINE_
86a2f789 1697#include "client_side_request.cci"
1698#endif
de31d06f 1699
a83c6ed6 1700#if USE_ADAPTATION
a22e6cd3
AR
1701/// Initiate an asynchronous adaptation transaction which will call us back.
1702void
1703ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
3b299123 1704{
a22e6cd3 1705 debugs(85, 3, HERE << "adaptation needed for " << this);
a83c6ed6
AR
1706 assert(!virginHeadSource);
1707 assert(!adaptedBodySource);
a22e6cd3 1708 virginHeadSource = initiateAdaptation(
4cb2536f 1709 new Adaptation::Iterator(request, NULL, g));
a83c6ed6 1710
e1381638 1711 // we could try to guess whether we can bypass this adaptation
a22e6cd3 1712 // initiation failure, but it should not really happen
4299f876 1713 Must(initiated(virginHeadSource));
de31d06f 1714}
1715
1716void
3af10ac0 1717ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer &answer)
de31d06f 1718{
de31d06f 1719 assert(cbdataReferenceValid(this)); // indicates bug
3af10ac0
AR
1720 clearAdaptation(virginHeadSource);
1721 assert(!adaptedBodySource);
1722
1723 switch (answer.kind) {
1724 case Adaptation::Answer::akForward:
1725 handleAdaptedHeader(answer.message);
1726 break;
1727
1728 case Adaptation::Answer::akBlock:
1729 handleAdaptationBlock(answer);
1730 break;
1731
1732 case Adaptation::Answer::akError:
1733 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_ABORT, !answer.final);
1734 break;
1735 }
1736}
1737
1738void
ec4d1a1d 1739ClientHttpRequest::handleAdaptedHeader(HttpMsg *msg)
3af10ac0 1740{
5f8252d2 1741 assert(msg);
1742
b044675d 1743 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
200ac359 1744 /*
5f8252d2 1745 * Replace the old request with the new request.
200ac359 1746 */
6dd9f4bd 1747 HTTPMSGUNLOCK(request);
1748 request = HTTPMSGLOCK(new_req);
200ac359 1749 /*
1750 * Store the new URI for logging
1751 */
1752 xfree(uri);
1753 uri = xstrdup(urlCanonical(request));
1754 setLogUri(this, urlCanonicalClean(request));
914b89a2 1755 assert(request->method.id());
b044675d 1756 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
1757 debugs(85,3,HERE << "REQMOD reply is HTTP reply");
1758
5f8252d2 1759 // subscribe to receive reply body
1760 if (new_rep->body_pipe != NULL) {
a83c6ed6 1761 adaptedBodySource = new_rep->body_pipe;
d222a56c
HN
1762 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
1763 assert(consumer_ok);
5f8252d2 1764 }
1765
b044675d 1766 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1767 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1768 repContext->createStoreEntry(request->method, request->flags);
1769
1770 EBIT_CLR(storeEntry()->flags, ENTRY_FWD_HDR_WAIT);
1771 request_satisfaction_mode = true;
1772 request_satisfaction_offset = 0;
1773 storeEntry()->replaceHttpReply(new_rep);
97ae5196 1774 storeEntry()->timestampsSet();
cb4c4288 1775
a83c6ed6 1776 if (!adaptedBodySource) // no body
cb4c4288 1777 storeEntry()->complete();
b044675d 1778 clientGetMoreData(node, this);
200ac359 1779 }
de31d06f 1780
5f8252d2 1781 // we are done with getting headers (but may be receiving body)
a83c6ed6 1782 clearAdaptation(virginHeadSource);
5f8252d2 1783
b044675d 1784 if (!request_satisfaction_mode)
1785 doCallouts();
de31d06f 1786}
1787
1788void
3af10ac0 1789ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer &answer)
de31d06f 1790{
3af10ac0
AR
1791 request->detailError(ERR_ACCESS_DENIED, ERR_DETAIL_REQMOD_BLOCK);
1792 AclMatchedName = answer.ruleId.termedBuf();
1793 assert(calloutContext);
1794 calloutContext->clientAccessCheckDone(ACCESS_DENIED);
1795 AclMatchedName = NULL;
de31d06f 1796}
1797
0ad2b63b
CT
1798void
1799ClientHttpRequest::resumeBodyStorage()
1800{
e83cdc25 1801 if (!adaptedBodySource)
0ad2b63b
CT
1802 return;
1803
1804 noteMoreBodyDataAvailable(adaptedBodySource);
1805}
1806
de31d06f 1807void
1cf238db 1808ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
de31d06f 1809{
5f8252d2 1810 assert(request_satisfaction_mode);
a83c6ed6 1811 assert(adaptedBodySource != NULL);
5f8252d2 1812
0ad2b63b 1813 if (size_t contentSize = adaptedBodySource->buf().contentSize()) {
4dc2b072 1814 const size_t spaceAvailable = storeEntry()->bytesWanted(Range<size_t>(0,contentSize));
0ad2b63b
CT
1815
1816 if (spaceAvailable < contentSize ) {
1817 // No or partial body data consuming
1818 typedef NullaryMemFunT<ClientHttpRequest> Dialer;
1819 AsyncCall::Pointer call = asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage",
1820 Dialer(this, &ClientHttpRequest::resumeBodyStorage));
1821 storeEntry()->deferProducer(call);
1822 }
1823
4dc2b072 1824 if (!spaceAvailable)
0ad2b63b
CT
1825 return;
1826
1827 if (spaceAvailable < contentSize )
1828 contentSize = spaceAvailable;
1829
a83c6ed6 1830 BodyPipeCheckout bpc(*adaptedBodySource);
0ad2b63b 1831 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset, contentSize);
5f8252d2 1832 storeEntry()->write(ioBuf);
0ad2b63b
CT
1833 // assume StoreEntry::write() writes the entire ioBuf
1834 request_satisfaction_offset += ioBuf.length;
4ce0e99b 1835 bpc.buf.consume(contentSize);
5f8252d2 1836 bpc.checkIn();
1837 }
1838
a83c6ed6 1839 if (adaptedBodySource->exhausted())
5f8252d2 1840 endRequestSatisfaction();
1841 // else wait for more body data
de31d06f 1842}
1843
1844void
1cf238db 1845ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
de31d06f 1846{
a83c6ed6 1847 assert(!virginHeadSource);
0ad2b63b
CT
1848 // should we end request satisfaction now?
1849 if (adaptedBodySource != NULL && adaptedBodySource->exhausted())
5f8252d2 1850 endRequestSatisfaction();
5f8252d2 1851}
3b299123 1852
5f8252d2 1853void
26ac0430
AJ
1854ClientHttpRequest::endRequestSatisfaction()
1855{
5f8252d2 1856 debugs(85,4, HERE << this << " ends request satisfaction");
1857 assert(request_satisfaction_mode);
a83c6ed6 1858 stopConsumingFrom(adaptedBodySource);
3b299123 1859
5f8252d2 1860 // TODO: anything else needed to end store entry formation correctly?
1861 storeEntry()->complete();
1862}
de31d06f 1863
5f8252d2 1864void
1cf238db 1865ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
5f8252d2 1866{
a83c6ed6
AR
1867 assert(!virginHeadSource);
1868 stopConsumingFrom(adaptedBodySource);
eae3a9a6
AR
1869
1870 debugs(85,3, HERE << "REQMOD body production failed");
1871 if (request_satisfaction_mode) { // too late to recover or serve an error
1872 request->detailError(ERR_ICAP_FAILURE, ERR_DETAIL_CLT_REQMOD_RESP_BODY);
73c36fd9 1873 const Comm::ConnectionPointer c = getConn()->clientConnection;
e7cea0ed
AJ
1874 Must(Comm::IsConnOpen(c));
1875 c->close(); // drastic, but we may be writing a response already
eae3a9a6
AR
1876 } else {
1877 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_REQ_BODY);
1878 }
5f8252d2 1879}
3b299123 1880
5f8252d2 1881void
64b66b76 1882ClientHttpRequest::handleAdaptationFailure(int errDetail, bool bypassable)
5f8252d2 1883{
a83c6ed6 1884 debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")");
3b299123 1885
5f8252d2 1886 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
1887 const bool usedPipe = request->body_pipe != NULL &&
26ac0430 1888 request->body_pipe->consumedSize() > 0;
3b299123 1889
9d4d7c5e 1890 if (bypassable && !usedStore && !usedPipe) {
1891 debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext);
5f8252d2 1892 if (calloutContext)
1893 doCallouts();
1894 return;
1895 }
3b299123 1896
5f8252d2 1897 debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error");
3b299123 1898
5f8252d2 1899 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1900 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1901 assert(repContext);
de31d06f 1902
26ac0430 1903 // The original author of the code also wanted to pass an errno to
5f8252d2 1904 // setReplyToError, but it seems unlikely that the errno reflects the
1905 // true cause of the error at this point, so I did not pass it.
2bd84e5f
CT
1906 if (calloutContext) {
1907 Ip::Address noAddr;
1908 noAddr.SetNoAddr();
1909 ConnStateData * c = getConn();
1910 calloutContext->error = clientBuildError(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR,
87f237a9
A
1911 NULL,
1912 c != NULL ? c->clientConnection->remote : noAddr,
1913 request
1914 );
79fc6915 1915#if USE_AUTH
87f237a9 1916 calloutContext->error->auth_user_request =
2bd84e5f 1917 c != NULL && c->auth_user_request != NULL ? c->auth_user_request : request->auth_user_request;
79fc6915 1918#endif
129fe2a1 1919 calloutContext->error->detailError(errDetail);
2bd84e5f
CT
1920 calloutContext->readNextRequest = true;
1921 c->expectNoForwarding();
1922 doCallouts();
1923 }
1924 //else if(calloutContext == NULL) is it possible?
de31d06f 1925}
1926
1927#endif