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