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