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