]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_request.cc
Regression fix: upgrade existing icons
[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 }
801 request->setPinnedConnection(http_conn);
802 }
803 }
804
805 /* check if connection auth is used, and flag as candidate for pinning
806 * in such case.
807 * Note: we may need to set flags.connection_auth even if the connection
808 * is already pinned if it was pinned earlier due to proxy auth
809 */
810 if (!request->flags.connection_auth) {
811 if (req_hdr->has(HDR_AUTHORIZATION) || req_hdr->has(HDR_PROXY_AUTHORIZATION)) {
812 HttpHeaderPos pos = HttpHeaderInitPos;
813 HttpHeaderEntry *e;
814 int may_pin = 0;
815 while ((e = req_hdr->getEntry(&pos))) {
816 if (e->id == HDR_AUTHORIZATION || e->id == HDR_PROXY_AUTHORIZATION) {
817 const char *value = e->value.rawBuf();
818 if (strncasecmp(value, "NTLM ", 5) == 0
819 ||
820 strncasecmp(value, "Negotiate ", 10) == 0
821 ||
822 strncasecmp(value, "Kerberos ", 9) == 0) {
823 if (e->id == HDR_AUTHORIZATION) {
824 request->flags.connection_auth = 1;
825 may_pin = 1;
826 } else {
827 request->flags.connection_proxy_auth = 1;
828 may_pin = 1;
829 }
830 }
831 }
832 }
833 if (may_pin && !request->pinnedConnection()) {
834 request->setPinnedConnection(http->getConn());
835 }
836 }
837 }
838}
839
edce4d98 840static void
59a1efb2 841clientInterpretRequestHeaders(ClientHttpRequest * http)
edce4d98 842{
190154cf 843 HttpRequest *request = http->request;
0ef77270 844 HttpHeader *req_hdr = &request->header;
edce4d98 845 int no_cache = 0;
edce4d98 846 const char *str;
62e76326 847
edce4d98 848 request->imslen = -1;
a9925b40 849 request->ims = req_hdr->getTime(HDR_IF_MODIFIED_SINCE);
62e76326 850
edce4d98 851 if (request->ims > 0)
62e76326 852 request->flags.ims = 1;
853
432bc83c
HN
854 if (!request->flags.ignore_cc) {
855 if (req_hdr->has(HDR_PRAGMA)) {
856 String s = req_hdr->getList(HDR_PRAGMA);
62e76326 857
432bc83c
HN
858 if (strListIsMember(&s, "no-cache", ','))
859 no_cache++;
30abd221 860
432bc83c
HN
861 s.clean();
862 }
62e76326 863
432bc83c
HN
864 if (request->cache_control)
865 if (EBIT_TEST(request->cache_control->mask, CC_NO_CACHE))
866 no_cache++;
62e76326 867
432bc83c
HN
868 /*
869 * Work around for supporting the Reload button in IE browsers when Squid
870 * is used as an accelerator or transparent proxy, by turning accelerated
871 * IMS request to no-cache requests. Now knows about IE 5.5 fix (is
872 * actually only fixed in SP1, but we can't tell whether we are talking to
873 * SP1 or not so all 5.5 versions are treated 'normally').
874 */
875 if (Config.onoff.ie_refresh) {
876 if (http->flags.accel && request->flags.ims) {
877 if ((str = req_hdr->getStr(HDR_USER_AGENT))) {
878 if (strstr(str, "MSIE 5.01") != NULL)
879 no_cache++;
880 else if (strstr(str, "MSIE 5.0") != NULL)
881 no_cache++;
882 else if (strstr(str, "MSIE 4.") != NULL)
883 no_cache++;
884 else if (strstr(str, "MSIE 3.") != NULL)
885 no_cache++;
886 }
62e76326 887 }
888 }
edce4d98 889 }
914b89a2 890
891 if (request->method == METHOD_OTHER) {
26ac0430 892 no_cache++;
60745f24 893 }
62e76326 894
edce4d98 895 if (no_cache) {
626096be 896#if USE_HTTP_VIOLATIONS
62e76326 897
898 if (Config.onoff.reload_into_ims)
899 request->flags.nocache_hack = 1;
900 else if (refresh_nocache_hack)
901 request->flags.nocache_hack = 1;
902 else
edce4d98 903#endif
62e76326 904
905 request->flags.nocache = 1;
edce4d98 906 }
62e76326 907
0ef77270 908 /* ignore range header in non-GETs or non-HEADs */
909 if (request->method == METHOD_GET || request->method == METHOD_HEAD) {
56713d9a
AR
910 // XXX: initialize if we got here without HttpRequest::parseHeader()
911 if (!request->range)
912 request->range = req_hdr->getRange();
62e76326 913
914 if (request->range) {
915 request->flags.range = 1;
916 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
917 /* XXX: This is suboptimal. We should give the stream the range set,
918 * and thereby let the top of the stream set the offset when the
26ac0430 919 * size becomes known. As it is, we will end up requesting from 0
62e76326 920 * for evey -X range specification.
921 * RBC - this may be somewhat wrong. We should probably set the range
922 * iter up at this point.
923 */
924 node->readBuffer.offset = request->range->lowestOffset(0);
925 http->range_iter.pos = request->range->begin();
926 http->range_iter.valid = true;
927 }
edce4d98 928 }
62e76326 929
0ef77270 930 /* Only HEAD and GET requests permit a Range or Request-Range header.
931 * If these headers appear on any other type of request, delete them now.
932 */
933 else {
934 req_hdr->delById(HDR_RANGE);
935 req_hdr->delById(HDR_REQUEST_RANGE);
56713d9a 936 delete request->range;
0ef77270 937 request->range = NULL;
938 }
939
a9925b40 940 if (req_hdr->has(HDR_AUTHORIZATION))
62e76326 941 request->flags.auth = 1;
942
46a1f562 943 clientCheckPinning(http);
d67acb4e 944
edce4d98 945 if (request->login[0] != '\0')
62e76326 946 request->flags.auth = 1;
947
a9925b40 948 if (req_hdr->has(HDR_VIA)) {
30abd221 949 String s = req_hdr->getList(HDR_VIA);
62e76326 950 /*
3c4fcf0f 951 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
62e76326 952 * Note ThisCache2 has a space prepended to the hostname so we don't
953 * accidentally match super-domains.
954 */
955
956 if (strListIsSubstr(&s, ThisCache2, ',')) {
957 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
958 request, (ObjPackMethod) & httpRequestPack);
959 request->flags.loopdetect = 1;
960 }
961
21f6708d 962#if USE_FORW_VIA_DB
bb790702 963 fvdbCountVia(s.termedBuf());
62e76326 964
edce4d98 965#endif
62e76326 966
30abd221 967 s.clean();
edce4d98 968 }
62e76326 969
21f6708d 970#if USE_FORW_VIA_DB
62e76326 971
a9925b40 972 if (req_hdr->has(HDR_X_FORWARDED_FOR)) {
30abd221 973 String s = req_hdr->getList(HDR_X_FORWARDED_FOR);
bb790702 974 fvdbCountForw(s.termedBuf());
30abd221 975 s.clean();
edce4d98 976 }
62e76326 977
edce4d98 978#endif
62e76326 979
610ee341 980 request->flags.cachable = http->request->cacheable();
62e76326 981
edce4d98 982 if (clientHierarchical(http))
62e76326 983 request->flags.hierarchical = 1;
984
bf8fe701 985 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
986 (request->flags.nocache ? "SET" : "NOT SET"));
987 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
988 (request->flags.cachable ? "SET" : "NOT SET"));
989 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
990 (request->flags.hierarchical ? "SET" : "NOT SET"));
62e76326 991
edce4d98 992}
993
994void
de31d06f 995clientRedirectDoneWrapper(void *data, char *result)
edce4d98 996{
de31d06f 997 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
db02222f 998
de31d06f 999 if (!calloutContext->httpStateIsValid())
62e76326 1000 return;
62e76326 1001
de31d06f 1002 calloutContext->clientRedirectDone(result);
1003}
1004
1005void
1006ClientRequestContext::clientRedirectDone(char *result)
1007{
190154cf 1008 HttpRequest *new_request = NULL;
1009 HttpRequest *old_request = http->request;
bf8fe701 1010 debugs(85, 5, "clientRedirectDone: '" << http->uri << "' result=" << (result ? result : "NULL"));
de31d06f 1011 assert(redirect_state == REDIRECT_PENDING);
1012 redirect_state = REDIRECT_DONE;
62e76326 1013
edce4d98 1014 if (result) {
62e76326 1015 http_status status = (http_status) atoi(result);
1016
1017 if (status == HTTP_MOVED_PERMANENTLY
1018 || status == HTTP_MOVED_TEMPORARILY
1019 || status == HTTP_SEE_OTHER
1020 || status == HTTP_TEMPORARY_REDIRECT) {
1021 char *t = result;
1022
1023 if ((t = strchr(result, ':')) != NULL) {
1024 http->redirect.status = status;
1025 http->redirect.location = xstrdup(t + 1);
e5b677f0 1026 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
62e76326 1027 } else {
e5b677f0
AJ
1028 if (old_request->http_ver < HttpVersion(1,1))
1029 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid 302 redirect Location: " << result);
1030 else
1031 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid 303 redirect Location: " << result);
62e76326 1032 }
e5b677f0
AJ
1033 } else if (strcmp(result, http->uri)) {
1034 if (!(new_request = HttpRequest::CreateFromUrlAndMethod(result, old_request->method)))
1035 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " <<
1036 old_request->method << " " << result << " HTTP/1.1");
74b48915 1037 }
edce4d98 1038 }
62e76326 1039
edce4d98 1040 if (new_request) {
62e76326 1041 safe_free(http->uri);
1042 http->uri = xstrdup(urlCanonical(new_request));
1043 new_request->http_ver = old_request->http_ver;
a9925b40 1044 new_request->header.append(&old_request->header);
62e76326 1045 new_request->client_addr = old_request->client_addr;
3d674977
AJ
1046#if FOLLOW_X_FORWARDED_FOR
1047 new_request->indirect_client_addr = old_request->indirect_client_addr;
1048#endif /* FOLLOW_X_FORWARDED_FOR */
62e76326 1049 new_request->my_addr = old_request->my_addr;
62e76326 1050 new_request->flags = old_request->flags;
3c1f01bc 1051 new_request->flags.redirected = 1;
2f1431ea 1052#if USE_AUTH
a33a428a 1053 new_request->auth_user_request = old_request->auth_user_request;
2f1431ea 1054#endif
5f8252d2 1055 if (old_request->body_pipe != NULL) {
1056 new_request->body_pipe = old_request->body_pipe;
1057 old_request->body_pipe = NULL;
4194f7b6
AJ
1058 debugs(61,2, HERE << "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
1059 " from request " << old_request << " to " << new_request);
62e76326 1060 }
1061
1062 new_request->content_length = old_request->content_length;
abb929f0 1063 new_request->extacl_user = old_request->extacl_user;
1064 new_request->extacl_passwd = old_request->extacl_passwd;
62e76326 1065 new_request->flags.proxy_keepalive = old_request->flags.proxy_keepalive;
6dd9f4bd 1066 HTTPMSGUNLOCK(old_request);
1067 http->request = HTTPMSGLOCK(new_request);
edce4d98 1068 }
62e76326 1069
edce4d98 1070 /* FIXME PIPELINE: This is innacurate during pipelining */
62e76326 1071
5f8252d2 1072 if (http->getConn() != NULL)
98242069 1073 fd_note(http->getConn()->fd, http->uri);
62e76326 1074
c8be6d7b 1075 assert(http->uri);
62e76326 1076
de31d06f 1077 http->doCallouts();
edce4d98 1078}
1079
b50e327b
AJ
1080/** Test cache allow/deny configuration
1081 * Sets flags.cachable=1 if caching is not denied.
1082 */
edce4d98 1083void
8e2745f4 1084ClientRequestContext::checkNoCache()
edce4d98 1085{
b50e327b
AJ
1086 if (Config.accessList.noCache) {
1087 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1088 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1089 } else {
1090 /* unless otherwise specified, we try to cache. */
1091 checkNoCacheDone(1);
1092 }
edce4d98 1093}
1094
de31d06f 1095static void
1096checkNoCacheDoneWrapper(int answer, void *data)
edce4d98 1097{
de31d06f 1098 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
e4a67a80 1099
de31d06f 1100 if (!calloutContext->httpStateIsValid())
1101 return;
1102
1103 calloutContext->checkNoCacheDone(answer);
8e2745f4 1104}
4fb35c3c 1105
8e2745f4 1106void
1107ClientRequestContext::checkNoCacheDone(int answer)
62e76326 1108{
8e2745f4 1109 acl_checklist = NULL;
de31d06f 1110 http->request->flags.cachable = answer;
1111 http->doCallouts();
edce4d98 1112}
1113
69660be0 1114/*
1115 * Identify requests that do not go through the store and client side stream
1116 * and forward them to the appropriate location. All other requests, request
1117 * them.
edce4d98 1118 */
1119void
8e2745f4 1120ClientHttpRequest::processRequest()
edce4d98 1121{
60745f24 1122 debugs(85, 4, "clientProcessRequest: " << RequestMethodStr(request->method) << " '" << uri << "'");
62e76326 1123
3712be3f 1124#if USE_SSL
1125 if (request->method == METHOD_CONNECT && sslBumpNeeded()) {
1126 sslBumpStart();
1127 return;
1128 }
1129#endif
1130
2baf58c3 1131 if (request->method == METHOD_CONNECT && !redirect.status) {
62e76326 1132 logType = LOG_TCP_MISS;
f84dd7eb 1133 getConn()->stopReading(); // tunnels read for themselves
11007d4b 1134 tunnelStart(this, &out.size, &al.http.code);
62e76326 1135 return;
edce4d98 1136 }
62e76326 1137
8e2745f4 1138 httpStart();
1139}
1140
1141void
1142ClientHttpRequest::httpStart()
1143{
559da936 1144 PROF_start(httpStart);
8e2745f4 1145 logType = LOG_TAG_NONE;
bf8fe701 1146 debugs(85, 4, "ClientHttpRequest::httpStart: " << log_tags[logType] << " for '" << uri << "'");
1147
edce4d98 1148 /* no one should have touched this */
8e2745f4 1149 assert(out.offset == 0);
edce4d98 1150 /* Use the Stream Luke */
8e2745f4 1151 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1152 clientStreamRead(node, this, node->readBuffer);
559da936 1153 PROF_stop(httpStart);
edce4d98 1154}
0655fa4d 1155
3712be3f 1156#if USE_SSL
1157
1158// determines whether we should bump the CONNECT request
1159bool
26ac0430
AJ
1160ClientHttpRequest::sslBumpNeeded() const
1161{
3712be3f 1162 if (!getConn()->port->sslBump || !Config.accessList.ssl_bump)
1163 return false;
1164
1165 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1166
c0941a6a 1167 ACLFilledChecklist check(Config.accessList.ssl_bump, request, NULL);
3712be3f 1168 check.src_addr = request->client_addr;
26ac0430 1169 check.my_addr = request->my_addr;
26ac0430 1170 return check.fastCheck() == 1;
3712be3f 1171}
1172
1173// called when comm_write has completed
1174static void
1175SslBumpEstablish(int, char *, size_t, comm_err_t errflag, int, void *data)
1176{
1177 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1178 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1179
1180 assert(r && cbdataReferenceValid(r));
1181 r->sslBumpEstablish(errflag);
1182}
1183
1184void
1185ClientHttpRequest::sslBumpEstablish(comm_err_t errflag)
1186{
1187 // Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up
1188 if (errflag == COMM_ERR_CLOSING)
1189 return;
1190
1191 if (errflag) {
1192 getConn()->startClosing("CONNECT response failure in SslBump");
1193 return;
1194 }
1195
95d2589c 1196 getConn()->switchToHttps(request->GetHost());
3712be3f 1197}
1198
1199void
1200ClientHttpRequest::sslBumpStart()
1201{
1202 debugs(85, 5, HERE << "ClientHttpRequest::sslBumpStart");
1203
1204 // send an HTTP 200 response to kick client SSL negotiation
1205 const int fd = getConn()->fd;
1206 debugs(33, 7, HERE << "Confirming CONNECT tunnel on FD " << fd);
1207
1208 // TODO: Unify with tunnel.cc and add a Server(?) header
1209 static const char *const conn_established =
3c4fcf0f 1210 "HTTP/1.1 200 Connection established\r\n\r\n";
ec41b64c
AJ
1211 AsyncCall::Pointer call = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1212 CommIoCbPtrFun(&SslBumpEstablish, this));
1213 Comm::Write(fd, conn_established, strlen(conn_established), call, NULL);
3712be3f 1214}
1215
1216#endif
1217
0655fa4d 1218bool
1219ClientHttpRequest::gotEnough() const
1220{
86a2f789 1221 /** TODO: should be querying the stream. */
7173d5b0 1222 int64_t contentLength =
06a5ae20 1223 memObject()->getReply()->bodySize(request->method);
0655fa4d 1224 assert(contentLength >= 0);
1225
1226 if (out.offset < contentLength)
1227 return false;
1228
1229 return true;
1230}
1231
86a2f789 1232void
1233ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1234{
1235 entry_ = newEntry;
1236}
1237
0976f8db 1238void
1239ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1240{
1241 if (loggingEntry_)
97b5e68f 1242 loggingEntry_->unlock();
0976f8db 1243
1244 loggingEntry_ = newEntry;
1245
1246 if (loggingEntry_)
3d0ac046 1247 loggingEntry_->lock();
0976f8db 1248}
86a2f789 1249
de31d06f 1250/*
1251 * doCallouts() - This function controls the order of "callout"
1252 * executions, including non-blocking access control checks, the
1253 * redirector, and ICAP. Previously, these callouts were chained
1254 * together such that "clientAccessCheckDone()" would call
1255 * "clientRedirectStart()" and so on.
1256 *
1257 * The ClientRequestContext (aka calloutContext) class holds certain
1258 * state data for the callout/callback operations. Previously
1259 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1260 * for a short time. ClientRequestContext would then delete itself
1261 * and pass control back to ClientHttpRequest when all callouts
1262 * were finished.
1263 *
1264 * This caused some problems for ICAP because we want to make the
1265 * ICAP callout after checking ACLs, but before checking the no_cache
1266 * list. We can't stuff the ICAP state into the ClientRequestContext
1267 * class because we still need the ICAP state after ClientRequestContext
1268 * goes away.
1269 *
1270 * Note that ClientRequestContext is created before the first call
1271 * to doCallouts().
1272 *
1273 * If one of the callouts notices that ClientHttpRequest is no
1274 * longer valid, it should call cbdataReferenceDone() so that
1275 * ClientHttpRequest's reference count goes to zero and it will get
1276 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1277 *
1278 * Note that we set the _done flags here before actually starting
1279 * the callout. This is strictly for convenience.
1280 */
1281
425de4c8
AJ
1282extern tos_t aclMapTOS (acl_tos * head, ACLChecklist * ch);
1283extern nfmark_t aclMapNfmark (acl_nfmark * head, ACLChecklist * ch);
057f5854 1284
de31d06f 1285void
1286ClientHttpRequest::doCallouts()
1287{
1288 assert(calloutContext);
1289
6fca33e0
CT
1290 /*Save the original request for logging purposes*/
1291 if (!calloutContext->http->al.request)
105d1937 1292 calloutContext->http->al.request = HTTPMSGLOCK(request);
6fca33e0 1293
de31d06f 1294 if (!calloutContext->http_access_done) {
3712be3f 1295 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()");
57abaac0 1296 calloutContext->http_access_done = true;
de31d06f 1297 calloutContext->clientAccessCheck();
1298 return;
1299 }
1300
a83c6ed6 1301#if USE_ADAPTATION
abd4b611 1302 if (!calloutContext->adaptation_acl_check_done) {
a83c6ed6 1303 calloutContext->adaptation_acl_check_done = true;
abd4b611 1304 if (Adaptation::AccessCheck::Start(
26ac0430
AJ
1305 Adaptation::methodReqmod, Adaptation::pointPreCache,
1306 request, NULL, adaptationAclCheckDoneWrapper, calloutContext))
abd4b611 1307 return; // will call callback
de31d06f 1308 }
de31d06f 1309#endif
1310
1311 if (!calloutContext->redirect_done) {
57abaac0 1312 calloutContext->redirect_done = true;
de31d06f 1313 assert(calloutContext->redirect_state == REDIRECT_NONE);
1314
1315 if (Config.Program.redirect) {
3712be3f 1316 debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()");
de31d06f 1317 calloutContext->redirect_state = REDIRECT_PENDING;
1318 calloutContext->clientRedirectStart();
1319 return;
1320 }
1321 }
1322
533493da
AJ
1323 if (!calloutContext->adapted_http_access_done) {
1324 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()");
1325 calloutContext->adapted_http_access_done = true;
1326 calloutContext->clientAccessCheck2();
1327 return;
1328 }
1329
57abaac0 1330 if (!calloutContext->interpreted_req_hdrs) {
3712be3f 1331 debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()");
57abaac0 1332 calloutContext->interpreted_req_hdrs = 1;
1333 clientInterpretRequestHeaders(this);
1334 }
1335
de31d06f 1336 if (!calloutContext->no_cache_done) {
57abaac0 1337 calloutContext->no_cache_done = true;
de31d06f 1338
1339 if (Config.accessList.noCache && request->flags.cachable) {
3712be3f 1340 debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()");
de31d06f 1341 calloutContext->checkNoCache();
1342 return;
1343 }
1344 }
1345
425de4c8
AJ
1346 if (!calloutContext->tosToClientDone) {
1347 calloutContext->tosToClientDone = true;
3712be3f 1348 if (getConn() != NULL) {
c0941a6a 1349 ACLFilledChecklist ch(NULL, request, NULL);
057f5854 1350 ch.src_addr = request->client_addr;
1351 ch.my_addr = request->my_addr;
425de4c8 1352 tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch);
3712be3f 1353 if (tos)
425de4c8
AJ
1354 Ip::Qos::setSockTos(getConn()->fd, tos);
1355 }
1356 }
1357
1358 if (!calloutContext->nfmarkToClientDone) {
1359 calloutContext->nfmarkToClientDone = true;
1360 if (getConn() != NULL) {
1361 ACLFilledChecklist ch(NULL, request, NULL);
1362 ch.src_addr = request->client_addr;
1363 ch.my_addr = request->my_addr;
1364 nfmark_t mark = aclMapNfmark(Ip::Qos::TheConfig.nfmarkToClient, &ch);
1365 if (mark)
1366 Ip::Qos::setSockNfmark(getConn()->fd, mark);
3712be3f 1367 }
057f5854 1368 }
1369
de31d06f 1370 cbdataReferenceDone(calloutContext->http);
1371 delete calloutContext;
1372 calloutContext = NULL;
de31d06f 1373#if HEADERS_LOG
1374
1375 headersLog(0, 1, request->method, request);
1376#endif
1377
58d7150d 1378 debugs(83, 3, HERE << "calling processRequest()");
de31d06f 1379 processRequest();
3ff65596
AR
1380
1381#if ICAP_CLIENT
1382 Adaptation::Icap::History::Pointer ih = request->icapHistory();
1383 if (ih != NULL)
1384 ih->logType = logType;
1385#endif
de31d06f 1386}
1387
32d002cb 1388#if !_USE_INLINE_
86a2f789 1389#include "client_side_request.cci"
1390#endif
de31d06f 1391
a83c6ed6 1392#if USE_ADAPTATION
a22e6cd3
AR
1393/// Initiate an asynchronous adaptation transaction which will call us back.
1394void
1395ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
3b299123 1396{
a22e6cd3 1397 debugs(85, 3, HERE << "adaptation needed for " << this);
a83c6ed6
AR
1398 assert(!virginHeadSource);
1399 assert(!adaptedBodySource);
a22e6cd3 1400 virginHeadSource = initiateAdaptation(
4cb2536f 1401 new Adaptation::Iterator(request, NULL, g));
a83c6ed6 1402
e1381638 1403 // we could try to guess whether we can bypass this adaptation
a22e6cd3 1404 // initiation failure, but it should not really happen
4299f876 1405 Must(initiated(virginHeadSource));
de31d06f 1406}
1407
1408void
3af10ac0 1409ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer &answer)
de31d06f 1410{
de31d06f 1411 assert(cbdataReferenceValid(this)); // indicates bug
3af10ac0
AR
1412 clearAdaptation(virginHeadSource);
1413 assert(!adaptedBodySource);
1414
1415 switch (answer.kind) {
1416 case Adaptation::Answer::akForward:
1417 handleAdaptedHeader(answer.message);
1418 break;
1419
1420 case Adaptation::Answer::akBlock:
1421 handleAdaptationBlock(answer);
1422 break;
1423
1424 case Adaptation::Answer::akError:
1425 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_ABORT, !answer.final);
1426 break;
1427 }
1428}
1429
1430void
ec4d1a1d 1431ClientHttpRequest::handleAdaptedHeader(HttpMsg *msg)
3af10ac0 1432{
5f8252d2 1433 assert(msg);
1434
b044675d 1435 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
200ac359 1436 /*
5f8252d2 1437 * Replace the old request with the new request.
200ac359 1438 */
6dd9f4bd 1439 HTTPMSGUNLOCK(request);
1440 request = HTTPMSGLOCK(new_req);
200ac359 1441 /*
1442 * Store the new URI for logging
1443 */
1444 xfree(uri);
1445 uri = xstrdup(urlCanonical(request));
1446 setLogUri(this, urlCanonicalClean(request));
914b89a2 1447 assert(request->method.id());
b044675d 1448 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
1449 debugs(85,3,HERE << "REQMOD reply is HTTP reply");
1450
5f8252d2 1451 // subscribe to receive reply body
1452 if (new_rep->body_pipe != NULL) {
a83c6ed6 1453 adaptedBodySource = new_rep->body_pipe;
d222a56c
HN
1454 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
1455 assert(consumer_ok);
5f8252d2 1456 }
1457
b044675d 1458 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1459 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1460 repContext->createStoreEntry(request->method, request->flags);
1461
1462 EBIT_CLR(storeEntry()->flags, ENTRY_FWD_HDR_WAIT);
1463 request_satisfaction_mode = true;
1464 request_satisfaction_offset = 0;
1465 storeEntry()->replaceHttpReply(new_rep);
97ae5196 1466 storeEntry()->timestampsSet();
cb4c4288 1467
a83c6ed6 1468 if (!adaptedBodySource) // no body
cb4c4288 1469 storeEntry()->complete();
b044675d 1470 clientGetMoreData(node, this);
200ac359 1471 }
de31d06f 1472
5f8252d2 1473 // we are done with getting headers (but may be receiving body)
a83c6ed6 1474 clearAdaptation(virginHeadSource);
5f8252d2 1475
b044675d 1476 if (!request_satisfaction_mode)
1477 doCallouts();
de31d06f 1478}
1479
1480void
3af10ac0 1481ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer &answer)
de31d06f 1482{
3af10ac0
AR
1483 request->detailError(ERR_ACCESS_DENIED, ERR_DETAIL_REQMOD_BLOCK);
1484 AclMatchedName = answer.ruleId.termedBuf();
1485 assert(calloutContext);
1486 calloutContext->clientAccessCheckDone(ACCESS_DENIED);
1487 AclMatchedName = NULL;
de31d06f 1488}
1489
1490void
1cf238db 1491ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
de31d06f 1492{
5f8252d2 1493 assert(request_satisfaction_mode);
a83c6ed6 1494 assert(adaptedBodySource != NULL);
5f8252d2 1495
4ce0e99b 1496 if (const size_t contentSize = adaptedBodySource->buf().contentSize()) {
a83c6ed6 1497 BodyPipeCheckout bpc(*adaptedBodySource);
4ce0e99b 1498 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset);
5f8252d2 1499 storeEntry()->write(ioBuf);
1500 // assume can write everything
1501 request_satisfaction_offset += contentSize;
4ce0e99b 1502 bpc.buf.consume(contentSize);
5f8252d2 1503 bpc.checkIn();
1504 }
1505
a83c6ed6 1506 if (adaptedBodySource->exhausted())
5f8252d2 1507 endRequestSatisfaction();
1508 // else wait for more body data
de31d06f 1509}
1510
1511void
1cf238db 1512ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
de31d06f 1513{
a83c6ed6
AR
1514 assert(!virginHeadSource);
1515 if (adaptedBodySource != NULL) { // did not end request satisfaction yet
26ac0430 1516 // We do not expect more because noteMoreBodyDataAvailable always
5f8252d2 1517 // consumes everything. We do not even have a mechanism to consume
1518 // leftovers after noteMoreBodyDataAvailable notifications seize.
a83c6ed6 1519 assert(adaptedBodySource->exhausted());
5f8252d2 1520 endRequestSatisfaction();
1521 }
1522}
3b299123 1523
5f8252d2 1524void
26ac0430
AJ
1525ClientHttpRequest::endRequestSatisfaction()
1526{
5f8252d2 1527 debugs(85,4, HERE << this << " ends request satisfaction");
1528 assert(request_satisfaction_mode);
a83c6ed6 1529 stopConsumingFrom(adaptedBodySource);
3b299123 1530
5f8252d2 1531 // TODO: anything else needed to end store entry formation correctly?
1532 storeEntry()->complete();
1533}
de31d06f 1534
5f8252d2 1535void
1cf238db 1536ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
5f8252d2 1537{
a83c6ed6
AR
1538 assert(!virginHeadSource);
1539 stopConsumingFrom(adaptedBodySource);
eae3a9a6
AR
1540
1541 debugs(85,3, HERE << "REQMOD body production failed");
1542 if (request_satisfaction_mode) { // too late to recover or serve an error
1543 request->detailError(ERR_ICAP_FAILURE, ERR_DETAIL_CLT_REQMOD_RESP_BODY);
1544 const int fd = getConn()->fd;
1545 Must(fd >= 0);
1546 comm_close(fd); // drastic, but we may be writing a response already
1547 } else {
1548 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_REQ_BODY);
1549 }
5f8252d2 1550}
3b299123 1551
5f8252d2 1552void
64b66b76 1553ClientHttpRequest::handleAdaptationFailure(int errDetail, bool bypassable)
5f8252d2 1554{
a83c6ed6 1555 debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")");
3b299123 1556
5f8252d2 1557 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
1558 const bool usedPipe = request->body_pipe != NULL &&
26ac0430 1559 request->body_pipe->consumedSize() > 0;
3b299123 1560
9d4d7c5e 1561 if (bypassable && !usedStore && !usedPipe) {
1562 debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext);
5f8252d2 1563 if (calloutContext)
1564 doCallouts();
1565 return;
1566 }
3b299123 1567
5f8252d2 1568 debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error");
3b299123 1569
5f8252d2 1570 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1571 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1572 assert(repContext);
de31d06f 1573
26ac0430 1574 // The original author of the code also wanted to pass an errno to
5f8252d2 1575 // setReplyToError, but it seems unlikely that the errno reflects the
1576 // true cause of the error at this point, so I did not pass it.
b7ac5457 1577 Ip::Address noAddr;
b70ba605 1578 noAddr.SetNoAddr();
1cf238db 1579 ConnStateData * c = getConn();
5f8252d2 1580 repContext->setReplyToError(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR,
26ac0430
AJ
1581 request->method, NULL,
1582 (c != NULL ? c->peer : noAddr), request, NULL,
a33a428a 1583 (c != NULL && c->auth_user_request != NULL ?
26ac0430 1584 c->auth_user_request : request->auth_user_request));
de31d06f 1585
64b66b76
CT
1586 request->detailError(ERR_ICAP_FAILURE, errDetail);
1587
5f8252d2 1588 node = (clientStreamNode *)client_stream.tail->data;
1589 clientStreamRead(node, this, node->readBuffer);
de31d06f 1590}
1591
1592#endif