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