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