]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_request.cc
SourceFormat Enforcement
[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:");
05b28f84 549 hostHeaderVerifyFailed("local IP", "any domain IP");
fe97983f
AJ
550}
551
552void
05b28f84 553ClientRequestContext::hostHeaderVerifyFailed(const char *A, const char *B)
fe97983f 554{
05b28f84
AJ
555 debugs(85, 1, "SECURITY ALERT: Host: header forgery detected from " << http->getConn()->clientConnection <<
556 " (" << A << " does not match " << B << ")");
fe97983f
AJ
557
558 // IP address validation for Host: failed. reject the connection.
559 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
560 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
561 assert (repContext);
562 repContext->setReplyToError(ERR_INVALID_REQ, HTTP_CONFLICT,
563 http->request->method, NULL,
564 http->getConn()->clientConnection->remote,
565 http->request,
566 NULL,
567#if USE_AUTH
568 http->getConn() != NULL && http->getConn()->auth_user_request != NULL ?
569 http->getConn()->auth_user_request : http->request->auth_user_request);
570#else
571 NULL);
572#endif
573 node = (clientStreamNode *)http->client_stream.tail->data;
574 clientStreamRead(node, http, node->readBuffer);
575}
576
577void
578ClientRequestContext::hostHeaderVerify()
579{
580 // Require a Host: header.
581 const char *host = http->request->header.getStr(HDR_HOST);
582 char *hostB = NULL;
583
584 if (!host) {
585 // TODO: dump out the HTTP/1.1 error about missing host header.
586 // otherwise this is fine, can't forge a header value when its not even set.
587 debugs(85, 3, HERE << "validate skipped with no Host: header present.");
588 http->doCallouts();
589 return;
590 }
591
592 // Locate if there is a port attached, strip ready for IP lookup
593 char *portStr = NULL;
594 uint16_t port = 0;
595 if (host[0] == '[') {
596 // IPv6 literal.
597 // check for a port?
598 hostB = xstrdup(host+1);
599 portStr = strchr(hostB, ']');
600 if (!portStr) {
601 safe_free(hostB); // well, that wasn't an IPv6 literal.
602 } else {
603 *portStr = '\0';
604 if (*(++portStr) == ':')
605 port = xatoi(++portStr);
606 else
607 portStr=NULL; // no port to check.
608 }
609 if (hostB)
610 host = hostB; // point host at the local version for lookup
611 } else if (strrchr(host, ':') != NULL) {
612 // Domain or IPv4 literal with port
613 hostB = xstrdup(host);
614 portStr = strrchr(hostB, ':');
615 *portStr = '\0';
616 port = xatoi(++portStr);
617 host = hostB; // point host at the local version for lookup
618 }
619
620 debugs(85, 3, HERE << "validate host=" << host << ", port=" << port << ", portStr=" << (portStr?portStr:"NULL"));
621 if (http->request->flags.intercepted || http->request->flags.spoof_client_ip) {
622 // verify the port (if any) matches the apparent destination
623 if (portStr && port != http->getConn()->clientConnection->local.GetPort()) {
05b28f84
AJ
624 debugs(85, 3, HERE << "FAIL on validate port " << http->getConn()->clientConnection->local.GetPort() <<
625 " matches Host: port " << port << " (" << portStr << ")");
626 hostHeaderVerifyFailed("intercepted port", portStr);
fe97983f
AJ
627 safe_free(hostB);
628 return;
629 }
630 // XXX: match the scheme default port against the apparent destination
631
632 // verify the destination DNS is one of the Host: headers IPs
633 ipcache_nbgethostbyname(host, hostHeaderIpVerifyWrapper, this);
634 safe_free(hostB);
635 return;
636 }
637 safe_free(hostB);
638
639 // Verify forward-proxy requested URL domain matches the Host: header
640 host = http->request->header.getStr(HDR_HOST);
641 if (strcmp(host, http->request->GetHost()) != 0) {
642 debugs(85, 3, HERE << "FAIL on validate URL domain " << http->request->GetHost() << " matches Host: " << host);
05b28f84 643 hostHeaderVerifyFailed(host, http->request->GetHost());
fe97983f
AJ
644 return;
645 }
646
647 debugs(85, 3, HERE << "validate passed.");
648 http->doCallouts();
649}
650
edce4d98 651/* This is the entry point for external users of the client_side routines */
652void
de31d06f 653ClientRequestContext::clientAccessCheck()
edce4d98 654{
3d674977
AJ
655#if FOLLOW_X_FORWARDED_FOR
656 if (!http->request->flags.done_follow_x_forwarded_for &&
26ac0430
AJ
657 Config.accessList.followXFF &&
658 http->request->header.has(HDR_X_FORWARDED_FOR)) {
d096ace1
AJ
659
660 /* we always trust the direct client address for actual use */
661 http->request->indirect_client_addr = http->request->client_addr;
fafd0efa 662 http->request->indirect_client_addr.SetPort(0);
d096ace1
AJ
663
664 /* setup the XFF iterator for processing */
665 http->request->x_forwarded_for_iterator = http->request->header.getList(HDR_X_FORWARDED_FOR);
666
667 /* begin by checking to see if we trust direct client enough to walk XFF */
668 acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
669 acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, this);
3d674977
AJ
670 return;
671 }
672#endif /* FOLLOW_X_FORWARDED_FOR */
493d3865 673
b50e327b
AJ
674 if (Config.accessList.http) {
675 acl_checklist = clientAclChecklistCreate(Config.accessList.http, http);
676 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
677 } else {
678 debugs(0, DBG_CRITICAL, "No http_access configuration found. This will block ALL traffic");
679 clientAccessCheckDone(ACCESS_DENIED);
680 }
edce4d98 681}
682
533493da
AJ
683/**
684 * Identical in operation to clientAccessCheck() but performed later using different configured ACL list.
685 * The default here is to allow all. Since the earlier http_access should do a default deny all.
686 * This check is just for a last-minute denial based on adapted request headers.
687 */
688void
689ClientRequestContext::clientAccessCheck2()
690{
691 if (Config.accessList.adapted_http) {
692 acl_checklist = clientAclChecklistCreate(Config.accessList.adapted_http, http);
693 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
694 } else {
327e2131 695 debugs(85, 2, HERE << "No adapted_http_access configuration. default: ALLOW");
533493da
AJ
696 clientAccessCheckDone(ACCESS_ALLOWED);
697 }
698}
699
edce4d98 700void
2efeb0b7 701clientAccessCheckDoneWrapper(allow_t answer, void *data)
edce4d98 702{
de31d06f 703 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
fbade053 704
de31d06f 705 if (!calloutContext->httpStateIsValid())
62e76326 706 return;
62e76326 707
de31d06f 708 calloutContext->clientAccessCheckDone(answer);
709}
710
711void
2efeb0b7 712ClientRequestContext::clientAccessCheckDone(const allow_t &answer)
de31d06f 713{
714 acl_checklist = NULL;
edce4d98 715 err_type page_id;
716 http_status status;
26ac0430
AJ
717 debugs(85, 2, "The request " <<
718 RequestMethodStr(http->request->method) << " " <<
2efeb0b7 719 http->uri << " is " << answer <<
26ac0430
AJ
720 ", because it matched '" <<
721 (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" );
f5691f9c 722
2f1431ea
AJ
723#if USE_AUTH
724 char const *proxy_auth_msg = "<null>";
94a396a3 725 if (http->getConn() != NULL && http->getConn()->auth_user_request != NULL)
f5691f9c 726 proxy_auth_msg = http->getConn()->auth_user_request->denyMessage("<null>");
727 else if (http->request->auth_user_request != NULL)
728 proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
2f1431ea 729#endif
62e76326 730
309347ef
AJ
731 if (answer != ACCESS_ALLOWED && answer != ACCESS_AUTH_EXPIRED_OK) {
732 // auth has a grace period where credentials can be expired but okay not to challenge.
733
734 /* Send an auth challenge or error */
735 // XXX: do we still need aclIsProxyAuth() ?
736 bool auth_challenge = (answer == ACCESS_AUTH_REQUIRED || answer == ACCESS_AUTH_EXPIRED_BAD || aclIsProxyAuth(AclMatchedName));
bf8fe701 737 debugs(85, 5, "Access Denied: " << http->uri);
738 debugs(85, 5, "AclMatchedName = " << (AclMatchedName ? AclMatchedName : "<null>"));
2f1431ea 739#if USE_AUTH
309347ef 740 if (auth_challenge)
bf8fe701 741 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg ? proxy_auth_msg : "<null>"));
2f1431ea 742#endif
9ce7856a 743
62e76326 744 /*
745 * NOTE: get page_id here, based on AclMatchedName because if
746 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
747 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
748 * <pribeiro@isel.pt>
749 */
7dfddb79 750 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, answer != ACCESS_AUTH_REQUIRED);
9ce7856a 751
62e76326 752 http->logType = LOG_TCP_DENIED;
753
309347ef 754 if (auth_challenge) {
2f1431ea 755#if USE_AUTH
62e76326 756 if (!http->flags.accel) {
757 /* Proxy authorisation needed */
758 status = HTTP_PROXY_AUTHENTICATION_REQUIRED;
759 } else {
760 /* WWW authorisation needed */
761 status = HTTP_UNAUTHORIZED;
762 }
2f1431ea
AJ
763#else
764 // need auth, but not possible to do.
765 status = HTTP_FORBIDDEN;
766#endif
62e76326 767 if (page_id == ERR_NONE)
768 page_id = ERR_CACHE_ACCESS_DENIED;
769 } else {
770 status = HTTP_FORBIDDEN;
771
772 if (page_id == ERR_NONE)
773 page_id = ERR_ACCESS_DENIED;
774 }
775
de31d06f 776 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
0655fa4d 777 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
778 assert (repContext);
b7ac5457 779 Ip::Address tmpnoaddr;
26ac0430 780 tmpnoaddr.SetNoAddr();
0655fa4d 781 repContext->setReplyToError(page_id, status,
782 http->request->method, NULL,
73c36fd9 783 http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmpnoaddr,
cc192b50 784 http->request,
785 NULL,
2f1431ea 786#if USE_AUTH
a33a428a 787 http->getConn() != NULL && http->getConn()->auth_user_request != NULL ?
cc192b50 788 http->getConn()->auth_user_request : http->request->auth_user_request);
2f1431ea
AJ
789#else
790 NULL);
791#endif
62e76326 792 node = (clientStreamNode *)http->client_stream.tail->data;
793 clientStreamRead(node, http, node->readBuffer);
a546b04b 794 return;
edce4d98 795 }
de31d06f 796
309347ef 797 /* ACCESS_ALLOWED (or auth in grace period ACCESS_AUTH_EXPIRED_OK) continues here ... */
de31d06f 798 safe_free(http->uri);
799
800 http->uri = xstrdup(urlCanonical(http->request));
801
802 http->doCallouts();
803}
804
a83c6ed6 805#if USE_ADAPTATION
de31d06f 806static void
a22e6cd3 807adaptationAclCheckDoneWrapper(Adaptation::ServiceGroupPointer g, void *data)
de31d06f 808{
809 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
810
811 if (!calloutContext->httpStateIsValid())
812 return;
813
a22e6cd3 814 calloutContext->adaptationAclCheckDone(g);
de31d06f 815}
816
817void
a22e6cd3 818ClientRequestContext::adaptationAclCheckDone(Adaptation::ServiceGroupPointer g)
de31d06f 819{
a83c6ed6 820 debugs(93,3,HERE << this << " adaptationAclCheckDone called");
6ec67de9 821 assert(http);
822
e1381638 823#if ICAP_CLIENT
3ff65596 824 Adaptation::Icap::History::Pointer ih = http->request->icapHistory();
e1381638
AJ
825 if (ih != NULL) {
826 if (http->getConn() != NULL) {
73c36fd9 827 ih->rfc931 = http->getConn()->clientConnection->rfc931;
e1381638 828#if USE_SSL
73c36fd9
AJ
829 assert(http->getConn()->clientConnection != NULL);
830 ih->ssluser = sslGetUserEmail(fd_table[http->getConn()->clientConnection->fd].ssl);
e1381638 831#endif
3ff65596
AR
832 }
833 ih->log_uri = http->log_uri;
834 ih->req_sz = http->req_sz;
835 }
836#endif
837
a22e6cd3
AR
838 if (!g) {
839 debugs(85,3, HERE << "no adaptation needed");
5f8252d2 840 http->doCallouts();
841 return;
842 }
de31d06f 843
a22e6cd3 844 http->startAdaptation(g);
edce4d98 845}
846
de31d06f 847#endif
848
14cc8559 849static void
2efeb0b7 850clientRedirectAccessCheckDone(allow_t answer, void *data)
14cc8559 851{
852 ClientRequestContext *context = (ClientRequestContext *)data;
59a1efb2 853 ClientHttpRequest *http = context->http;
14cc8559 854 context->acl_checklist = NULL;
855
856 if (answer == ACCESS_ALLOWED)
de31d06f 857 redirectStart(http, clientRedirectDoneWrapper, context);
14cc8559 858 else
de31d06f 859 context->clientRedirectDone(NULL);
14cc8559 860}
861
de31d06f 862void
863ClientRequestContext::clientRedirectStart()
14cc8559 864{
bf8fe701 865 debugs(33, 5, "clientRedirectStart: '" << http->uri << "'");
14cc8559 866
14cc8559 867 if (Config.accessList.redirector) {
de31d06f 868 acl_checklist = clientAclChecklistCreate(Config.accessList.redirector, http);
869 acl_checklist->nonBlockingCheck(clientRedirectAccessCheckDone, this);
14cc8559 870 } else
de31d06f 871 redirectStart(http, clientRedirectDoneWrapper, this);
14cc8559 872}
873
edce4d98 874static int
59a1efb2 875clientHierarchical(ClientHttpRequest * http)
edce4d98 876{
877 const char *url = http->uri;
190154cf 878 HttpRequest *request = http->request;
60745f24 879 HttpRequestMethod method = request->method;
edce4d98 880 const wordlist *p = NULL;
881
69660be0 882 /*
883 * IMS needs a private key, so we can use the hierarchy for IMS only if our
884 * neighbors support private keys
885 */
62e76326 886
edce4d98 887 if (request->flags.ims && !neighbors_do_private_keys)
62e76326 888 return 0;
889
69660be0 890 /*
891 * This is incorrect: authenticating requests can be sent via a hierarchy
06b97e72 892 * (they can even be cached if the correct headers are set on the reply)
edce4d98 893 */
894 if (request->flags.auth)
62e76326 895 return 0;
896
edce4d98 897 if (method == METHOD_TRACE)
62e76326 898 return 1;
899
edce4d98 900 if (method != METHOD_GET)
62e76326 901 return 0;
902
edce4d98 903 /* scan hierarchy_stoplist */
904 for (p = Config.hierarchy_stoplist; p; p = p->next)
62e76326 905 if (strstr(url, p->key))
906 return 0;
907
edce4d98 908 if (request->flags.loopdetect)
62e76326 909 return 0;
910
0c3d3f65 911 if (request->protocol == AnyP::PROTO_HTTP)
62e76326 912 return httpCachable(method);
913
0c3d3f65 914 if (request->protocol == AnyP::PROTO_GOPHER)
62e76326 915 return gopherCachable(request);
916
39a19cb7 917 if (request->protocol == AnyP::PROTO_CACHE_OBJECT)
62e76326 918 return 0;
919
edce4d98 920 return 1;
921}
922
46a1f562
HN
923static void
924clientCheckPinning(ClientHttpRequest * http)
925{
926 HttpRequest *request = http->request;
927 HttpHeader *req_hdr = &request->header;
928 ConnStateData *http_conn = http->getConn();
929
930 /* Internal requests such as those from ESI includes may be without
931 * a client connection
932 */
933 if (!http_conn)
f54f527e 934 return;
46a1f562
HN
935
936 request->flags.connection_auth_disabled = http_conn->port->connection_auth_disabled;
937 if (!request->flags.connection_auth_disabled) {
73c36fd9 938 if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) {
46a1f562
HN
939 if (http_conn->pinning.auth) {
940 request->flags.connection_auth = 1;
941 request->flags.auth = 1;
942 } else {
943 request->flags.connection_proxy_auth = 1;
944 }
b1cf2350
AJ
945 // These should already be linked correctly.
946 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
947 }
948 }
949
950 /* check if connection auth is used, and flag as candidate for pinning
951 * in such case.
952 * Note: we may need to set flags.connection_auth even if the connection
953 * is already pinned if it was pinned earlier due to proxy auth
954 */
955 if (!request->flags.connection_auth) {
956 if (req_hdr->has(HDR_AUTHORIZATION) || req_hdr->has(HDR_PROXY_AUTHORIZATION)) {
957 HttpHeaderPos pos = HttpHeaderInitPos;
958 HttpHeaderEntry *e;
959 int may_pin = 0;
960 while ((e = req_hdr->getEntry(&pos))) {
961 if (e->id == HDR_AUTHORIZATION || e->id == HDR_PROXY_AUTHORIZATION) {
962 const char *value = e->value.rawBuf();
963 if (strncasecmp(value, "NTLM ", 5) == 0
964 ||
965 strncasecmp(value, "Negotiate ", 10) == 0
966 ||
967 strncasecmp(value, "Kerberos ", 9) == 0) {
968 if (e->id == HDR_AUTHORIZATION) {
969 request->flags.connection_auth = 1;
970 may_pin = 1;
971 } else {
972 request->flags.connection_proxy_auth = 1;
973 may_pin = 1;
974 }
975 }
976 }
977 }
978 if (may_pin && !request->pinnedConnection()) {
b1cf2350
AJ
979 // These should already be linked correctly. Just need the ServerConnection to pinn.
980 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
981 }
982 }
983 }
984}
985
edce4d98 986static void
59a1efb2 987clientInterpretRequestHeaders(ClientHttpRequest * http)
edce4d98 988{
190154cf 989 HttpRequest *request = http->request;
0ef77270 990 HttpHeader *req_hdr = &request->header;
edce4d98 991 int no_cache = 0;
edce4d98 992 const char *str;
62e76326 993
edce4d98 994 request->imslen = -1;
a9925b40 995 request->ims = req_hdr->getTime(HDR_IF_MODIFIED_SINCE);
62e76326 996
edce4d98 997 if (request->ims > 0)
62e76326 998 request->flags.ims = 1;
999
432bc83c
HN
1000 if (!request->flags.ignore_cc) {
1001 if (req_hdr->has(HDR_PRAGMA)) {
1002 String s = req_hdr->getList(HDR_PRAGMA);
62e76326 1003
432bc83c
HN
1004 if (strListIsMember(&s, "no-cache", ','))
1005 no_cache++;
30abd221 1006
432bc83c
HN
1007 s.clean();
1008 }
62e76326 1009
432bc83c
HN
1010 if (request->cache_control)
1011 if (EBIT_TEST(request->cache_control->mask, CC_NO_CACHE))
1012 no_cache++;
62e76326 1013
432bc83c
HN
1014 /*
1015 * Work around for supporting the Reload button in IE browsers when Squid
1016 * is used as an accelerator or transparent proxy, by turning accelerated
1017 * IMS request to no-cache requests. Now knows about IE 5.5 fix (is
1018 * actually only fixed in SP1, but we can't tell whether we are talking to
1019 * SP1 or not so all 5.5 versions are treated 'normally').
1020 */
1021 if (Config.onoff.ie_refresh) {
1022 if (http->flags.accel && request->flags.ims) {
1023 if ((str = req_hdr->getStr(HDR_USER_AGENT))) {
1024 if (strstr(str, "MSIE 5.01") != NULL)
1025 no_cache++;
1026 else if (strstr(str, "MSIE 5.0") != NULL)
1027 no_cache++;
1028 else if (strstr(str, "MSIE 4.") != NULL)
1029 no_cache++;
1030 else if (strstr(str, "MSIE 3.") != NULL)
1031 no_cache++;
1032 }
62e76326 1033 }
1034 }
edce4d98 1035 }
914b89a2 1036
1037 if (request->method == METHOD_OTHER) {
26ac0430 1038 no_cache++;
60745f24 1039 }
62e76326 1040
edce4d98 1041 if (no_cache) {
626096be 1042#if USE_HTTP_VIOLATIONS
62e76326 1043
1044 if (Config.onoff.reload_into_ims)
1045 request->flags.nocache_hack = 1;
1046 else if (refresh_nocache_hack)
1047 request->flags.nocache_hack = 1;
1048 else
edce4d98 1049#endif
62e76326 1050
1051 request->flags.nocache = 1;
edce4d98 1052 }
62e76326 1053
0ef77270 1054 /* ignore range header in non-GETs or non-HEADs */
1055 if (request->method == METHOD_GET || request->method == METHOD_HEAD) {
56713d9a
AR
1056 // XXX: initialize if we got here without HttpRequest::parseHeader()
1057 if (!request->range)
1058 request->range = req_hdr->getRange();
62e76326 1059
1060 if (request->range) {
1061 request->flags.range = 1;
1062 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
1063 /* XXX: This is suboptimal. We should give the stream the range set,
1064 * and thereby let the top of the stream set the offset when the
26ac0430 1065 * size becomes known. As it is, we will end up requesting from 0
62e76326 1066 * for evey -X range specification.
1067 * RBC - this may be somewhat wrong. We should probably set the range
1068 * iter up at this point.
1069 */
1070 node->readBuffer.offset = request->range->lowestOffset(0);
1071 http->range_iter.pos = request->range->begin();
1072 http->range_iter.valid = true;
1073 }
edce4d98 1074 }
62e76326 1075
0ef77270 1076 /* Only HEAD and GET requests permit a Range or Request-Range header.
1077 * If these headers appear on any other type of request, delete them now.
1078 */
1079 else {
1080 req_hdr->delById(HDR_RANGE);
1081 req_hdr->delById(HDR_REQUEST_RANGE);
56713d9a 1082 delete request->range;
0ef77270 1083 request->range = NULL;
1084 }
1085
a9925b40 1086 if (req_hdr->has(HDR_AUTHORIZATION))
62e76326 1087 request->flags.auth = 1;
1088
46a1f562 1089 clientCheckPinning(http);
d67acb4e 1090
edce4d98 1091 if (request->login[0] != '\0')
62e76326 1092 request->flags.auth = 1;
1093
a9925b40 1094 if (req_hdr->has(HDR_VIA)) {
30abd221 1095 String s = req_hdr->getList(HDR_VIA);
62e76326 1096 /*
3c4fcf0f 1097 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
62e76326 1098 * Note ThisCache2 has a space prepended to the hostname so we don't
1099 * accidentally match super-domains.
1100 */
1101
1102 if (strListIsSubstr(&s, ThisCache2, ',')) {
1103 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
1104 request, (ObjPackMethod) & httpRequestPack);
1105 request->flags.loopdetect = 1;
1106 }
1107
21f6708d 1108#if USE_FORW_VIA_DB
bb790702 1109 fvdbCountVia(s.termedBuf());
62e76326 1110
edce4d98 1111#endif
62e76326 1112
30abd221 1113 s.clean();
edce4d98 1114 }
62e76326 1115
21f6708d 1116#if USE_FORW_VIA_DB
62e76326 1117
a9925b40 1118 if (req_hdr->has(HDR_X_FORWARDED_FOR)) {
30abd221 1119 String s = req_hdr->getList(HDR_X_FORWARDED_FOR);
bb790702 1120 fvdbCountForw(s.termedBuf());
30abd221 1121 s.clean();
edce4d98 1122 }
62e76326 1123
edce4d98 1124#endif
62e76326 1125
610ee341 1126 request->flags.cachable = http->request->cacheable();
62e76326 1127
edce4d98 1128 if (clientHierarchical(http))
62e76326 1129 request->flags.hierarchical = 1;
1130
bf8fe701 1131 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
1132 (request->flags.nocache ? "SET" : "NOT SET"));
1133 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
1134 (request->flags.cachable ? "SET" : "NOT SET"));
1135 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
1136 (request->flags.hierarchical ? "SET" : "NOT SET"));
62e76326 1137
edce4d98 1138}
1139
1140void
de31d06f 1141clientRedirectDoneWrapper(void *data, char *result)
edce4d98 1142{
de31d06f 1143 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
db02222f 1144
de31d06f 1145 if (!calloutContext->httpStateIsValid())
62e76326 1146 return;
62e76326 1147
de31d06f 1148 calloutContext->clientRedirectDone(result);
1149}
1150
1151void
1152ClientRequestContext::clientRedirectDone(char *result)
1153{
190154cf 1154 HttpRequest *old_request = http->request;
bf8fe701 1155 debugs(85, 5, "clientRedirectDone: '" << http->uri << "' result=" << (result ? result : "NULL"));
de31d06f 1156 assert(redirect_state == REDIRECT_PENDING);
1157 redirect_state = REDIRECT_DONE;
62e76326 1158
edce4d98 1159 if (result) {
62e76326 1160 http_status status = (http_status) atoi(result);
1161
1162 if (status == HTTP_MOVED_PERMANENTLY
1163 || status == HTTP_MOVED_TEMPORARILY
1164 || status == HTTP_SEE_OTHER
1165 || status == HTTP_TEMPORARY_REDIRECT) {
1166 char *t = result;
1167
1168 if ((t = strchr(result, ':')) != NULL) {
1169 http->redirect.status = status;
1170 http->redirect.location = xstrdup(t + 1);
e5b677f0 1171 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
62e76326 1172 } else {
e5b677f0
AJ
1173 if (old_request->http_ver < HttpVersion(1,1))
1174 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid 302 redirect Location: " << result);
1175 else
1176 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid 303 redirect Location: " << result);
62e76326 1177 }
e5b677f0 1178 } else if (strcmp(result, http->uri)) {
9be14530
AJ
1179 // XXX: validate the URL properly *without* generating a whole new request object right here.
1180 // XXX: the clone() should be done only AFTER we know the new URL is valid.
1181 HttpRequest *new_request = old_request->clone();
1182 if (urlParse(old_request->method, result, new_request)) {
1183 debugs(61,2, HERE << "URL-rewriter diverts URL from " << urlCanonical(old_request) << " to " << urlCanonical(new_request));
1184
1185 // update the new request to flag the re-writing was done on it
1186 new_request->flags.redirected = 1;
1187
1188 // unlink bodypipe from the old request. Not needed there any longer.
1189 if (old_request->body_pipe != NULL) {
1190 old_request->body_pipe = NULL;
1191 debugs(61,2, HERE << "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
1192 " from request " << old_request << " to " << new_request);
1193 }
1194
1195 // update the current working ClientHttpRequest fields
1196 safe_free(http->uri);
1197 http->uri = xstrdup(urlCanonical(new_request));
1198 HTTPMSGUNLOCK(old_request);
1199 http->request = HTTPMSGLOCK(new_request);
1200 } else {
e5b677f0 1201 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " <<
c9fd01b4 1202 old_request->method << " " << result << " " << old_request->http_ver);
9be14530
AJ
1203 delete new_request;
1204 }
74b48915 1205 }
edce4d98 1206 }
62e76326 1207
edce4d98 1208 /* FIXME PIPELINE: This is innacurate during pipelining */
62e76326 1209
73c36fd9
AJ
1210 if (http->getConn() != NULL && Comm::IsConnOpen(http->getConn()->clientConnection))
1211 fd_note(http->getConn()->clientConnection->fd, http->uri);
62e76326 1212
c8be6d7b 1213 assert(http->uri);
62e76326 1214
de31d06f 1215 http->doCallouts();
edce4d98 1216}
1217
b50e327b
AJ
1218/** Test cache allow/deny configuration
1219 * Sets flags.cachable=1 if caching is not denied.
1220 */
edce4d98 1221void
8e2745f4 1222ClientRequestContext::checkNoCache()
edce4d98 1223{
b50e327b
AJ
1224 if (Config.accessList.noCache) {
1225 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1226 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1227 } else {
1228 /* unless otherwise specified, we try to cache. */
2efeb0b7 1229 checkNoCacheDone(ACCESS_ALLOWED);
b50e327b 1230 }
edce4d98 1231}
1232
de31d06f 1233static void
2efeb0b7 1234checkNoCacheDoneWrapper(allow_t answer, void *data)
edce4d98 1235{
de31d06f 1236 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
e4a67a80 1237
de31d06f 1238 if (!calloutContext->httpStateIsValid())
1239 return;
1240
1241 calloutContext->checkNoCacheDone(answer);
8e2745f4 1242}
4fb35c3c 1243
8e2745f4 1244void
2efeb0b7 1245ClientRequestContext::checkNoCacheDone(const allow_t &answer)
62e76326 1246{
8e2745f4 1247 acl_checklist = NULL;
2efeb0b7 1248 http->request->flags.cachable = (answer == ACCESS_ALLOWED);
de31d06f 1249 http->doCallouts();
edce4d98 1250}
1251
e0c0d54c
CT
1252#if USE_SSL
1253bool
1254ClientRequestContext::sslBumpAccessCheck()
1255{
1256 if (http->request->method == METHOD_CONNECT &&
f8901ea9 1257 Config.accessList.ssl_bump && http->getConn()->port->sslBump) {
e0c0d54c
CT
1258 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1259
1260 ACLFilledChecklist *acl_checklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http);
1261 acl_checklist->nonBlockingCheck(sslBumpAccessCheckDoneWrapper, this);
1262 return true;
f8901ea9 1263 } else {
e0c0d54c
CT
1264 http->sslBumpNeeded(false);
1265 return false;
1266 }
1267}
1268
f8901ea9 1269/**
e0c0d54c
CT
1270 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1271 * as ACLFilledChecklist callback
1272 */
1273static void
2efeb0b7 1274sslBumpAccessCheckDoneWrapper(allow_t answer, void *data)
e0c0d54c
CT
1275{
1276 ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data);
1277
1278 if (!calloutContext->httpStateIsValid())
1279 return;
1280 calloutContext->sslBumpAccessCheckDone(answer == ACCESS_ALLOWED);
1281}
1282
1283void
1284ClientRequestContext::sslBumpAccessCheckDone(bool doSslBump)
1285{
1286 http->sslBumpNeeded(doSslBump);
1287 http->doCallouts();
1288}
1289#endif
1290
69660be0 1291/*
1292 * Identify requests that do not go through the store and client side stream
1293 * and forward them to the appropriate location. All other requests, request
1294 * them.
edce4d98 1295 */
1296void
8e2745f4 1297ClientHttpRequest::processRequest()
edce4d98 1298{
60745f24 1299 debugs(85, 4, "clientProcessRequest: " << RequestMethodStr(request->method) << " '" << uri << "'");
62e76326 1300
31281814 1301 if (request->method == METHOD_CONNECT && !redirect.status) {
3712be3f 1302#if USE_SSL
31281814
AJ
1303 if (sslBumpNeeded()) {
1304 sslBumpStart();
1305 return;
1306 }
3712be3f 1307#endif
62e76326 1308 logType = LOG_TCP_MISS;
f84dd7eb 1309 getConn()->stopReading(); // tunnels read for themselves
11007d4b 1310 tunnelStart(this, &out.size, &al.http.code);
62e76326 1311 return;
edce4d98 1312 }
62e76326 1313
8e2745f4 1314 httpStart();
1315}
1316
1317void
1318ClientHttpRequest::httpStart()
1319{
559da936 1320 PROF_start(httpStart);
8e2745f4 1321 logType = LOG_TAG_NONE;
38e16f92 1322 debugs(85, 4, "ClientHttpRequest::httpStart: " << Format::log_tags[logType] << " for '" << uri << "'");
bf8fe701 1323
edce4d98 1324 /* no one should have touched this */
8e2745f4 1325 assert(out.offset == 0);
edce4d98 1326 /* Use the Stream Luke */
8e2745f4 1327 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1328 clientStreamRead(node, this, node->readBuffer);
559da936 1329 PROF_stop(httpStart);
edce4d98 1330}
0655fa4d 1331
3712be3f 1332#if USE_SSL
1333
3712be3f 1334bool
26ac0430
AJ
1335ClientHttpRequest::sslBumpNeeded() const
1336{
e0c0d54c
CT
1337 assert(sslBumpNeed != needUnknown);
1338 return (sslBumpNeed == needConfirmed);
1339}
3712be3f 1340
e0c0d54c
CT
1341void
1342ClientHttpRequest::sslBumpNeeded(bool isNeeded)
1343{
1344 debugs(83, 3, HERE << "sslBump required: "<< (isNeeded ? "Yes" : "No"));
1345 sslBumpNeed = (isNeeded ? needConfirmed : needNot);
3712be3f 1346}
1347
1348// called when comm_write has completed
1349static void
e0d28505 1350SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, comm_err_t errflag, int, void *data)
3712be3f 1351{
1352 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1353 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1354
1355 assert(r && cbdataReferenceValid(r));
1356 r->sslBumpEstablish(errflag);
1357}
1358
1359void
1360ClientHttpRequest::sslBumpEstablish(comm_err_t errflag)
1361{
1362 // Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up
1363 if (errflag == COMM_ERR_CLOSING)
1364 return;
1365
1366 if (errflag) {
1fa35be8 1367 debugs(85, 3, HERE << "CONNECT response failure in SslBump: " << errflag);
bbc83914 1368 getConn()->clientConnection->close();
3712be3f 1369 return;
1370 }
1371
95d2589c 1372 getConn()->switchToHttps(request->GetHost());
3712be3f 1373}
1374
1375void
1376ClientHttpRequest::sslBumpStart()
1377{
73c36fd9 1378 debugs(85, 5, HERE << "Confirming CONNECT tunnel on FD " << getConn()->clientConnection);
3712be3f 1379 // send an HTTP 200 response to kick client SSL negotiation
73c36fd9 1380 debugs(33, 7, HERE << "Confirming CONNECT tunnel on FD " << getConn()->clientConnection);
3712be3f 1381
1382 // TODO: Unify with tunnel.cc and add a Server(?) header
b0388924 1383 static const char *const conn_established = "HTTP/1.1 200 Connection established\r\n\r\n";
ec41b64c
AJ
1384 AsyncCall::Pointer call = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1385 CommIoCbPtrFun(&SslBumpEstablish, this));
73c36fd9 1386 Comm::Write(getConn()->clientConnection, conn_established, strlen(conn_established), call, NULL);
3712be3f 1387}
1388
1389#endif
1390
0655fa4d 1391bool
1392ClientHttpRequest::gotEnough() const
1393{
86a2f789 1394 /** TODO: should be querying the stream. */
7173d5b0 1395 int64_t contentLength =
06a5ae20 1396 memObject()->getReply()->bodySize(request->method);
0655fa4d 1397 assert(contentLength >= 0);
1398
1399 if (out.offset < contentLength)
1400 return false;
1401
1402 return true;
1403}
1404
86a2f789 1405void
1406ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1407{
1408 entry_ = newEntry;
1409}
1410
0976f8db 1411void
1412ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1413{
1414 if (loggingEntry_)
97b5e68f 1415 loggingEntry_->unlock();
0976f8db 1416
1417 loggingEntry_ = newEntry;
1418
1419 if (loggingEntry_)
3d0ac046 1420 loggingEntry_->lock();
0976f8db 1421}
86a2f789 1422
de31d06f 1423/*
1424 * doCallouts() - This function controls the order of "callout"
1425 * executions, including non-blocking access control checks, the
1426 * redirector, and ICAP. Previously, these callouts were chained
1427 * together such that "clientAccessCheckDone()" would call
1428 * "clientRedirectStart()" and so on.
1429 *
1430 * The ClientRequestContext (aka calloutContext) class holds certain
1431 * state data for the callout/callback operations. Previously
1432 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1433 * for a short time. ClientRequestContext would then delete itself
1434 * and pass control back to ClientHttpRequest when all callouts
1435 * were finished.
1436 *
1437 * This caused some problems for ICAP because we want to make the
1438 * ICAP callout after checking ACLs, but before checking the no_cache
1439 * list. We can't stuff the ICAP state into the ClientRequestContext
1440 * class because we still need the ICAP state after ClientRequestContext
1441 * goes away.
1442 *
1443 * Note that ClientRequestContext is created before the first call
1444 * to doCallouts().
1445 *
1446 * If one of the callouts notices that ClientHttpRequest is no
1447 * longer valid, it should call cbdataReferenceDone() so that
1448 * ClientHttpRequest's reference count goes to zero and it will get
1449 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1450 *
1451 * Note that we set the _done flags here before actually starting
1452 * the callout. This is strictly for convenience.
1453 */
1454
425de4c8
AJ
1455extern tos_t aclMapTOS (acl_tos * head, ACLChecklist * ch);
1456extern nfmark_t aclMapNfmark (acl_nfmark * head, ACLChecklist * ch);
057f5854 1457
de31d06f 1458void
1459ClientHttpRequest::doCallouts()
1460{
1461 assert(calloutContext);
1462
6fca33e0
CT
1463 /*Save the original request for logging purposes*/
1464 if (!calloutContext->http->al.request)
105d1937 1465 calloutContext->http->al.request = HTTPMSGLOCK(request);
6fca33e0 1466
fe97983f
AJ
1467 // CVE-2009-0801: verify the Host: header is consistent with other known details.
1468 if (!calloutContext->host_header_verify_done) {
1469 debugs(83, 3, HERE << "Doing calloutContext->hostHeaderVerify()");
1470 calloutContext->host_header_verify_done = true;
1471 calloutContext->hostHeaderVerify();
1472 return;
1473 }
1474
de31d06f 1475 if (!calloutContext->http_access_done) {
3712be3f 1476 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()");
57abaac0 1477 calloutContext->http_access_done = true;
de31d06f 1478 calloutContext->clientAccessCheck();
1479 return;
1480 }
1481
a83c6ed6 1482#if USE_ADAPTATION
abd4b611 1483 if (!calloutContext->adaptation_acl_check_done) {
a83c6ed6 1484 calloutContext->adaptation_acl_check_done = true;
abd4b611 1485 if (Adaptation::AccessCheck::Start(
26ac0430
AJ
1486 Adaptation::methodReqmod, Adaptation::pointPreCache,
1487 request, NULL, adaptationAclCheckDoneWrapper, calloutContext))
abd4b611 1488 return; // will call callback
de31d06f 1489 }
de31d06f 1490#endif
1491
1492 if (!calloutContext->redirect_done) {
57abaac0 1493 calloutContext->redirect_done = true;
de31d06f 1494 assert(calloutContext->redirect_state == REDIRECT_NONE);
1495
1496 if (Config.Program.redirect) {
3712be3f 1497 debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()");
de31d06f 1498 calloutContext->redirect_state = REDIRECT_PENDING;
1499 calloutContext->clientRedirectStart();
1500 return;
1501 }
1502 }
1503
533493da
AJ
1504 if (!calloutContext->adapted_http_access_done) {
1505 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()");
1506 calloutContext->adapted_http_access_done = true;
1507 calloutContext->clientAccessCheck2();
1508 return;
1509 }
1510
57abaac0 1511 if (!calloutContext->interpreted_req_hdrs) {
3712be3f 1512 debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()");
57abaac0 1513 calloutContext->interpreted_req_hdrs = 1;
1514 clientInterpretRequestHeaders(this);
1515 }
1516
de31d06f 1517 if (!calloutContext->no_cache_done) {
57abaac0 1518 calloutContext->no_cache_done = true;
de31d06f 1519
1520 if (Config.accessList.noCache && request->flags.cachable) {
3712be3f 1521 debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()");
de31d06f 1522 calloutContext->checkNoCache();
1523 return;
1524 }
1525 }
1526
425de4c8
AJ
1527 if (!calloutContext->tosToClientDone) {
1528 calloutContext->tosToClientDone = true;
73c36fd9 1529 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
c0941a6a 1530 ACLFilledChecklist ch(NULL, request, NULL);
057f5854 1531 ch.src_addr = request->client_addr;
1532 ch.my_addr = request->my_addr;
425de4c8 1533 tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch);
3712be3f 1534 if (tos)
73c36fd9 1535 Ip::Qos::setSockTos(getConn()->clientConnection, tos);
425de4c8
AJ
1536 }
1537 }
1538
1539 if (!calloutContext->nfmarkToClientDone) {
1540 calloutContext->nfmarkToClientDone = true;
73c36fd9 1541 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
425de4c8
AJ
1542 ACLFilledChecklist ch(NULL, request, NULL);
1543 ch.src_addr = request->client_addr;
1544 ch.my_addr = request->my_addr;
1545 nfmark_t mark = aclMapNfmark(Ip::Qos::TheConfig.nfmarkToClient, &ch);
1546 if (mark)
73c36fd9 1547 Ip::Qos::setSockNfmark(getConn()->clientConnection, mark);
3712be3f 1548 }
057f5854 1549 }
1550
d2565320 1551#if USE_SSL
e0c0d54c
CT
1552 if (!calloutContext->sslBumpCheckDone) {
1553 calloutContext->sslBumpCheckDone = true;
1554 if (calloutContext->sslBumpAccessCheck())
1555 return;
1556 /* else no ssl bump required*/
1557 }
d2565320 1558#endif
e0c0d54c 1559
de31d06f 1560 cbdataReferenceDone(calloutContext->http);
1561 delete calloutContext;
1562 calloutContext = NULL;
de31d06f 1563#if HEADERS_LOG
1564
1565 headersLog(0, 1, request->method, request);
1566#endif
1567
58d7150d 1568 debugs(83, 3, HERE << "calling processRequest()");
de31d06f 1569 processRequest();
3ff65596
AR
1570
1571#if ICAP_CLIENT
1572 Adaptation::Icap::History::Pointer ih = request->icapHistory();
1573 if (ih != NULL)
1574 ih->logType = logType;
1575#endif
de31d06f 1576}
1577
32d002cb 1578#if !_USE_INLINE_
86a2f789 1579#include "client_side_request.cci"
1580#endif
de31d06f 1581
a83c6ed6 1582#if USE_ADAPTATION
a22e6cd3
AR
1583/// Initiate an asynchronous adaptation transaction which will call us back.
1584void
1585ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
3b299123 1586{
a22e6cd3 1587 debugs(85, 3, HERE << "adaptation needed for " << this);
a83c6ed6
AR
1588 assert(!virginHeadSource);
1589 assert(!adaptedBodySource);
a22e6cd3 1590 virginHeadSource = initiateAdaptation(
4cb2536f 1591 new Adaptation::Iterator(request, NULL, g));
a83c6ed6 1592
e1381638 1593 // we could try to guess whether we can bypass this adaptation
a22e6cd3 1594 // initiation failure, but it should not really happen
4299f876 1595 Must(initiated(virginHeadSource));
de31d06f 1596}
1597
1598void
3af10ac0 1599ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer &answer)
de31d06f 1600{
de31d06f 1601 assert(cbdataReferenceValid(this)); // indicates bug
3af10ac0
AR
1602 clearAdaptation(virginHeadSource);
1603 assert(!adaptedBodySource);
1604
1605 switch (answer.kind) {
1606 case Adaptation::Answer::akForward:
1607 handleAdaptedHeader(answer.message);
1608 break;
1609
1610 case Adaptation::Answer::akBlock:
1611 handleAdaptationBlock(answer);
1612 break;
1613
1614 case Adaptation::Answer::akError:
1615 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_ABORT, !answer.final);
1616 break;
1617 }
1618}
1619
1620void
ec4d1a1d 1621ClientHttpRequest::handleAdaptedHeader(HttpMsg *msg)
3af10ac0 1622{
5f8252d2 1623 assert(msg);
1624
b044675d 1625 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
200ac359 1626 /*
5f8252d2 1627 * Replace the old request with the new request.
200ac359 1628 */
6dd9f4bd 1629 HTTPMSGUNLOCK(request);
1630 request = HTTPMSGLOCK(new_req);
200ac359 1631 /*
1632 * Store the new URI for logging
1633 */
1634 xfree(uri);
1635 uri = xstrdup(urlCanonical(request));
1636 setLogUri(this, urlCanonicalClean(request));
914b89a2 1637 assert(request->method.id());
b044675d 1638 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
1639 debugs(85,3,HERE << "REQMOD reply is HTTP reply");
1640
5f8252d2 1641 // subscribe to receive reply body
1642 if (new_rep->body_pipe != NULL) {
a83c6ed6 1643 adaptedBodySource = new_rep->body_pipe;
d222a56c
HN
1644 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
1645 assert(consumer_ok);
5f8252d2 1646 }
1647
b044675d 1648 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1649 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1650 repContext->createStoreEntry(request->method, request->flags);
1651
1652 EBIT_CLR(storeEntry()->flags, ENTRY_FWD_HDR_WAIT);
1653 request_satisfaction_mode = true;
1654 request_satisfaction_offset = 0;
1655 storeEntry()->replaceHttpReply(new_rep);
97ae5196 1656 storeEntry()->timestampsSet();
cb4c4288 1657
a83c6ed6 1658 if (!adaptedBodySource) // no body
cb4c4288 1659 storeEntry()->complete();
b044675d 1660 clientGetMoreData(node, this);
200ac359 1661 }
de31d06f 1662
5f8252d2 1663 // we are done with getting headers (but may be receiving body)
a83c6ed6 1664 clearAdaptation(virginHeadSource);
5f8252d2 1665
b044675d 1666 if (!request_satisfaction_mode)
1667 doCallouts();
de31d06f 1668}
1669
1670void
3af10ac0 1671ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer &answer)
de31d06f 1672{
3af10ac0
AR
1673 request->detailError(ERR_ACCESS_DENIED, ERR_DETAIL_REQMOD_BLOCK);
1674 AclMatchedName = answer.ruleId.termedBuf();
1675 assert(calloutContext);
1676 calloutContext->clientAccessCheckDone(ACCESS_DENIED);
1677 AclMatchedName = NULL;
de31d06f 1678}
1679
1680void
1cf238db 1681ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
de31d06f 1682{
5f8252d2 1683 assert(request_satisfaction_mode);
a83c6ed6 1684 assert(adaptedBodySource != NULL);
5f8252d2 1685
4ce0e99b 1686 if (const size_t contentSize = adaptedBodySource->buf().contentSize()) {
a83c6ed6 1687 BodyPipeCheckout bpc(*adaptedBodySource);
4ce0e99b 1688 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset);
5f8252d2 1689 storeEntry()->write(ioBuf);
1690 // assume can write everything
1691 request_satisfaction_offset += contentSize;
4ce0e99b 1692 bpc.buf.consume(contentSize);
5f8252d2 1693 bpc.checkIn();
1694 }
1695
a83c6ed6 1696 if (adaptedBodySource->exhausted())
5f8252d2 1697 endRequestSatisfaction();
1698 // else wait for more body data
de31d06f 1699}
1700
1701void
1cf238db 1702ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
de31d06f 1703{
a83c6ed6
AR
1704 assert(!virginHeadSource);
1705 if (adaptedBodySource != NULL) { // did not end request satisfaction yet
26ac0430 1706 // We do not expect more because noteMoreBodyDataAvailable always
5f8252d2 1707 // consumes everything. We do not even have a mechanism to consume
1708 // leftovers after noteMoreBodyDataAvailable notifications seize.
a83c6ed6 1709 assert(adaptedBodySource->exhausted());
5f8252d2 1710 endRequestSatisfaction();
1711 }
1712}
3b299123 1713
5f8252d2 1714void
26ac0430
AJ
1715ClientHttpRequest::endRequestSatisfaction()
1716{
5f8252d2 1717 debugs(85,4, HERE << this << " ends request satisfaction");
1718 assert(request_satisfaction_mode);
a83c6ed6 1719 stopConsumingFrom(adaptedBodySource);
3b299123 1720
5f8252d2 1721 // TODO: anything else needed to end store entry formation correctly?
1722 storeEntry()->complete();
1723}
de31d06f 1724
5f8252d2 1725void
1cf238db 1726ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
5f8252d2 1727{
a83c6ed6
AR
1728 assert(!virginHeadSource);
1729 stopConsumingFrom(adaptedBodySource);
eae3a9a6
AR
1730
1731 debugs(85,3, HERE << "REQMOD body production failed");
1732 if (request_satisfaction_mode) { // too late to recover or serve an error
1733 request->detailError(ERR_ICAP_FAILURE, ERR_DETAIL_CLT_REQMOD_RESP_BODY);
73c36fd9 1734 const Comm::ConnectionPointer c = getConn()->clientConnection;
e7cea0ed
AJ
1735 Must(Comm::IsConnOpen(c));
1736 c->close(); // drastic, but we may be writing a response already
eae3a9a6
AR
1737 } else {
1738 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_REQ_BODY);
1739 }
5f8252d2 1740}
3b299123 1741
5f8252d2 1742void
64b66b76 1743ClientHttpRequest::handleAdaptationFailure(int errDetail, bool bypassable)
5f8252d2 1744{
a83c6ed6 1745 debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")");
3b299123 1746
5f8252d2 1747 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
1748 const bool usedPipe = request->body_pipe != NULL &&
26ac0430 1749 request->body_pipe->consumedSize() > 0;
3b299123 1750
9d4d7c5e 1751 if (bypassable && !usedStore && !usedPipe) {
1752 debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext);
5f8252d2 1753 if (calloutContext)
1754 doCallouts();
1755 return;
1756 }
3b299123 1757
5f8252d2 1758 debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error");
3b299123 1759
5f8252d2 1760 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1761 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1762 assert(repContext);
de31d06f 1763
26ac0430 1764 // The original author of the code also wanted to pass an errno to
5f8252d2 1765 // setReplyToError, but it seems unlikely that the errno reflects the
1766 // true cause of the error at this point, so I did not pass it.
b7ac5457 1767 Ip::Address noAddr;
b70ba605 1768 noAddr.SetNoAddr();
1cf238db 1769 ConnStateData * c = getConn();
5f8252d2 1770 repContext->setReplyToError(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR,
26ac0430 1771 request->method, NULL,
73c36fd9 1772 (c != NULL ? c->clientConnection->remote : noAddr), request, NULL,
79fc6915 1773#if USE_AUTH
a33a428a 1774 (c != NULL && c->auth_user_request != NULL ?
26ac0430 1775 c->auth_user_request : request->auth_user_request));
79fc6915
AJ
1776#else
1777 NULL);
1778#endif
de31d06f 1779
64b66b76
CT
1780 request->detailError(ERR_ICAP_FAILURE, errDetail);
1781
5f8252d2 1782 node = (clientStreamNode *)client_stream.tail->data;
1783 clientStreamRead(node, this, node->readBuffer);
de31d06f 1784}
1785
1786#endif