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