2 * Copyright (C) 1996-2023 The Squid Software Foundation and contributors
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.
9 /* DEBUG: section 85 Client-side Request Routines */
12 * General logic of request processing:
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.
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 "error/Detail.h"
32 #include "errorpage.h"
35 #include "format/Token.h"
38 #include "helper/Reply.h"
40 #include "http/Stream.h"
41 #include "HttpHdrCc.h"
42 #include "HttpReply.h"
43 #include "HttpRequest.h"
44 #include "ip/NfMarkConfig.h"
45 #include "ip/QosConfig.h"
47 #include "log/access_log.h"
48 #include "MemObject.h"
50 #include "proxyp/Header.h"
53 #include "sbuf/StringConvert.h"
54 #include "SquidConfig.h"
60 #include "auth/UserRequest.h"
63 #include "adaptation/AccessCheck.h"
64 #include "adaptation/Answer.h"
65 #include "adaptation/Iterator.h"
66 #include "adaptation/Service.h"
68 #include "adaptation/icap/History.h"
72 #include "ssl/ServerBump.h"
73 #include "ssl/support.h"
76 #if FOLLOW_X_FORWARDED_FOR
77 static void clientFollowXForwardedForCheck(Acl::Answer answer
, void *data
);
78 #endif /* FOLLOW_X_FORWARDED_FOR */
80 ErrorState
*clientBuildError(err_type
, Http::StatusCode
, char const *url
, const ConnStateData
*, HttpRequest
*, const AccessLogEntry::Pointer
&);
82 CBDATA_CLASS_INIT(ClientRequestContext
);
86 static void clientAccessCheckDoneWrapper(Acl::Answer
, void *);
88 static void sslBumpAccessCheckDoneWrapper(Acl::Answer
, void *);
90 static int clientHierarchical(ClientHttpRequest
* http
);
91 static void clientInterpretRequestHeaders(ClientHttpRequest
* http
);
92 static HLPCB clientRedirectDoneWrapper
;
93 static HLPCB clientStoreIdDoneWrapper
;
94 static void checkNoCacheDoneWrapper(Acl::Answer
, void *);
95 SQUIDCEXTERN CSR clientGetMoreData
;
96 SQUIDCEXTERN CSS clientReplyStatus
;
97 SQUIDCEXTERN CSD clientReplyDetach
;
98 static void checkFailureRatio(err_type
, hier_code
);
100 ClientRequestContext::~ClientRequestContext()
103 * Release our "lock" on our parent, ClientHttpRequest, if we
108 cbdataReferenceDone(http
);
111 debugs(85,3, "ClientRequestContext destructed, this=" << this);
114 ClientRequestContext::ClientRequestContext(ClientHttpRequest
*anHttp
) :
115 http(cbdataReference(anHttp
))
117 debugs(85, 3, "ClientRequestContext constructed, this=" << this);
120 CBDATA_CLASS_INIT(ClientHttpRequest
);
122 ClientHttpRequest::ClientHttpRequest(ConnStateData
* aConn
) :
124 AsyncJob("ClientHttpRequest"),
126 al(new AccessLogEntry()),
127 conn_(cbdataReference(aConn
))
129 CodeContext::Reset(al
);
130 al
->cache
.start_time
= current_time
;
132 al
->tcpClient
= aConn
->clientConnection
;
133 al
->cache
.port
= aConn
->port
;
134 al
->cache
.caddr
= aConn
->log_addr
;
135 al
->proxyProtocolHeader
= aConn
->proxyProtocolHeader();
136 al
->updateError(aConn
->bareError
);
139 if (aConn
->clientConnection
!= nullptr && aConn
->clientConnection
->isOpen()) {
140 if (auto ssl
= fd_table
[aConn
->clientConnection
->fd
].ssl
.get())
141 al
->cache
.sslClientCert
.resetWithoutLocking(SSL_get_peer_certificate(ssl
));
145 dlinkAdd(this, &active
, &ClientActiveRequests
);
149 * returns true if client specified that the object must come from the cache
150 * without contacting origin server
153 ClientHttpRequest::onlyIfCached()const
156 return request
->cache_control
&&
157 request
->cache_control
->hasOnlyIfCached();
161 * This function is designed to serve a fairly specific purpose.
162 * Occasionally our vBNS-connected caches can talk to each other, but not
163 * the rest of the world. Here we try to detect frequent failures which
164 * make the cache unusable (e.g. DNS lookup and connect() failures). If
165 * the failure:success ratio goes above 1.0 then we go into "hit only"
166 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
167 * will only fetch HITs from us if they are using the ICP protocol. We
168 * stay in this mode for 5 minutes.
170 * Duane W., Sept 16, 1996
173 checkFailureRatio(err_type etype
, hier_code hcode
)
175 // Can be set at compile time with -D compiler flag
176 #ifndef FAILURE_MODE_TIME
177 #define FAILURE_MODE_TIME 300
180 if (hcode
== HIER_NONE
)
183 // don't bother when ICP is disabled.
184 if (Config
.Port
.icp
<= 0)
187 static double magic_factor
= 100.0;
191 n_good
= magic_factor
/ (1.0 + request_failure_ratio
);
193 n_bad
= magic_factor
- n_good
;
199 case ERR_CONNECT_FAIL
:
200 case ERR_SECURE_CONNECT_FAIL
:
210 request_failure_ratio
= n_bad
/ n_good
;
212 if (hit_only_mode_until
> squid_curtime
)
215 if (request_failure_ratio
< 1.0)
218 debugs(33, DBG_CRITICAL
, "WARNING: Failure Ratio at "<< std::setw(4)<<
219 std::setprecision(3) << request_failure_ratio
);
221 debugs(33, DBG_CRITICAL
, "WARNING: ICP going into HIT-only mode for " <<
222 FAILURE_MODE_TIME
/ 60 << " minutes...");
224 hit_only_mode_until
= squid_curtime
+ FAILURE_MODE_TIME
;
226 request_failure_ratio
= 0.8; /* reset to something less than 1.0 */
229 ClientHttpRequest::~ClientHttpRequest()
231 debugs(33, 3, "httpRequestFree: " << uri
);
233 // Even though freeResources() below may destroy the request,
234 // we no longer set request->body_pipe to NULL here
235 // because we did not initiate that pipe (ConnStateData did)
237 /* the ICP check here was erroneous
238 * - StoreEntry::releaseRequest was always called if entry was valid
243 loggingEntry(nullptr);
246 checkFailureRatio(request
->error
.category
, al
->hier
.code
);
251 announceInitiatorAbort(virginHeadSource
);
253 if (adaptedBodySource
!= nullptr)
254 stopConsumingFrom(adaptedBodySource
);
257 delete calloutContext
;
260 cbdataReferenceDone(conn_
);
262 /* moving to the next connection is handled by the context free */
263 dlinkDelete(&active
, &ClientActiveRequests
);
267 * Create a request and kick it off
272 * TODO: Pass in the buffers to be used in the initial Read request, as they are
273 * determined by the user
276 clientBeginRequest(const HttpRequestMethod
& method
, char const *url
, CSCB
* streamcallback
,
277 CSD
* streamdetach
, ClientStreamData streamdata
, HttpHeader
const *header
,
278 char *tailbuf
, size_t taillen
, const MasterXaction::Pointer
&mx
)
281 ClientHttpRequest
*http
= new ClientHttpRequest(nullptr);
282 HttpRequest
*request
;
283 StoreIOBuffer tempBuffer
;
284 if (http
->al
!= nullptr)
285 http
->al
->cache
.start_time
= current_time
;
286 /* this is only used to adjust the connection offset in client_side.c */
288 tempBuffer
.length
= taillen
;
289 tempBuffer
.data
= tailbuf
;
290 /* client stream setup */
291 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
292 clientReplyStatus
, new clientReplyContext(http
), streamcallback
,
293 streamdetach
, streamdata
, tempBuffer
);
294 /* make it visible in the 'current acctive requests list' */
296 /* internal requests only makes sense in an
297 * accelerator today. TODO: accept flags ? */
298 http
->flags
.accel
= true;
299 /* allow size for url rewriting */
300 url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
301 http
->uri
= (char *)xcalloc(url_sz
, 1);
302 strcpy(http
->uri
, url
); // XXX: polluting http->uri before parser validation
304 request
= HttpRequest::FromUrlXXX(http
->uri
, mx
, method
);
306 debugs(85, 5, "Invalid URL: " << http
->uri
);
311 * now update the headers in request with our supplied headers.
312 * HttpRequest::FromUrl() should return a blank header set, but
313 * we use Update to be sure of correctness.
316 request
->header
.update(header
);
318 /* http struct now ready */
321 * build new header list *? TODO
323 request
->flags
.accelerated
= http
->flags
.accel
;
325 /* this is an internally created
326 * request, not subject to acceleration
327 * target overrides */
328 // TODO: detect and handle internal requests of internal objects?
330 /* Internally created requests cannot have bodies today */
331 request
->content_length
= 0;
333 request
->client_addr
.setNoAddr();
335 #if FOLLOW_X_FORWARDED_FOR
336 request
->indirect_client_addr
.setNoAddr();
337 #endif /* FOLLOW_X_FORWARDED_FOR */
339 request
->my_addr
.setNoAddr(); /* undefined for internal requests */
341 request
->my_addr
.port(0);
343 request
->http_ver
= Http::ProtocolVersion();
345 http
->initRequest(request
);
347 /* optional - skip the access check ? */
348 http
->calloutContext
= new ClientRequestContext(http
);
350 http
->calloutContext
->http_access_done
= false;
352 http
->calloutContext
->redirect_done
= true;
354 http
->calloutContext
->no_cache_done
= true;
362 ClientRequestContext::httpStateIsValid()
364 ClientHttpRequest
*http_
= http
;
366 if (cbdataReferenceValid(http_
))
371 cbdataReferenceDone(http_
);
376 #if FOLLOW_X_FORWARDED_FOR
378 * clientFollowXForwardedForCheck() checks the content of X-Forwarded-For:
379 * against the followXFF ACL, or cleans up and passes control to
380 * clientAccessCheck().
382 * The trust model here is a little ambiguous. So to clarify the logic:
383 * - we may always use the direct client address as the client IP.
384 * - these trust tests merey tell whether we trust given IP enough to believe the
385 * IP string which it appended to the X-Forwarded-For: header.
386 * - if at any point we don't trust what an IP adds we stop looking.
387 * - at that point the current contents of indirect_client_addr are the value set
388 * by the last previously trusted IP.
389 * ++ indirect_client_addr contains the remote direct client from the trusted peers viewpoint.
392 clientFollowXForwardedForCheck(Acl::Answer answer
, void *data
)
394 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
396 if (!calloutContext
->httpStateIsValid())
399 ClientHttpRequest
*http
= calloutContext
->http
;
400 HttpRequest
*request
= http
->request
;
402 if (answer
.allowed() && request
->x_forwarded_for_iterator
.size() != 0) {
405 * Remove the last comma-delimited element from the
406 * x_forwarded_for_iterator and use it to repeat the cycle.
409 const char *asciiaddr
;
412 p
= request
->x_forwarded_for_iterator
.termedBuf();
413 l
= request
->x_forwarded_for_iterator
.size();
416 * XXX x_forwarded_for_iterator should really be a list of
417 * IP addresses, but it's a String instead. We have to
418 * walk backwards through the String, biting off the last
419 * comma-delimited part each time. As long as the data is in
420 * a String, we should probably implement and use a variant of
421 * strListGetItem() that walks backwards instead of forwards
422 * through a comma-separated list. But we don't even do that;
423 * we just do the work in-line here.
425 /* skip trailing space and commas */
426 while (l
> 0 && (p
[l
-1] == ',' || xisspace(p
[l
-1])))
428 request
->x_forwarded_for_iterator
.cut(l
);
429 /* look for start of last item in list */
430 while (l
> 0 && ! (p
[l
-1] == ',' || xisspace(p
[l
-1])))
433 if ((addr
= asciiaddr
)) {
434 request
->indirect_client_addr
= addr
;
435 request
->x_forwarded_for_iterator
.cut(l
);
436 calloutContext
->acl_checklist
= clientAclChecklistCreate(Config
.accessList
.followXFF
, http
);
437 if (!Config
.onoff
.acl_uses_indirect_client
) {
438 /* override the default src_addr tested if we have to go deeper than one level into XFF */
439 Filled(calloutContext
->acl_checklist
)->src_addr
= request
->indirect_client_addr
;
441 calloutContext
->acl_checklist
->nonBlockingCheck(clientFollowXForwardedForCheck
, data
);
446 /* clean up, and pass control to clientAccessCheck */
447 if (Config
.onoff
.log_uses_indirect_client
) {
449 * Ensure that the access log shows the indirect client
450 * instead of the direct client.
452 http
->al
->cache
.caddr
= request
->indirect_client_addr
;
453 if (ConnStateData
*conn
= http
->getConn())
454 conn
->log_addr
= request
->indirect_client_addr
;
456 request
->x_forwarded_for_iterator
.clean();
457 request
->flags
.done_follow_x_forwarded_for
= true;
459 if (answer
.conflicted()) {
460 debugs(28, DBG_CRITICAL
, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request
->indirect_client_addr
);
463 /* process actual access ACL as normal. */
464 calloutContext
->clientAccessCheck();
466 #endif /* FOLLOW_X_FORWARDED_FOR */
469 hostHeaderIpVerifyWrapper(const ipcache_addrs
* ia
, const Dns::LookupDetails
&dns
, void *data
)
471 ClientRequestContext
*c
= static_cast<ClientRequestContext
*>(data
);
472 c
->hostHeaderIpVerify(ia
, dns
);
476 ClientRequestContext::hostHeaderIpVerify(const ipcache_addrs
* ia
, const Dns::LookupDetails
&dns
)
478 Comm::ConnectionPointer clientConn
= http
->getConn()->clientConnection
;
480 // note the DNS details for the transaction stats.
481 http
->request
->recordLookup(dns
);
483 // Is the NAT destination IP in DNS?
484 if (ia
&& ia
->have(clientConn
->local
)) {
485 debugs(85, 3, "validate IP " << clientConn
->local
<< " possible from Host:");
486 http
->request
->flags
.hostVerified
= true;
490 debugs(85, 3, "FAIL: validate IP " << clientConn
->local
<< " possible from Host:");
491 hostHeaderVerifyFailed("local IP", "any domain IP");
495 ClientRequestContext::hostHeaderVerifyFailed(const char *A
, const char *B
)
497 // IP address validation for Host: failed. Admin wants to ignore them.
498 // NP: we do not yet handle CONNECT tunnels well, so ignore for them
499 if (!Config
.onoff
.hostStrictVerify
&& http
->request
->method
!= Http::METHOD_CONNECT
) {
500 debugs(85, 3, "SECURITY ALERT: Host header forgery detected on " << http
->getConn()->clientConnection
<<
501 " (" << A
<< " does not match " << B
<< ") on URL: " << http
->request
->effectiveRequestUri());
503 // MUST NOT cache (for now). It is tempting to set flags.noCache, but
504 // that flag is about satisfying _this_ request. We are actually OK with
505 // satisfying this request from the cache, but want to prevent _other_
506 // requests from being satisfied using this response.
507 http
->request
->flags
.cachable
.veto();
509 // XXX: when we have updated the cache key to base on raw-IP + URI this cacheable limit can go.
510 http
->request
->flags
.hierarchical
= false; // MUST NOT pass to peers (for now)
511 // XXX: when we have sorted out the best way to relay requests properly to peers this hierarchical limit can go.
516 debugs(85, DBG_IMPORTANT
, "SECURITY ALERT: Host header forgery detected on " <<
517 http
->getConn()->clientConnection
<< " (" << A
<< " does not match " << B
<< ")");
518 if (const char *ua
= http
->request
->header
.getStr(Http::HdrType::USER_AGENT
))
519 debugs(85, DBG_IMPORTANT
, "SECURITY ALERT: By user agent: " << ua
);
520 debugs(85, DBG_IMPORTANT
, "SECURITY ALERT: on URL: " << http
->request
->effectiveRequestUri());
522 // IP address validation for Host: failed. reject the connection.
523 clientStreamNode
*node
= (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
524 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
526 repContext
->setReplyToError(ERR_CONFLICT_HOST
, Http::scConflict
,
532 http
->getConn() != nullptr && http
->getConn()->getAuth() != nullptr ?
533 http
->getConn()->getAuth() : http
->request
->auth_user_request
);
537 node
= (clientStreamNode
*)http
->client_stream
.tail
->data
;
538 clientStreamRead(node
, http
, node
->readBuffer
);
542 ClientRequestContext::hostHeaderVerify()
544 // Require a Host: header.
545 const char *host
= http
->request
->header
.getStr(Http::HdrType::HOST
);
548 // TODO: dump out the HTTP/1.1 error about missing host header.
549 // otherwise this is fine, can't forge a header value when its not even set.
550 debugs(85, 3, "validate skipped with no Host: header present.");
555 if (http
->request
->flags
.internal
) {
556 // TODO: kill this when URL handling allows partial URLs out of accel mode
557 // and we no longer screw with the URL just to add our internal host there
558 debugs(85, 6, "validate skipped due to internal composite URL.");
563 // TODO: Unify Host value parsing below with AnyP::Uri authority parsing
564 // Locate if there is a port attached, strip ready for IP lookup
565 char *portStr
= nullptr;
566 char *hostB
= xstrdup(host
);
568 if (host
[0] == '[') {
570 portStr
= strchr(hostB
, ']');
571 if (portStr
&& *(++portStr
) != ':') {
575 // Domain or IPv4 literal with port
576 portStr
= strrchr(hostB
, ':');
581 *portStr
= '\0'; // strip the ':'
582 if (*(++portStr
) != '\0') {
584 int64_t ret
= strtoll(portStr
, &end
, 10);
585 if (end
== portStr
|| *end
!= '\0' || ret
< 1 || ret
> 0xFFFF) {
586 // invalid port details. Replace the ':'
590 port
= (ret
& 0xFFFF);
594 debugs(85, 3, "validate host=" << host
<< ", port=" << port
<< ", portStr=" << (portStr
?portStr
:"NULL"));
595 if (http
->request
->flags
.intercepted
|| http
->request
->flags
.interceptTproxy
) {
596 // verify the Host: port (if any) matches the apparent destination
597 if (portStr
&& port
!= http
->getConn()->clientConnection
->local
.port()) {
598 debugs(85, 3, "FAIL on validate port " << http
->getConn()->clientConnection
->local
.port() <<
599 " matches Host: port " << port
<< " (" << portStr
<< ")");
600 hostHeaderVerifyFailed("intercepted port", portStr
);
602 // XXX: match the scheme default port against the apparent destination
604 // verify the destination DNS is one of the Host: headers IPs
605 ipcache_nbgethostbyname(host
, hostHeaderIpVerifyWrapper
, this);
607 } else if (!Config
.onoff
.hostStrictVerify
) {
608 debugs(85, 3, "validate skipped.");
610 } else if (strlen(host
) != strlen(http
->request
->url
.host())) {
611 // Verify forward-proxy requested URL domain matches the Host: header
612 debugs(85, 3, "FAIL on validate URL domain length " << http
->request
->url
.host() << " matches Host: " << host
);
613 hostHeaderVerifyFailed(host
, http
->request
->url
.host());
614 } else if (matchDomainName(host
, http
->request
->url
.host()) != 0) {
615 // Verify forward-proxy requested URL domain matches the Host: header
616 debugs(85, 3, "FAIL on validate URL domain " << http
->request
->url
.host() << " matches Host: " << host
);
617 hostHeaderVerifyFailed(host
, http
->request
->url
.host());
618 } else if (portStr
&& !http
->request
->url
.port()) {
619 debugs(85, 3, "FAIL on validate portless URI matches Host: " << portStr
);
620 hostHeaderVerifyFailed("portless URI", portStr
);
621 } else if (portStr
&& port
!= *http
->request
->url
.port()) {
622 // Verify forward-proxy requested URL domain matches the Host: header
623 debugs(85, 3, "FAIL on validate URL port " << *http
->request
->url
.port() << " matches Host: port " << portStr
);
624 hostHeaderVerifyFailed("URL port", portStr
);
625 } else if (!portStr
&& http
->request
->method
!= Http::METHOD_CONNECT
&& http
->request
->url
.port() != http
->request
->url
.getScheme().defaultPort()) {
626 // Verify forward-proxy requested URL domain matches the Host: header
627 // Special case: we don't have a default-port to check for CONNECT. Assume URL is correct.
628 debugs(85, 3, "FAIL on validate URL port " << http
->request
->url
.port().value_or(0) << " matches Host: default port " << http
->request
->url
.getScheme().defaultPort().value_or(0));
629 hostHeaderVerifyFailed("URL port", "default port");
632 debugs(85, 3, "validate passed.");
633 http
->request
->flags
.hostVerified
= true;
639 /* This is the entry point for external users of the client_side routines */
641 ClientRequestContext::clientAccessCheck()
643 #if FOLLOW_X_FORWARDED_FOR
644 if (!http
->request
->flags
.doneFollowXff() &&
645 Config
.accessList
.followXFF
&&
646 http
->request
->header
.has(Http::HdrType::X_FORWARDED_FOR
)) {
648 /* we always trust the direct client address for actual use */
649 http
->request
->indirect_client_addr
= http
->request
->client_addr
;
650 http
->request
->indirect_client_addr
.port(0);
652 /* setup the XFF iterator for processing */
653 http
->request
->x_forwarded_for_iterator
= http
->request
->header
.getList(Http::HdrType::X_FORWARDED_FOR
);
655 /* begin by checking to see if we trust direct client enough to walk XFF */
656 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.followXFF
, http
);
657 acl_checklist
->nonBlockingCheck(clientFollowXForwardedForCheck
, this);
662 if (Config
.accessList
.http
) {
663 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.http
, http
);
664 acl_checklist
->nonBlockingCheck(clientAccessCheckDoneWrapper
, this);
666 debugs(0, DBG_CRITICAL
, "No http_access configuration found. This will block ALL traffic");
667 clientAccessCheckDone(ACCESS_DENIED
);
672 * Identical in operation to clientAccessCheck() but performed later using different configured ACL list.
673 * The default here is to allow all. Since the earlier http_access should do a default deny all.
674 * This check is just for a last-minute denial based on adapted request headers.
677 ClientRequestContext::clientAccessCheck2()
679 if (Config
.accessList
.adapted_http
) {
680 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.adapted_http
, http
);
681 acl_checklist
->nonBlockingCheck(clientAccessCheckDoneWrapper
, this);
683 debugs(85, 2, "No adapted_http_access configuration. default: ALLOW");
684 clientAccessCheckDone(ACCESS_ALLOWED
);
689 clientAccessCheckDoneWrapper(Acl::Answer answer
, void *data
)
691 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
693 if (!calloutContext
->httpStateIsValid())
696 calloutContext
->clientAccessCheckDone(answer
);
700 ClientRequestContext::clientAccessCheckDone(const Acl::Answer
&answer
)
702 acl_checklist
= nullptr;
704 Http::StatusCode status
;
705 debugs(85, 2, "The request " << http
->request
->method
<< ' ' <<
706 http
->uri
<< " is " << answer
<<
707 "; last ACL checked: " << (AclMatchedName
? AclMatchedName
: "[none]"));
710 char const *proxy_auth_msg
= "<null>";
711 if (http
->getConn() != nullptr && http
->getConn()->getAuth() != nullptr)
712 proxy_auth_msg
= http
->getConn()->getAuth()->denyMessage("<null>");
713 else if (http
->request
->auth_user_request
!= nullptr)
714 proxy_auth_msg
= http
->request
->auth_user_request
->denyMessage("<null>");
717 if (!answer
.allowed()) {
718 // auth has a grace period where credentials can be expired but okay not to challenge.
720 /* Send an auth challenge or error */
721 // XXX: do we still need aclIsProxyAuth() ?
722 bool auth_challenge
= (answer
== ACCESS_AUTH_REQUIRED
|| aclIsProxyAuth(AclMatchedName
));
723 debugs(85, 5, "Access Denied: " << http
->uri
);
724 debugs(85, 5, "AclMatchedName = " << (AclMatchedName
? AclMatchedName
: "<null>"));
727 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg
? proxy_auth_msg
: "<null>"));
731 * NOTE: get page_id here, based on AclMatchedName because if
732 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
733 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
736 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, answer
!= ACCESS_AUTH_REQUIRED
);
738 http
->updateLoggingTags(LOG_TCP_DENIED
);
740 if (auth_challenge
) {
742 if (http
->request
->flags
.sslBumped
) {
743 /*SSL Bumped request, authentication is not possible*/
744 status
= Http::scForbidden
;
745 } else if (!http
->flags
.accel
) {
746 /* Proxy authorisation needed */
747 status
= Http::scProxyAuthenticationRequired
;
749 /* WWW authorisation needed */
750 status
= Http::scUnauthorized
;
753 // need auth, but not possible to do.
754 status
= Http::scForbidden
;
756 if (page_id
== ERR_NONE
)
757 page_id
= ERR_CACHE_ACCESS_DENIED
;
759 status
= Http::scForbidden
;
761 if (page_id
== ERR_NONE
)
762 page_id
= ERR_ACCESS_DENIED
;
765 error
= clientBuildError(page_id
, status
, nullptr, http
->getConn(), http
->request
, http
->al
);
768 error
->auth_user_request
=
769 http
->getConn() != nullptr && http
->getConn()->getAuth() != nullptr ?
770 http
->getConn()->getAuth() : http
->request
->auth_user_request
;
773 readNextRequest
= true;
776 /* ACCESS_ALLOWED continues here ... */
778 http
->uri
= SBufToCstring(http
->request
->effectiveRequestUri());
784 ClientHttpRequest::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer g
)
786 debugs(93,3, this << " adaptationAclCheckDone called");
789 Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
791 if (getConn() != nullptr && getConn()->clientConnection
!= nullptr) {
792 ih
->rfc931
= getConn()->clientConnection
->rfc931
;
794 if (getConn()->clientConnection
->isOpen()) {
795 ih
->ssluser
= sslGetUserEmail(fd_table
[getConn()->clientConnection
->fd
].ssl
.get());
799 ih
->log_uri
= log_uri
;
805 debugs(85,3, "no adaptation needed");
816 clientRedirectAccessCheckDone(Acl::Answer answer
, void *data
)
818 ClientRequestContext
*context
= (ClientRequestContext
*)data
;
819 ClientHttpRequest
*http
= context
->http
;
820 context
->acl_checklist
= nullptr;
822 if (answer
.allowed())
823 redirectStart(http
, clientRedirectDoneWrapper
, context
);
825 Helper::Reply
const nilReply(Helper::Error
);
826 context
->clientRedirectDone(nilReply
);
831 ClientRequestContext::clientRedirectStart()
833 debugs(33, 5, "'" << http
->uri
<< "'");
834 http
->al
->syncNotes(http
->request
);
835 if (Config
.accessList
.redirector
) {
836 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.redirector
, http
);
837 acl_checklist
->nonBlockingCheck(clientRedirectAccessCheckDone
, this);
839 redirectStart(http
, clientRedirectDoneWrapper
, this);
843 * This methods handles Access checks result of StoreId access list.
844 * Will handle as "ERR" (no change) in a case Access is not allowed.
847 clientStoreIdAccessCheckDone(Acl::Answer answer
, void *data
)
849 ClientRequestContext
*context
= static_cast<ClientRequestContext
*>(data
);
850 ClientHttpRequest
*http
= context
->http
;
851 context
->acl_checklist
= nullptr;
853 if (answer
.allowed())
854 storeIdStart(http
, clientStoreIdDoneWrapper
, context
);
856 debugs(85, 3, "access denied expected ERR reply handling: " << answer
);
857 Helper::Reply
const nilReply(Helper::Error
);
858 context
->clientStoreIdDone(nilReply
);
863 * Start locating an alternative storage ID string (if any) from admin
864 * configured helper program. This is an asynchronous operation terminating in
865 * ClientRequestContext::clientStoreIdDone() when completed.
868 ClientRequestContext::clientStoreIdStart()
870 debugs(33, 5,"'" << http
->uri
<< "'");
872 if (Config
.accessList
.store_id
) {
873 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.store_id
, http
);
874 acl_checklist
->nonBlockingCheck(clientStoreIdAccessCheckDone
, this);
876 storeIdStart(http
, clientStoreIdDoneWrapper
, this);
880 clientHierarchical(ClientHttpRequest
* http
)
882 HttpRequest
*request
= http
->request
;
883 HttpRequestMethod method
= request
->method
;
885 // intercepted requests MUST NOT (yet) be sent to peers unless verified
886 if (!request
->flags
.hostVerified
&& (request
->flags
.intercepted
|| request
->flags
.interceptTproxy
))
890 * IMS needs a private key, so we can use the hierarchy for IMS only if our
891 * neighbors support private keys
894 if (request
->flags
.ims
&& !neighbors_do_private_keys
)
898 * This is incorrect: authenticating requests can be sent via a hierarchy
899 * (they can even be cached if the correct headers are set on the reply)
901 if (request
->flags
.auth
)
904 if (method
== Http::METHOD_TRACE
)
907 if (method
!= Http::METHOD_GET
)
910 if (request
->flags
.loopDetected
)
913 if (request
->url
.getScheme() == AnyP::PROTO_HTTP
)
914 return method
.respMaybeCacheable();
920 clientCheckPinning(ClientHttpRequest
* http
)
922 HttpRequest
*request
= http
->request
;
923 HttpHeader
*req_hdr
= &request
->header
;
924 ConnStateData
*http_conn
= http
->getConn();
926 /* Internal requests such as those from ESI includes may be without
927 * a client connection
932 request
->flags
.connectionAuthDisabled
= http_conn
->port
->connection_auth_disabled
;
933 if (!request
->flags
.connectionAuthDisabled
) {
934 if (Comm::IsConnOpen(http_conn
->pinning
.serverConnection
)) {
935 if (http_conn
->pinning
.auth
) {
936 request
->flags
.connectionAuth
= true;
937 request
->flags
.auth
= true;
939 request
->flags
.connectionProxyAuth
= true;
941 // These should already be linked correctly.
942 assert(request
->clientConnectionManager
== http_conn
);
946 /* check if connection auth is used, and flag as candidate for pinning
948 * Note: we may need to set flags.connectionAuth even if the connection
949 * is already pinned if it was pinned earlier due to proxy auth
951 if (!request
->flags
.connectionAuth
) {
952 if (req_hdr
->has(Http::HdrType::AUTHORIZATION
) || req_hdr
->has(Http::HdrType::PROXY_AUTHORIZATION
)) {
953 HttpHeaderPos pos
= HttpHeaderInitPos
;
956 while ((e
= req_hdr
->getEntry(&pos
))) {
957 if (e
->id
== Http::HdrType::AUTHORIZATION
|| e
->id
== Http::HdrType::PROXY_AUTHORIZATION
) {
958 const char *value
= e
->value
.rawBuf();
959 if (strncasecmp(value
, "NTLM ", 5) == 0
961 strncasecmp(value
, "Negotiate ", 10) == 0
963 strncasecmp(value
, "Kerberos ", 9) == 0) {
964 if (e
->id
== Http::HdrType::AUTHORIZATION
) {
965 request
->flags
.connectionAuth
= true;
968 request
->flags
.connectionProxyAuth
= true;
974 if (may_pin
&& !request
->pinnedConnection()) {
975 // These should already be linked correctly. Just need the ServerConnection to pinn.
976 assert(request
->clientConnectionManager
== http_conn
);
983 clientInterpretRequestHeaders(ClientHttpRequest
* http
)
985 HttpRequest
*request
= http
->request
;
986 HttpHeader
*req_hdr
= &request
->header
;
987 bool no_cache
= false;
989 request
->imslen
= -1;
990 request
->ims
= req_hdr
->getTime(Http::HdrType::IF_MODIFIED_SINCE
);
992 if (request
->ims
> 0)
993 request
->flags
.ims
= true;
995 if (!request
->flags
.ignoreCc
) {
996 if (request
->cache_control
) {
997 if (request
->cache_control
->hasNoCache())
1000 // RFC 2616: treat Pragma:no-cache as if it was Cache-Control:no-cache when Cache-Control is missing
1001 } else if (req_hdr
->has(Http::HdrType::PRAGMA
))
1002 no_cache
= req_hdr
->hasListMember(Http::HdrType::PRAGMA
,"no-cache",',');
1005 if (request
->method
== Http::METHOD_OTHER
) {
1010 #if USE_HTTP_VIOLATIONS
1012 if (Config
.onoff
.reload_into_ims
)
1013 request
->flags
.nocacheHack
= true;
1014 else if (refresh_nocache_hack
)
1015 request
->flags
.nocacheHack
= true;
1019 request
->flags
.noCache
= true;
1022 /* ignore range header in non-GETs or non-HEADs */
1023 if (request
->method
== Http::METHOD_GET
|| request
->method
== Http::METHOD_HEAD
) {
1024 // XXX: initialize if we got here without HttpRequest::parseHeader()
1025 if (!request
->range
)
1026 request
->range
= req_hdr
->getRange();
1028 if (request
->range
) {
1029 request
->flags
.isRanged
= true;
1030 clientStreamNode
*node
= (clientStreamNode
*)http
->client_stream
.tail
->data
;
1031 /* XXX: This is suboptimal. We should give the stream the range set,
1032 * and thereby let the top of the stream set the offset when the
1033 * size becomes known. As it is, we will end up requesting from 0
1034 * for evey -X range specification.
1035 * RBC - this may be somewhat wrong. We should probably set the range
1036 * iter up at this point.
1038 node
->readBuffer
.offset
= request
->range
->lowestOffset(0);
1042 /* Only HEAD and GET requests permit a Range or Request-Range header.
1043 * If these headers appear on any other type of request, delete them now.
1046 req_hdr
->delById(Http::HdrType::RANGE
);
1047 req_hdr
->delById(Http::HdrType::REQUEST_RANGE
);
1048 request
->ignoreRange("neither HEAD nor GET");
1051 if (req_hdr
->has(Http::HdrType::AUTHORIZATION
))
1052 request
->flags
.auth
= true;
1054 clientCheckPinning(http
);
1056 if (!request
->url
.userInfo().isEmpty())
1057 request
->flags
.auth
= true;
1059 if (req_hdr
->has(Http::HdrType::VIA
)) {
1060 String s
= req_hdr
->getList(Http::HdrType::VIA
);
1062 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
1063 * Note ThisCache2 has a space prepended to the hostname so we don't
1064 * accidentally match super-domains.
1067 if (strListIsSubstr(&s
, ThisCache2
, ',')) {
1068 request
->flags
.loopDetected
= true;
1072 fvdbCountVia(StringToSBuf(s
));
1079 // headers only relevant to reverse-proxy
1080 if (request
->flags
.accelerated
) {
1081 // check for a cdn-info member with a cdn-id matching surrogate_id
1082 // XXX: HttpHeader::hasListMember() does not handle OWS around ";" yet
1083 if (req_hdr
->hasListMember(Http::HdrType::CDN_LOOP
, Config
.Accel
.surrogate_id
, ','))
1084 request
->flags
.loopDetected
= true;
1087 if (request
->flags
.loopDetected
) {
1088 debugObj(33, DBG_IMPORTANT
, "WARNING: Forwarding loop detected for:\n",
1089 request
, (ObjPackMethod
) & httpRequestPack
);
1094 if (req_hdr
->has(Http::HdrType::X_FORWARDED_FOR
)) {
1095 String s
= req_hdr
->getList(Http::HdrType::X_FORWARDED_FOR
);
1096 fvdbCountForwarded(StringToSBuf(s
));
1102 if (http
->request
->maybeCacheable())
1103 request
->flags
.cachable
.support();
1105 request
->flags
.cachable
.veto();
1107 if (clientHierarchical(http
))
1108 request
->flags
.hierarchical
= true;
1110 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
1111 (request
->flags
.noCache
? "SET" : "NOT SET"));
1112 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
1113 (request
->flags
.cachable
? "SET" : "NOT SET"));
1114 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
1115 (request
->flags
.hierarchical
? "SET" : "NOT SET"));
1120 clientRedirectDoneWrapper(void *data
, const Helper::Reply
&result
)
1122 ClientRequestContext
*calloutContext
= (ClientRequestContext
*)data
;
1124 if (!calloutContext
->httpStateIsValid())
1127 calloutContext
->clientRedirectDone(result
);
1131 clientStoreIdDoneWrapper(void *data
, const Helper::Reply
&result
)
1133 ClientRequestContext
*calloutContext
= (ClientRequestContext
*)data
;
1135 if (!calloutContext
->httpStateIsValid())
1138 calloutContext
->clientStoreIdDone(result
);
1142 ClientRequestContext::clientRedirectDone(const Helper::Reply
&reply
)
1144 HttpRequest
*old_request
= http
->request
;
1145 debugs(85, 5, "'" << http
->uri
<< "' result=" << reply
);
1146 assert(redirect_state
== REDIRECT_PENDING
);
1147 redirect_state
= REDIRECT_DONE
;
1149 // Put helper response Notes into the transaction state record (ALE) eventually
1150 // do it early to ensure that no matter what the outcome the notes are present.
1152 http
->al
->syncNotes(old_request
);
1154 UpdateRequestNotes(http
->getConn(), *old_request
, reply
.notes
);
1156 switch (reply
.result
) {
1157 case Helper::TimedOut
:
1158 if (Config
.onUrlRewriteTimeout
.action
!= toutActBypass
) {
1159 static const auto d
= MakeNamedErrorDetail("REDIRECTOR_TIMEDOUT");
1160 http
->calloutsError(ERR_GATEWAY_FAILURE
, d
);
1161 debugs(85, DBG_IMPORTANT
, "ERROR: URL rewrite helper: Timedout");
1165 case Helper::Unknown
:
1167 // Handler in redirect.cc should have already mapped Unknown
1168 // IF it contained valid entry for the old URL-rewrite helper protocol
1169 debugs(85, DBG_IMPORTANT
, "ERROR: URL rewrite helper returned invalid result code. Wrong helper? " << reply
);
1172 case Helper::BrokenHelper
:
1173 debugs(85, DBG_IMPORTANT
, "ERROR: URL rewrite helper: " << reply
);
1177 // no change to be done.
1180 case Helper::Okay
: {
1181 // #1: redirect with a specific status code OK status=NNN url="..."
1182 // #2: redirect with a default status code OK url="..."
1183 // #3: re-write the URL OK rewrite-url="..."
1185 const char *statusNote
= reply
.notes
.findFirst("status");
1186 const char *urlNote
= reply
.notes
.findFirst("url");
1188 if (urlNote
!= nullptr) {
1189 // HTTP protocol redirect to be done.
1191 // TODO: change default redirect status for appropriate requests
1192 // Squid defaults to 302 status for now for better compatibility with old clients.
1193 // HTTP/1.0 client should get 302 (Http::scFound)
1194 // HTTP/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect)
1195 // HTTP/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther)
1196 Http::StatusCode status
= Http::scFound
;
1197 if (statusNote
!= nullptr) {
1198 const char * result
= statusNote
;
1199 status
= static_cast<Http::StatusCode
>(atoi(result
));
1202 if (status
== Http::scMovedPermanently
1203 || status
== Http::scFound
1204 || status
== Http::scSeeOther
1205 || status
== Http::scPermanentRedirect
1206 || status
== Http::scTemporaryRedirect
) {
1207 http
->redirect
.status
= status
;
1208 http
->redirect
.location
= xstrdup(urlNote
);
1209 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
1211 debugs(85, DBG_CRITICAL
, "ERROR: URL-rewrite produces invalid " << status
<< " redirect Location: " << urlNote
);
1214 // URL-rewrite wanted. Ew.
1215 urlNote
= reply
.notes
.findFirst("rewrite-url");
1217 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1218 if (urlNote
!= nullptr && strcmp(urlNote
, http
->uri
)) {
1220 if (tmpUrl
.parse(old_request
->method
, SBuf(urlNote
))) {
1221 HttpRequest
*new_request
= old_request
->clone();
1222 new_request
->url
= tmpUrl
;
1223 debugs(61, 2, "URL-rewriter diverts URL from " << old_request
->effectiveRequestUri() << " to " << new_request
->effectiveRequestUri());
1225 // update the new request to flag the re-writing was done on it
1226 new_request
->flags
.redirected
= true;
1228 // unlink bodypipe from the old request. Not needed there any longer.
1229 if (old_request
->body_pipe
!= nullptr) {
1230 old_request
->body_pipe
= nullptr;
1231 debugs(61,2, "URL-rewriter diverts body_pipe " << new_request
->body_pipe
<<
1232 " from request " << old_request
<< " to " << new_request
);
1235 http
->resetRequest(new_request
);
1236 old_request
= nullptr;
1238 debugs(85, DBG_CRITICAL
, "ERROR: URL-rewrite produces invalid request: " <<
1239 old_request
->method
<< " " << urlNote
<< " " << old_request
->http_ver
);
1247 /* XXX PIPELINE: This is inaccurate during pipelining */
1249 if (http
->getConn() != nullptr && Comm::IsConnOpen(http
->getConn()->clientConnection
))
1250 fd_note(http
->getConn()->clientConnection
->fd
, http
->uri
);
1258 * This method handles the different replies from StoreID helper.
1261 ClientRequestContext::clientStoreIdDone(const Helper::Reply
&reply
)
1263 HttpRequest
*old_request
= http
->request
;
1264 debugs(85, 5, "'" << http
->uri
<< "' result=" << reply
);
1265 assert(store_id_state
== REDIRECT_PENDING
);
1266 store_id_state
= REDIRECT_DONE
;
1268 // Put helper response Notes into the transaction state record (ALE) eventually
1269 // do it early to ensure that no matter what the outcome the notes are present.
1271 http
->al
->syncNotes(old_request
);
1273 UpdateRequestNotes(http
->getConn(), *old_request
, reply
.notes
);
1275 switch (reply
.result
) {
1276 case Helper::Unknown
:
1278 // Handler in redirect.cc should have already mapped Unknown
1279 // IF it contained valid entry for the old helper protocol
1280 debugs(85, DBG_IMPORTANT
, "ERROR: storeID helper returned invalid result code. Wrong helper? " << reply
);
1283 case Helper::TimedOut
:
1284 // Timeouts for storeID are not implemented
1285 case Helper::BrokenHelper
:
1286 debugs(85, DBG_IMPORTANT
, "ERROR: storeID helper: " << reply
);
1290 // no change to be done.
1293 case Helper::Okay
: {
1294 const char *urlNote
= reply
.notes
.findFirst("store-id");
1296 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1297 if (urlNote
!= nullptr && strcmp(urlNote
, http
->uri
) ) {
1298 // Debug section required for some very specific cases.
1299 debugs(85, 9, "Setting storeID with: " << urlNote
);
1300 http
->request
->store_id
= urlNote
;
1301 http
->store_id
= urlNote
;
1310 /// applies "cache allow/deny" rules, asynchronously if needed
1312 ClientRequestContext::checkNoCache()
1314 if (Config
.accessList
.noCache
) {
1315 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.noCache
, http
);
1316 acl_checklist
->nonBlockingCheck(checkNoCacheDoneWrapper
, this);
1318 /* unless otherwise specified, we try to cache. */
1319 checkNoCacheDone(ACCESS_ALLOWED
);
1324 checkNoCacheDoneWrapper(Acl::Answer answer
, void *data
)
1326 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
1328 if (!calloutContext
->httpStateIsValid())
1331 calloutContext
->checkNoCacheDone(answer
);
1335 ClientRequestContext::checkNoCacheDone(const Acl::Answer
&answer
)
1337 acl_checklist
= nullptr;
1338 if (answer
.denied()) {
1339 http
->request
->flags
.disableCacheUse("a cache deny rule matched");
1346 ClientRequestContext::sslBumpAccessCheck()
1348 if (!http
->getConn()) {
1349 http
->al
->ssl
.bumpMode
= Ssl::bumpEnd
; // SslBump does not apply; log -
1353 const Ssl::BumpMode bumpMode
= http
->getConn()->sslBumpMode
;
1354 if (http
->request
->flags
.forceTunnel
) {
1355 debugs(85, 5, "not needed; already decided to tunnel " << http
->getConn());
1356 if (bumpMode
!= Ssl::bumpEnd
)
1357 http
->al
->ssl
.bumpMode
= bumpMode
; // inherited from bumped connection
1361 // If SSL connection tunneling or bumping decision has been made, obey it.
1362 if (bumpMode
!= Ssl::bumpEnd
) {
1363 debugs(85, 5, "SslBump already decided (" << bumpMode
<<
1364 "), " << "ignoring ssl_bump for " << http
->getConn());
1366 // We need the following "if" for transparently bumped TLS connection,
1367 // because in this case we are running ssl_bump access list before
1368 // the doCallouts runs. It can be removed after the bug #4340 fixed.
1369 // We do not want to proceed to bumping steps:
1370 // - if the TLS connection with the client is already established
1371 // because we are accepting normal HTTP requests on TLS port,
1372 // or because of the client-first bumping mode
1373 // - When the bumping is already started
1374 if (!http
->getConn()->switchedToHttps() &&
1375 !http
->getConn()->serverBump())
1376 http
->sslBumpNeed(bumpMode
); // for processRequest() to bump if needed and not already bumped
1377 http
->al
->ssl
.bumpMode
= bumpMode
; // inherited from bumped connection
1381 // If we have not decided yet, decide whether to bump now.
1383 // Bumping here can only start with a CONNECT request on a bumping port
1384 // (bumping of intercepted SSL conns is decided before we get 1st request).
1385 // We also do not bump redirected CONNECT requests.
1386 if (http
->request
->method
!= Http::METHOD_CONNECT
|| http
->redirect
.status
||
1387 !Config
.accessList
.ssl_bump
||
1388 !http
->getConn()->port
->flags
.tunnelSslBumping
) {
1389 http
->al
->ssl
.bumpMode
= Ssl::bumpEnd
; // SslBump does not apply; log -
1390 debugs(85, 5, "cannot SslBump this request");
1394 // Do not bump during authentication: clients would not proxy-authenticate
1395 // if we delay a 407 response and respond with 200 OK to CONNECT.
1396 if (error
&& error
->httpStatus
== Http::scProxyAuthenticationRequired
) {
1397 http
->al
->ssl
.bumpMode
= Ssl::bumpEnd
; // SslBump does not apply; log -
1398 debugs(85, 5, "no SslBump during proxy authentication");
1403 debugs(85, 5, "SslBump applies. Force bump action on error " << errorTypeName(error
->type
));
1404 http
->sslBumpNeed(Ssl::bumpBump
);
1405 http
->al
->ssl
.bumpMode
= Ssl::bumpBump
;
1409 debugs(85, 5, "SslBump possible, checking ACL");
1411 ACLFilledChecklist
*aclChecklist
= clientAclChecklistCreate(Config
.accessList
.ssl_bump
, http
);
1412 aclChecklist
->nonBlockingCheck(sslBumpAccessCheckDoneWrapper
, this);
1417 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1418 * as ACLFilledChecklist callback
1421 sslBumpAccessCheckDoneWrapper(Acl::Answer answer
, void *data
)
1423 ClientRequestContext
*calloutContext
= static_cast<ClientRequestContext
*>(data
);
1425 if (!calloutContext
->httpStateIsValid())
1427 calloutContext
->sslBumpAccessCheckDone(answer
);
1431 ClientRequestContext::sslBumpAccessCheckDone(const Acl::Answer
&answer
)
1433 if (!httpStateIsValid())
1436 const Ssl::BumpMode bumpMode
= answer
.allowed() ?
1437 static_cast<Ssl::BumpMode
>(answer
.kind
) : Ssl::bumpSplice
;
1438 http
->sslBumpNeed(bumpMode
); // for processRequest() to bump if needed
1439 http
->al
->ssl
.bumpMode
= bumpMode
; // for logging
1441 if (bumpMode
== Ssl::bumpTerminate
) {
1442 const Comm::ConnectionPointer clientConn
= http
->getConn() ? http
->getConn()->clientConnection
: nullptr;
1443 if (Comm::IsConnOpen(clientConn
)) {
1444 debugs(85, 3, "closing after Ssl::bumpTerminate ");
1445 clientConn
->close();
1455 * Identify requests that do not go through the store and client side stream
1456 * and forward them to the appropriate location. All other requests, request
1460 ClientHttpRequest::processRequest()
1462 debugs(85, 4, request
->method
<< ' ' << uri
);
1464 const bool untouchedConnect
= request
->method
== Http::METHOD_CONNECT
&& !redirect
.status
;
1467 if (untouchedConnect
&& sslBumpNeeded()) {
1468 assert(!request
->flags
.forceTunnel
);
1474 if (untouchedConnect
|| request
->flags
.forceTunnel
) {
1475 getConn()->stopReading(); // tunnels read for themselves
1484 ClientHttpRequest::httpStart()
1486 // XXX: Re-initializes rather than updates. Should not be needed at all.
1487 updateLoggingTags(LOG_TAG_NONE
);
1488 debugs(85, 4, loggingTags().c_str() << " for '" << uri
<< "'");
1490 /* no one should have touched this */
1491 assert(out
.offset
== 0);
1492 /* Use the Stream Luke */
1493 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->data
;
1494 clientStreamRead(node
, this, node
->readBuffer
);
1500 ClientHttpRequest::sslBumpNeed(Ssl::BumpMode mode
)
1502 debugs(83, 3, "sslBump required: "<< Ssl::bumpMode(mode
));
1503 sslBumpNeed_
= mode
;
1506 // called when comm_write has completed
1508 SslBumpEstablish(const Comm::ConnectionPointer
&, char *, size_t, Comm::Flag errflag
, int, void *data
)
1510 ClientHttpRequest
*r
= static_cast<ClientHttpRequest
*>(data
);
1511 debugs(85, 5, "responded to CONNECT: " << r
<< " ? " << errflag
);
1513 assert(r
&& cbdataReferenceValid(r
));
1514 r
->sslBumpEstablish(errflag
);
1518 ClientHttpRequest::sslBumpEstablish(Comm::Flag errflag
)
1520 // Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up
1521 if (errflag
== Comm::ERR_CLOSING
)
1525 debugs(85, 3, "CONNECT response failure in SslBump: " << errflag
);
1526 getConn()->clientConnection
->close();
1531 // Preserve authentication info for the ssl-bumped request
1532 if (request
->auth_user_request
!= nullptr)
1533 getConn()->setAuth(request
->auth_user_request
, "SSL-bumped CONNECT");
1536 assert(sslBumpNeeded());
1537 getConn()->switchToHttps(this, sslBumpNeed_
);
1541 ClientHttpRequest::sslBumpStart()
1543 debugs(85, 5, "Confirming " << Ssl::bumpMode(sslBumpNeed_
) <<
1544 "-bumped CONNECT tunnel on FD " << getConn()->clientConnection
);
1545 getConn()->sslBumpMode
= sslBumpNeed_
;
1547 AsyncCall::Pointer bumpCall
= commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1548 CommIoCbPtrFun(&SslBumpEstablish
, this));
1550 if (request
->flags
.interceptTproxy
|| request
->flags
.intercepted
) {
1551 CommIoCbParams
¶ms
= GetCommParams
<CommIoCbParams
>(bumpCall
);
1552 params
.flag
= Comm::OK
;
1553 params
.conn
= getConn()->clientConnection
;
1554 ScheduleCallHere(bumpCall
);
1558 al
->reply
= HttpReply::MakeConnectionEstablished();
1560 const auto mb
= al
->reply
->pack();
1561 // send an HTTP 200 response to kick client SSL negotiation
1562 // TODO: Unify with tunnel.cc and add a Server(?) header
1563 Comm::Write(getConn()->clientConnection
, mb
, bumpCall
);
1570 ClientHttpRequest::updateError(const Error
&error
)
1573 request
->error
.update(error
);
1575 al
->updateError(error
);
1579 ClientHttpRequest::gotEnough() const
1581 // TODO: See also (and unify with) clientReplyContext::storeNotOKTransferDone()
1582 int64_t contentLength
=
1583 memObject()->baseReply().bodySize(request
->method
);
1584 assert(contentLength
>= 0);
1586 if (out
.offset
< contentLength
)
1593 ClientHttpRequest::storeEntry(StoreEntry
*newEntry
)
1599 ClientHttpRequest::loggingEntry(StoreEntry
*newEntry
)
1602 loggingEntry_
->unlock("ClientHttpRequest::loggingEntry");
1604 loggingEntry_
= newEntry
;
1607 loggingEntry_
->lock("ClientHttpRequest::loggingEntry");
1611 ClientHttpRequest::initRequest(HttpRequest
*aRequest
)
1613 assignRequest(aRequest
);
1614 if (const auto csd
= getConn()) {
1615 if (!csd
->notes()->empty())
1616 request
->notes()->appendNewOnly(csd
->notes().getRaw());
1618 // al is created in the constructor
1621 al
->request
= request
;
1622 HTTPMSGLOCK(al
->request
);
1623 al
->syncNotes(request
);
1628 ClientHttpRequest::resetRequest(HttpRequest
*newRequest
)
1630 assert(request
!= newRequest
);
1632 assignRequest(newRequest
);
1634 uri
= SBufToCstring(request
->effectiveRequestUri());
1638 ClientHttpRequest::assignRequest(HttpRequest
*newRequest
)
1642 const_cast<HttpRequest
*&>(request
) = newRequest
;
1643 HTTPMSGLOCK(request
);
1644 setLogUriToRequestUri();
1648 ClientHttpRequest::clearRequest()
1650 HttpRequest
*oldRequest
= request
;
1651 HTTPMSGUNLOCK(oldRequest
);
1652 const_cast<HttpRequest
*&>(request
) = nullptr;
1653 absorbLogUri(nullptr);
1657 * doCallouts() - This function controls the order of "callout"
1658 * executions, including non-blocking access control checks, the
1659 * redirector, and ICAP. Previously, these callouts were chained
1660 * together such that "clientAccessCheckDone()" would call
1661 * "clientRedirectStart()" and so on.
1663 * The ClientRequestContext (aka calloutContext) class holds certain
1664 * state data for the callout/callback operations. Previously
1665 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1666 * for a short time. ClientRequestContext would then delete itself
1667 * and pass control back to ClientHttpRequest when all callouts
1670 * This caused some problems for ICAP because we want to make the
1671 * ICAP callout after checking ACLs, but before checking the no_cache
1672 * list. We can't stuff the ICAP state into the ClientRequestContext
1673 * class because we still need the ICAP state after ClientRequestContext
1676 * Note that ClientRequestContext is created before the first call
1679 * If one of the callouts notices that ClientHttpRequest is no
1680 * longer valid, it should call cbdataReferenceDone() so that
1681 * ClientHttpRequest's reference count goes to zero and it will get
1682 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1684 * Note that we set the _done flags here before actually starting
1685 * the callout. This is strictly for convenience.
1689 ClientHttpRequest::doCallouts()
1691 assert(calloutContext
);
1693 if (!calloutContext
->error
) {
1694 // CVE-2009-0801: verify the Host: header is consistent with other known details.
1695 if (!calloutContext
->host_header_verify_done
) {
1696 debugs(83, 3, "Doing calloutContext->hostHeaderVerify()");
1697 calloutContext
->host_header_verify_done
= true;
1698 calloutContext
->hostHeaderVerify();
1702 if (!calloutContext
->http_access_done
) {
1703 debugs(83, 3, "Doing calloutContext->clientAccessCheck()");
1704 calloutContext
->http_access_done
= true;
1705 calloutContext
->clientAccessCheck();
1710 if (!calloutContext
->adaptation_acl_check_done
) {
1711 calloutContext
->adaptation_acl_check_done
= true;
1712 if (Adaptation::AccessCheck::Start(
1713 Adaptation::methodReqmod
, Adaptation::pointPreCache
,
1714 request
, nullptr, calloutContext
->http
->al
, this))
1715 return; // will call callback
1719 if (!calloutContext
->redirect_done
) {
1720 calloutContext
->redirect_done
= true;
1722 if (Config
.Program
.redirect
) {
1723 debugs(83, 3, "Doing calloutContext->clientRedirectStart()");
1724 calloutContext
->redirect_state
= REDIRECT_PENDING
;
1725 calloutContext
->clientRedirectStart();
1730 if (!calloutContext
->adapted_http_access_done
) {
1731 debugs(83, 3, "Doing calloutContext->clientAccessCheck2()");
1732 calloutContext
->adapted_http_access_done
= true;
1733 calloutContext
->clientAccessCheck2();
1737 if (!calloutContext
->store_id_done
) {
1738 calloutContext
->store_id_done
= true;
1740 if (Config
.Program
.store_id
) {
1741 debugs(83, 3,"Doing calloutContext->clientStoreIdStart()");
1742 calloutContext
->store_id_state
= REDIRECT_PENDING
;
1743 calloutContext
->clientStoreIdStart();
1748 if (!calloutContext
->interpreted_req_hdrs
) {
1749 debugs(83, 3, "Doing clientInterpretRequestHeaders()");
1750 calloutContext
->interpreted_req_hdrs
= 1;
1751 clientInterpretRequestHeaders(this);
1754 if (!calloutContext
->no_cache_done
) {
1755 calloutContext
->no_cache_done
= true;
1757 if (Config
.accessList
.noCache
&& request
->flags
.cachable
) {
1758 debugs(83, 3, "Doing calloutContext->checkNoCache()");
1759 calloutContext
->checkNoCache();
1763 } // if !calloutContext->error
1765 // Set appropriate MARKs and CONNMARKs if needed.
1766 if (getConn() && Comm::IsConnOpen(getConn()->clientConnection
)) {
1767 ACLFilledChecklist
ch(nullptr, request
, nullptr);
1768 ch
.al
= calloutContext
->http
->al
;
1769 ch
.src_addr
= request
->client_addr
;
1770 ch
.my_addr
= request
->my_addr
;
1771 ch
.syncAle(request
, log_uri
);
1773 if (!calloutContext
->toClientMarkingDone
) {
1774 calloutContext
->toClientMarkingDone
= true;
1775 tos_t tos
= aclMapTOS(Ip::Qos::TheConfig
.tosToClient
, &ch
);
1777 Ip::Qos::setSockTos(getConn()->clientConnection
, tos
);
1779 const auto packetMark
= aclFindNfMarkConfig(Ip::Qos::TheConfig
.nfmarkToClient
, &ch
);
1780 if (!packetMark
.isEmpty())
1781 Ip::Qos::setSockNfmark(getConn()->clientConnection
, packetMark
.mark
);
1783 const auto connmark
= aclFindNfMarkConfig(Ip::Qos::TheConfig
.nfConnmarkToClient
, &ch
);
1784 if (!connmark
.isEmpty())
1785 Ip::Qos::setNfConnmark(getConn()->clientConnection
, Ip::Qos::dirAccepted
, connmark
);
1790 // Even with calloutContext->error, we call sslBumpAccessCheck() to decide
1791 // whether SslBump applies to this transaction. If it applies, we will
1792 // attempt to bump the client to serve the error.
1793 if (!calloutContext
->sslBumpCheckDone
) {
1794 calloutContext
->sslBumpCheckDone
= true;
1795 if (calloutContext
->sslBumpAccessCheck())
1797 /* else no ssl bump required*/
1801 if (calloutContext
->error
) {
1802 // XXX: prformance regression. c_str() reallocates
1803 SBuf
storeUriBuf(request
->storeId());
1804 const char *storeUri
= storeUriBuf
.c_str();
1805 StoreEntry
*e
= storeCreateEntry(storeUri
, storeUri
, request
->flags
, request
->method
);
1807 if (sslBumpNeeded()) {
1808 // We have to serve an error, so bump the client first.
1809 sslBumpNeed(Ssl::bumpClientFirst
);
1810 // set final error but delay sending until we bump
1811 Ssl::ServerBump
*srvBump
= new Ssl::ServerBump(this, e
, Ssl::bumpClientFirst
);
1812 errorAppendEntry(e
, calloutContext
->error
);
1813 calloutContext
->error
= nullptr;
1814 getConn()->setServerBump(srvBump
);
1815 e
->unlock("ClientHttpRequest::doCallouts+sslBumpNeeded");
1819 // send the error to the client now
1820 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
1821 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1822 assert (repContext
);
1823 repContext
->setReplyToStoreEntry(e
, "immediate SslBump error");
1824 errorAppendEntry(e
, calloutContext
->error
);
1825 calloutContext
->error
= nullptr;
1826 if (calloutContext
->readNextRequest
&& getConn())
1827 getConn()->flags
.readMore
= true; // resume any pipeline reads.
1828 node
= (clientStreamNode
*)client_stream
.tail
->data
;
1829 clientStreamRead(node
, this, node
->readBuffer
);
1830 e
->unlock("ClientHttpRequest::doCallouts-sslBumpNeeded");
1835 cbdataReferenceDone(calloutContext
->http
);
1836 delete calloutContext
;
1837 calloutContext
= nullptr;
1839 debugs(83, 3, "calling processRequest()");
1843 Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
1845 ih
->logType
= loggingTags();
1850 ClientHttpRequest::setLogUriToRequestUri()
1853 const auto canonicalUri
= request
->canonicalCleanUrl();
1854 absorbLogUri(xstrndup(canonicalUri
, MAX_URL
));
1858 ClientHttpRequest::setLogUriToRawUri(const char *rawUri
, const HttpRequestMethod
&method
)
1861 // Should(!request);
1863 // TODO: SBuf() performance regression, fix by converting rawUri to SBuf
1864 char *canonicalUri
= urlCanonicalCleanWithoutRequest(SBuf(rawUri
), method
, AnyP::UriScheme());
1866 absorbLogUri(AnyP::Uri::cleanup(canonicalUri
));
1868 char *cleanedRawUri
= AnyP::Uri::cleanup(rawUri
);
1869 al
->setVirginUrlForMissingRequest(SBuf(cleanedRawUri
));
1870 xfree(cleanedRawUri
);
1874 ClientHttpRequest::absorbLogUri(char *aUri
)
1877 const_cast<char *&>(log_uri
) = aUri
;
1881 ClientHttpRequest::setErrorUri(const char *aUri
)
1885 // Should(!request);
1887 uri
= xstrdup(aUri
);
1888 // TODO: SBuf() performance regression, fix by converting setErrorUri() parameter to SBuf
1889 const SBuf
errorUri(aUri
);
1890 const auto canonicalUri
= urlCanonicalCleanWithoutRequest(errorUri
, HttpRequestMethod(), AnyP::UriScheme());
1891 absorbLogUri(xstrndup(canonicalUri
, MAX_URL
));
1893 al
->setVirginUrlForMissingRequest(errorUri
);
1896 // XXX: This should not be a _request_ method. Move range_iter elsewhere.
1898 ClientHttpRequest::prepPartialResponseGeneration()
1901 assert(request
->range
);
1903 range_iter
.pos
= request
->range
->begin();
1904 range_iter
.end
= request
->range
->end();
1905 range_iter
.debt_size
= 0;
1906 const auto multipart
= request
->range
->specs
.size() > 1;
1908 range_iter
.boundary
= rangeBoundaryStr();
1909 range_iter
.valid
= true; // TODO: Remove.
1910 range_iter
.updateSpec(); // TODO: Refactor to initialize rather than update.
1912 assert(range_iter
.pos
!= range_iter
.end
);
1913 const auto &firstRange
= *range_iter
.pos
;
1915 out
.offset
= firstRange
->offset
;
1917 return multipart
? mRangeCLen() : firstRange
->length
;
1921 /// Initiate an asynchronous adaptation transaction which will call us back.
1923 ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer
&g
)
1925 debugs(85, 3, "adaptation needed for " << this);
1926 assert(!virginHeadSource
);
1927 assert(!adaptedBodySource
);
1928 virginHeadSource
= initiateAdaptation(
1929 new Adaptation::Iterator(request
, nullptr, al
, g
));
1931 // we could try to guess whether we can bypass this adaptation
1932 // initiation failure, but it should not really happen
1933 Must(initiated(virginHeadSource
));
1937 ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer
&answer
)
1939 assert(cbdataReferenceValid(this)); // indicates bug
1940 clearAdaptation(virginHeadSource
);
1941 assert(!adaptedBodySource
);
1943 switch (answer
.kind
) {
1944 case Adaptation::Answer::akForward
:
1945 handleAdaptedHeader(const_cast<Http::Message
*>(answer
.message
.getRaw()));
1948 case Adaptation::Answer::akBlock
:
1949 handleAdaptationBlock(answer
);
1952 case Adaptation::Answer::akError
: {
1953 static const auto d
= MakeNamedErrorDetail("CLT_REQMOD_ABORT");
1954 handleAdaptationFailure(d
, !answer
.final
);
1961 ClientHttpRequest::handleAdaptedHeader(Http::Message
*msg
)
1965 if (HttpRequest
*new_req
= dynamic_cast<HttpRequest
*>(msg
)) {
1966 // update the new message to flag whether URL re-writing was done on it
1967 if (request
->effectiveRequestUri() != new_req
->effectiveRequestUri())
1968 new_req
->flags
.redirected
= true;
1969 resetRequest(new_req
);
1970 assert(request
->method
.id());
1971 } else if (HttpReply
*new_rep
= dynamic_cast<HttpReply
*>(msg
)) {
1972 debugs(85,3, "REQMOD reply is HTTP reply");
1974 // subscribe to receive reply body
1975 if (new_rep
->body_pipe
!= nullptr) {
1976 adaptedBodySource
= new_rep
->body_pipe
;
1977 int consumer_ok
= adaptedBodySource
->setConsumerIfNotLate(this);
1978 assert(consumer_ok
);
1981 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
1982 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1984 repContext
->createStoreEntry(request
->method
, request
->flags
);
1986 request_satisfaction_mode
= true;
1987 request_satisfaction_offset
= 0;
1988 storeEntry()->replaceHttpReply(new_rep
);
1989 storeEntry()->timestampsSet();
1991 al
->reply
= new_rep
;
1993 if (!adaptedBodySource
) // no body
1994 storeEntry()->complete();
1995 clientGetMoreData(node
, this);
1998 // we are done with getting headers (but may be receiving body)
1999 clearAdaptation(virginHeadSource
);
2001 if (!request_satisfaction_mode
)
2006 ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer
&answer
)
2008 static const auto d
= MakeNamedErrorDetail("REQMOD_BLOCK");
2009 request
->detailError(ERR_ACCESS_DENIED
, d
);
2010 AclMatchedName
= answer
.ruleId
.termedBuf();
2011 assert(calloutContext
);
2012 calloutContext
->clientAccessCheckDone(ACCESS_DENIED
);
2013 AclMatchedName
= nullptr;
2017 ClientHttpRequest::resumeBodyStorage()
2019 if (!adaptedBodySource
)
2022 noteMoreBodyDataAvailable(adaptedBodySource
);
2026 ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
2028 assert(request_satisfaction_mode
);
2029 assert(adaptedBodySource
!= nullptr);
2031 if (size_t contentSize
= adaptedBodySource
->buf().contentSize()) {
2032 const size_t spaceAvailable
= storeEntry()->bytesWanted(Range
<size_t>(0,contentSize
));
2034 if (spaceAvailable
< contentSize
) {
2035 // No or partial body data consuming
2036 typedef NullaryMemFunT
<ClientHttpRequest
> Dialer
;
2037 AsyncCall::Pointer call
= asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage",
2038 Dialer(this, &ClientHttpRequest::resumeBodyStorage
));
2039 storeEntry()->deferProducer(call
);
2042 if (!spaceAvailable
)
2045 if (spaceAvailable
< contentSize
)
2046 contentSize
= spaceAvailable
;
2048 BodyPipeCheckout
bpc(*adaptedBodySource
);
2049 const StoreIOBuffer
ioBuf(&bpc
.buf
, request_satisfaction_offset
, contentSize
);
2050 storeEntry()->write(ioBuf
);
2051 // assume StoreEntry::write() writes the entire ioBuf
2052 request_satisfaction_offset
+= ioBuf
.length
;
2053 bpc
.buf
.consume(contentSize
);
2057 if (adaptedBodySource
->exhausted()) {
2058 // XXX: Setting receivedWholeAdaptedReply here is a workaround for a
2059 // regression, as described in https://bugs.squid-cache.org/show_bug.cgi?id=5187#c6
2060 receivedWholeAdaptedReply
= true;
2061 debugs(85, DBG_IMPORTANT
, "WARNING: Squid bug 5187 workaround triggered");
2062 endRequestSatisfaction();
2064 // else wait for more body data
2068 ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer
)
2070 assert(!virginHeadSource
);
2072 // distinguish this code path from future noteBodyProducerAborted() that
2073 // would continue storing/delivering (truncated) reply if necessary (TODO)
2074 receivedWholeAdaptedReply
= true;
2076 // should we end request satisfaction now?
2077 if (adaptedBodySource
!= nullptr && adaptedBodySource
->exhausted())
2078 endRequestSatisfaction();
2082 ClientHttpRequest::endRequestSatisfaction()
2084 debugs(85,4, this << " ends request satisfaction");
2085 assert(request_satisfaction_mode
);
2086 stopConsumingFrom(adaptedBodySource
);
2088 // TODO: anything else needed to end store entry formation correctly?
2089 if (receivedWholeAdaptedReply
) {
2090 // We received the entire reply per receivedWholeAdaptedReply.
2091 // We are called when we consumed everything received (per our callers).
2092 // We consume only what we store per noteMoreBodyDataAvailable().
2093 storeEntry()->completeSuccessfully("received, consumed, and, hence, stored the entire REQMOD reply");
2095 storeEntry()->completeTruncated("REQMOD request satisfaction default");
2100 ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer
)
2102 assert(!virginHeadSource
);
2103 stopConsumingFrom(adaptedBodySource
);
2105 debugs(85,3, "REQMOD body production failed");
2106 if (request_satisfaction_mode
) { // too late to recover or serve an error
2107 static const auto d
= MakeNamedErrorDetail("CLT_REQMOD_RESP_BODY");
2108 request
->detailError(ERR_ICAP_FAILURE
, d
);
2109 const Comm::ConnectionPointer c
= getConn()->clientConnection
;
2110 Must(Comm::IsConnOpen(c
));
2111 c
->close(); // drastic, but we may be writing a response already
2113 static const auto d
= MakeNamedErrorDetail("CLT_REQMOD_REQ_BODY");
2114 handleAdaptationFailure(d
);
2119 ClientHttpRequest::handleAdaptationFailure(const ErrorDetail::Pointer
&errDetail
, bool bypassable
)
2121 debugs(85,3, "handleAdaptationFailure(" << bypassable
<< ")");
2123 const bool usedStore
= storeEntry() && !storeEntry()->isEmpty();
2124 const bool usedPipe
= request
->body_pipe
!= nullptr &&
2125 request
->body_pipe
->consumedSize() > 0;
2127 if (bypassable
&& !usedStore
&& !usedPipe
) {
2128 debugs(85,3, "ICAP REQMOD callout failed, bypassing: " << calloutContext
);
2134 debugs(85,3, "ICAP REQMOD callout failed, responding with error");
2136 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
2137 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2140 calloutsError(ERR_ICAP_FAILURE
, errDetail
);
2147 ClientHttpRequest::callException(const std::exception
&ex
)
2149 if (const auto clientConn
= getConn() ? getConn()->clientConnection
: nullptr) {
2150 if (Comm::IsConnOpen(clientConn
)) {
2151 debugs(85, 3, "closing after exception: " << ex
.what());
2152 clientConn
->close(); // initiate orderly top-to-bottom cleanup
2156 debugs(85, DBG_IMPORTANT
, "ClientHttpRequest exception without connection. Ignoring " << ex
.what());
2157 // XXX: Normally, we mustStop() but we cannot do that here because it is
2158 // likely to leave Http::Stream and ConnStateData with a dangling http
2159 // pointer. See r13480 or XXX in Http::Stream class description.
2163 // XXX: modify and use with ClientRequestContext::clientAccessCheckDone too.
2165 ClientHttpRequest::calloutsError(const err_type error
, const ErrorDetail::Pointer
&errDetail
)
2167 // The original author of the code also wanted to pass an errno to
2168 // setReplyToError, but it seems unlikely that the errno reflects the
2169 // true cause of the error at this point, so I did not pass it.
2170 if (calloutContext
) {
2171 ConnStateData
* c
= getConn();
2172 calloutContext
->error
= clientBuildError(error
, Http::scInternalServerError
,
2173 nullptr, c
, request
, al
);
2175 calloutContext
->error
->auth_user_request
=
2176 c
!= nullptr && c
->getAuth() != nullptr ? c
->getAuth() : request
->auth_user_request
;
2178 calloutContext
->error
->detailError(errDetail
);
2179 calloutContext
->readNextRequest
= true;
2181 c
->expectNoForwarding();
2183 //else if(calloutContext == NULL) is it possible?