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