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