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