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