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