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