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