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