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