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