]> git.ipfire.org Git - thirdparty/squid.git/blob - src/client_side_request.cc
Merge from trunk
[thirdparty/squid.git] / src / client_side_request.cc
1
2 /*
3 * $Id$
4 *
5 * DEBUG: section 85 Client-side Request Routines
6 * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c)
7 *
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
10 *
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 *
34 */
35
36
37 /*
38 * General logic of request processing:
39 *
40 * We run a series of tests to determine if access will be permitted, and to do
41 * any redirection. Then we call into the result clientStream to retrieve data.
42 * From that point on it's up to reply management.
43 */
44
45 #include "squid.h"
46 #include "clientStream.h"
47 #include "client_side_request.h"
48 #include "auth/UserRequest.h"
49 #include "HttpRequest.h"
50 #include "ProtoPort.h"
51 #include "acl/FilledChecklist.h"
52 #include "acl/Gadgets.h"
53 #include "client_side.h"
54 #include "client_side_reply.h"
55 #include "Store.h"
56 #include "HttpReply.h"
57 #include "MemObject.h"
58 #include "ClientRequestContext.h"
59 #include "SquidTime.h"
60 #include "wordlist.h"
61 #include "inet_pton.h"
62 #include "fde.h"
63
64 #if USE_ADAPTATION
65 #include "adaptation/AccessCheck.h"
66 #include "adaptation/Iterator.h"
67 #include "adaptation/Service.h"
68 #if ICAP_CLIENT
69 #include "adaptation/icap/History.h"
70 #endif
71 //static void adaptationAclCheckDoneWrapper(Adaptation::ServicePointer service, void *data);
72 #endif
73
74
75
76 #if LINGERING_CLOSE
77 #define comm_close comm_lingering_close
78 #endif
79
80 static const char *const crlf = "\r\n";
81
82 #if FOLLOW_X_FORWARDED_FOR
83 static void
84 clientFollowXForwardedForCheck(int answer, void *data);
85 #endif /* FOLLOW_X_FORWARDED_FOR */
86
87 CBDATA_CLASS_INIT(ClientRequestContext);
88
89 void *
90 ClientRequestContext::operator new (size_t size)
91 {
92 assert (size == sizeof(ClientRequestContext));
93 CBDATA_INIT_TYPE(ClientRequestContext);
94 ClientRequestContext *result = cbdataAlloc(ClientRequestContext);
95 return result;
96 }
97
98 void
99 ClientRequestContext::operator delete (void *address)
100 {
101 ClientRequestContext *t = static_cast<ClientRequestContext *>(address);
102 cbdataFree(t);
103 }
104
105 /* Local functions */
106 /* other */
107 static void clientAccessCheckDoneWrapper(int, void *);
108 static int clientHierarchical(ClientHttpRequest * http);
109 static void clientInterpretRequestHeaders(ClientHttpRequest * http);
110 static RH clientRedirectDoneWrapper;
111 static PF checkNoCacheDoneWrapper;
112 extern "C" CSR clientGetMoreData;
113 extern "C" CSS clientReplyStatus;
114 extern "C" CSD clientReplyDetach;
115 static void checkFailureRatio(err_type, hier_code);
116
117 ClientRequestContext::~ClientRequestContext()
118 {
119 /*
120 * Release our "lock" on our parent, ClientHttpRequest, if we
121 * still have one
122 */
123
124 if (http)
125 cbdataReferenceDone(http);
126
127 debugs(85,3, HERE << this << " ClientRequestContext destructed");
128 }
129
130 ClientRequestContext::ClientRequestContext(ClientHttpRequest *anHttp) : http(cbdataReference(anHttp)), acl_checklist (NULL), redirect_state (REDIRECT_NONE)
131 {
132 http_access_done = false;
133 redirect_done = false;
134 no_cache_done = false;
135 interpreted_req_hdrs = false;
136 debugs(85,3, HERE << this << " ClientRequestContext constructed");
137 }
138
139 CBDATA_CLASS_INIT(ClientHttpRequest);
140
141 void *
142 ClientHttpRequest::operator new (size_t size)
143 {
144 assert (size == sizeof (ClientHttpRequest));
145 CBDATA_INIT_TYPE(ClientHttpRequest);
146 ClientHttpRequest *result = cbdataAlloc(ClientHttpRequest);
147 return result;
148 }
149
150 void
151 ClientHttpRequest::operator delete (void *address)
152 {
153 ClientHttpRequest *t = static_cast<ClientHttpRequest *>(address);
154 cbdataFree(t);
155 }
156
157 ClientHttpRequest::ClientHttpRequest(ConnStateData * aConn) :
158 #if USE_ADAPTATION
159 AsyncJob("ClientHttpRequest"),
160 #endif
161 loggingEntry_(NULL)
162 {
163 start_time = current_time;
164 setConn(aConn);
165 dlinkAdd(this, &active, &ClientActiveRequests);
166 #if USE_ADAPTATION
167 request_satisfaction_mode = false;
168 #endif
169 }
170
171 /*
172 * returns true if client specified that the object must come from the cache
173 * without contacting origin server
174 */
175 bool
176 ClientHttpRequest::onlyIfCached()const
177 {
178 assert(request);
179 return request->cache_control &&
180 EBIT_TEST(request->cache_control->mask, CC_ONLY_IF_CACHED);
181 }
182
183 /*
184 * This function is designed to serve a fairly specific purpose.
185 * Occasionally our vBNS-connected caches can talk to each other, but not
186 * the rest of the world. Here we try to detect frequent failures which
187 * make the cache unusable (e.g. DNS lookup and connect() failures). If
188 * the failure:success ratio goes above 1.0 then we go into "hit only"
189 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
190 * will only fetch HITs from us if they are using the ICP protocol. We
191 * stay in this mode for 5 minutes.
192 *
193 * Duane W., Sept 16, 1996
194 */
195
196 #define FAILURE_MODE_TIME 300
197
198 static void
199 checkFailureRatio(err_type etype, hier_code hcode)
200 {
201 static double magic_factor = 100.0;
202 double n_good;
203 double n_bad;
204
205 if (hcode == HIER_NONE)
206 return;
207
208 n_good = magic_factor / (1.0 + request_failure_ratio);
209
210 n_bad = magic_factor - n_good;
211
212 switch (etype) {
213
214 case ERR_DNS_FAIL:
215
216 case ERR_CONNECT_FAIL:
217 case ERR_SECURE_CONNECT_FAIL:
218
219 case ERR_READ_ERROR:
220 n_bad++;
221 break;
222
223 default:
224 n_good++;
225 }
226
227 request_failure_ratio = n_bad / n_good;
228
229 if (hit_only_mode_until > squid_curtime)
230 return;
231
232 if (request_failure_ratio < 1.0)
233 return;
234
235 debugs(33, 0, "Failure Ratio at "<< std::setw(4)<<
236 std::setprecision(3) << request_failure_ratio);
237
238 debugs(33, 0, "Going into hit-only-mode for " <<
239 FAILURE_MODE_TIME / 60 << " minutes...");
240
241 hit_only_mode_until = squid_curtime + FAILURE_MODE_TIME;
242
243 request_failure_ratio = 0.8; /* reset to something less than 1.0 */
244 }
245
246 ClientHttpRequest::~ClientHttpRequest()
247 {
248 debugs(33, 3, "httpRequestFree: " << uri);
249 PROF_start(httpRequestFree);
250
251 // Even though freeResources() below may destroy the request,
252 // we no longer set request->body_pipe to NULL here
253 // because we did not initiate that pipe (ConnStateData did)
254
255 /* the ICP check here was erroneous
256 * - StoreEntry::releaseRequest was always called if entry was valid
257 */
258 assert(logType < LOG_TYPE_MAX);
259
260 logRequest();
261
262 loggingEntry(NULL);
263
264 if (request)
265 checkFailureRatio(request->errType, al.hier.code);
266
267 freeResources();
268
269 #if USE_ADAPTATION
270 announceInitiatorAbort(virginHeadSource);
271
272 if (adaptedBodySource != NULL)
273 stopConsumingFrom(adaptedBodySource);
274 #endif
275
276 if (calloutContext)
277 delete calloutContext;
278
279 if (conn_)
280 cbdataReferenceDone(conn_);
281
282 /* moving to the next connection is handled by the context free */
283 dlinkDelete(&active, &ClientActiveRequests);
284
285 PROF_stop(httpRequestFree);
286 }
287
288 /**
289 * Create a request and kick it off
290 *
291 * \retval 0 success
292 * \retval -1 failure
293 *
294 * TODO: Pass in the buffers to be used in the inital Read request, as they are
295 * determined by the user
296 */
297 int
298 clientBeginRequest(const HttpRequestMethod& method, char const *url, CSCB * streamcallback,
299 CSD * streamdetach, ClientStreamData streamdata, HttpHeader const *header,
300 char *tailbuf, size_t taillen)
301 {
302 size_t url_sz;
303 ClientHttpRequest *http = new ClientHttpRequest(NULL);
304 HttpRequest *request;
305 StoreIOBuffer tempBuffer;
306 http->start_time = current_time;
307 /* this is only used to adjust the connection offset in client_side.c */
308 http->req_sz = 0;
309 tempBuffer.length = taillen;
310 tempBuffer.data = tailbuf;
311 /* client stream setup */
312 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
313 clientReplyStatus, new clientReplyContext(http), streamcallback,
314 streamdetach, streamdata, tempBuffer);
315 /* make it visible in the 'current acctive requests list' */
316 /* Set flags */
317 /* internal requests only makes sense in an
318 * accelerator today. TODO: accept flags ? */
319 http->flags.accel = 1;
320 /* allow size for url rewriting */
321 url_sz = strlen(url) + Config.appendDomainLen + 5;
322 http->uri = (char *)xcalloc(url_sz, 1);
323 strcpy(http->uri, url);
324
325 if ((request = HttpRequest::CreateFromUrlAndMethod(http->uri, method)) == NULL) {
326 debugs(85, 5, "Invalid URL: " << http->uri);
327 return -1;
328 }
329
330 /*
331 * now update the headers in request with our supplied headers. urlParse
332 * should return a blank header set, but we use Update to be sure of
333 * correctness.
334 */
335 if (header)
336 request->header.update(header, NULL);
337
338 http->log_uri = xstrdup(urlCanonicalClean(request));
339
340 /* http struct now ready */
341
342 /*
343 * build new header list *? TODO
344 */
345 request->flags.accelerated = http->flags.accel;
346
347 request->flags.internalclient = 1;
348
349 /* this is an internally created
350 * request, not subject to acceleration
351 * target overrides */
352 /*
353 * FIXME? Do we want to detect and handle internal requests of internal
354 * objects ?
355 */
356
357 /* Internally created requests cannot have bodies today */
358 request->content_length = 0;
359
360 request->client_addr.SetNoAddr();
361
362 #if FOLLOW_X_FORWARDED_FOR
363 request->indirect_client_addr.SetNoAddr();
364 #endif /* FOLLOW_X_FORWARDED_FOR */
365
366 request->my_addr.SetNoAddr(); /* undefined for internal requests */
367
368 request->my_addr.SetPort(0);
369
370 /* RFC 2616 says 'upgrade' to our 1.0 regardless of what the client is */
371 HttpVersion http_ver(1,0);
372 request->http_ver = http_ver;
373
374 http->request = HTTPMSGLOCK(request);
375
376 /* optional - skip the access check ? */
377 http->calloutContext = new ClientRequestContext(http);
378
379 http->calloutContext->http_access_done = false;
380
381 http->calloutContext->redirect_done = true;
382
383 http->calloutContext->no_cache_done = true;
384
385 http->doCallouts();
386
387 return 0;
388 }
389
390 bool
391 ClientRequestContext::httpStateIsValid()
392 {
393 ClientHttpRequest *http_ = http;
394
395 if (cbdataReferenceValid(http_))
396 return true;
397
398 http = NULL;
399
400 cbdataReferenceDone(http_);
401
402 return false;
403 }
404
405 #if FOLLOW_X_FORWARDED_FOR
406 /**
407 * clientFollowXForwardedForCheck() checks the content of X-Forwarded-For:
408 * against the followXFF ACL, or cleans up and passes control to
409 * clientAccessCheck().
410 *
411 * The trust model here is a little ambiguous. So to clarify the logic:
412 * - we may always use the direct client address as the client IP.
413 * - these trust tests merey tell whether we trust given IP enough to believe the
414 * IP string which it appended to the X-Forwarded-For: header.
415 * - if at any point we don't trust what an IP adds we stop looking.
416 * - at that point the current contents of indirect_client_addr are the value set
417 * by the last previously trusted IP.
418 * ++ indirect_client_addr contains the remote direct client from the trusted peers viewpoint.
419 */
420 static void
421 clientFollowXForwardedForCheck(int answer, void *data)
422 {
423 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
424
425 if (!calloutContext->httpStateIsValid())
426 return;
427
428 ClientHttpRequest *http = calloutContext->http;
429 HttpRequest *request = http->request;
430
431 /*
432 * answer should be be ACCESS_ALLOWED or ACCESS_DENIED if we are
433 * called as a result of ACL checks, or -1 if we are called when
434 * there's nothing left to do.
435 */
436 if (answer == ACCESS_ALLOWED &&
437 request->x_forwarded_for_iterator.size () != 0) {
438
439 /*
440 * Remove the last comma-delimited element from the
441 * x_forwarded_for_iterator and use it to repeat the cycle.
442 */
443 const char *p;
444 const char *asciiaddr;
445 int l;
446 IpAddress addr;
447 p = request->x_forwarded_for_iterator.termedBuf();
448 l = request->x_forwarded_for_iterator.size();
449
450 /*
451 * XXX x_forwarded_for_iterator should really be a list of
452 * IP addresses, but it's a String instead. We have to
453 * walk backwards through the String, biting off the last
454 * comma-delimited part each time. As long as the data is in
455 * a String, we should probably implement and use a variant of
456 * strListGetItem() that walks backwards instead of forwards
457 * through a comma-separated list. But we don't even do that;
458 * we just do the work in-line here.
459 */
460 /* skip trailing space and commas */
461 while (l > 0 && (p[l-1] == ',' || xisspace(p[l-1])))
462 l--;
463 request->x_forwarded_for_iterator.cut(l);
464 /* look for start of last item in list */
465 while (l > 0 && ! (p[l-1] == ',' || xisspace(p[l-1])))
466 l--;
467 asciiaddr = p+l;
468 if ((addr = asciiaddr)) {
469 request->indirect_client_addr = addr;
470 request->x_forwarded_for_iterator.cut(l);
471 calloutContext->acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
472 if (!Config.onoff.acl_uses_indirect_client) {
473 /* override the default src_addr tested if we have to go deeper than one level into XFF */
474 Filled(calloutContext->acl_checklist)->src_addr = request->indirect_client_addr;
475 }
476 calloutContext->acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, data);
477 return;
478 }
479 } /*if (answer == ACCESS_ALLOWED &&
480 request->x_forwarded_for_iterator.size () != 0)*/
481
482 /* clean up, and pass control to clientAccessCheck */
483 if (Config.onoff.log_uses_indirect_client) {
484 /*
485 * Ensure that the access log shows the indirect client
486 * instead of the direct client.
487 */
488 ConnStateData *conn = http->getConn();
489 conn->log_addr = request->indirect_client_addr;
490 }
491 request->x_forwarded_for_iterator.clean();
492 request->flags.done_follow_x_forwarded_for = 1;
493
494 if (answer != ACCESS_ALLOWED && answer != ACCESS_DENIED) {
495 debugs(28, DBG_CRITICAL, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request->indirect_client_addr );
496 }
497
498 /* process actual access ACL as normal. */
499 calloutContext->clientAccessCheck();
500 }
501 #endif /* FOLLOW_X_FORWARDED_FOR */
502
503 /* This is the entry point for external users of the client_side routines */
504 void
505 ClientRequestContext::clientAccessCheck()
506 {
507 #if FOLLOW_X_FORWARDED_FOR
508 if (!http->request->flags.done_follow_x_forwarded_for &&
509 Config.accessList.followXFF &&
510 http->request->header.has(HDR_X_FORWARDED_FOR)) {
511
512 /* we always trust the direct client address for actual use */
513 http->request->indirect_client_addr = http->request->client_addr;
514 http->request->indirect_client_addr.SetPort(0);
515
516 /* setup the XFF iterator for processing */
517 http->request->x_forwarded_for_iterator = http->request->header.getList(HDR_X_FORWARDED_FOR);
518
519 /* begin by checking to see if we trust direct client enough to walk XFF */
520 acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
521 acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, this);
522 return;
523 }
524 #endif /* FOLLOW_X_FORWARDED_FOR */
525
526 if (Config.accessList.http) {
527 acl_checklist = clientAclChecklistCreate(Config.accessList.http, http);
528 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
529 } else {
530 debugs(0, DBG_CRITICAL, "No http_access configuration found. This will block ALL traffic");
531 clientAccessCheckDone(ACCESS_DENIED);
532 }
533 }
534
535 /**
536 * Identical in operation to clientAccessCheck() but performed later using different configured ACL list.
537 * The default here is to allow all. Since the earlier http_access should do a default deny all.
538 * This check is just for a last-minute denial based on adapted request headers.
539 */
540 void
541 ClientRequestContext::clientAccessCheck2()
542 {
543 if (Config.accessList.adapted_http) {
544 acl_checklist = clientAclChecklistCreate(Config.accessList.adapted_http, http);
545 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
546 } else {
547 debugs(85, 2, HERE << "No adapted_http_access configuration.");
548 clientAccessCheckDone(ACCESS_ALLOWED);
549 }
550 }
551
552 void
553 clientAccessCheckDoneWrapper(int answer, void *data)
554 {
555 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
556
557 if (!calloutContext->httpStateIsValid())
558 return;
559
560 calloutContext->clientAccessCheckDone(answer);
561 }
562
563 void
564 ClientRequestContext::clientAccessCheckDone(int answer)
565 {
566 acl_checklist = NULL;
567 err_type page_id;
568 http_status status;
569 debugs(85, 2, "The request " <<
570 RequestMethodStr(http->request->method) << " " <<
571 http->uri << " is " <<
572 (answer == ACCESS_ALLOWED ? "ALLOWED" : "DENIED") <<
573 ", because it matched '" <<
574 (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" );
575 char const *proxy_auth_msg = "<null>";
576
577 if (http->getConn() != NULL && http->getConn()->auth_user_request != NULL)
578 proxy_auth_msg = http->getConn()->auth_user_request->denyMessage("<null>");
579 else if (http->request->auth_user_request != NULL)
580 proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
581
582 if (answer != ACCESS_ALLOWED) {
583 /* Send an error */
584 int require_auth = (answer == ACCESS_REQ_PROXY_AUTH || aclIsProxyAuth(AclMatchedName));
585 debugs(85, 5, "Access Denied: " << http->uri);
586 debugs(85, 5, "AclMatchedName = " << (AclMatchedName ? AclMatchedName : "<null>"));
587
588 if (require_auth)
589 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg ? proxy_auth_msg : "<null>"));
590
591 /*
592 * NOTE: get page_id here, based on AclMatchedName because if
593 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
594 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
595 * <pribeiro@isel.pt>
596 */
597 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, answer != ACCESS_REQ_PROXY_AUTH);
598
599 http->logType = LOG_TCP_DENIED;
600
601 if (require_auth) {
602 if (!http->flags.accel) {
603 /* Proxy authorisation needed */
604 status = HTTP_PROXY_AUTHENTICATION_REQUIRED;
605 } else {
606 /* WWW authorisation needed */
607 status = HTTP_UNAUTHORIZED;
608 }
609
610 if (page_id == ERR_NONE)
611 page_id = ERR_CACHE_ACCESS_DENIED;
612 } else {
613 status = HTTP_FORBIDDEN;
614
615 if (page_id == ERR_NONE)
616 page_id = ERR_ACCESS_DENIED;
617 }
618
619 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
620 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
621 assert (repContext);
622 IpAddress tmpnoaddr;
623 tmpnoaddr.SetNoAddr();
624 repContext->setReplyToError(page_id, status,
625 http->request->method, NULL,
626 http->getConn() != NULL ? http->getConn()->peer : tmpnoaddr,
627 http->request,
628 NULL,
629 http->getConn() != NULL && http->getConn()->auth_user_request ?
630 http->getConn()->auth_user_request : http->request->auth_user_request);
631
632 node = (clientStreamNode *)http->client_stream.tail->data;
633 clientStreamRead(node, http, node->readBuffer);
634 return;
635 }
636
637 /* ACCESS_ALLOWED continues here ... */
638 safe_free(http->uri);
639
640 http->uri = xstrdup(urlCanonical(http->request));
641
642 http->doCallouts();
643 }
644
645 #if USE_ADAPTATION
646 static void
647 adaptationAclCheckDoneWrapper(Adaptation::ServiceGroupPointer g, void *data)
648 {
649 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
650
651 if (!calloutContext->httpStateIsValid())
652 return;
653
654 calloutContext->adaptationAclCheckDone(g);
655 }
656
657 void
658 ClientRequestContext::adaptationAclCheckDone(Adaptation::ServiceGroupPointer g)
659 {
660 debugs(93,3,HERE << this << " adaptationAclCheckDone called");
661 assert(http);
662
663 #if ICAP_CLIENT
664 Adaptation::Icap::History::Pointer ih = http->request->icapHistory();
665 if (ih != NULL) {
666 if (http->getConn() != NULL) {
667 ih->rfc931 = http->getConn()->rfc931;
668 #if USE_SSL
669 ih->ssluser = sslGetUserEmail(fd_table[http->getConn()->fd].ssl);
670 #endif
671 }
672 ih->log_uri = http->log_uri;
673 ih->req_sz = http->req_sz;
674 }
675 #endif
676
677 if (!g) {
678 debugs(85,3, HERE << "no adaptation needed");
679 http->doCallouts();
680 return;
681 }
682
683 http->startAdaptation(g);
684 }
685
686 #endif
687
688 static void
689 clientRedirectAccessCheckDone(int answer, void *data)
690 {
691 ClientRequestContext *context = (ClientRequestContext *)data;
692 ClientHttpRequest *http = context->http;
693 context->acl_checklist = NULL;
694
695 if (answer == ACCESS_ALLOWED)
696 redirectStart(http, clientRedirectDoneWrapper, context);
697 else
698 context->clientRedirectDone(NULL);
699 }
700
701 void
702 ClientRequestContext::clientRedirectStart()
703 {
704 debugs(33, 5, "clientRedirectStart: '" << http->uri << "'");
705
706 if (Config.accessList.redirector) {
707 acl_checklist = clientAclChecklistCreate(Config.accessList.redirector, http);
708 acl_checklist->nonBlockingCheck(clientRedirectAccessCheckDone, this);
709 } else
710 redirectStart(http, clientRedirectDoneWrapper, this);
711 }
712
713 static int
714 clientHierarchical(ClientHttpRequest * http)
715 {
716 const char *url = http->uri;
717 HttpRequest *request = http->request;
718 HttpRequestMethod method = request->method;
719 const wordlist *p = NULL;
720
721 /*
722 * IMS needs a private key, so we can use the hierarchy for IMS only if our
723 * neighbors support private keys
724 */
725
726 if (request->flags.ims && !neighbors_do_private_keys)
727 return 0;
728
729 /*
730 * This is incorrect: authenticating requests can be sent via a hierarchy
731 * (they can even be cached if the correct headers are set on the reply)
732 */
733 if (request->flags.auth)
734 return 0;
735
736 if (method == METHOD_TRACE)
737 return 1;
738
739 if (method != METHOD_GET)
740 return 0;
741
742 /* scan hierarchy_stoplist */
743 for (p = Config.hierarchy_stoplist; p; p = p->next)
744 if (strstr(url, p->key))
745 return 0;
746
747 if (request->flags.loopdetect)
748 return 0;
749
750 if (request->protocol == PROTO_HTTP)
751 return httpCachable(method);
752
753 if (request->protocol == PROTO_GOPHER)
754 return gopherCachable(request);
755
756 if (request->protocol == PROTO_CACHEOBJ)
757 return 0;
758
759 return 1;
760 }
761
762
763 static void
764 clientCheckPinning(ClientHttpRequest * http)
765 {
766 HttpRequest *request = http->request;
767 HttpHeader *req_hdr = &request->header;
768 ConnStateData *http_conn = http->getConn();
769
770 /* Internal requests such as those from ESI includes may be without
771 * a client connection
772 */
773 if (!http_conn)
774 return;
775
776 request->flags.connection_auth_disabled = http_conn->port->connection_auth_disabled;
777 if (!request->flags.connection_auth_disabled) {
778 if (http_conn->pinning.fd != -1) {
779 if (http_conn->pinning.auth) {
780 request->flags.connection_auth = 1;
781 request->flags.auth = 1;
782 } else {
783 request->flags.connection_proxy_auth = 1;
784 }
785 request->setPinnedConnection(http_conn);
786 }
787 }
788
789 /* check if connection auth is used, and flag as candidate for pinning
790 * in such case.
791 * Note: we may need to set flags.connection_auth even if the connection
792 * is already pinned if it was pinned earlier due to proxy auth
793 */
794 if (!request->flags.connection_auth) {
795 if (req_hdr->has(HDR_AUTHORIZATION) || req_hdr->has(HDR_PROXY_AUTHORIZATION)) {
796 HttpHeaderPos pos = HttpHeaderInitPos;
797 HttpHeaderEntry *e;
798 int may_pin = 0;
799 while ((e = req_hdr->getEntry(&pos))) {
800 if (e->id == HDR_AUTHORIZATION || e->id == HDR_PROXY_AUTHORIZATION) {
801 const char *value = e->value.rawBuf();
802 if (strncasecmp(value, "NTLM ", 5) == 0
803 ||
804 strncasecmp(value, "Negotiate ", 10) == 0
805 ||
806 strncasecmp(value, "Kerberos ", 9) == 0) {
807 if (e->id == HDR_AUTHORIZATION) {
808 request->flags.connection_auth = 1;
809 may_pin = 1;
810 } else {
811 request->flags.connection_proxy_auth = 1;
812 may_pin = 1;
813 }
814 }
815 }
816 }
817 if (may_pin && !request->pinnedConnection()) {
818 request->setPinnedConnection(http->getConn());
819 }
820 }
821 }
822 }
823
824 static void
825 clientInterpretRequestHeaders(ClientHttpRequest * http)
826 {
827 HttpRequest *request = http->request;
828 HttpHeader *req_hdr = &request->header;
829 int no_cache = 0;
830 const char *str;
831
832 request->imslen = -1;
833 request->ims = req_hdr->getTime(HDR_IF_MODIFIED_SINCE);
834
835 if (request->ims > 0)
836 request->flags.ims = 1;
837
838 if (!request->flags.ignore_cc) {
839 if (req_hdr->has(HDR_PRAGMA)) {
840 String s = req_hdr->getList(HDR_PRAGMA);
841
842 if (strListIsMember(&s, "no-cache", ','))
843 no_cache++;
844
845 s.clean();
846 }
847
848 if (request->cache_control)
849 if (EBIT_TEST(request->cache_control->mask, CC_NO_CACHE))
850 no_cache++;
851
852 /*
853 * Work around for supporting the Reload button in IE browsers when Squid
854 * is used as an accelerator or transparent proxy, by turning accelerated
855 * IMS request to no-cache requests. Now knows about IE 5.5 fix (is
856 * actually only fixed in SP1, but we can't tell whether we are talking to
857 * SP1 or not so all 5.5 versions are treated 'normally').
858 */
859 if (Config.onoff.ie_refresh) {
860 if (http->flags.accel && request->flags.ims) {
861 if ((str = req_hdr->getStr(HDR_USER_AGENT))) {
862 if (strstr(str, "MSIE 5.01") != NULL)
863 no_cache++;
864 else if (strstr(str, "MSIE 5.0") != NULL)
865 no_cache++;
866 else if (strstr(str, "MSIE 4.") != NULL)
867 no_cache++;
868 else if (strstr(str, "MSIE 3.") != NULL)
869 no_cache++;
870 }
871 }
872 }
873 }
874
875 if (request->method == METHOD_OTHER) {
876 no_cache++;
877 }
878
879 if (no_cache) {
880 #if HTTP_VIOLATIONS
881
882 if (Config.onoff.reload_into_ims)
883 request->flags.nocache_hack = 1;
884 else if (refresh_nocache_hack)
885 request->flags.nocache_hack = 1;
886 else
887 #endif
888
889 request->flags.nocache = 1;
890 }
891
892 /* ignore range header in non-GETs or non-HEADs */
893 if (request->method == METHOD_GET || request->method == METHOD_HEAD) {
894 request->range = req_hdr->getRange();
895
896 if (request->range) {
897 request->flags.range = 1;
898 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
899 /* XXX: This is suboptimal. We should give the stream the range set,
900 * and thereby let the top of the stream set the offset when the
901 * size becomes known. As it is, we will end up requesting from 0
902 * for evey -X range specification.
903 * RBC - this may be somewhat wrong. We should probably set the range
904 * iter up at this point.
905 */
906 node->readBuffer.offset = request->range->lowestOffset(0);
907 http->range_iter.pos = request->range->begin();
908 http->range_iter.valid = true;
909 }
910 }
911
912 /* Only HEAD and GET requests permit a Range or Request-Range header.
913 * If these headers appear on any other type of request, delete them now.
914 */
915 else {
916 req_hdr->delById(HDR_RANGE);
917 req_hdr->delById(HDR_REQUEST_RANGE);
918 request->range = NULL;
919 }
920
921 if (req_hdr->has(HDR_AUTHORIZATION))
922 request->flags.auth = 1;
923
924 clientCheckPinning(http);
925
926 if (request->login[0] != '\0')
927 request->flags.auth = 1;
928
929 if (req_hdr->has(HDR_VIA)) {
930 String s = req_hdr->getList(HDR_VIA);
931 /*
932 * ThisCache cannot be a member of Via header, "1.0 ThisCache" can.
933 * Note ThisCache2 has a space prepended to the hostname so we don't
934 * accidentally match super-domains.
935 */
936
937 if (strListIsSubstr(&s, ThisCache2, ',')) {
938 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
939 request, (ObjPackMethod) & httpRequestPack);
940 request->flags.loopdetect = 1;
941 }
942
943 #if FORW_VIA_DB
944 fvdbCountVia(s.termedBuf());
945
946 #endif
947
948 s.clean();
949 }
950
951 /**
952 \todo --enable-useragent-log and --enable-referer-log. We should
953 probably drop those two as the custom log formats accomplish pretty much the same thing..
954 */
955 #if USE_USERAGENT_LOG
956 if ((str = req_hdr->getStr(HDR_USER_AGENT)))
957 logUserAgent(fqdnFromAddr(http->getConn()->log_addr), str);
958
959 #endif
960 #if USE_REFERER_LOG
961
962 if ((str = req_hdr->getStr(HDR_REFERER)))
963 logReferer(fqdnFromAddr(http->getConn()->log_addr), str, http->log_uri);
964
965 #endif
966 #if FORW_VIA_DB
967
968 if (req_hdr->has(HDR_X_FORWARDED_FOR)) {
969 String s = req_hdr->getList(HDR_X_FORWARDED_FOR);
970 fvdbCountForw(s.termedBuf());
971 s.clean();
972 }
973
974 #endif
975 if (request->method == METHOD_TRACE || request->method == METHOD_OPTIONS) {
976 request->max_forwards = req_hdr->getInt64(HDR_MAX_FORWARDS);
977 }
978
979 request->flags.cachable = http->request->cacheable();
980
981 if (clientHierarchical(http))
982 request->flags.hierarchical = 1;
983
984 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
985 (request->flags.nocache ? "SET" : "NOT SET"));
986 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
987 (request->flags.cachable ? "SET" : "NOT SET"));
988 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
989 (request->flags.hierarchical ? "SET" : "NOT SET"));
990
991 }
992
993 void
994 clientRedirectDoneWrapper(void *data, char *result)
995 {
996 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
997
998 if (!calloutContext->httpStateIsValid())
999 return;
1000
1001 calloutContext->clientRedirectDone(result);
1002 }
1003
1004 void
1005 ClientRequestContext::clientRedirectDone(char *result)
1006 {
1007 HttpRequest *new_request = NULL;
1008 HttpRequest *old_request = http->request;
1009 debugs(85, 5, "clientRedirectDone: '" << http->uri << "' result=" << (result ? result : "NULL"));
1010 assert(redirect_state == REDIRECT_PENDING);
1011 redirect_state = REDIRECT_DONE;
1012
1013 if (result) {
1014 http_status status = (http_status) atoi(result);
1015
1016 if (status == HTTP_MOVED_PERMANENTLY
1017 || status == HTTP_MOVED_TEMPORARILY
1018 || status == HTTP_SEE_OTHER
1019 || status == HTTP_TEMPORARY_REDIRECT) {
1020 char *t = result;
1021
1022 if ((t = strchr(result, ':')) != NULL) {
1023 http->redirect.status = status;
1024 http->redirect.location = xstrdup(t + 1);
1025 } else {
1026 debugs(85, 1, "clientRedirectDone: bad input: " << result);
1027 }
1028 } else if (strcmp(result, http->uri))
1029 new_request = HttpRequest::CreateFromUrlAndMethod(result, old_request->method);
1030 }
1031
1032 if (new_request) {
1033 safe_free(http->uri);
1034 http->uri = xstrdup(urlCanonical(new_request));
1035 new_request->http_ver = old_request->http_ver;
1036 new_request->header.append(&old_request->header);
1037 new_request->client_addr = old_request->client_addr;
1038 #if FOLLOW_X_FORWARDED_FOR
1039 new_request->indirect_client_addr = old_request->indirect_client_addr;
1040 #endif /* FOLLOW_X_FORWARDED_FOR */
1041 new_request->my_addr = old_request->my_addr;
1042 new_request->flags = old_request->flags;
1043 new_request->flags.redirected = 1;
1044
1045 if (old_request->auth_user_request) {
1046 new_request->auth_user_request = old_request->auth_user_request;
1047 AUTHUSERREQUESTLOCK(new_request->auth_user_request, "new request");
1048 }
1049
1050 if (old_request->body_pipe != NULL) {
1051 new_request->body_pipe = old_request->body_pipe;
1052 old_request->body_pipe = NULL;
1053 debugs(0,0,HERE << "redirecting body_pipe " << new_request->body_pipe << " from request " << old_request << " to " << new_request);
1054 }
1055
1056 new_request->content_length = old_request->content_length;
1057 new_request->extacl_user = old_request->extacl_user;
1058 new_request->extacl_passwd = old_request->extacl_passwd;
1059 new_request->flags.proxy_keepalive = old_request->flags.proxy_keepalive;
1060 HTTPMSGUNLOCK(old_request);
1061 http->request = HTTPMSGLOCK(new_request);
1062 }
1063
1064 /* FIXME PIPELINE: This is innacurate during pipelining */
1065
1066 if (http->getConn() != NULL)
1067 fd_note(http->getConn()->fd, http->uri);
1068
1069 assert(http->uri);
1070
1071 http->doCallouts();
1072 }
1073
1074 /** Test cache allow/deny configuration
1075 * Sets flags.cachable=1 if caching is not denied.
1076 */
1077 void
1078 ClientRequestContext::checkNoCache()
1079 {
1080 if (Config.accessList.noCache) {
1081 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1082 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1083 } else {
1084 /* unless otherwise specified, we try to cache. */
1085 checkNoCacheDone(1);
1086 }
1087 }
1088
1089 static void
1090 checkNoCacheDoneWrapper(int answer, void *data)
1091 {
1092 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
1093
1094 if (!calloutContext->httpStateIsValid())
1095 return;
1096
1097 calloutContext->checkNoCacheDone(answer);
1098 }
1099
1100 void
1101 ClientRequestContext::checkNoCacheDone(int answer)
1102 {
1103 acl_checklist = NULL;
1104 http->request->flags.cachable = answer;
1105 http->doCallouts();
1106 }
1107
1108 /*
1109 * Identify requests that do not go through the store and client side stream
1110 * and forward them to the appropriate location. All other requests, request
1111 * them.
1112 */
1113 void
1114 ClientHttpRequest::processRequest()
1115 {
1116 debugs(85, 4, "clientProcessRequest: " << RequestMethodStr(request->method) << " '" << uri << "'");
1117
1118 #if USE_SSL
1119 if (request->method == METHOD_CONNECT && sslBumpNeeded()) {
1120 sslBumpStart();
1121 return;
1122 }
1123 #endif
1124
1125 if (request->method == METHOD_CONNECT && !redirect.status) {
1126 logType = LOG_TCP_MISS;
1127 tunnelStart(this, &out.size, &al.http.code);
1128 return;
1129 }
1130
1131 httpStart();
1132 }
1133
1134 void
1135 ClientHttpRequest::httpStart()
1136 {
1137 PROF_start(httpStart);
1138 logType = LOG_TAG_NONE;
1139 debugs(85, 4, "ClientHttpRequest::httpStart: " << log_tags[logType] << " for '" << uri << "'");
1140
1141 /* no one should have touched this */
1142 assert(out.offset == 0);
1143 /* Use the Stream Luke */
1144 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1145 clientStreamRead(node, this, node->readBuffer);
1146 PROF_stop(httpStart);
1147 }
1148
1149 #if USE_SSL
1150
1151 // determines whether we should bump the CONNECT request
1152 bool
1153 ClientHttpRequest::sslBumpNeeded() const
1154 {
1155 if (!getConn()->port->sslBump || !Config.accessList.ssl_bump)
1156 return false;
1157
1158 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1159
1160 ACLFilledChecklist check(Config.accessList.ssl_bump, request, NULL);
1161 check.src_addr = request->client_addr;
1162 check.my_addr = request->my_addr;
1163 return check.fastCheck() == 1;
1164 }
1165
1166 // called when comm_write has completed
1167 static void
1168 SslBumpEstablish(int, char *, size_t, comm_err_t errflag, int, void *data)
1169 {
1170 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1171 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1172
1173 assert(r && cbdataReferenceValid(r));
1174 r->sslBumpEstablish(errflag);
1175 }
1176
1177 void
1178 ClientHttpRequest::sslBumpEstablish(comm_err_t errflag)
1179 {
1180 // Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up
1181 if (errflag == COMM_ERR_CLOSING)
1182 return;
1183
1184 if (errflag) {
1185 getConn()->startClosing("CONNECT response failure in SslBump");
1186 return;
1187 }
1188
1189 getConn()->switchToHttps();
1190 }
1191
1192 void
1193 ClientHttpRequest::sslBumpStart()
1194 {
1195 debugs(85, 5, HERE << "ClientHttpRequest::sslBumpStart");
1196
1197 // send an HTTP 200 response to kick client SSL negotiation
1198 const int fd = getConn()->fd;
1199 debugs(33, 7, HERE << "Confirming CONNECT tunnel on FD " << fd);
1200
1201 // TODO: Unify with tunnel.cc and add a Server(?) header
1202 static const char *const conn_established =
1203 "HTTP/1.0 200 Connection established\r\n\r\n";
1204 comm_write(fd, conn_established, strlen(conn_established),
1205 &SslBumpEstablish, this, NULL);
1206 }
1207
1208 #endif
1209
1210 bool
1211 ClientHttpRequest::gotEnough() const
1212 {
1213 /** TODO: should be querying the stream. */
1214 int64_t contentLength =
1215 memObject()->getReply()->bodySize(request->method);
1216 assert(contentLength >= 0);
1217
1218 if (out.offset < contentLength)
1219 return false;
1220
1221 return true;
1222 }
1223
1224 void
1225 ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1226 {
1227 entry_ = newEntry;
1228 }
1229
1230 void
1231 ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1232 {
1233 if (loggingEntry_)
1234 loggingEntry_->unlock();
1235
1236 loggingEntry_ = newEntry;
1237
1238 if (loggingEntry_)
1239 loggingEntry_->lock();
1240 }
1241
1242 /*
1243 * doCallouts() - This function controls the order of "callout"
1244 * executions, including non-blocking access control checks, the
1245 * redirector, and ICAP. Previously, these callouts were chained
1246 * together such that "clientAccessCheckDone()" would call
1247 * "clientRedirectStart()" and so on.
1248 *
1249 * The ClientRequestContext (aka calloutContext) class holds certain
1250 * state data for the callout/callback operations. Previously
1251 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1252 * for a short time. ClientRequestContext would then delete itself
1253 * and pass control back to ClientHttpRequest when all callouts
1254 * were finished.
1255 *
1256 * This caused some problems for ICAP because we want to make the
1257 * ICAP callout after checking ACLs, but before checking the no_cache
1258 * list. We can't stuff the ICAP state into the ClientRequestContext
1259 * class because we still need the ICAP state after ClientRequestContext
1260 * goes away.
1261 *
1262 * Note that ClientRequestContext is created before the first call
1263 * to doCallouts().
1264 *
1265 * If one of the callouts notices that ClientHttpRequest is no
1266 * longer valid, it should call cbdataReferenceDone() so that
1267 * ClientHttpRequest's reference count goes to zero and it will get
1268 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1269 *
1270 * Note that we set the _done flags here before actually starting
1271 * the callout. This is strictly for convenience.
1272 */
1273
1274 extern int aclMapTOS (acl_tos * head, ACLChecklist * ch);
1275
1276 void
1277 ClientHttpRequest::doCallouts()
1278 {
1279 assert(calloutContext);
1280
1281 /*Save the original request for logging purposes*/
1282 if (!calloutContext->http->al.request)
1283 calloutContext->http->al.request = HTTPMSGLOCK(request);
1284
1285 if (!calloutContext->http_access_done) {
1286 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()");
1287 calloutContext->http_access_done = true;
1288 calloutContext->clientAccessCheck();
1289 return;
1290 }
1291
1292 #if USE_ADAPTATION
1293 if (!calloutContext->adaptation_acl_check_done) {
1294 calloutContext->adaptation_acl_check_done = true;
1295 if (Adaptation::AccessCheck::Start(
1296 Adaptation::methodReqmod, Adaptation::pointPreCache,
1297 request, NULL, adaptationAclCheckDoneWrapper, calloutContext))
1298 return; // will call callback
1299 }
1300 #endif
1301
1302 if (!calloutContext->redirect_done) {
1303 calloutContext->redirect_done = true;
1304 assert(calloutContext->redirect_state == REDIRECT_NONE);
1305
1306 if (Config.Program.redirect) {
1307 debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()");
1308 calloutContext->redirect_state = REDIRECT_PENDING;
1309 calloutContext->clientRedirectStart();
1310 return;
1311 }
1312 }
1313
1314 if (!calloutContext->adapted_http_access_done) {
1315 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()");
1316 calloutContext->adapted_http_access_done = true;
1317 calloutContext->clientAccessCheck2();
1318 return;
1319 }
1320
1321 if (!calloutContext->interpreted_req_hdrs) {
1322 debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()");
1323 calloutContext->interpreted_req_hdrs = 1;
1324 clientInterpretRequestHeaders(this);
1325 }
1326
1327 if (!calloutContext->no_cache_done) {
1328 calloutContext->no_cache_done = true;
1329
1330 if (Config.accessList.noCache && request->flags.cachable) {
1331 debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()");
1332 calloutContext->checkNoCache();
1333 return;
1334 }
1335 }
1336
1337 if (!calloutContext->clientside_tos_done) {
1338 calloutContext->clientside_tos_done = true;
1339 if (getConn() != NULL) {
1340 ACLFilledChecklist ch(NULL, request, NULL);
1341 ch.src_addr = request->client_addr;
1342 ch.my_addr = request->my_addr;
1343 int tos = aclMapTOS(Config.accessList.clientside_tos, &ch);
1344 if (tos)
1345 comm_set_tos(getConn()->fd, tos);
1346 }
1347 }
1348
1349 cbdataReferenceDone(calloutContext->http);
1350 delete calloutContext;
1351 calloutContext = NULL;
1352 #if HEADERS_LOG
1353
1354 headersLog(0, 1, request->method, request);
1355 #endif
1356
1357 debugs(83, 3, HERE << "calling processRequest()");
1358 processRequest();
1359
1360 #if ICAP_CLIENT
1361 Adaptation::Icap::History::Pointer ih = request->icapHistory();
1362 if (ih != NULL)
1363 ih->logType = logType;
1364 #endif
1365 }
1366
1367 #ifndef _USE_INLINE_
1368 #include "client_side_request.cci"
1369 #endif
1370
1371 #if USE_ADAPTATION
1372 /// Initiate an asynchronous adaptation transaction which will call us back.
1373 void
1374 ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
1375 {
1376 debugs(85, 3, HERE << "adaptation needed for " << this);
1377 assert(!virginHeadSource);
1378 assert(!adaptedBodySource);
1379 virginHeadSource = initiateAdaptation(
1380 new Adaptation::Iterator(this, request, NULL, g));
1381
1382 // we could try to guess whether we can bypass this adaptation
1383 // initiation failure, but it should not really happen
1384 assert(virginHeadSource != NULL); // Must, really
1385 }
1386
1387 void
1388 ClientHttpRequest::noteAdaptationAnswer(HttpMsg *msg)
1389 {
1390 assert(cbdataReferenceValid(this)); // indicates bug
1391 assert(msg);
1392
1393 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
1394 /*
1395 * Replace the old request with the new request.
1396 */
1397 HTTPMSGUNLOCK(request);
1398 request = HTTPMSGLOCK(new_req);
1399 /*
1400 * Store the new URI for logging
1401 */
1402 xfree(uri);
1403 uri = xstrdup(urlCanonical(request));
1404 setLogUri(this, urlCanonicalClean(request));
1405 assert(request->method.id());
1406 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
1407 debugs(85,3,HERE << "REQMOD reply is HTTP reply");
1408
1409 // subscribe to receive reply body
1410 if (new_rep->body_pipe != NULL) {
1411 adaptedBodySource = new_rep->body_pipe;
1412 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
1413 assert(consumer_ok);
1414 }
1415
1416 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1417 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1418 repContext->createStoreEntry(request->method, request->flags);
1419
1420 EBIT_CLR(storeEntry()->flags, ENTRY_FWD_HDR_WAIT);
1421 request_satisfaction_mode = true;
1422 request_satisfaction_offset = 0;
1423 storeEntry()->replaceHttpReply(new_rep);
1424 storeEntry()->timestampsSet();
1425
1426 if (!adaptedBodySource) // no body
1427 storeEntry()->complete();
1428 clientGetMoreData(node, this);
1429 }
1430
1431 // we are done with getting headers (but may be receiving body)
1432 clearAdaptation(virginHeadSource);
1433
1434 if (!request_satisfaction_mode)
1435 doCallouts();
1436 }
1437
1438 void
1439 ClientHttpRequest::noteAdaptationQueryAbort(bool final)
1440 {
1441 clearAdaptation(virginHeadSource);
1442 assert(!adaptedBodySource);
1443 handleAdaptationFailure(!final);
1444 }
1445
1446 void
1447 ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
1448 {
1449 assert(request_satisfaction_mode);
1450 assert(adaptedBodySource != NULL);
1451
1452 if (const size_t contentSize = adaptedBodySource->buf().contentSize()) {
1453 BodyPipeCheckout bpc(*adaptedBodySource);
1454 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset);
1455 storeEntry()->write(ioBuf);
1456 // assume can write everything
1457 request_satisfaction_offset += contentSize;
1458 bpc.buf.consume(contentSize);
1459 bpc.checkIn();
1460 }
1461
1462 if (adaptedBodySource->exhausted())
1463 endRequestSatisfaction();
1464 // else wait for more body data
1465 }
1466
1467 void
1468 ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
1469 {
1470 assert(!virginHeadSource);
1471 if (adaptedBodySource != NULL) { // did not end request satisfaction yet
1472 // We do not expect more because noteMoreBodyDataAvailable always
1473 // consumes everything. We do not even have a mechanism to consume
1474 // leftovers after noteMoreBodyDataAvailable notifications seize.
1475 assert(adaptedBodySource->exhausted());
1476 endRequestSatisfaction();
1477 }
1478 }
1479
1480 void
1481 ClientHttpRequest::endRequestSatisfaction()
1482 {
1483 debugs(85,4, HERE << this << " ends request satisfaction");
1484 assert(request_satisfaction_mode);
1485 stopConsumingFrom(adaptedBodySource);
1486
1487 // TODO: anything else needed to end store entry formation correctly?
1488 storeEntry()->complete();
1489 }
1490
1491 void
1492 ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
1493 {
1494 assert(!virginHeadSource);
1495 stopConsumingFrom(adaptedBodySource);
1496 handleAdaptationFailure();
1497 }
1498
1499 void
1500 ClientHttpRequest::handleAdaptationFailure(bool bypassable)
1501 {
1502 debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")");
1503
1504 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
1505 const bool usedPipe = request->body_pipe != NULL &&
1506 request->body_pipe->consumedSize() > 0;
1507
1508 if (bypassable && !usedStore && !usedPipe) {
1509 debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext);
1510 if (calloutContext)
1511 doCallouts();
1512 return;
1513 }
1514
1515 debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error");
1516
1517 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1518 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1519 assert(repContext);
1520
1521 // The original author of the code also wanted to pass an errno to
1522 // setReplyToError, but it seems unlikely that the errno reflects the
1523 // true cause of the error at this point, so I did not pass it.
1524 IpAddress noAddr;
1525 noAddr.SetNoAddr();
1526 ConnStateData * c = getConn();
1527 repContext->setReplyToError(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR,
1528 request->method, NULL,
1529 (c != NULL ? c->peer : noAddr), request, NULL,
1530 (c != NULL && c->auth_user_request ?
1531 c->auth_user_request : request->auth_user_request));
1532
1533 node = (clientStreamNode *)client_stream.tail->data;
1534 clientStreamRead(node, this, node->readBuffer);
1535 }
1536
1537 #endif