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