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