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