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