]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_request.cc
Upgrade Acl::Node::name to SBuf; remove AclMatchedName global (#1766)
[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
60745f24 281clientBeginRequest(const HttpRequestMethod& method, char const *url, CSCB * streamcallback,
0655fa4d 282 CSD * streamdetach, ClientStreamData streamdata, HttpHeader const *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);
d096ace1
AJ
441 calloutContext->acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
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 */
444 Filled(calloutContext->acl_checklist)->src_addr = request->indirect_client_addr;
3d674977 445 }
45b6522e
TL
446 if (++calloutContext->currentXffHopNumber < SQUID_X_FORWARDED_FOR_HOP_MAX) {
447 calloutContext->acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, data);
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 */
669 acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
670 acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, this);
3d674977
AJ
671 return;
672 }
fbe9e379 673#endif
493d3865 674
b50e327b
AJ
675 if (Config.accessList.http) {
676 acl_checklist = clientAclChecklistCreate(Config.accessList.http, http);
677 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
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) {
693 acl_checklist = clientAclChecklistCreate(Config.accessList.adapted_http, http);
694 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
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{
aee3523a 715 acl_checklist = nullptr;
955394ce 716 Http::StatusCode status;
7f06a3d8 717 debugs(85, 2, "The request " << http->request->method << ' ' <<
9d5e7196 718 http->uri << " is " << answer <<
25aa6c9a 719 "; last ACL checked: " << answer.lastCheckDescription());
f5691f9c 720
2f1431ea
AJ
721#if USE_AUTH
722 char const *proxy_auth_msg = "<null>";
aee3523a 723 if (http->getConn() != nullptr && http->getConn()->getAuth() != nullptr)
cc1e110a 724 proxy_auth_msg = http->getConn()->getAuth()->denyMessage("<null>");
aee3523a 725 else if (http->request->auth_user_request != nullptr)
f5691f9c 726 proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
2f1431ea 727#endif
62e76326 728
06bf5384 729 if (!answer.allowed()) {
9d5e7196 730 // auth has a grace period where credentials can be expired but okay not to challenge.
309347ef 731
9d5e7196
AJ
732 /* Send an auth challenge or error */
733 // XXX: do we still need aclIsProxyAuth() ?
25aa6c9a 734 const auto auth_challenge = (answer == ACCESS_AUTH_REQUIRED || aclIsProxyAuth(answer.lastCheckedName));
9d5e7196 735 debugs(85, 5, "Access Denied: " << http->uri);
2f1431ea 736#if USE_AUTH
9d5e7196
AJ
737 if (auth_challenge)
738 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg ? proxy_auth_msg : "<null>"));
2f1431ea 739#endif
9ce7856a 740
25aa6c9a 741 auto page_id = FindDenyInfoPage(answer, answer != ACCESS_AUTH_REQUIRED);
9ce7856a 742
12f5a662 743 http->updateLoggingTags(LOG_TCP_DENIED);
62e76326 744
9d5e7196 745 if (auth_challenge) {
2f1431ea 746#if USE_AUTH
450fe1cb 747 if (http->request->flags.sslBumped) {
9d5e7196 748 /*SSL Bumped request, authentication is not possible*/
955394ce 749 status = Http::scForbidden;
9d5e7196
AJ
750 } else if (!http->flags.accel) {
751 /* Proxy authorisation needed */
955394ce 752 status = Http::scProxyAuthenticationRequired;
9d5e7196
AJ
753 } else {
754 /* WWW authorisation needed */
955394ce 755 status = Http::scUnauthorized;
9d5e7196 756 }
ed6163ef 757#else
9d5e7196 758 // need auth, but not possible to do.
955394ce 759 status = Http::scForbidden;
ed6163ef 760#endif
9d5e7196
AJ
761 if (page_id == ERR_NONE)
762 page_id = ERR_CACHE_ACCESS_DENIED;
763 } else {
955394ce 764 status = Http::scForbidden;
ed6163ef 765
9d5e7196
AJ
766 if (page_id == ERR_NONE)
767 page_id = ERR_ACCESS_DENIED;
768 }
62e76326 769
7976fed3 770 error = clientBuildError(page_id, status, nullptr, http->getConn(), http->request, http->al);
68715527 771
2f1431ea 772#if USE_AUTH
87f237a9 773 error->auth_user_request =
aee3523a 774 http->getConn() != nullptr && http->getConn()->getAuth() != nullptr ?
cc1e110a 775 http->getConn()->getAuth() : http->request->auth_user_request;
2f1431ea 776#endif
68715527
CT
777
778 readNextRequest = true;
9d5e7196 779 }
de31d06f 780
dd332b92 781 /* ACCESS_ALLOWED continues here ... */
3f0e38d6
AJ
782 xfree(http->uri);
783 http->uri = SBufToCstring(http->request->effectiveRequestUri());
de31d06f 784 http->doCallouts();
785}
786
a83c6ed6 787#if USE_ADAPTATION
de31d06f 788void
79628299 789ClientHttpRequest::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer g)
de31d06f 790{
bf95c10a 791 debugs(93,3, this << " adaptationAclCheckDone called");
6ec67de9 792
e1381638 793#if ICAP_CLIENT
79628299 794 Adaptation::Icap::History::Pointer ih = request->icapHistory();
aee3523a
AR
795 if (ih != nullptr) {
796 if (getConn() != nullptr && getConn()->clientConnection != nullptr) {
79628299 797 ih->rfc931 = getConn()->clientConnection->rfc931;
cb4f4424 798#if USE_OPENSSL
6bc2a98d 799 if (getConn()->clientConnection->isOpen()) {
33cc0629 800 ih->ssluser = sslGetUserEmail(fd_table[getConn()->clientConnection->fd].ssl.get());
6bc2a98d 801 }
e1381638 802#endif
3ff65596 803 }
79628299
CT
804 ih->log_uri = log_uri;
805 ih->req_sz = req_sz;
3ff65596
AR
806 }
807#endif
808
a22e6cd3 809 if (!g) {
bf95c10a 810 debugs(85,3, "no adaptation needed");
79628299 811 doCallouts();
5f8252d2 812 return;
813 }
de31d06f 814
79628299 815 startAdaptation(g);
edce4d98 816}
817
de31d06f 818#endif
819
14cc8559 820static void
329c128c 821clientRedirectAccessCheckDone(Acl::Answer answer, void *data)
14cc8559 822{
823 ClientRequestContext *context = (ClientRequestContext *)data;
9d5e7196 824 ClientHttpRequest *http = context->http;
aee3523a 825 context->acl_checklist = nullptr;
14cc8559 826
06bf5384 827 if (answer.allowed())
9d5e7196 828 redirectStart(http, clientRedirectDoneWrapper, context);
bc98bc4b 829 else {
ddc77a2e 830 Helper::Reply const nilReply(Helper::Error);
bc98bc4b
AJ
831 context->clientRedirectDone(nilReply);
832 }
14cc8559 833}
834
de31d06f 835void
836ClientRequestContext::clientRedirectStart()
14cc8559 837{
bf95c10a 838 debugs(33, 5, "'" << http->uri << "'");
75d47340 839 http->al->syncNotes(http->request);
14cc8559 840 if (Config.accessList.redirector) {
de31d06f 841 acl_checklist = clientAclChecklistCreate(Config.accessList.redirector, http);
842 acl_checklist->nonBlockingCheck(clientRedirectAccessCheckDone, this);
14cc8559 843 } else
de31d06f 844 redirectStart(http, clientRedirectDoneWrapper, this);
14cc8559 845}
846
a8a0b1c2
EC
847/**
848 * This methods handles Access checks result of StoreId access list.
849 * Will handle as "ERR" (no change) in a case Access is not allowed.
850 */
851static void
329c128c 852clientStoreIdAccessCheckDone(Acl::Answer answer, void *data)
a8a0b1c2
EC
853{
854 ClientRequestContext *context = static_cast<ClientRequestContext *>(data);
855 ClientHttpRequest *http = context->http;
aee3523a 856 context->acl_checklist = nullptr;
a8a0b1c2 857
06bf5384 858 if (answer.allowed())
a8a0b1c2
EC
859 storeIdStart(http, clientStoreIdDoneWrapper, context);
860 else {
861 debugs(85, 3, "access denied expected ERR reply handling: " << answer);
ddc77a2e 862 Helper::Reply const nilReply(Helper::Error);
a8a0b1c2
EC
863 context->clientStoreIdDone(nilReply);
864 }
865}
866
867/**
2f8abb64 868 * Start locating an alternative storage ID string (if any) from admin
a8a0b1c2
EC
869 * configured helper program. This is an asynchronous operation terminating in
870 * ClientRequestContext::clientStoreIdDone() when completed.
871 */
872void
873ClientRequestContext::clientStoreIdStart()
874{
875 debugs(33, 5,"'" << http->uri << "'");
876
877 if (Config.accessList.store_id) {
878 acl_checklist = clientAclChecklistCreate(Config.accessList.store_id, http);
879 acl_checklist->nonBlockingCheck(clientStoreIdAccessCheckDone, this);
880 } else
881 storeIdStart(http, clientStoreIdDoneWrapper, this);
882}
883
edce4d98 884static int
59a1efb2 885clientHierarchical(ClientHttpRequest * http)
edce4d98 886{
190154cf 887 HttpRequest *request = http->request;
60745f24 888 HttpRequestMethod method = request->method;
edce4d98 889
2962f8b8 890 // intercepted requests MUST NOT (yet) be sent to peers unless verified
0d901ef4 891 if (!request->flags.hostVerified && (request->flags.intercepted || request->flags.interceptTproxy))
2962f8b8
AJ
892 return 0;
893
69660be0 894 /*
895 * IMS needs a private key, so we can use the hierarchy for IMS only if our
896 * neighbors support private keys
897 */
62e76326 898
45e5102d 899 if (request->flags.ims && !neighbors_do_private_keys)
62e76326 900 return 0;
901
69660be0 902 /*
903 * This is incorrect: authenticating requests can be sent via a hierarchy
06b97e72 904 * (they can even be cached if the correct headers are set on the reply)
edce4d98 905 */
45e5102d 906 if (request->flags.auth)
62e76326 907 return 0;
908
c2a7cefd 909 if (method == Http::METHOD_TRACE)
62e76326 910 return 1;
911
c2a7cefd 912 if (method != Http::METHOD_GET)
62e76326 913 return 0;
914
450fe1cb 915 if (request->flags.loopDetected)
62e76326 916 return 0;
917
4e3f4dc7 918 if (request->url.getScheme() == AnyP::PROTO_HTTP)
c2a7cefd 919 return method.respMaybeCacheable();
62e76326 920
edce4d98 921 return 1;
922}
923
46a1f562
HN
924static void
925clientCheckPinning(ClientHttpRequest * http)
926{
927 HttpRequest *request = http->request;
928 HttpHeader *req_hdr = &request->header;
929 ConnStateData *http_conn = http->getConn();
930
931 /* Internal requests such as those from ESI includes may be without
932 * a client connection
933 */
934 if (!http_conn)
f54f527e 935 return;
46a1f562 936
450fe1cb
FC
937 request->flags.connectionAuthDisabled = http_conn->port->connection_auth_disabled;
938 if (!request->flags.connectionAuthDisabled) {
73c36fd9 939 if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) {
46a1f562 940 if (http_conn->pinning.auth) {
e857372a
FC
941 request->flags.connectionAuth = true;
942 request->flags.auth = true;
46a1f562 943 } else {
e857372a 944 request->flags.connectionProxyAuth = true;
46a1f562 945 }
b1cf2350
AJ
946 // These should already be linked correctly.
947 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
948 }
949 }
950
951 /* check if connection auth is used, and flag as candidate for pinning
45e5102d 952 * in such case.
450fe1cb 953 * Note: we may need to set flags.connectionAuth even if the connection
46a1f562
HN
954 * is already pinned if it was pinned earlier due to proxy auth
955 */
450fe1cb 956 if (!request->flags.connectionAuth) {
789217a2 957 if (req_hdr->has(Http::HdrType::AUTHORIZATION) || req_hdr->has(Http::HdrType::PROXY_AUTHORIZATION)) {
46a1f562
HN
958 HttpHeaderPos pos = HttpHeaderInitPos;
959 HttpHeaderEntry *e;
960 int may_pin = 0;
961 while ((e = req_hdr->getEntry(&pos))) {
789217a2 962 if (e->id == Http::HdrType::AUTHORIZATION || e->id == Http::HdrType::PROXY_AUTHORIZATION) {
46a1f562
HN
963 const char *value = e->value.rawBuf();
964 if (strncasecmp(value, "NTLM ", 5) == 0
965 ||
966 strncasecmp(value, "Negotiate ", 10) == 0
967 ||
968 strncasecmp(value, "Kerberos ", 9) == 0) {
789217a2 969 if (e->id == Http::HdrType::AUTHORIZATION) {
e857372a 970 request->flags.connectionAuth = true;
46a1f562
HN
971 may_pin = 1;
972 } else {
e857372a 973 request->flags.connectionProxyAuth = true;
46a1f562
HN
974 may_pin = 1;
975 }
976 }
977 }
978 }
979 if (may_pin && !request->pinnedConnection()) {
b1cf2350
AJ
980 // These should already be linked correctly. Just need the ServerConnection to pinn.
981 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
982 }
983 }
984 }
985}
986
edce4d98 987static void
59a1efb2 988clientInterpretRequestHeaders(ClientHttpRequest * http)
edce4d98 989{
190154cf 990 HttpRequest *request = http->request;
0ef77270 991 HttpHeader *req_hdr = &request->header;
5086523e 992 bool no_cache = false;
62e76326 993
edce4d98 994 request->imslen = -1;
789217a2 995 request->ims = req_hdr->getTime(Http::HdrType::IF_MODIFIED_SINCE);
62e76326 996
edce4d98 997 if (request->ims > 0)
e857372a 998 request->flags.ims = true;
62e76326 999
450fe1cb 1000 if (!request->flags.ignoreCc) {
47fbd2a7 1001 if (request->cache_control) {
1259f9cf 1002 if (request->cache_control->hasNoCache())
5086523e 1003 no_cache=true;
62e76326 1004
adc2a453 1005 // RFC 2616: treat Pragma:no-cache as if it was Cache-Control:no-cache when Cache-Control is missing
789217a2
FC
1006 } else if (req_hdr->has(Http::HdrType::PRAGMA))
1007 no_cache = req_hdr->hasListMember(Http::HdrType::PRAGMA,"no-cache",',');
edce4d98 1008 }
914b89a2 1009
c2a7cefd 1010 if (request->method == Http::METHOD_OTHER) {
5086523e 1011 no_cache=true;
60745f24 1012 }
62e76326 1013
edce4d98 1014 if (no_cache) {
626096be 1015#if USE_HTTP_VIOLATIONS
62e76326 1016
1017 if (Config.onoff.reload_into_ims)
e857372a 1018 request->flags.nocacheHack = true;
62e76326 1019 else if (refresh_nocache_hack)
e857372a 1020 request->flags.nocacheHack = true;
62e76326 1021 else
edce4d98 1022#endif
62e76326 1023
e857372a 1024 request->flags.noCache = true;
edce4d98 1025 }
62e76326 1026
0ef77270 1027 /* ignore range header in non-GETs or non-HEADs */
c2a7cefd 1028 if (request->method == Http::METHOD_GET || request->method == Http::METHOD_HEAD) {
56713d9a
AR
1029 // XXX: initialize if we got here without HttpRequest::parseHeader()
1030 if (!request->range)
1031 request->range = req_hdr->getRange();
62e76326 1032
1033 if (request->range) {
e857372a 1034 request->flags.isRanged = true;
62e76326 1035 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
1036 /* XXX: This is suboptimal. We should give the stream the range set,
1037 * and thereby let the top of the stream set the offset when the
26ac0430 1038 * size becomes known. As it is, we will end up requesting from 0
62e76326 1039 * for evey -X range specification.
1040 * RBC - this may be somewhat wrong. We should probably set the range
1041 * iter up at this point.
1042 */
1043 node->readBuffer.offset = request->range->lowestOffset(0);
62e76326 1044 }
edce4d98 1045 }
62e76326 1046
0ef77270 1047 /* Only HEAD and GET requests permit a Range or Request-Range header.
1048 * If these headers appear on any other type of request, delete them now.
1049 */
1050 else {
789217a2
FC
1051 req_hdr->delById(Http::HdrType::RANGE);
1052 req_hdr->delById(Http::HdrType::REQUEST_RANGE);
f0baf149 1053 request->ignoreRange("neither HEAD nor GET");
0ef77270 1054 }
1055
789217a2 1056 if (req_hdr->has(Http::HdrType::AUTHORIZATION))
e857372a 1057 request->flags.auth = true;
62e76326 1058
46a1f562 1059 clientCheckPinning(http);
d67acb4e 1060
92d6986d 1061 if (!request->url.userInfo().isEmpty())
e857372a 1062 request->flags.auth = true;
62e76326 1063
789217a2
FC
1064 if (req_hdr->has(Http::HdrType::VIA)) {
1065 String s = req_hdr->getList(Http::HdrType::VIA);
62e76326 1066 /*
3c4fcf0f 1067 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
62e76326 1068 * Note ThisCache2 has a space prepended to the hostname so we don't
1069 * accidentally match super-domains.
1070 */
1071
1072 if (strListIsSubstr(&s, ThisCache2, ',')) {
e857372a 1073 request->flags.loopDetected = true;
62e76326 1074 }
1075
21f6708d 1076#if USE_FORW_VIA_DB
cf1f23ee 1077 fvdbCountVia(StringToSBuf(s));
62e76326 1078
edce4d98 1079#endif
62e76326 1080
30abd221 1081 s.clean();
edce4d98 1082 }
62e76326 1083
609d5e06
AJ
1084 // headers only relevant to reverse-proxy
1085 if (request->flags.accelerated) {
1086 // check for a cdn-info member with a cdn-id matching surrogate_id
1087 // XXX: HttpHeader::hasListMember() does not handle OWS around ";" yet
1088 if (req_hdr->hasListMember(Http::HdrType::CDN_LOOP, Config.Accel.surrogate_id, ','))
1089 request->flags.loopDetected = true;
1090 }
1091
1092 if (request->flags.loopDetected) {
1093 debugObj(33, DBG_IMPORTANT, "WARNING: Forwarding loop detected for:\n",
1094 request, (ObjPackMethod) & httpRequestPack);
1095 }
1096
21f6708d 1097#if USE_FORW_VIA_DB
62e76326 1098
789217a2
FC
1099 if (req_hdr->has(Http::HdrType::X_FORWARDED_FOR)) {
1100 String s = req_hdr->getList(Http::HdrType::X_FORWARDED_FOR);
9386f99d 1101 fvdbCountForwarded(StringToSBuf(s));
30abd221 1102 s.clean();
edce4d98 1103 }
62e76326 1104
edce4d98 1105#endif
62e76326 1106
aeeff7fd
AR
1107 if (http->request->maybeCacheable())
1108 request->flags.cachable.support();
1109 else
1110 request->flags.cachable.veto();
62e76326 1111
edce4d98 1112 if (clientHierarchical(http))
e857372a 1113 request->flags.hierarchical = true;
62e76326 1114
bf8fe701 1115 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
450fe1cb 1116 (request->flags.noCache ? "SET" : "NOT SET"));
bf8fe701 1117 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
45e5102d 1118 (request->flags.cachable ? "SET" : "NOT SET"));
bf8fe701 1119 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
45e5102d 1120 (request->flags.hierarchical ? "SET" : "NOT SET"));
62e76326 1121
edce4d98 1122}
1123
1124void
24438ec5 1125clientRedirectDoneWrapper(void *data, const Helper::Reply &result)
edce4d98 1126{
de31d06f 1127 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
db02222f 1128
de31d06f 1129 if (!calloutContext->httpStateIsValid())
62e76326 1130 return;
62e76326 1131
de31d06f 1132 calloutContext->clientRedirectDone(result);
1133}
1134
a8a0b1c2 1135void
24438ec5 1136clientStoreIdDoneWrapper(void *data, const Helper::Reply &result)
a8a0b1c2
EC
1137{
1138 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
1139
1140 if (!calloutContext->httpStateIsValid())
1141 return;
1142
1143 calloutContext->clientStoreIdDone(result);
1144}
1145
de31d06f 1146void
24438ec5 1147ClientRequestContext::clientRedirectDone(const Helper::Reply &reply)
de31d06f 1148{
190154cf 1149 HttpRequest *old_request = http->request;
bf95c10a 1150 debugs(85, 5, "'" << http->uri << "' result=" << reply);
de31d06f 1151 assert(redirect_state == REDIRECT_PENDING);
1152 redirect_state = REDIRECT_DONE;
62e76326 1153
cf9f0261 1154 // Put helper response Notes into the transaction state record (ALE) eventually
d06e17ea 1155 // do it early to ensure that no matter what the outcome the notes are present.
75d47340
CT
1156 if (http->al)
1157 http->al->syncNotes(old_request);
457857fe
CT
1158
1159 UpdateRequestNotes(http->getConn(), *old_request, reply.notes);
d06e17ea 1160
63fc9fb5 1161 switch (reply.result) {
32fd6d8a
CT
1162 case Helper::TimedOut:
1163 if (Config.onUrlRewriteTimeout.action != toutActBypass) {
83b053a0
CT
1164 static const auto d = MakeNamedErrorDetail("REDIRECTOR_TIMEDOUT");
1165 http->calloutsError(ERR_GATEWAY_FAILURE, d);
32fd6d8a
CT
1166 debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper: Timedout");
1167 }
1168 break;
1169
2428ce02
AJ
1170 case Helper::Unknown:
1171 case Helper::TT:
d06e17ea
AJ
1172 // Handler in redirect.cc should have already mapped Unknown
1173 // IF it contained valid entry for the old URL-rewrite helper protocol
1174 debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper returned invalid result code. Wrong helper? " << reply);
1175 break;
1176
2428ce02 1177 case Helper::BrokenHelper:
32fd6d8a 1178 debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper: " << reply);
d06e17ea
AJ
1179 break;
1180
2428ce02 1181 case Helper::Error:
d06e17ea
AJ
1182 // no change to be done.
1183 break;
62e76326 1184
2428ce02 1185 case Helper::Okay: {
d06e17ea
AJ
1186 // #1: redirect with a specific status code OK status=NNN url="..."
1187 // #2: redirect with a default status code OK url="..."
1188 // #3: re-write the URL OK rewrite-url="..."
1189
cf9f0261
CT
1190 const char *statusNote = reply.notes.findFirst("status");
1191 const char *urlNote = reply.notes.findFirst("url");
d06e17ea 1192
aee3523a 1193 if (urlNote != nullptr) {
d06e17ea
AJ
1194 // HTTP protocol redirect to be done.
1195
1196 // TODO: change default redirect status for appropriate requests
1197 // Squid defaults to 302 status for now for better compatibility with old clients.
f11c8e2f 1198 // HTTP/1.0 client should get 302 (Http::scFound)
955394ce
AJ
1199 // HTTP/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect)
1200 // HTTP/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther)
f11c8e2f 1201 Http::StatusCode status = Http::scFound;
aee3523a 1202 if (statusNote != nullptr) {
cf9f0261 1203 const char * result = statusNote;
955394ce 1204 status = static_cast<Http::StatusCode>(atoi(result));
d06e17ea 1205 }
62e76326 1206
955394ce 1207 if (status == Http::scMovedPermanently
f11c8e2f 1208 || status == Http::scFound
955394ce
AJ
1209 || status == Http::scSeeOther
1210 || status == Http::scPermanentRedirect
1211 || status == Http::scTemporaryRedirect) {
62e76326 1212 http->redirect.status = status;
cf9f0261 1213 http->redirect.location = xstrdup(urlNote);
e5b677f0 1214 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
62e76326 1215 } else {
cf9f0261 1216 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid " << status << " redirect Location: " << urlNote);
62e76326 1217 }
d06e17ea
AJ
1218 } else {
1219 // URL-rewrite wanted. Ew.
cf9f0261 1220 urlNote = reply.notes.findFirst("rewrite-url");
d06e17ea
AJ
1221
1222 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
aee3523a 1223 if (urlNote != nullptr && strcmp(urlNote, http->uri)) {
c8ab5ec6 1224 AnyP::Uri tmpUrl;
6c880a16 1225 if (tmpUrl.parse(old_request->method, SBuf(urlNote))) {
91489e45
AJ
1226 HttpRequest *new_request = old_request->clone();
1227 new_request->url = tmpUrl;
851feda6 1228 debugs(61, 2, "URL-rewriter diverts URL from " << old_request->effectiveRequestUri() << " to " << new_request->effectiveRequestUri());
d06e17ea 1229
d06e17ea 1230 // unlink bodypipe from the old request. Not needed there any longer.
aee3523a
AR
1231 if (old_request->body_pipe != nullptr) {
1232 old_request->body_pipe = nullptr;
bf95c10a 1233 debugs(61,2, "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
d06e17ea
AJ
1234 " from request " << old_request << " to " << new_request);
1235 }
9be14530 1236
333c433b 1237 http->resetRequestXXX(new_request, true);
bec110e4 1238 old_request = nullptr;
d06e17ea
AJ
1239 } else {
1240 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " <<
cf9f0261 1241 old_request->method << " " << urlNote << " " << old_request->http_ver);
d06e17ea 1242 }
9be14530 1243 }
74b48915 1244 }
edce4d98 1245 }
d06e17ea
AJ
1246 break;
1247 }
62e76326 1248
9837567d 1249 /* XXX PIPELINE: This is inaccurate during pipelining */
62e76326 1250
aee3523a 1251 if (http->getConn() != nullptr && Comm::IsConnOpen(http->getConn()->clientConnection))
73c36fd9 1252 fd_note(http->getConn()->clientConnection->fd, http->uri);
62e76326 1253
c8be6d7b 1254 assert(http->uri);
62e76326 1255
de31d06f 1256 http->doCallouts();
edce4d98 1257}
1258
a8a0b1c2
EC
1259/**
1260 * This method handles the different replies from StoreID helper.
1261 */
1262void
24438ec5 1263ClientRequestContext::clientStoreIdDone(const Helper::Reply &reply)
a8a0b1c2
EC
1264{
1265 HttpRequest *old_request = http->request;
1266 debugs(85, 5, "'" << http->uri << "' result=" << reply);
1267 assert(store_id_state == REDIRECT_PENDING);
1268 store_id_state = REDIRECT_DONE;
1269
cf9f0261 1270 // Put helper response Notes into the transaction state record (ALE) eventually
a8a0b1c2 1271 // do it early to ensure that no matter what the outcome the notes are present.
75d47340
CT
1272 if (http->al)
1273 http->al->syncNotes(old_request);
457857fe
CT
1274
1275 UpdateRequestNotes(http->getConn(), *old_request, reply.notes);
a8a0b1c2
EC
1276
1277 switch (reply.result) {
2428ce02
AJ
1278 case Helper::Unknown:
1279 case Helper::TT:
a8a0b1c2
EC
1280 // Handler in redirect.cc should have already mapped Unknown
1281 // IF it contained valid entry for the old helper protocol
1282 debugs(85, DBG_IMPORTANT, "ERROR: storeID helper returned invalid result code. Wrong helper? " << reply);
1283 break;
1284
32fd6d8a 1285 case Helper::TimedOut:
f53969cc 1286 // Timeouts for storeID are not implemented
2428ce02 1287 case Helper::BrokenHelper:
32fd6d8a 1288 debugs(85, DBG_IMPORTANT, "ERROR: storeID helper: " << reply);
a8a0b1c2
EC
1289 break;
1290
2428ce02 1291 case Helper::Error:
a8a0b1c2
EC
1292 // no change to be done.
1293 break;
1294
2428ce02 1295 case Helper::Okay: {
cf9f0261 1296 const char *urlNote = reply.notes.findFirst("store-id");
a8a0b1c2
EC
1297
1298 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
aee3523a 1299 if (urlNote != nullptr && strcmp(urlNote, http->uri) ) {
a8a0b1c2 1300 // Debug section required for some very specific cases.
cf9f0261
CT
1301 debugs(85, 9, "Setting storeID with: " << urlNote );
1302 http->request->store_id = urlNote;
1303 http->store_id = urlNote;
a8a0b1c2
EC
1304 }
1305 }
1306 break;
1307 }
1308
1309 http->doCallouts();
1310}
1311
aeeff7fd 1312/// applies "cache allow/deny" rules, asynchronously if needed
edce4d98 1313void
8e2745f4 1314ClientRequestContext::checkNoCache()
edce4d98 1315{
b50e327b
AJ
1316 if (Config.accessList.noCache) {
1317 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1318 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1319 } else {
1320 /* unless otherwise specified, we try to cache. */
2efeb0b7 1321 checkNoCacheDone(ACCESS_ALLOWED);
b50e327b 1322 }
edce4d98 1323}
1324
de31d06f 1325static void
329c128c 1326checkNoCacheDoneWrapper(Acl::Answer answer, void *data)
edce4d98 1327{
de31d06f 1328 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
e4a67a80 1329
de31d06f 1330 if (!calloutContext->httpStateIsValid())
1331 return;
1332
1333 calloutContext->checkNoCacheDone(answer);
8e2745f4 1334}
4fb35c3c 1335
8e2745f4 1336void
329c128c 1337ClientRequestContext::checkNoCacheDone(const Acl::Answer &answer)
62e76326 1338{
aee3523a 1339 acl_checklist = nullptr;
06bf5384 1340 if (answer.denied()) {
aeeff7fd 1341 http->request->flags.disableCacheUse("a cache deny rule matched");
58e1b950 1342 }
de31d06f 1343 http->doCallouts();
edce4d98 1344}
1345
cb4f4424 1346#if USE_OPENSSL
e0c0d54c
CT
1347bool
1348ClientRequestContext::sslBumpAccessCheck()
1349{
4b5ea8a6
CT
1350 if (!http->getConn()) {
1351 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1352 return false;
1353 }
1354
75f6c253 1355 const Ssl::BumpMode bumpMode = http->getConn()->sslBumpMode;
6b2b6cfe
CT
1356 if (http->request->flags.forceTunnel) {
1357 debugs(85, 5, "not needed; already decided to tunnel " << http->getConn());
75f6c253
CT
1358 if (bumpMode != Ssl::bumpEnd)
1359 http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
6b2b6cfe
CT
1360 return false;
1361 }
1362
08097970 1363 // If SSL connection tunneling or bumping decision has been made, obey it.
08097970 1364 if (bumpMode != Ssl::bumpEnd) {
bf95c10a 1365 debugs(85, 5, "SslBump already decided (" << bumpMode <<
08097970 1366 "), " << "ignoring ssl_bump for " << http->getConn());
91d7e7c4 1367
e1241cd3
CT
1368 // We need the following "if" for transparently bumped TLS connection,
1369 // because in this case we are running ssl_bump access list before
1370 // the doCallouts runs. It can be removed after the bug #4340 fixed.
1371 // We do not want to proceed to bumping steps:
1372 // - if the TLS connection with the client is already established
1373 // because we are accepting normal HTTP requests on TLS port,
1374 // or because of the client-first bumping mode
1375 // - When the bumping is already started
1376 if (!http->getConn()->switchedToHttps() &&
91d7e7c4 1377 !http->getConn()->serverBump())
b4049e38 1378 http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed and not already bumped
71cae389 1379 http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
08097970
AR
1380 return false;
1381 }
e0c0d54c 1382
08097970
AR
1383 // If we have not decided yet, decide whether to bump now.
1384
1385 // Bumping here can only start with a CONNECT request on a bumping port
1386 // (bumping of intercepted SSL conns is decided before we get 1st request).
1387 // We also do not bump redirected CONNECT requests.
c2a7cefd 1388 if (http->request->method != Http::METHOD_CONNECT || http->redirect.status ||
6a25a046
FC
1389 !Config.accessList.ssl_bump ||
1390 !http->getConn()->port->flags.tunnelSslBumping) {
71cae389 1391 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
bf95c10a 1392 debugs(85, 5, "cannot SslBump this request");
e0c0d54c
CT
1393 return false;
1394 }
08097970
AR
1395
1396 // Do not bump during authentication: clients would not proxy-authenticate
1397 // if we delay a 407 response and respond with 200 OK to CONNECT.
955394ce 1398 if (error && error->httpStatus == Http::scProxyAuthenticationRequired) {
71cae389 1399 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
bf95c10a 1400 debugs(85, 5, "no SslBump during proxy authentication");
08097970
AR
1401 return false;
1402 }
1403
93046e07
CT
1404 if (error) {
1405 debugs(85, 5, "SslBump applies. Force bump action on error " << errorTypeName(error->type));
1406 http->sslBumpNeed(Ssl::bumpBump);
1407 http->al->ssl.bumpMode = Ssl::bumpBump;
1408 return false;
1409 }
1410
bf95c10a 1411 debugs(85, 5, "SslBump possible, checking ACL");
08097970 1412
eb898410
AJ
1413 ACLFilledChecklist *aclChecklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http);
1414 aclChecklist->nonBlockingCheck(sslBumpAccessCheckDoneWrapper, this);
08097970 1415 return true;
e0c0d54c
CT
1416}
1417
f8901ea9 1418/**
e0c0d54c
CT
1419 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1420 * as ACLFilledChecklist callback
1421 */
1422static void
329c128c 1423sslBumpAccessCheckDoneWrapper(Acl::Answer answer, void *data)
e0c0d54c
CT
1424{
1425 ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data);
9d5e7196
AJ
1426
1427 if (!calloutContext->httpStateIsValid())
1428 return;
ed6163ef 1429 calloutContext->sslBumpAccessCheckDone(answer);
e0c0d54c
CT
1430}
1431
1432void
329c128c 1433ClientRequestContext::sslBumpAccessCheckDone(const Acl::Answer &answer)
e0c0d54c 1434{
ed6163ef
AJ
1435 if (!httpStateIsValid())
1436 return;
1437
06bf5384 1438 const Ssl::BumpMode bumpMode = answer.allowed() ?
bf352fb2 1439 static_cast<Ssl::BumpMode>(answer.kind) : Ssl::bumpSplice;
08097970 1440 http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed
71cae389 1441 http->al->ssl.bumpMode = bumpMode; // for logging
caf3666d 1442
bf352fb2
CT
1443 if (bumpMode == Ssl::bumpTerminate) {
1444 const Comm::ConnectionPointer clientConn = http->getConn() ? http->getConn()->clientConnection : nullptr;
1445 if (Comm::IsConnOpen(clientConn)) {
1446 debugs(85, 3, "closing after Ssl::bumpTerminate ");
1447 clientConn->close();
1448 }
1449 return;
1450 }
1451
e0c0d54c
CT
1452 http->doCallouts();
1453}
1454#endif
1455
69660be0 1456/*
1457 * Identify requests that do not go through the store and client side stream
1458 * and forward them to the appropriate location. All other requests, request
1459 * them.
edce4d98 1460 */
1461void
8e2745f4 1462ClientHttpRequest::processRequest()
edce4d98 1463{
7f06a3d8 1464 debugs(85, 4, request->method << ' ' << uri);
62e76326 1465
6b2b6cfe
CT
1466 const bool untouchedConnect = request->method == Http::METHOD_CONNECT && !redirect.status;
1467
cb4f4424 1468#if USE_OPENSSL
6b2b6cfe
CT
1469 if (untouchedConnect && sslBumpNeeded()) {
1470 assert(!request->flags.forceTunnel);
1471 sslBumpStart();
1472 return;
1473 }
3712be3f 1474#endif
6b2b6cfe
CT
1475
1476 if (untouchedConnect || request->flags.forceTunnel) {
f84dd7eb 1477 getConn()->stopReading(); // tunnels read for themselves
ac9f46af 1478 tunnelStart(this);
62e76326 1479 return;
edce4d98 1480 }
62e76326 1481
8e2745f4 1482 httpStart();
1483}
1484
1485void
1486ClientHttpRequest::httpStart()
1487{
d2a6dcba 1488 // XXX: Re-initializes rather than updates. Should not be needed at all.
12f5a662
EB
1489 updateLoggingTags(LOG_TAG_NONE);
1490 debugs(85, 4, loggingTags().c_str() << " for '" << uri << "'");
bf8fe701 1491
edce4d98 1492 /* no one should have touched this */
8e2745f4 1493 assert(out.offset == 0);
edce4d98 1494 /* Use the Stream Luke */
8e2745f4 1495 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1496 clientStreamRead(node, this, node->readBuffer);
edce4d98 1497}
0655fa4d 1498
cb4f4424 1499#if USE_OPENSSL
3712be3f 1500
e0c0d54c 1501void
08097970 1502ClientHttpRequest::sslBumpNeed(Ssl::BumpMode mode)
e0c0d54c 1503{
bf95c10a 1504 debugs(83, 3, "sslBump required: "<< Ssl::bumpMode(mode));
08097970 1505 sslBumpNeed_ = mode;
3712be3f 1506}
1507
1508// called when comm_write has completed
1509static void
c8407295 1510SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, Comm::Flag errflag, int, void *data)
3712be3f 1511{
1512 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
bf95c10a 1513 debugs(85, 5, "responded to CONNECT: " << r << " ? " << errflag);
3712be3f 1514
1515 assert(r && cbdataReferenceValid(r));
1516 r->sslBumpEstablish(errflag);
1517}
1518
1519void
c8407295 1520ClientHttpRequest::sslBumpEstablish(Comm::Flag errflag)
3712be3f 1521{
c8407295
AJ
1522 // Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up
1523 if (errflag == Comm::ERR_CLOSING)
3712be3f 1524 return;
1525
1526 if (errflag) {
bf95c10a 1527 debugs(85, 3, "CONNECT response failure in SslBump: " << errflag);
bbc83914 1528 getConn()->clientConnection->close();
3712be3f 1529 return;
1530 }
1531
21512911
CT
1532#if USE_AUTH
1533 // Preserve authentication info for the ssl-bumped request
aee3523a 1534 if (request->auth_user_request != nullptr)
cc1e110a 1535 getConn()->setAuth(request->auth_user_request, "SSL-bumped CONNECT");
21512911 1536#endif
03f00a11 1537
08097970 1538 assert(sslBumpNeeded());
f5e17947 1539 getConn()->switchToHttps(this, sslBumpNeed_);
3712be3f 1540}
1541
1542void
1543ClientHttpRequest::sslBumpStart()
1544{
bf95c10a 1545 debugs(85, 5, "Confirming " << Ssl::bumpMode(sslBumpNeed_) <<
08097970
AR
1546 "-bumped CONNECT tunnel on FD " << getConn()->clientConnection);
1547 getConn()->sslBumpMode = sslBumpNeed_;
3712be3f 1548
9e104535 1549 AsyncCall::Pointer bumpCall = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
f53969cc 1550 CommIoCbPtrFun(&SslBumpEstablish, this));
9e104535
CT
1551
1552 if (request->flags.interceptTproxy || request->flags.intercepted) {
1553 CommIoCbParams &params = GetCommParams<CommIoCbParams>(bumpCall);
1554 params.flag = Comm::OK;
1555 params.conn = getConn()->clientConnection;
1556 ScheduleCallHere(bumpCall);
1557 return;
1558 }
1559
ea55799d
EB
1560 al->reply = HttpReply::MakeConnectionEstablished();
1561
1562 const auto mb = al->reply->pack();
08097970 1563 // send an HTTP 200 response to kick client SSL negotiation
3712be3f 1564 // TODO: Unify with tunnel.cc and add a Server(?) header
ea55799d
EB
1565 Comm::Write(getConn()->clientConnection, mb, bumpCall);
1566 delete mb;
3712be3f 1567}
1568
1569#endif
1570
83b053a0
CT
1571void
1572ClientHttpRequest::updateError(const Error &error)
1573{
1574 if (request)
1575 request->error.update(error);
1576 else
1577 al->updateError(error);
1578}
1579
0655fa4d 1580bool
1581ClientHttpRequest::gotEnough() const
1582{
66d51f4f 1583 // TODO: See also (and unify with) clientReplyContext::storeNotOKTransferDone()
7173d5b0 1584 int64_t contentLength =
66d51f4f 1585 memObject()->baseReply().bodySize(request->method);
0655fa4d 1586 assert(contentLength >= 0);
1587
1588 if (out.offset < contentLength)
1589 return false;
1590
1591 return true;
1592}
1593
86a2f789 1594void
1595ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1596{
1597 entry_ = newEntry;
1598}
1599
0976f8db 1600void
1601ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1602{
1603 if (loggingEntry_)
1bfe9ade 1604 loggingEntry_->unlock("ClientHttpRequest::loggingEntry");
0976f8db 1605
1606 loggingEntry_ = newEntry;
1607
1608 if (loggingEntry_)
1bfe9ade 1609 loggingEntry_->lock("ClientHttpRequest::loggingEntry");
0976f8db 1610}
86a2f789 1611
bec110e4
EB
1612void
1613ClientHttpRequest::initRequest(HttpRequest *aRequest)
1614{
1615 assignRequest(aRequest);
1616 if (const auto csd = getConn()) {
1617 if (!csd->notes()->empty())
1618 request->notes()->appendNewOnly(csd->notes().getRaw());
1619 }
1620 // al is created in the constructor
1621 assert(al);
1622 if (!al->request) {
1623 al->request = request;
1624 HTTPMSGLOCK(al->request);
1625 al->syncNotes(request);
1626 }
1627}
1628
1629void
1630ClientHttpRequest::resetRequest(HttpRequest *newRequest)
333c433b
EB
1631{
1632 const auto uriChanged = request->effectiveRequestUri() != newRequest->effectiveRequestUri();
1633 resetRequestXXX(newRequest, uriChanged);
1634}
1635
1636void
1637ClientHttpRequest::resetRequestXXX(HttpRequest *newRequest, const bool uriChanged)
bec110e4
EB
1638{
1639 assert(request != newRequest);
1640 clearRequest();
1641 assignRequest(newRequest);
1642 xfree(uri);
1643 uri = SBufToCstring(request->effectiveRequestUri());
333c433b
EB
1644
1645 if (uriChanged) {
1646 request->flags.redirected = true;
1647 checkForInternalAccess();
1648 }
1649}
1650
1651void
1652ClientHttpRequest::checkForInternalAccess()
1653{
1654 if (!internalCheck(request->url.path()))
1655 return;
1656
6793ad05 1657 if (request->url.port() == getMyPort() && internalHostnameIs(SBuf(request->url.host()))) {
333c433b
EB
1658 debugs(33, 3, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true));
1659 request->flags.internal = true;
1660 } else if (Config.onoff.global_internal_static && internalStaticCheck(request->url.path())) {
1661 debugs(33, 3, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true) << " (global_internal_static on)");
1662 request->url.setScheme(AnyP::PROTO_HTTP, "http");
1663 request->url.host(internalHostname());
1664 request->url.port(getMyPort());
1665 request->flags.internal = true;
1666 setLogUriToRequestUri();
1667 } else {
1668 debugs(33, 3, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true) << " (not this proxy)");
1669 }
1670
1671 if (ForSomeCacheManager(request->url.path()))
1672 request->flags.disableCacheUse("cache manager URL");
bec110e4
EB
1673}
1674
1675void
1676ClientHttpRequest::assignRequest(HttpRequest *newRequest)
1677{
1678 assert(newRequest);
1679 assert(!request);
1680 const_cast<HttpRequest *&>(request) = newRequest;
1681 HTTPMSGLOCK(request);
1682 setLogUriToRequestUri();
1683}
1684
1685void
1686ClientHttpRequest::clearRequest()
1687{
1688 HttpRequest *oldRequest = request;
1689 HTTPMSGUNLOCK(oldRequest);
1690 const_cast<HttpRequest *&>(request) = nullptr;
1691 absorbLogUri(nullptr);
1692}
1693
de31d06f 1694/*
1695 * doCallouts() - This function controls the order of "callout"
1696 * executions, including non-blocking access control checks, the
1697 * redirector, and ICAP. Previously, these callouts were chained
1698 * together such that "clientAccessCheckDone()" would call
1699 * "clientRedirectStart()" and so on.
1700 *
1701 * The ClientRequestContext (aka calloutContext) class holds certain
1702 * state data for the callout/callback operations. Previously
1703 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1704 * for a short time. ClientRequestContext would then delete itself
1705 * and pass control back to ClientHttpRequest when all callouts
1706 * were finished.
1707 *
1708 * This caused some problems for ICAP because we want to make the
1709 * ICAP callout after checking ACLs, but before checking the no_cache
1710 * list. We can't stuff the ICAP state into the ClientRequestContext
1711 * class because we still need the ICAP state after ClientRequestContext
1712 * goes away.
1713 *
1714 * Note that ClientRequestContext is created before the first call
1715 * to doCallouts().
1716 *
1717 * If one of the callouts notices that ClientHttpRequest is no
1718 * longer valid, it should call cbdataReferenceDone() so that
1719 * ClientHttpRequest's reference count goes to zero and it will get
1720 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1721 *
1722 * Note that we set the _done flags here before actually starting
1723 * the callout. This is strictly for convenience.
1724 */
1725
1726void
1727ClientHttpRequest::doCallouts()
1728{
1729 assert(calloutContext);
1730
38450a50 1731 if (!calloutContext->error) {
87f237a9 1732 // CVE-2009-0801: verify the Host: header is consistent with other known details.
38450a50 1733 if (!calloutContext->host_header_verify_done) {
bf95c10a 1734 debugs(83, 3, "Doing calloutContext->hostHeaderVerify()");
38450a50
CT
1735 calloutContext->host_header_verify_done = true;
1736 calloutContext->hostHeaderVerify();
1737 return;
1738 }
fe97983f 1739
38450a50 1740 if (!calloutContext->http_access_done) {
bf95c10a 1741 debugs(83, 3, "Doing calloutContext->clientAccessCheck()");
38450a50
CT
1742 calloutContext->http_access_done = true;
1743 calloutContext->clientAccessCheck();
1744 return;
1745 }
de31d06f 1746
a83c6ed6 1747#if USE_ADAPTATION
38450a50
CT
1748 if (!calloutContext->adaptation_acl_check_done) {
1749 calloutContext->adaptation_acl_check_done = true;
1750 if (Adaptation::AccessCheck::Start(
87f237a9 1751 Adaptation::methodReqmod, Adaptation::pointPreCache,
aee3523a 1752 request, nullptr, calloutContext->http->al, this))
38450a50
CT
1753 return; // will call callback
1754 }
de31d06f 1755#endif
1756
38450a50
CT
1757 if (!calloutContext->redirect_done) {
1758 calloutContext->redirect_done = true;
de31d06f 1759
38450a50 1760 if (Config.Program.redirect) {
bf95c10a 1761 debugs(83, 3, "Doing calloutContext->clientRedirectStart()");
38450a50
CT
1762 calloutContext->redirect_state = REDIRECT_PENDING;
1763 calloutContext->clientRedirectStart();
1764 return;
1765 }
de31d06f 1766 }
de31d06f 1767
38450a50 1768 if (!calloutContext->adapted_http_access_done) {
bf95c10a 1769 debugs(83, 3, "Doing calloutContext->clientAccessCheck2()");
38450a50
CT
1770 calloutContext->adapted_http_access_done = true;
1771 calloutContext->clientAccessCheck2();
1772 return;
1773 }
533493da 1774
a8a0b1c2
EC
1775 if (!calloutContext->store_id_done) {
1776 calloutContext->store_id_done = true;
a8a0b1c2
EC
1777
1778 if (Config.Program.store_id) {
1779 debugs(83, 3,"Doing calloutContext->clientStoreIdStart()");
1780 calloutContext->store_id_state = REDIRECT_PENDING;
1781 calloutContext->clientStoreIdStart();
1782 return;
1783 }
1784 }
1785
38450a50 1786 if (!calloutContext->interpreted_req_hdrs) {
bf95c10a 1787 debugs(83, 3, "Doing clientInterpretRequestHeaders()");
38450a50
CT
1788 calloutContext->interpreted_req_hdrs = 1;
1789 clientInterpretRequestHeaders(this);
1790 }
57abaac0 1791
38450a50
CT
1792 if (!calloutContext->no_cache_done) {
1793 calloutContext->no_cache_done = true;
de31d06f 1794
45e5102d 1795 if (Config.accessList.noCache && request->flags.cachable) {
bf95c10a 1796 debugs(83, 3, "Doing calloutContext->checkNoCache()");
38450a50
CT
1797 calloutContext->checkNoCache();
1798 return;
1799 }
de31d06f 1800 }
38450a50 1801 } // if !calloutContext->error
de31d06f 1802
244da4ad
AG
1803 // Set appropriate MARKs and CONNMARKs if needed.
1804 if (getConn() && Comm::IsConnOpen(getConn()->clientConnection)) {
1805 ACLFilledChecklist ch(nullptr, request, nullptr);
cb365059 1806 ch.al = calloutContext->http->al;
244da4ad
AG
1807 ch.src_addr = request->client_addr;
1808 ch.my_addr = request->my_addr;
cb365059 1809 ch.syncAle(request, log_uri);
244da4ad
AG
1810
1811 if (!calloutContext->toClientMarkingDone) {
1812 calloutContext->toClientMarkingDone = true;
425de4c8 1813 tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch);
3712be3f 1814 if (tos)
73c36fd9 1815 Ip::Qos::setSockTos(getConn()->clientConnection, tos);
425de4c8 1816
244da4ad
AG
1817 const auto packetMark = aclFindNfMarkConfig(Ip::Qos::TheConfig.nfmarkToClient, &ch);
1818 if (!packetMark.isEmpty())
1819 Ip::Qos::setSockNfmark(getConn()->clientConnection, packetMark.mark);
1820
1821 const auto connmark = aclFindNfMarkConfig(Ip::Qos::TheConfig.nfConnmarkToClient, &ch);
1822 if (!connmark.isEmpty())
1823 Ip::Qos::setNfConnmark(getConn()->clientConnection, Ip::Qos::dirAccepted, connmark);
3712be3f 1824 }
057f5854 1825 }
1826
cb4f4424 1827#if USE_OPENSSL
93046e07
CT
1828 // Even with calloutContext->error, we call sslBumpAccessCheck() to decide
1829 // whether SslBump applies to this transaction. If it applies, we will
1830 // attempt to bump the client to serve the error.
e0c0d54c
CT
1831 if (!calloutContext->sslBumpCheckDone) {
1832 calloutContext->sslBumpCheckDone = true;
1833 if (calloutContext->sslBumpAccessCheck())
1834 return;
1835 /* else no ssl bump required*/
1836 }
d2565320 1837#endif
e0c0d54c 1838
2bd84e5f 1839 if (calloutContext->error) {
851feda6 1840 // XXX: prformance regression. c_str() reallocates
81e019a0
AR
1841 SBuf storeUriBuf(request->storeId());
1842 const char *storeUri = storeUriBuf.c_str();
1843 StoreEntry *e = storeCreateEntry(storeUri, storeUri, request->flags, request->method);
cb4f4424 1844#if USE_OPENSSL
08097970 1845 if (sslBumpNeeded()) {
9e104535
CT
1846 // We have to serve an error, so bump the client first.
1847 sslBumpNeed(Ssl::bumpClientFirst);
2bd84e5f 1848 // set final error but delay sending until we bump
f5e17947 1849 Ssl::ServerBump *srvBump = new Ssl::ServerBump(this, e, Ssl::bumpClientFirst);
2bd84e5f 1850 errorAppendEntry(e, calloutContext->error);
aee3523a 1851 calloutContext->error = nullptr;
2bd84e5f 1852 getConn()->setServerBump(srvBump);
1bfe9ade 1853 e->unlock("ClientHttpRequest::doCallouts+sslBumpNeeded");
87f237a9 1854 } else
2bd84e5f
CT
1855#endif
1856 {
7a957a93 1857 // send the error to the client now
2bd84e5f
CT
1858 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1859 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1860 assert (repContext);
f0baf149 1861 repContext->setReplyToStoreEntry(e, "immediate SslBump error");
2bd84e5f 1862 errorAppendEntry(e, calloutContext->error);
aee3523a 1863 calloutContext->error = nullptr;
c3760363 1864 if (calloutContext->readNextRequest && getConn())
2bd84e5f
CT
1865 getConn()->flags.readMore = true; // resume any pipeline reads.
1866 node = (clientStreamNode *)client_stream.tail->data;
1867 clientStreamRead(node, this, node->readBuffer);
1bfe9ade 1868 e->unlock("ClientHttpRequest::doCallouts-sslBumpNeeded");
2bd84e5f
CT
1869 return;
1870 }
1871 }
1872
de31d06f 1873 cbdataReferenceDone(calloutContext->http);
1874 delete calloutContext;
aee3523a 1875 calloutContext = nullptr;
de31d06f 1876
bf95c10a 1877 debugs(83, 3, "calling processRequest()");
de31d06f 1878 processRequest();
3ff65596
AR
1879
1880#if ICAP_CLIENT
1881 Adaptation::Icap::History::Pointer ih = request->icapHistory();
aee3523a 1882 if (ih != nullptr)
12f5a662 1883 ih->logType = loggingTags();
3ff65596 1884#endif
de31d06f 1885}
1886
bec110e4
EB
1887void
1888ClientHttpRequest::setLogUriToRequestUri()
1889{
1890 assert(request);
1891 const auto canonicalUri = request->canonicalCleanUrl();
1892 absorbLogUri(xstrndup(canonicalUri, MAX_URL));
1893}
1894
1895void
1896ClientHttpRequest::setLogUriToRawUri(const char *rawUri, const HttpRequestMethod &method)
1897{
1898 assert(rawUri);
1899 // Should(!request);
1900
1901 // TODO: SBuf() performance regression, fix by converting rawUri to SBuf
1902 char *canonicalUri = urlCanonicalCleanWithoutRequest(SBuf(rawUri), method, AnyP::UriScheme());
1903
1904 absorbLogUri(AnyP::Uri::cleanup(canonicalUri));
1905
1906 char *cleanedRawUri = AnyP::Uri::cleanup(rawUri);
1907 al->setVirginUrlForMissingRequest(SBuf(cleanedRawUri));
1908 xfree(cleanedRawUri);
1909}
1910
1911void
1912ClientHttpRequest::absorbLogUri(char *aUri)
1913{
1914 xfree(log_uri);
1915 const_cast<char *&>(log_uri) = aUri;
1916}
1917
1918void
1919ClientHttpRequest::setErrorUri(const char *aUri)
1920{
1921 assert(!uri);
1922 assert(aUri);
1923 // Should(!request);
1924
1925 uri = xstrdup(aUri);
1926 // TODO: SBuf() performance regression, fix by converting setErrorUri() parameter to SBuf
1927 const SBuf errorUri(aUri);
1928 const auto canonicalUri = urlCanonicalCleanWithoutRequest(errorUri, HttpRequestMethod(), AnyP::UriScheme());
1929 absorbLogUri(xstrndup(canonicalUri, MAX_URL));
1930
1931 al->setVirginUrlForMissingRequest(errorUri);
1932}
1933
7024fb73
AR
1934// XXX: This should not be a _request_ method. Move range_iter elsewhere.
1935int64_t
1936ClientHttpRequest::prepPartialResponseGeneration()
1937{
1938 assert(request);
1939 assert(request->range);
1940
1941 range_iter.pos = request->range->begin();
1942 range_iter.end = request->range->end();
1943 range_iter.debt_size = 0;
1944 const auto multipart = request->range->specs.size() > 1;
1945 if (multipart)
1946 range_iter.boundary = rangeBoundaryStr();
1947 range_iter.valid = true; // TODO: Remove.
1948 range_iter.updateSpec(); // TODO: Refactor to initialize rather than update.
1949
1950 assert(range_iter.pos != range_iter.end);
1951 const auto &firstRange = *range_iter.pos;
1952 assert(firstRange);
1953 out.offset = firstRange->offset;
1954
1955 return multipart ? mRangeCLen() : firstRange->length;
1956}
1957
a83c6ed6 1958#if USE_ADAPTATION
a22e6cd3
AR
1959/// Initiate an asynchronous adaptation transaction which will call us back.
1960void
1961ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
3b299123 1962{
bf95c10a 1963 debugs(85, 3, "adaptation needed for " << this);
a83c6ed6
AR
1964 assert(!virginHeadSource);
1965 assert(!adaptedBodySource);
a22e6cd3 1966 virginHeadSource = initiateAdaptation(
aee3523a 1967 new Adaptation::Iterator(request, nullptr, al, g));
a83c6ed6 1968
e1381638 1969 // we could try to guess whether we can bypass this adaptation
a22e6cd3 1970 // initiation failure, but it should not really happen
4299f876 1971 Must(initiated(virginHeadSource));
de31d06f 1972}
1973
1974void
3af10ac0 1975ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer &answer)
de31d06f 1976{
f53969cc 1977 assert(cbdataReferenceValid(this)); // indicates bug
3af10ac0
AR
1978 clearAdaptation(virginHeadSource);
1979 assert(!adaptedBodySource);
1980
1981 switch (answer.kind) {
1982 case Adaptation::Answer::akForward:
63df1d28 1983 handleAdaptedHeader(const_cast<Http::Message*>(answer.message.getRaw()));
3af10ac0
AR
1984 break;
1985
1986 case Adaptation::Answer::akBlock:
1987 handleAdaptationBlock(answer);
1988 break;
1989
83b053a0
CT
1990 case Adaptation::Answer::akError: {
1991 static const auto d = MakeNamedErrorDetail("CLT_REQMOD_ABORT");
1992 handleAdaptationFailure(d, !answer.final);
3af10ac0
AR
1993 break;
1994 }
83b053a0 1995 }
3af10ac0
AR
1996}
1997
1998void
63df1d28 1999ClientHttpRequest::handleAdaptedHeader(Http::Message *msg)
3af10ac0 2000{
5f8252d2 2001 assert(msg);
2002
b044675d 2003 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
bec110e4 2004 resetRequest(new_req);
914b89a2 2005 assert(request->method.id());
b044675d 2006 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
bf95c10a 2007 debugs(85,3, "REQMOD reply is HTTP reply");
b044675d 2008
5f8252d2 2009 // subscribe to receive reply body
aee3523a 2010 if (new_rep->body_pipe != nullptr) {
a83c6ed6 2011 adaptedBodySource = new_rep->body_pipe;
d222a56c
HN
2012 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
2013 assert(consumer_ok);
5f8252d2 2014 }
2015
b044675d 2016 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
2017 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
ea25a575 2018 assert(repContext);
b044675d 2019 repContext->createStoreEntry(request->method, request->flags);
2020
b044675d 2021 request_satisfaction_mode = true;
2022 request_satisfaction_offset = 0;
2023 storeEntry()->replaceHttpReply(new_rep);
97ae5196 2024 storeEntry()->timestampsSet();
cb4c4288 2025
49f57088
EB
2026 al->reply = new_rep;
2027
a83c6ed6 2028 if (!adaptedBodySource) // no body
cb4c4288 2029 storeEntry()->complete();
b044675d 2030 clientGetMoreData(node, this);
200ac359 2031 }
de31d06f 2032
5f8252d2 2033 // we are done with getting headers (but may be receiving body)
a83c6ed6 2034 clearAdaptation(virginHeadSource);
5f8252d2 2035
b044675d 2036 if (!request_satisfaction_mode)
2037 doCallouts();
de31d06f 2038}
2039
2040void
3af10ac0 2041ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer &answer)
de31d06f 2042{
83b053a0
CT
2043 static const auto d = MakeNamedErrorDetail("REQMOD_BLOCK");
2044 request->detailError(ERR_ACCESS_DENIED, d);
3af10ac0 2045 assert(calloutContext);
25aa6c9a 2046 calloutContext->clientAccessCheckDone(answer.blockedToChecklistAnswer());
de31d06f 2047}
2048
0ad2b63b
CT
2049void
2050ClientHttpRequest::resumeBodyStorage()
2051{
e83cdc25 2052 if (!adaptedBodySource)
0ad2b63b
CT
2053 return;
2054
2055 noteMoreBodyDataAvailable(adaptedBodySource);
2056}
2057
de31d06f 2058void
1cf238db 2059ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
de31d06f 2060{
5f8252d2 2061 assert(request_satisfaction_mode);
aee3523a 2062 assert(adaptedBodySource != nullptr);
5f8252d2 2063
0ad2b63b 2064 if (size_t contentSize = adaptedBodySource->buf().contentSize()) {
4dc2b072 2065 const size_t spaceAvailable = storeEntry()->bytesWanted(Range<size_t>(0,contentSize));
0ad2b63b
CT
2066
2067 if (spaceAvailable < contentSize ) {
2068 // No or partial body data consuming
2069 typedef NullaryMemFunT<ClientHttpRequest> Dialer;
2070 AsyncCall::Pointer call = asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage",
2071 Dialer(this, &ClientHttpRequest::resumeBodyStorage));
2072 storeEntry()->deferProducer(call);
2073 }
2074
4dc2b072 2075 if (!spaceAvailable)
0ad2b63b
CT
2076 return;
2077
2078 if (spaceAvailable < contentSize )
2079 contentSize = spaceAvailable;
2080
a83c6ed6 2081 BodyPipeCheckout bpc(*adaptedBodySource);
0ad2b63b 2082 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset, contentSize);
5f8252d2 2083 storeEntry()->write(ioBuf);
0ad2b63b
CT
2084 // assume StoreEntry::write() writes the entire ioBuf
2085 request_satisfaction_offset += ioBuf.length;
4ce0e99b 2086 bpc.buf.consume(contentSize);
5f8252d2 2087 bpc.checkIn();
2088 }
2089
3f267b93
AN
2090 if (adaptedBodySource->exhausted()) {
2091 // XXX: Setting receivedWholeAdaptedReply here is a workaround for a
2092 // regression, as described in https://bugs.squid-cache.org/show_bug.cgi?id=5187#c6
2093 receivedWholeAdaptedReply = true;
853de11d 2094 debugs(85, Important(72), "WARNING: Squid bug 5187 workaround triggered");
5f8252d2 2095 endRequestSatisfaction();
3f267b93 2096 }
5f8252d2 2097 // else wait for more body data
de31d06f 2098}
2099
2100void
1cf238db 2101ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
de31d06f 2102{
a83c6ed6 2103 assert(!virginHeadSource);
ba3fe8d9
EB
2104
2105 // distinguish this code path from future noteBodyProducerAborted() that
2106 // would continue storing/delivering (truncated) reply if necessary (TODO)
2107 receivedWholeAdaptedReply = true;
2108
0ad2b63b 2109 // should we end request satisfaction now?
aee3523a 2110 if (adaptedBodySource != nullptr && adaptedBodySource->exhausted())
5f8252d2 2111 endRequestSatisfaction();
5f8252d2 2112}
3b299123 2113
5f8252d2 2114void
26ac0430
AJ
2115ClientHttpRequest::endRequestSatisfaction()
2116{
bf95c10a 2117 debugs(85,4, this << " ends request satisfaction");
5f8252d2 2118 assert(request_satisfaction_mode);
a83c6ed6 2119 stopConsumingFrom(adaptedBodySource);
3b299123 2120
5f8252d2 2121 // TODO: anything else needed to end store entry formation correctly?
ba3fe8d9
EB
2122 if (receivedWholeAdaptedReply) {
2123 // We received the entire reply per receivedWholeAdaptedReply.
2124 // We are called when we consumed everything received (per our callers).
2125 // We consume only what we store per noteMoreBodyDataAvailable().
2126 storeEntry()->completeSuccessfully("received, consumed, and, hence, stored the entire REQMOD reply");
2127 } else {
2128 storeEntry()->completeTruncated("REQMOD request satisfaction default");
2129 }
5f8252d2 2130}
de31d06f 2131
5f8252d2 2132void
1cf238db 2133ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
5f8252d2 2134{
a83c6ed6
AR
2135 assert(!virginHeadSource);
2136 stopConsumingFrom(adaptedBodySource);
eae3a9a6 2137
bf95c10a 2138 debugs(85,3, "REQMOD body production failed");
eae3a9a6 2139 if (request_satisfaction_mode) { // too late to recover or serve an error
83b053a0
CT
2140 static const auto d = MakeNamedErrorDetail("CLT_REQMOD_RESP_BODY");
2141 request->detailError(ERR_ICAP_FAILURE, d);
73c36fd9 2142 const Comm::ConnectionPointer c = getConn()->clientConnection;
e7cea0ed
AJ
2143 Must(Comm::IsConnOpen(c));
2144 c->close(); // drastic, but we may be writing a response already
eae3a9a6 2145 } else {
83b053a0
CT
2146 static const auto d = MakeNamedErrorDetail("CLT_REQMOD_REQ_BODY");
2147 handleAdaptationFailure(d);
eae3a9a6 2148 }
5f8252d2 2149}
3b299123 2150
5f8252d2 2151void
83b053a0 2152ClientHttpRequest::handleAdaptationFailure(const ErrorDetail::Pointer &errDetail, bool bypassable)
5f8252d2 2153{
bf95c10a 2154 debugs(85,3, "handleAdaptationFailure(" << bypassable << ")");
3b299123 2155
5f8252d2 2156 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
aee3523a 2157 const bool usedPipe = request->body_pipe != nullptr &&
26ac0430 2158 request->body_pipe->consumedSize() > 0;
3b299123 2159
9d4d7c5e 2160 if (bypassable && !usedStore && !usedPipe) {
bf95c10a 2161 debugs(85,3, "ICAP REQMOD callout failed, bypassing: " << calloutContext);
5f8252d2 2162 if (calloutContext)
2163 doCallouts();
2164 return;
2165 }
3b299123 2166
bf95c10a 2167 debugs(85,3, "ICAP REQMOD callout failed, responding with error");
3b299123 2168
5f8252d2 2169 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
2170 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2171 assert(repContext);
de31d06f 2172
32fd6d8a
CT
2173 calloutsError(ERR_ICAP_FAILURE, errDetail);
2174
2175 if (calloutContext)
2176 doCallouts();
2177}
2178
9d52ba11
CT
2179void
2180ClientHttpRequest::callException(const std::exception &ex)
2181{
2182 if (const auto clientConn = getConn() ? getConn()->clientConnection : nullptr) {
2183 if (Comm::IsConnOpen(clientConn)) {
2184 debugs(85, 3, "closing after exception: " << ex.what());
2185 clientConn->close(); // initiate orderly top-to-bottom cleanup
2186 return;
2187 }
2188 }
2189 debugs(85, DBG_IMPORTANT, "ClientHttpRequest exception without connection. Ignoring " << ex.what());
2190 // XXX: Normally, we mustStop() but we cannot do that here because it is
2191 // likely to leave Http::Stream and ConnStateData with a dangling http
2192 // pointer. See r13480 or XXX in Http::Stream class description.
2193}
5f1d7e48
CT
2194#endif
2195
32fd6d8a
CT
2196// XXX: modify and use with ClientRequestContext::clientAccessCheckDone too.
2197void
83b053a0 2198ClientHttpRequest::calloutsError(const err_type error, const ErrorDetail::Pointer &errDetail)
32fd6d8a 2199{
26ac0430 2200 // The original author of the code also wanted to pass an errno to
5f8252d2 2201 // setReplyToError, but it seems unlikely that the errno reflects the
2202 // true cause of the error at this point, so I did not pass it.
2bd84e5f 2203 if (calloutContext) {
2bd84e5f 2204 ConnStateData * c = getConn();
32fd6d8a 2205 calloutContext->error = clientBuildError(error, Http::scInternalServerError,
7976fed3 2206 nullptr, c, request, al);
79fc6915 2207#if USE_AUTH
87f237a9 2208 calloutContext->error->auth_user_request =
aee3523a 2209 c != nullptr && c->getAuth() != nullptr ? c->getAuth() : request->auth_user_request;
79fc6915 2210#endif
129fe2a1 2211 calloutContext->error->detailError(errDetail);
2bd84e5f 2212 calloutContext->readNextRequest = true;
aee3523a 2213 if (c != nullptr)
7830d88a 2214 c->expectNoForwarding();
2bd84e5f
CT
2215 }
2216 //else if(calloutContext == NULL) is it possible?
de31d06f 2217}
2218