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