]> git.ipfire.org Git - thirdparty/squid.git/blob - src/client_side_request.cc
Hack to keep linker happy on missing symbols.
[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 USE_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 // XXX: initialize if we got here without HttpRequest::parseHeader()
892 if (!request->range)
893 request->range = req_hdr->getRange();
894
895 if (request->range) {
896 request->flags.range = 1;
897 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
898 /* XXX: This is suboptimal. We should give the stream the range set,
899 * and thereby let the top of the stream set the offset when the
900 * size becomes known. As it is, we will end up requesting from 0
901 * for evey -X range specification.
902 * RBC - this may be somewhat wrong. We should probably set the range
903 * iter up at this point.
904 */
905 node->readBuffer.offset = request->range->lowestOffset(0);
906 http->range_iter.pos = request->range->begin();
907 http->range_iter.valid = true;
908 }
909 }
910
911 /* Only HEAD and GET requests permit a Range or Request-Range header.
912 * If these headers appear on any other type of request, delete them now.
913 */
914 else {
915 req_hdr->delById(HDR_RANGE);
916 req_hdr->delById(HDR_REQUEST_RANGE);
917 delete 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 USE_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 USE_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 new_request->auth_user_request = old_request->auth_user_request;
1045
1046 if (old_request->body_pipe != NULL) {
1047 new_request->body_pipe = old_request->body_pipe;
1048 old_request->body_pipe = NULL;
1049 debugs(0,0,HERE << "redirecting body_pipe " << new_request->body_pipe << " from request " << old_request << " to " << new_request);
1050 }
1051
1052 new_request->content_length = old_request->content_length;
1053 new_request->extacl_user = old_request->extacl_user;
1054 new_request->extacl_passwd = old_request->extacl_passwd;
1055 new_request->flags.proxy_keepalive = old_request->flags.proxy_keepalive;
1056 HTTPMSGUNLOCK(old_request);
1057 http->request = HTTPMSGLOCK(new_request);
1058 }
1059
1060 /* FIXME PIPELINE: This is innacurate during pipelining */
1061
1062 if (http->getConn() != NULL)
1063 fd_note(http->getConn()->fd, http->uri);
1064
1065 assert(http->uri);
1066
1067 http->doCallouts();
1068 }
1069
1070 /** Test cache allow/deny configuration
1071 * Sets flags.cachable=1 if caching is not denied.
1072 */
1073 void
1074 ClientRequestContext::checkNoCache()
1075 {
1076 if (Config.accessList.noCache) {
1077 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1078 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1079 } else {
1080 /* unless otherwise specified, we try to cache. */
1081 checkNoCacheDone(1);
1082 }
1083 }
1084
1085 static void
1086 checkNoCacheDoneWrapper(int answer, void *data)
1087 {
1088 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
1089
1090 if (!calloutContext->httpStateIsValid())
1091 return;
1092
1093 calloutContext->checkNoCacheDone(answer);
1094 }
1095
1096 void
1097 ClientRequestContext::checkNoCacheDone(int answer)
1098 {
1099 acl_checklist = NULL;
1100 http->request->flags.cachable = answer;
1101 http->doCallouts();
1102 }
1103
1104 /*
1105 * Identify requests that do not go through the store and client side stream
1106 * and forward them to the appropriate location. All other requests, request
1107 * them.
1108 */
1109 void
1110 ClientHttpRequest::processRequest()
1111 {
1112 debugs(85, 4, "clientProcessRequest: " << RequestMethodStr(request->method) << " '" << uri << "'");
1113
1114 #if USE_SSL
1115 if (request->method == METHOD_CONNECT && sslBumpNeeded()) {
1116 sslBumpStart();
1117 return;
1118 }
1119 #endif
1120
1121 if (request->method == METHOD_CONNECT && !redirect.status) {
1122 logType = LOG_TCP_MISS;
1123 getConn()->stopReading(); // tunnels read for themselves
1124 tunnelStart(this, &out.size, &al.http.code);
1125 return;
1126 }
1127
1128 httpStart();
1129 }
1130
1131 void
1132 ClientHttpRequest::httpStart()
1133 {
1134 PROF_start(httpStart);
1135 logType = LOG_TAG_NONE;
1136 debugs(85, 4, "ClientHttpRequest::httpStart: " << log_tags[logType] << " for '" << uri << "'");
1137
1138 /* no one should have touched this */
1139 assert(out.offset == 0);
1140 /* Use the Stream Luke */
1141 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1142 clientStreamRead(node, this, node->readBuffer);
1143 PROF_stop(httpStart);
1144 }
1145
1146 #if USE_SSL
1147
1148 // determines whether we should bump the CONNECT request
1149 bool
1150 ClientHttpRequest::sslBumpNeeded() const
1151 {
1152 if (!getConn()->port->sslBump || !Config.accessList.ssl_bump)
1153 return false;
1154
1155 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1156
1157 ACLFilledChecklist check(Config.accessList.ssl_bump, request, NULL);
1158 check.src_addr = request->client_addr;
1159 check.my_addr = request->my_addr;
1160 return check.fastCheck() == 1;
1161 }
1162
1163 // called when comm_write has completed
1164 static void
1165 SslBumpEstablish(int, char *, size_t, comm_err_t errflag, int, void *data)
1166 {
1167 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1168 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1169
1170 assert(r && cbdataReferenceValid(r));
1171 r->sslBumpEstablish(errflag);
1172 }
1173
1174 void
1175 ClientHttpRequest::sslBumpEstablish(comm_err_t errflag)
1176 {
1177 // Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up
1178 if (errflag == COMM_ERR_CLOSING)
1179 return;
1180
1181 if (errflag) {
1182 getConn()->startClosing("CONNECT response failure in SslBump");
1183 return;
1184 }
1185
1186 getConn()->switchToHttps();
1187 }
1188
1189 void
1190 ClientHttpRequest::sslBumpStart()
1191 {
1192 debugs(85, 5, HERE << "ClientHttpRequest::sslBumpStart");
1193
1194 // send an HTTP 200 response to kick client SSL negotiation
1195 const int fd = getConn()->fd;
1196 debugs(33, 7, HERE << "Confirming CONNECT tunnel on FD " << fd);
1197
1198 // TODO: Unify with tunnel.cc and add a Server(?) header
1199 static const char *const conn_established =
1200 "HTTP/1.0 200 Connection established\r\n\r\n";
1201 comm_write(fd, conn_established, strlen(conn_established),
1202 &SslBumpEstablish, this, NULL);
1203 }
1204
1205 #endif
1206
1207 bool
1208 ClientHttpRequest::gotEnough() const
1209 {
1210 /** TODO: should be querying the stream. */
1211 int64_t contentLength =
1212 memObject()->getReply()->bodySize(request->method);
1213 assert(contentLength >= 0);
1214
1215 if (out.offset < contentLength)
1216 return false;
1217
1218 return true;
1219 }
1220
1221 void
1222 ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1223 {
1224 entry_ = newEntry;
1225 }
1226
1227 void
1228 ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1229 {
1230 if (loggingEntry_)
1231 loggingEntry_->unlock();
1232
1233 loggingEntry_ = newEntry;
1234
1235 if (loggingEntry_)
1236 loggingEntry_->lock();
1237 }
1238
1239 /*
1240 * doCallouts() - This function controls the order of "callout"
1241 * executions, including non-blocking access control checks, the
1242 * redirector, and ICAP. Previously, these callouts were chained
1243 * together such that "clientAccessCheckDone()" would call
1244 * "clientRedirectStart()" and so on.
1245 *
1246 * The ClientRequestContext (aka calloutContext) class holds certain
1247 * state data for the callout/callback operations. Previously
1248 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1249 * for a short time. ClientRequestContext would then delete itself
1250 * and pass control back to ClientHttpRequest when all callouts
1251 * were finished.
1252 *
1253 * This caused some problems for ICAP because we want to make the
1254 * ICAP callout after checking ACLs, but before checking the no_cache
1255 * list. We can't stuff the ICAP state into the ClientRequestContext
1256 * class because we still need the ICAP state after ClientRequestContext
1257 * goes away.
1258 *
1259 * Note that ClientRequestContext is created before the first call
1260 * to doCallouts().
1261 *
1262 * If one of the callouts notices that ClientHttpRequest is no
1263 * longer valid, it should call cbdataReferenceDone() so that
1264 * ClientHttpRequest's reference count goes to zero and it will get
1265 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1266 *
1267 * Note that we set the _done flags here before actually starting
1268 * the callout. This is strictly for convenience.
1269 */
1270
1271 extern int aclMapTOS (acl_tos * head, ACLChecklist * ch);
1272
1273 void
1274 ClientHttpRequest::doCallouts()
1275 {
1276 assert(calloutContext);
1277
1278 /*Save the original request for logging purposes*/
1279 if (!calloutContext->http->al.request)
1280 calloutContext->http->al.request = HTTPMSGLOCK(request);
1281
1282 if (!calloutContext->http_access_done) {
1283 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()");
1284 calloutContext->http_access_done = true;
1285 calloutContext->clientAccessCheck();
1286 return;
1287 }
1288
1289 #if USE_ADAPTATION
1290 if (!calloutContext->adaptation_acl_check_done) {
1291 calloutContext->adaptation_acl_check_done = true;
1292 if (Adaptation::AccessCheck::Start(
1293 Adaptation::methodReqmod, Adaptation::pointPreCache,
1294 request, NULL, adaptationAclCheckDoneWrapper, calloutContext))
1295 return; // will call callback
1296 }
1297 #endif
1298
1299 if (!calloutContext->redirect_done) {
1300 calloutContext->redirect_done = true;
1301 assert(calloutContext->redirect_state == REDIRECT_NONE);
1302
1303 if (Config.Program.redirect) {
1304 debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()");
1305 calloutContext->redirect_state = REDIRECT_PENDING;
1306 calloutContext->clientRedirectStart();
1307 return;
1308 }
1309 }
1310
1311 if (!calloutContext->adapted_http_access_done) {
1312 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()");
1313 calloutContext->adapted_http_access_done = true;
1314 calloutContext->clientAccessCheck2();
1315 return;
1316 }
1317
1318 if (!calloutContext->interpreted_req_hdrs) {
1319 debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()");
1320 calloutContext->interpreted_req_hdrs = 1;
1321 clientInterpretRequestHeaders(this);
1322 }
1323
1324 if (!calloutContext->no_cache_done) {
1325 calloutContext->no_cache_done = true;
1326
1327 if (Config.accessList.noCache && request->flags.cachable) {
1328 debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()");
1329 calloutContext->checkNoCache();
1330 return;
1331 }
1332 }
1333
1334 if (!calloutContext->clientside_tos_done) {
1335 calloutContext->clientside_tos_done = true;
1336 if (getConn() != NULL) {
1337 ACLFilledChecklist ch(NULL, request, NULL);
1338 ch.src_addr = request->client_addr;
1339 ch.my_addr = request->my_addr;
1340 int tos = aclMapTOS(Config.accessList.clientside_tos, &ch);
1341 if (tos)
1342 comm_set_tos(getConn()->fd, tos);
1343 }
1344 }
1345
1346 cbdataReferenceDone(calloutContext->http);
1347 delete calloutContext;
1348 calloutContext = NULL;
1349 #if HEADERS_LOG
1350
1351 headersLog(0, 1, request->method, request);
1352 #endif
1353
1354 debugs(83, 3, HERE << "calling processRequest()");
1355 processRequest();
1356
1357 #if ICAP_CLIENT
1358 Adaptation::Icap::History::Pointer ih = request->icapHistory();
1359 if (ih != NULL)
1360 ih->logType = logType;
1361 #endif
1362 }
1363
1364 #if !_USE_INLINE_
1365 #include "client_side_request.cci"
1366 #endif
1367
1368 #if USE_ADAPTATION
1369 /// Initiate an asynchronous adaptation transaction which will call us back.
1370 void
1371 ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
1372 {
1373 debugs(85, 3, HERE << "adaptation needed for " << this);
1374 assert(!virginHeadSource);
1375 assert(!adaptedBodySource);
1376 virginHeadSource = initiateAdaptation(
1377 new Adaptation::Iterator(this, request, NULL, g));
1378
1379 // we could try to guess whether we can bypass this adaptation
1380 // initiation failure, but it should not really happen
1381 assert(virginHeadSource != NULL); // Must, really
1382 }
1383
1384 void
1385 ClientHttpRequest::noteAdaptationAnswer(HttpMsg *msg)
1386 {
1387 assert(cbdataReferenceValid(this)); // indicates bug
1388 assert(msg);
1389
1390 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
1391 /*
1392 * Replace the old request with the new request.
1393 */
1394 HTTPMSGUNLOCK(request);
1395 request = HTTPMSGLOCK(new_req);
1396 /*
1397 * Store the new URI for logging
1398 */
1399 xfree(uri);
1400 uri = xstrdup(urlCanonical(request));
1401 setLogUri(this, urlCanonicalClean(request));
1402 assert(request->method.id());
1403 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
1404 debugs(85,3,HERE << "REQMOD reply is HTTP reply");
1405
1406 // subscribe to receive reply body
1407 if (new_rep->body_pipe != NULL) {
1408 adaptedBodySource = new_rep->body_pipe;
1409 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
1410 assert(consumer_ok);
1411 }
1412
1413 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1414 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1415 repContext->createStoreEntry(request->method, request->flags);
1416
1417 EBIT_CLR(storeEntry()->flags, ENTRY_FWD_HDR_WAIT);
1418 request_satisfaction_mode = true;
1419 request_satisfaction_offset = 0;
1420 storeEntry()->replaceHttpReply(new_rep);
1421 storeEntry()->timestampsSet();
1422
1423 if (!adaptedBodySource) // no body
1424 storeEntry()->complete();
1425 clientGetMoreData(node, this);
1426 }
1427
1428 // we are done with getting headers (but may be receiving body)
1429 clearAdaptation(virginHeadSource);
1430
1431 if (!request_satisfaction_mode)
1432 doCallouts();
1433 }
1434
1435 void
1436 ClientHttpRequest::noteAdaptationQueryAbort(bool final)
1437 {
1438 clearAdaptation(virginHeadSource);
1439 assert(!adaptedBodySource);
1440 handleAdaptationFailure(!final);
1441 }
1442
1443 void
1444 ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
1445 {
1446 assert(request_satisfaction_mode);
1447 assert(adaptedBodySource != NULL);
1448
1449 if (const size_t contentSize = adaptedBodySource->buf().contentSize()) {
1450 BodyPipeCheckout bpc(*adaptedBodySource);
1451 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset);
1452 storeEntry()->write(ioBuf);
1453 // assume can write everything
1454 request_satisfaction_offset += contentSize;
1455 bpc.buf.consume(contentSize);
1456 bpc.checkIn();
1457 }
1458
1459 if (adaptedBodySource->exhausted())
1460 endRequestSatisfaction();
1461 // else wait for more body data
1462 }
1463
1464 void
1465 ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
1466 {
1467 assert(!virginHeadSource);
1468 if (adaptedBodySource != NULL) { // did not end request satisfaction yet
1469 // We do not expect more because noteMoreBodyDataAvailable always
1470 // consumes everything. We do not even have a mechanism to consume
1471 // leftovers after noteMoreBodyDataAvailable notifications seize.
1472 assert(adaptedBodySource->exhausted());
1473 endRequestSatisfaction();
1474 }
1475 }
1476
1477 void
1478 ClientHttpRequest::endRequestSatisfaction()
1479 {
1480 debugs(85,4, HERE << this << " ends request satisfaction");
1481 assert(request_satisfaction_mode);
1482 stopConsumingFrom(adaptedBodySource);
1483
1484 // TODO: anything else needed to end store entry formation correctly?
1485 storeEntry()->complete();
1486 }
1487
1488 void
1489 ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
1490 {
1491 assert(!virginHeadSource);
1492 stopConsumingFrom(adaptedBodySource);
1493 handleAdaptationFailure();
1494 }
1495
1496 void
1497 ClientHttpRequest::handleAdaptationFailure(bool bypassable)
1498 {
1499 debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")");
1500
1501 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
1502 const bool usedPipe = request->body_pipe != NULL &&
1503 request->body_pipe->consumedSize() > 0;
1504
1505 if (bypassable && !usedStore && !usedPipe) {
1506 debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext);
1507 if (calloutContext)
1508 doCallouts();
1509 return;
1510 }
1511
1512 debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error");
1513
1514 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1515 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1516 assert(repContext);
1517
1518 // The original author of the code also wanted to pass an errno to
1519 // setReplyToError, but it seems unlikely that the errno reflects the
1520 // true cause of the error at this point, so I did not pass it.
1521 Ip::Address noAddr;
1522 noAddr.SetNoAddr();
1523 ConnStateData * c = getConn();
1524 repContext->setReplyToError(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR,
1525 request->method, NULL,
1526 (c != NULL ? c->peer : noAddr), request, NULL,
1527 (c != NULL && c->auth_user_request != NULL ?
1528 c->auth_user_request : request->auth_user_request));
1529
1530 node = (clientStreamNode *)client_stream.tail->data;
1531 clientStreamRead(node, this, node->readBuffer);
1532 }
1533
1534 #endif