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