2 * Copyright (C) 1996-2021 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 "profiler/Profiler.h"
51 #include "proxyp/Header.h"
54 #include "sbuf/StringConvert.h"
55 #include "SquidConfig.h"
56 #include "SquidTime.h"
62 #include "auth/UserRequest.h"
65 #include "adaptation/AccessCheck.h"
66 #include "adaptation/Answer.h"
67 #include "adaptation/Iterator.h"
68 #include "adaptation/Service.h"
70 #include "adaptation/icap/History.h"
74 #include "ssl/ServerBump.h"
75 #include "ssl/support.h"
78 static const char *const crlf
= "\r\n";
80 #if FOLLOW_X_FORWARDED_FOR
81 static void clientFollowXForwardedForCheck(Acl::Answer answer
, void *data
);
82 #endif /* FOLLOW_X_FORWARDED_FOR */
84 ErrorState
*clientBuildError(err_type
, Http::StatusCode
, char const *url
, const ConnStateData
*, HttpRequest
*, const AccessLogEntry::Pointer
&);
86 CBDATA_CLASS_INIT(ClientRequestContext
);
90 static void clientAccessCheckDoneWrapper(Acl::Answer
, void *);
92 static void sslBumpAccessCheckDoneWrapper(Acl::Answer
, void *);
94 static int clientHierarchical(ClientHttpRequest
* http
);
95 static void clientInterpretRequestHeaders(ClientHttpRequest
* http
);
96 static HLPCB clientRedirectDoneWrapper
;
97 static HLPCB clientStoreIdDoneWrapper
;
98 static void checkNoCacheDoneWrapper(Acl::Answer
, void *);
99 SQUIDCEXTERN CSR clientGetMoreData
;
100 SQUIDCEXTERN CSS clientReplyStatus
;
101 SQUIDCEXTERN CSD clientReplyDetach
;
102 static void checkFailureRatio(err_type
, hier_code
);
104 ClientRequestContext::~ClientRequestContext()
107 * Release our "lock" on our parent, ClientHttpRequest, if we
112 cbdataReferenceDone(http
);
115 debugs(85,3, "ClientRequestContext destructed, this=" << this);
118 ClientRequestContext::ClientRequestContext(ClientHttpRequest
*anHttp
) :
119 http(cbdataReference(anHttp
)),
121 redirect_state(REDIRECT_NONE
),
122 store_id_state(REDIRECT_NONE
),
123 host_header_verify_done(false),
124 http_access_done(false),
125 adapted_http_access_done(false),
127 adaptation_acl_check_done(false),
129 redirect_done(false),
130 store_id_done(false),
131 no_cache_done(false),
132 interpreted_req_hdrs(false),
133 toClientMarkingDone(false),
135 sslBumpCheckDone(false),
138 readNextRequest(false)
140 debugs(85, 3, "ClientRequestContext constructed, this=" << this);
143 CBDATA_CLASS_INIT(ClientHttpRequest
);
145 ClientHttpRequest::ClientHttpRequest(ConnStateData
* aConn
) :
147 AsyncJob("ClientHttpRequest"),
153 calloutContext(NULL
),
154 maxReplyBodySize_(0),
157 conn_(cbdataReference(aConn
))
159 , sslBumpNeed_(Ssl::bumpEnd
)
162 , request_satisfaction_mode(false)
163 , request_satisfaction_offset(0)
166 al
= new AccessLogEntry
;
167 CodeContext::Reset(al
);
168 al
->cache
.start_time
= current_time
;
170 al
->tcpClient
= clientConnection
= aConn
->clientConnection
;
171 al
->cache
.port
= aConn
->port
;
172 al
->cache
.caddr
= aConn
->log_addr
;
173 al
->proxyProtocolHeader
= aConn
->proxyProtocolHeader();
174 al
->updateError(aConn
->bareError
);
177 if (aConn
->clientConnection
!= NULL
&& aConn
->clientConnection
->isOpen()) {
178 if (auto ssl
= fd_table
[aConn
->clientConnection
->fd
].ssl
.get())
179 al
->cache
.sslClientCert
.resetWithoutLocking(SSL_get_peer_certificate(ssl
));
183 dlinkAdd(this, &active
, &ClientActiveRequests
);
187 * returns true if client specified that the object must come from the cache
188 * without contacting origin server
191 ClientHttpRequest::onlyIfCached()const
194 return request
->cache_control
&&
195 request
->cache_control
->hasOnlyIfCached();
199 * This function is designed to serve a fairly specific purpose.
200 * Occasionally our vBNS-connected caches can talk to each other, but not
201 * the rest of the world. Here we try to detect frequent failures which
202 * make the cache unusable (e.g. DNS lookup and connect() failures). If
203 * the failure:success ratio goes above 1.0 then we go into "hit only"
204 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
205 * will only fetch HITs from us if they are using the ICP protocol. We
206 * stay in this mode for 5 minutes.
208 * Duane W., Sept 16, 1996
211 checkFailureRatio(err_type etype
, hier_code hcode
)
213 // Can be set at compile time with -D compiler flag
214 #ifndef FAILURE_MODE_TIME
215 #define FAILURE_MODE_TIME 300
218 if (hcode
== HIER_NONE
)
221 // don't bother when ICP is disabled.
222 if (Config
.Port
.icp
<= 0)
225 static double magic_factor
= 100.0;
229 n_good
= magic_factor
/ (1.0 + request_failure_ratio
);
231 n_bad
= magic_factor
- n_good
;
237 case ERR_CONNECT_FAIL
:
238 case ERR_SECURE_CONNECT_FAIL
:
248 request_failure_ratio
= n_bad
/ n_good
;
250 if (hit_only_mode_until
> squid_curtime
)
253 if (request_failure_ratio
< 1.0)
256 debugs(33, DBG_CRITICAL
, "WARNING: Failure Ratio at "<< std::setw(4)<<
257 std::setprecision(3) << request_failure_ratio
);
259 debugs(33, DBG_CRITICAL
, "WARNING: ICP going into HIT-only mode for " <<
260 FAILURE_MODE_TIME
/ 60 << " minutes...");
262 hit_only_mode_until
= squid_curtime
+ FAILURE_MODE_TIME
;
264 request_failure_ratio
= 0.8; /* reset to something less than 1.0 */
267 ClientHttpRequest::~ClientHttpRequest()
269 debugs(33, 3, "httpRequestFree: " << uri
);
270 PROF_start(httpRequestFree
);
272 // Even though freeResources() below may destroy the request,
273 // we no longer set request->body_pipe to NULL here
274 // because we did not initiate that pipe (ConnStateData did)
276 /* the ICP check here was erroneous
277 * - StoreEntry::releaseRequest was always called if entry was valid
285 checkFailureRatio(request
->error
.category
, al
->hier
.code
);
290 announceInitiatorAbort(virginHeadSource
);
292 if (adaptedBodySource
!= NULL
)
293 stopConsumingFrom(adaptedBodySource
);
297 delete calloutContext
;
299 clientConnection
= NULL
;
302 cbdataReferenceDone(conn_
);
304 /* moving to the next connection is handled by the context free */
305 dlinkDelete(&active
, &ClientActiveRequests
);
307 PROF_stop(httpRequestFree
);
311 * Create a request and kick it off
316 * TODO: Pass in the buffers to be used in the initial Read request, as they are
317 * determined by the user
320 clientBeginRequest(const HttpRequestMethod
& method
, char const *url
, CSCB
* streamcallback
,
321 CSD
* streamdetach
, ClientStreamData streamdata
, HttpHeader
const *header
,
322 char *tailbuf
, size_t taillen
, const MasterXaction::Pointer
&mx
)
325 ClientHttpRequest
*http
= new ClientHttpRequest(NULL
);
326 HttpRequest
*request
;
327 StoreIOBuffer tempBuffer
;
328 if (http
->al
!= NULL
)
329 http
->al
->cache
.start_time
= current_time
;
330 /* this is only used to adjust the connection offset in client_side.c */
332 tempBuffer
.length
= taillen
;
333 tempBuffer
.data
= tailbuf
;
334 /* client stream setup */
335 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
336 clientReplyStatus
, new clientReplyContext(http
), streamcallback
,
337 streamdetach
, streamdata
, tempBuffer
);
338 /* make it visible in the 'current acctive requests list' */
340 /* internal requests only makes sense in an
341 * accelerator today. TODO: accept flags ? */
342 http
->flags
.accel
= true;
343 /* allow size for url rewriting */
344 url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
345 http
->uri
= (char *)xcalloc(url_sz
, 1);
346 strcpy(http
->uri
, url
); // XXX: polluting http->uri before parser validation
348 request
= HttpRequest::FromUrlXXX(http
->uri
, mx
, method
);
350 debugs(85, 5, "Invalid URL: " << http
->uri
);
355 * now update the headers in request with our supplied headers.
356 * HttpRequest::FromUrl() should return a blank header set, but
357 * we use Update to be sure of correctness.
360 request
->header
.update(header
);
362 /* http struct now ready */
365 * build new header list *? TODO
367 request
->flags
.accelerated
= http
->flags
.accel
;
369 /* this is an internally created
370 * request, not subject to acceleration
371 * target overrides */
372 // TODO: detect and handle internal requests of internal objects?
374 /* Internally created requests cannot have bodies today */
375 request
->content_length
= 0;
377 request
->client_addr
.setNoAddr();
379 #if FOLLOW_X_FORWARDED_FOR
380 request
->indirect_client_addr
.setNoAddr();
381 #endif /* FOLLOW_X_FORWARDED_FOR */
383 request
->my_addr
.setNoAddr(); /* undefined for internal requests */
385 request
->my_addr
.port(0);
387 request
->http_ver
= Http::ProtocolVersion();
389 http
->initRequest(request
);
391 /* optional - skip the access check ? */
392 http
->calloutContext
= new ClientRequestContext(http
);
394 http
->calloutContext
->http_access_done
= false;
396 http
->calloutContext
->redirect_done
= true;
398 http
->calloutContext
->no_cache_done
= true;
406 ClientRequestContext::httpStateIsValid()
408 ClientHttpRequest
*http_
= http
;
410 if (cbdataReferenceValid(http_
))
415 cbdataReferenceDone(http_
);
420 #if FOLLOW_X_FORWARDED_FOR
422 * clientFollowXForwardedForCheck() checks the content of X-Forwarded-For:
423 * against the followXFF ACL, or cleans up and passes control to
424 * clientAccessCheck().
426 * The trust model here is a little ambiguous. So to clarify the logic:
427 * - we may always use the direct client address as the client IP.
428 * - these trust tests merey tell whether we trust given IP enough to believe the
429 * IP string which it appended to the X-Forwarded-For: header.
430 * - if at any point we don't trust what an IP adds we stop looking.
431 * - at that point the current contents of indirect_client_addr are the value set
432 * by the last previously trusted IP.
433 * ++ indirect_client_addr contains the remote direct client from the trusted peers viewpoint.
436 clientFollowXForwardedForCheck(Acl::Answer answer
, void *data
)
438 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
440 if (!calloutContext
->httpStateIsValid())
443 ClientHttpRequest
*http
= calloutContext
->http
;
444 HttpRequest
*request
= http
->request
;
446 if (answer
.allowed() && request
->x_forwarded_for_iterator
.size() != 0) {
449 * Remove the last comma-delimited element from the
450 * x_forwarded_for_iterator and use it to repeat the cycle.
453 const char *asciiaddr
;
456 p
= request
->x_forwarded_for_iterator
.termedBuf();
457 l
= request
->x_forwarded_for_iterator
.size();
460 * XXX x_forwarded_for_iterator should really be a list of
461 * IP addresses, but it's a String instead. We have to
462 * walk backwards through the String, biting off the last
463 * comma-delimited part each time. As long as the data is in
464 * a String, we should probably implement and use a variant of
465 * strListGetItem() that walks backwards instead of forwards
466 * through a comma-separated list. But we don't even do that;
467 * we just do the work in-line here.
469 /* skip trailing space and commas */
470 while (l
> 0 && (p
[l
-1] == ',' || xisspace(p
[l
-1])))
472 request
->x_forwarded_for_iterator
.cut(l
);
473 /* look for start of last item in list */
474 while (l
> 0 && ! (p
[l
-1] == ',' || xisspace(p
[l
-1])))
477 if ((addr
= asciiaddr
)) {
478 request
->indirect_client_addr
= addr
;
479 request
->x_forwarded_for_iterator
.cut(l
);
480 calloutContext
->acl_checklist
= clientAclChecklistCreate(Config
.accessList
.followXFF
, http
);
481 if (!Config
.onoff
.acl_uses_indirect_client
) {
482 /* override the default src_addr tested if we have to go deeper than one level into XFF */
483 Filled(calloutContext
->acl_checklist
)->src_addr
= request
->indirect_client_addr
;
485 calloutContext
->acl_checklist
->nonBlockingCheck(clientFollowXForwardedForCheck
, data
);
490 /* clean up, and pass control to clientAccessCheck */
491 if (Config
.onoff
.log_uses_indirect_client
) {
493 * Ensure that the access log shows the indirect client
494 * instead of the direct client.
496 http
->al
->cache
.caddr
= request
->indirect_client_addr
;
497 if (ConnStateData
*conn
= http
->getConn())
498 conn
->log_addr
= request
->indirect_client_addr
;
500 request
->x_forwarded_for_iterator
.clean();
501 request
->flags
.done_follow_x_forwarded_for
= true;
503 if (answer
.conflicted()) {
504 debugs(28, DBG_CRITICAL
, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request
->indirect_client_addr
);
507 /* process actual access ACL as normal. */
508 calloutContext
->clientAccessCheck();
510 #endif /* FOLLOW_X_FORWARDED_FOR */
513 hostHeaderIpVerifyWrapper(const ipcache_addrs
* ia
, const Dns::LookupDetails
&dns
, void *data
)
515 ClientRequestContext
*c
= static_cast<ClientRequestContext
*>(data
);
516 c
->hostHeaderIpVerify(ia
, dns
);
520 ClientRequestContext::hostHeaderIpVerify(const ipcache_addrs
* ia
, const Dns::LookupDetails
&dns
)
522 Comm::ConnectionPointer clientConn
= http
->getConn()->clientConnection
;
524 // note the DNS details for the transaction stats.
525 http
->request
->recordLookup(dns
);
527 // Is the NAT destination IP in DNS?
528 if (ia
&& ia
->have(clientConn
->local
)) {
529 debugs(85, 3, "validate IP " << clientConn
->local
<< " possible from Host:");
530 http
->request
->flags
.hostVerified
= true;
534 debugs(85, 3, HERE
<< "FAIL: validate IP " << clientConn
->local
<< " possible from Host:");
535 hostHeaderVerifyFailed("local IP", "any domain IP");
539 ClientRequestContext::hostHeaderVerifyFailed(const char *A
, const char *B
)
541 // IP address validation for Host: failed. Admin wants to ignore them.
542 // NP: we do not yet handle CONNECT tunnels well, so ignore for them
543 if (!Config
.onoff
.hostStrictVerify
&& http
->request
->method
!= Http::METHOD_CONNECT
) {
544 debugs(85, 3, "SECURITY ALERT: Host header forgery detected on " << http
->getConn()->clientConnection
<<
545 " (" << A
<< " does not match " << B
<< ") on URL: " << http
->request
->effectiveRequestUri());
547 // NP: it is tempting to use 'flags.noCache' but that is all about READing cache data.
548 // The problems here are about WRITE for new cache content, which means flags.cachable
549 http
->request
->flags
.cachable
= false; // MUST NOT cache (for now)
550 // XXX: when we have updated the cache key to base on raw-IP + URI this cacheable limit can go.
551 http
->request
->flags
.hierarchical
= false; // MUST NOT pass to peers (for now)
552 // XXX: when we have sorted out the best way to relay requests properly to peers this hierarchical limit can go.
557 debugs(85, DBG_IMPORTANT
, "SECURITY ALERT: Host header forgery detected on " <<
558 http
->getConn()->clientConnection
<< " (" << A
<< " does not match " << B
<< ")");
559 if (const char *ua
= http
->request
->header
.getStr(Http::HdrType::USER_AGENT
))
560 debugs(85, DBG_IMPORTANT
, "SECURITY ALERT: By user agent: " << ua
);
561 debugs(85, DBG_IMPORTANT
, "SECURITY ALERT: on URL: " << http
->request
->effectiveRequestUri());
563 // IP address validation for Host: failed. reject the connection.
564 clientStreamNode
*node
= (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
565 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
567 repContext
->setReplyToError(ERR_CONFLICT_HOST
, Http::scConflict
,
568 http
->request
->method
, NULL
,
573 http
->getConn() != NULL
&& http
->getConn()->getAuth() != NULL
?
574 http
->getConn()->getAuth() : http
->request
->auth_user_request
);
578 node
= (clientStreamNode
*)http
->client_stream
.tail
->data
;
579 clientStreamRead(node
, http
, node
->readBuffer
);
583 ClientRequestContext::hostHeaderVerify()
585 // Require a Host: header.
586 const char *host
= http
->request
->header
.getStr(Http::HdrType::HOST
);
589 // TODO: dump out the HTTP/1.1 error about missing host header.
590 // otherwise this is fine, can't forge a header value when its not even set.
591 debugs(85, 3, HERE
<< "validate skipped with no Host: header present.");
596 if (http
->request
->flags
.internal
) {
597 // TODO: kill this when URL handling allows partial URLs out of accel mode
598 // and we no longer screw with the URL just to add our internal host there
599 debugs(85, 6, HERE
<< "validate skipped due to internal composite URL.");
604 // Locate if there is a port attached, strip ready for IP lookup
605 char *portStr
= NULL
;
606 char *hostB
= xstrdup(host
);
608 if (host
[0] == '[') {
610 portStr
= strchr(hostB
, ']');
611 if (portStr
&& *(++portStr
) != ':') {
615 // Domain or IPv4 literal with port
616 portStr
= strrchr(hostB
, ':');
621 *portStr
= '\0'; // strip the ':'
622 if (*(++portStr
) != '\0') {
624 int64_t ret
= strtoll(portStr
, &end
, 10);
625 if (end
== portStr
|| *end
!= '\0' || ret
< 1 || ret
> 0xFFFF) {
626 // invalid port details. Replace the ':'
630 port
= (ret
& 0xFFFF);
634 debugs(85, 3, "validate host=" << host
<< ", port=" << port
<< ", portStr=" << (portStr
?portStr
:"NULL"));
635 if (http
->request
->flags
.intercepted
|| http
->request
->flags
.interceptTproxy
) {
636 // verify the Host: port (if any) matches the apparent destination
637 if (portStr
&& port
!= http
->getConn()->clientConnection
->local
.port()) {
638 debugs(85, 3, "FAIL on validate port " << http
->getConn()->clientConnection
->local
.port() <<
639 " matches Host: port " << port
<< " (" << portStr
<< ")");
640 hostHeaderVerifyFailed("intercepted port", portStr
);
642 // XXX: match the scheme default port against the apparent destination
644 // verify the destination DNS is one of the Host: headers IPs
645 ipcache_nbgethostbyname(host
, hostHeaderIpVerifyWrapper
, this);
647 } else if (!Config
.onoff
.hostStrictVerify
) {
648 debugs(85, 3, "validate skipped.");
650 } else if (strlen(host
) != strlen(http
->request
->url
.host())) {
651 // Verify forward-proxy requested URL domain matches the Host: header
652 debugs(85, 3, "FAIL on validate URL domain length " << http
->request
->url
.host() << " matches Host: " << host
);
653 hostHeaderVerifyFailed(host
, http
->request
->url
.host());
654 } else if (matchDomainName(host
, http
->request
->url
.host()) != 0) {
655 // Verify forward-proxy requested URL domain matches the Host: header
656 debugs(85, 3, "FAIL on validate URL domain " << http
->request
->url
.host() << " matches Host: " << host
);
657 hostHeaderVerifyFailed(host
, http
->request
->url
.host());
658 } else if (portStr
&& port
!= http
->request
->url
.port()) {
659 // Verify forward-proxy requested URL domain matches the Host: header
660 debugs(85, 3, "FAIL on validate URL port " << http
->request
->url
.port() << " matches Host: port " << portStr
);
661 hostHeaderVerifyFailed("URL port", portStr
);
662 } else if (!portStr
&& http
->request
->method
!= Http::METHOD_CONNECT
&& http
->request
->url
.port() != http
->request
->url
.getScheme().defaultPort()) {
663 // Verify forward-proxy requested URL domain matches the Host: header
664 // Special case: we don't have a default-port to check for CONNECT. Assume URL is correct.
665 debugs(85, 3, "FAIL on validate URL port " << http
->request
->url
.port() << " matches Host: default port " << http
->request
->url
.getScheme().defaultPort());
666 hostHeaderVerifyFailed("URL port", "default port");
669 debugs(85, 3, "validate passed.");
670 http
->request
->flags
.hostVerified
= true;
676 /* This is the entry point for external users of the client_side routines */
678 ClientRequestContext::clientAccessCheck()
680 #if FOLLOW_X_FORWARDED_FOR
681 if (!http
->request
->flags
.doneFollowXff() &&
682 Config
.accessList
.followXFF
&&
683 http
->request
->header
.has(Http::HdrType::X_FORWARDED_FOR
)) {
685 /* we always trust the direct client address for actual use */
686 http
->request
->indirect_client_addr
= http
->request
->client_addr
;
687 http
->request
->indirect_client_addr
.port(0);
689 /* setup the XFF iterator for processing */
690 http
->request
->x_forwarded_for_iterator
= http
->request
->header
.getList(Http::HdrType::X_FORWARDED_FOR
);
692 /* begin by checking to see if we trust direct client enough to walk XFF */
693 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.followXFF
, http
);
694 acl_checklist
->nonBlockingCheck(clientFollowXForwardedForCheck
, this);
699 if (Config
.accessList
.http
) {
700 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.http
, http
);
701 acl_checklist
->nonBlockingCheck(clientAccessCheckDoneWrapper
, this);
703 debugs(0, DBG_CRITICAL
, "No http_access configuration found. This will block ALL traffic");
704 clientAccessCheckDone(ACCESS_DENIED
);
709 * Identical in operation to clientAccessCheck() but performed later using different configured ACL list.
710 * The default here is to allow all. Since the earlier http_access should do a default deny all.
711 * This check is just for a last-minute denial based on adapted request headers.
714 ClientRequestContext::clientAccessCheck2()
716 if (Config
.accessList
.adapted_http
) {
717 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.adapted_http
, http
);
718 acl_checklist
->nonBlockingCheck(clientAccessCheckDoneWrapper
, this);
720 debugs(85, 2, HERE
<< "No adapted_http_access configuration. default: ALLOW");
721 clientAccessCheckDone(ACCESS_ALLOWED
);
726 clientAccessCheckDoneWrapper(Acl::Answer answer
, void *data
)
728 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
730 if (!calloutContext
->httpStateIsValid())
733 calloutContext
->clientAccessCheckDone(answer
);
737 ClientRequestContext::clientAccessCheckDone(const Acl::Answer
&answer
)
739 acl_checklist
= NULL
;
741 Http::StatusCode status
;
742 debugs(85, 2, "The request " << http
->request
->method
<< ' ' <<
743 http
->uri
<< " is " << answer
<<
744 "; last ACL checked: " << (AclMatchedName
? AclMatchedName
: "[none]"));
747 char const *proxy_auth_msg
= "<null>";
748 if (http
->getConn() != NULL
&& http
->getConn()->getAuth() != NULL
)
749 proxy_auth_msg
= http
->getConn()->getAuth()->denyMessage("<null>");
750 else if (http
->request
->auth_user_request
!= NULL
)
751 proxy_auth_msg
= http
->request
->auth_user_request
->denyMessage("<null>");
754 if (!answer
.allowed()) {
755 // auth has a grace period where credentials can be expired but okay not to challenge.
757 /* Send an auth challenge or error */
758 // XXX: do we still need aclIsProxyAuth() ?
759 bool auth_challenge
= (answer
== ACCESS_AUTH_REQUIRED
|| aclIsProxyAuth(AclMatchedName
));
760 debugs(85, 5, "Access Denied: " << http
->uri
);
761 debugs(85, 5, "AclMatchedName = " << (AclMatchedName
? AclMatchedName
: "<null>"));
764 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg
? proxy_auth_msg
: "<null>"));
768 * NOTE: get page_id here, based on AclMatchedName because if
769 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
770 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
773 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, answer
!= ACCESS_AUTH_REQUIRED
);
775 http
->logType
.update(LOG_TCP_DENIED
);
777 if (auth_challenge
) {
779 if (http
->request
->flags
.sslBumped
) {
780 /*SSL Bumped request, authentication is not possible*/
781 status
= Http::scForbidden
;
782 } else if (!http
->flags
.accel
) {
783 /* Proxy authorisation needed */
784 status
= Http::scProxyAuthenticationRequired
;
786 /* WWW authorisation needed */
787 status
= Http::scUnauthorized
;
790 // need auth, but not possible to do.
791 status
= Http::scForbidden
;
793 if (page_id
== ERR_NONE
)
794 page_id
= ERR_CACHE_ACCESS_DENIED
;
796 status
= Http::scForbidden
;
798 if (page_id
== ERR_NONE
)
799 page_id
= ERR_ACCESS_DENIED
;
802 error
= clientBuildError(page_id
, status
, nullptr, http
->getConn(), http
->request
, http
->al
);
805 error
->auth_user_request
=
806 http
->getConn() != NULL
&& http
->getConn()->getAuth() != NULL
?
807 http
->getConn()->getAuth() : http
->request
->auth_user_request
;
810 readNextRequest
= true;
813 /* ACCESS_ALLOWED continues here ... */
815 http
->uri
= SBufToCstring(http
->request
->effectiveRequestUri());
821 ClientHttpRequest::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer g
)
823 debugs(93,3,HERE
<< this << " adaptationAclCheckDone called");
826 Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
828 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
) {
829 ih
->rfc931
= getConn()->clientConnection
->rfc931
;
831 if (getConn()->clientConnection
->isOpen()) {
832 ih
->ssluser
= sslGetUserEmail(fd_table
[getConn()->clientConnection
->fd
].ssl
.get());
836 ih
->log_uri
= log_uri
;
842 debugs(85,3, HERE
<< "no adaptation needed");
853 clientRedirectAccessCheckDone(Acl::Answer answer
, void *data
)
855 ClientRequestContext
*context
= (ClientRequestContext
*)data
;
856 ClientHttpRequest
*http
= context
->http
;
857 context
->acl_checklist
= NULL
;
859 if (answer
.allowed())
860 redirectStart(http
, clientRedirectDoneWrapper
, context
);
862 Helper::Reply
const nilReply(Helper::Error
);
863 context
->clientRedirectDone(nilReply
);
868 ClientRequestContext::clientRedirectStart()
870 debugs(33, 5, HERE
<< "'" << http
->uri
<< "'");
871 http
->al
->syncNotes(http
->request
);
872 if (Config
.accessList
.redirector
) {
873 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.redirector
, http
);
874 acl_checklist
->nonBlockingCheck(clientRedirectAccessCheckDone
, this);
876 redirectStart(http
, clientRedirectDoneWrapper
, this);
880 * This methods handles Access checks result of StoreId access list.
881 * Will handle as "ERR" (no change) in a case Access is not allowed.
884 clientStoreIdAccessCheckDone(Acl::Answer answer
, void *data
)
886 ClientRequestContext
*context
= static_cast<ClientRequestContext
*>(data
);
887 ClientHttpRequest
*http
= context
->http
;
888 context
->acl_checklist
= NULL
;
890 if (answer
.allowed())
891 storeIdStart(http
, clientStoreIdDoneWrapper
, context
);
893 debugs(85, 3, "access denied expected ERR reply handling: " << answer
);
894 Helper::Reply
const nilReply(Helper::Error
);
895 context
->clientStoreIdDone(nilReply
);
900 * Start locating an alternative storage ID string (if any) from admin
901 * configured helper program. This is an asynchronous operation terminating in
902 * ClientRequestContext::clientStoreIdDone() when completed.
905 ClientRequestContext::clientStoreIdStart()
907 debugs(33, 5,"'" << http
->uri
<< "'");
909 if (Config
.accessList
.store_id
) {
910 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.store_id
, http
);
911 acl_checklist
->nonBlockingCheck(clientStoreIdAccessCheckDone
, this);
913 storeIdStart(http
, clientStoreIdDoneWrapper
, this);
917 clientHierarchical(ClientHttpRequest
* http
)
919 HttpRequest
*request
= http
->request
;
920 HttpRequestMethod method
= request
->method
;
922 // intercepted requests MUST NOT (yet) be sent to peers unless verified
923 if (!request
->flags
.hostVerified
&& (request
->flags
.intercepted
|| request
->flags
.interceptTproxy
))
927 * IMS needs a private key, so we can use the hierarchy for IMS only if our
928 * neighbors support private keys
931 if (request
->flags
.ims
&& !neighbors_do_private_keys
)
935 * This is incorrect: authenticating requests can be sent via a hierarchy
936 * (they can even be cached if the correct headers are set on the reply)
938 if (request
->flags
.auth
)
941 if (method
== Http::METHOD_TRACE
)
944 if (method
!= Http::METHOD_GET
)
947 if (request
->flags
.loopDetected
)
950 if (request
->url
.getScheme() == AnyP::PROTO_HTTP
)
951 return method
.respMaybeCacheable();
953 if (request
->url
.getScheme() == AnyP::PROTO_GOPHER
)
954 return gopherCachable(request
);
956 if (request
->url
.getScheme() == AnyP::PROTO_CACHE_OBJECT
)
963 clientCheckPinning(ClientHttpRequest
* http
)
965 HttpRequest
*request
= http
->request
;
966 HttpHeader
*req_hdr
= &request
->header
;
967 ConnStateData
*http_conn
= http
->getConn();
969 /* Internal requests such as those from ESI includes may be without
970 * a client connection
975 request
->flags
.connectionAuthDisabled
= http_conn
->port
->connection_auth_disabled
;
976 if (!request
->flags
.connectionAuthDisabled
) {
977 if (Comm::IsConnOpen(http_conn
->pinning
.serverConnection
)) {
978 if (http_conn
->pinning
.auth
) {
979 request
->flags
.connectionAuth
= true;
980 request
->flags
.auth
= true;
982 request
->flags
.connectionProxyAuth
= true;
984 // These should already be linked correctly.
985 assert(request
->clientConnectionManager
== http_conn
);
989 /* check if connection auth is used, and flag as candidate for pinning
991 * Note: we may need to set flags.connectionAuth even if the connection
992 * is already pinned if it was pinned earlier due to proxy auth
994 if (!request
->flags
.connectionAuth
) {
995 if (req_hdr
->has(Http::HdrType::AUTHORIZATION
) || req_hdr
->has(Http::HdrType::PROXY_AUTHORIZATION
)) {
996 HttpHeaderPos pos
= HttpHeaderInitPos
;
999 while ((e
= req_hdr
->getEntry(&pos
))) {
1000 if (e
->id
== Http::HdrType::AUTHORIZATION
|| e
->id
== Http::HdrType::PROXY_AUTHORIZATION
) {
1001 const char *value
= e
->value
.rawBuf();
1002 if (strncasecmp(value
, "NTLM ", 5) == 0
1004 strncasecmp(value
, "Negotiate ", 10) == 0
1006 strncasecmp(value
, "Kerberos ", 9) == 0) {
1007 if (e
->id
== Http::HdrType::AUTHORIZATION
) {
1008 request
->flags
.connectionAuth
= true;
1011 request
->flags
.connectionProxyAuth
= true;
1017 if (may_pin
&& !request
->pinnedConnection()) {
1018 // These should already be linked correctly. Just need the ServerConnection to pinn.
1019 assert(request
->clientConnectionManager
== http_conn
);
1026 clientInterpretRequestHeaders(ClientHttpRequest
* http
)
1028 HttpRequest
*request
= http
->request
;
1029 HttpHeader
*req_hdr
= &request
->header
;
1030 bool no_cache
= false;
1032 request
->imslen
= -1;
1033 request
->ims
= req_hdr
->getTime(Http::HdrType::IF_MODIFIED_SINCE
);
1035 if (request
->ims
> 0)
1036 request
->flags
.ims
= true;
1038 if (!request
->flags
.ignoreCc
) {
1039 if (request
->cache_control
) {
1040 if (request
->cache_control
->hasNoCache())
1043 // RFC 2616: treat Pragma:no-cache as if it was Cache-Control:no-cache when Cache-Control is missing
1044 } else if (req_hdr
->has(Http::HdrType::PRAGMA
))
1045 no_cache
= req_hdr
->hasListMember(Http::HdrType::PRAGMA
,"no-cache",',');
1048 if (request
->method
== Http::METHOD_OTHER
) {
1053 #if USE_HTTP_VIOLATIONS
1055 if (Config
.onoff
.reload_into_ims
)
1056 request
->flags
.nocacheHack
= true;
1057 else if (refresh_nocache_hack
)
1058 request
->flags
.nocacheHack
= true;
1062 request
->flags
.noCache
= true;
1065 /* ignore range header in non-GETs or non-HEADs */
1066 if (request
->method
== Http::METHOD_GET
|| request
->method
== Http::METHOD_HEAD
) {
1067 // XXX: initialize if we got here without HttpRequest::parseHeader()
1068 if (!request
->range
)
1069 request
->range
= req_hdr
->getRange();
1071 if (request
->range
) {
1072 request
->flags
.isRanged
= true;
1073 clientStreamNode
*node
= (clientStreamNode
*)http
->client_stream
.tail
->data
;
1074 /* XXX: This is suboptimal. We should give the stream the range set,
1075 * and thereby let the top of the stream set the offset when the
1076 * size becomes known. As it is, we will end up requesting from 0
1077 * for evey -X range specification.
1078 * RBC - this may be somewhat wrong. We should probably set the range
1079 * iter up at this point.
1081 node
->readBuffer
.offset
= request
->range
->lowestOffset(0);
1085 /* Only HEAD and GET requests permit a Range or Request-Range header.
1086 * If these headers appear on any other type of request, delete them now.
1089 req_hdr
->delById(Http::HdrType::RANGE
);
1090 req_hdr
->delById(Http::HdrType::REQUEST_RANGE
);
1091 request
->ignoreRange("neither HEAD nor GET");
1094 if (req_hdr
->has(Http::HdrType::AUTHORIZATION
))
1095 request
->flags
.auth
= true;
1097 clientCheckPinning(http
);
1099 if (!request
->url
.userInfo().isEmpty())
1100 request
->flags
.auth
= true;
1102 if (req_hdr
->has(Http::HdrType::VIA
)) {
1103 String s
= req_hdr
->getList(Http::HdrType::VIA
);
1105 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
1106 * Note ThisCache2 has a space prepended to the hostname so we don't
1107 * accidentally match super-domains.
1110 if (strListIsSubstr(&s
, ThisCache2
, ',')) {
1111 request
->flags
.loopDetected
= true;
1115 fvdbCountVia(StringToSBuf(s
));
1122 // headers only relevant to reverse-proxy
1123 if (request
->flags
.accelerated
) {
1124 // check for a cdn-info member with a cdn-id matching surrogate_id
1125 // XXX: HttpHeader::hasListMember() does not handle OWS around ";" yet
1126 if (req_hdr
->hasListMember(Http::HdrType::CDN_LOOP
, Config
.Accel
.surrogate_id
, ','))
1127 request
->flags
.loopDetected
= true;
1130 if (request
->flags
.loopDetected
) {
1131 debugObj(33, DBG_IMPORTANT
, "WARNING: Forwarding loop detected for:\n",
1132 request
, (ObjPackMethod
) & httpRequestPack
);
1137 if (req_hdr
->has(Http::HdrType::X_FORWARDED_FOR
)) {
1138 String s
= req_hdr
->getList(Http::HdrType::X_FORWARDED_FOR
);
1139 fvdbCountForw(s
.termedBuf());
1145 request
->flags
.cachable
= http
->request
->maybeCacheable();
1147 if (clientHierarchical(http
))
1148 request
->flags
.hierarchical
= true;
1150 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
1151 (request
->flags
.noCache
? "SET" : "NOT SET"));
1152 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
1153 (request
->flags
.cachable
? "SET" : "NOT SET"));
1154 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
1155 (request
->flags
.hierarchical
? "SET" : "NOT SET"));
1160 clientRedirectDoneWrapper(void *data
, const Helper::Reply
&result
)
1162 ClientRequestContext
*calloutContext
= (ClientRequestContext
*)data
;
1164 if (!calloutContext
->httpStateIsValid())
1167 calloutContext
->clientRedirectDone(result
);
1171 clientStoreIdDoneWrapper(void *data
, const Helper::Reply
&result
)
1173 ClientRequestContext
*calloutContext
= (ClientRequestContext
*)data
;
1175 if (!calloutContext
->httpStateIsValid())
1178 calloutContext
->clientStoreIdDone(result
);
1182 ClientRequestContext::clientRedirectDone(const Helper::Reply
&reply
)
1184 HttpRequest
*old_request
= http
->request
;
1185 debugs(85, 5, HERE
<< "'" << http
->uri
<< "' result=" << reply
);
1186 assert(redirect_state
== REDIRECT_PENDING
);
1187 redirect_state
= REDIRECT_DONE
;
1189 // Put helper response Notes into the transaction state record (ALE) eventually
1190 // do it early to ensure that no matter what the outcome the notes are present.
1192 http
->al
->syncNotes(old_request
);
1194 UpdateRequestNotes(http
->getConn(), *old_request
, reply
.notes
);
1196 switch (reply
.result
) {
1197 case Helper::TimedOut
:
1198 if (Config
.onUrlRewriteTimeout
.action
!= toutActBypass
) {
1199 static const auto d
= MakeNamedErrorDetail("REDIRECTOR_TIMEDOUT");
1200 http
->calloutsError(ERR_GATEWAY_FAILURE
, d
);
1201 debugs(85, DBG_IMPORTANT
, "ERROR: URL rewrite helper: Timedout");
1205 case Helper::Unknown
:
1207 // Handler in redirect.cc should have already mapped Unknown
1208 // IF it contained valid entry for the old URL-rewrite helper protocol
1209 debugs(85, DBG_IMPORTANT
, "ERROR: URL rewrite helper returned invalid result code. Wrong helper? " << reply
);
1212 case Helper::BrokenHelper
:
1213 debugs(85, DBG_IMPORTANT
, "ERROR: URL rewrite helper: " << reply
);
1217 // no change to be done.
1220 case Helper::Okay
: {
1221 // #1: redirect with a specific status code OK status=NNN url="..."
1222 // #2: redirect with a default status code OK url="..."
1223 // #3: re-write the URL OK rewrite-url="..."
1225 const char *statusNote
= reply
.notes
.findFirst("status");
1226 const char *urlNote
= reply
.notes
.findFirst("url");
1228 if (urlNote
!= NULL
) {
1229 // HTTP protocol redirect to be done.
1231 // TODO: change default redirect status for appropriate requests
1232 // Squid defaults to 302 status for now for better compatibility with old clients.
1233 // HTTP/1.0 client should get 302 (Http::scFound)
1234 // HTTP/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect)
1235 // HTTP/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther)
1236 Http::StatusCode status
= Http::scFound
;
1237 if (statusNote
!= NULL
) {
1238 const char * result
= statusNote
;
1239 status
= static_cast<Http::StatusCode
>(atoi(result
));
1242 if (status
== Http::scMovedPermanently
1243 || status
== Http::scFound
1244 || status
== Http::scSeeOther
1245 || status
== Http::scPermanentRedirect
1246 || status
== Http::scTemporaryRedirect
) {
1247 http
->redirect
.status
= status
;
1248 http
->redirect
.location
= xstrdup(urlNote
);
1249 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
1251 debugs(85, DBG_CRITICAL
, "ERROR: URL-rewrite produces invalid " << status
<< " redirect Location: " << urlNote
);
1254 // URL-rewrite wanted. Ew.
1255 urlNote
= reply
.notes
.findFirst("rewrite-url");
1257 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1258 if (urlNote
!= NULL
&& strcmp(urlNote
, http
->uri
)) {
1260 if (tmpUrl
.parse(old_request
->method
, SBuf(urlNote
))) {
1261 HttpRequest
*new_request
= old_request
->clone();
1262 new_request
->url
= tmpUrl
;
1263 debugs(61, 2, "URL-rewriter diverts URL from " << old_request
->effectiveRequestUri() << " to " << new_request
->effectiveRequestUri());
1265 // update the new request to flag the re-writing was done on it
1266 new_request
->flags
.redirected
= true;
1268 // unlink bodypipe from the old request. Not needed there any longer.
1269 if (old_request
->body_pipe
!= NULL
) {
1270 old_request
->body_pipe
= NULL
;
1271 debugs(61,2, HERE
<< "URL-rewriter diverts body_pipe " << new_request
->body_pipe
<<
1272 " from request " << old_request
<< " to " << new_request
);
1275 http
->resetRequest(new_request
);
1276 old_request
= nullptr;
1278 debugs(85, DBG_CRITICAL
, "ERROR: URL-rewrite produces invalid request: " <<
1279 old_request
->method
<< " " << urlNote
<< " " << old_request
->http_ver
);
1287 /* XXX PIPELINE: This is inaccurate during pipelining */
1289 if (http
->getConn() != NULL
&& Comm::IsConnOpen(http
->getConn()->clientConnection
))
1290 fd_note(http
->getConn()->clientConnection
->fd
, http
->uri
);
1298 * This method handles the different replies from StoreID helper.
1301 ClientRequestContext::clientStoreIdDone(const Helper::Reply
&reply
)
1303 HttpRequest
*old_request
= http
->request
;
1304 debugs(85, 5, "'" << http
->uri
<< "' result=" << reply
);
1305 assert(store_id_state
== REDIRECT_PENDING
);
1306 store_id_state
= REDIRECT_DONE
;
1308 // Put helper response Notes into the transaction state record (ALE) eventually
1309 // do it early to ensure that no matter what the outcome the notes are present.
1311 http
->al
->syncNotes(old_request
);
1313 UpdateRequestNotes(http
->getConn(), *old_request
, reply
.notes
);
1315 switch (reply
.result
) {
1316 case Helper::Unknown
:
1318 // Handler in redirect.cc should have already mapped Unknown
1319 // IF it contained valid entry for the old helper protocol
1320 debugs(85, DBG_IMPORTANT
, "ERROR: storeID helper returned invalid result code. Wrong helper? " << reply
);
1323 case Helper::TimedOut
:
1324 // Timeouts for storeID are not implemented
1325 case Helper::BrokenHelper
:
1326 debugs(85, DBG_IMPORTANT
, "ERROR: storeID helper: " << reply
);
1330 // no change to be done.
1333 case Helper::Okay
: {
1334 const char *urlNote
= reply
.notes
.findFirst("store-id");
1336 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1337 if (urlNote
!= NULL
&& strcmp(urlNote
, http
->uri
) ) {
1338 // Debug section required for some very specific cases.
1339 debugs(85, 9, "Setting storeID with: " << urlNote
);
1340 http
->request
->store_id
= urlNote
;
1341 http
->store_id
= urlNote
;
1350 /** Test cache allow/deny configuration
1351 * Sets flags.cachable=1 if caching is not denied.
1354 ClientRequestContext::checkNoCache()
1356 if (Config
.accessList
.noCache
) {
1357 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.noCache
, http
);
1358 acl_checklist
->nonBlockingCheck(checkNoCacheDoneWrapper
, this);
1360 /* unless otherwise specified, we try to cache. */
1361 checkNoCacheDone(ACCESS_ALLOWED
);
1366 checkNoCacheDoneWrapper(Acl::Answer answer
, void *data
)
1368 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
1370 if (!calloutContext
->httpStateIsValid())
1373 calloutContext
->checkNoCacheDone(answer
);
1377 ClientRequestContext::checkNoCacheDone(const Acl::Answer
&answer
)
1379 acl_checklist
= NULL
;
1380 if (answer
.denied()) {
1381 http
->request
->flags
.noCache
= true; // do not read reply from cache
1382 http
->request
->flags
.cachable
= false; // do not store reply into cache
1389 ClientRequestContext::sslBumpAccessCheck()
1391 if (!http
->getConn()) {
1392 http
->al
->ssl
.bumpMode
= Ssl::bumpEnd
; // SslBump does not apply; log -
1396 const Ssl::BumpMode bumpMode
= http
->getConn()->sslBumpMode
;
1397 if (http
->request
->flags
.forceTunnel
) {
1398 debugs(85, 5, "not needed; already decided to tunnel " << http
->getConn());
1399 if (bumpMode
!= Ssl::bumpEnd
)
1400 http
->al
->ssl
.bumpMode
= bumpMode
; // inherited from bumped connection
1404 // If SSL connection tunneling or bumping decision has been made, obey it.
1405 if (bumpMode
!= Ssl::bumpEnd
) {
1406 debugs(85, 5, HERE
<< "SslBump already decided (" << bumpMode
<<
1407 "), " << "ignoring ssl_bump for " << http
->getConn());
1409 // We need the following "if" for transparently bumped TLS connection,
1410 // because in this case we are running ssl_bump access list before
1411 // the doCallouts runs. It can be removed after the bug #4340 fixed.
1412 // We do not want to proceed to bumping steps:
1413 // - if the TLS connection with the client is already established
1414 // because we are accepting normal HTTP requests on TLS port,
1415 // or because of the client-first bumping mode
1416 // - When the bumping is already started
1417 if (!http
->getConn()->switchedToHttps() &&
1418 !http
->getConn()->serverBump())
1419 http
->sslBumpNeed(bumpMode
); // for processRequest() to bump if needed and not already bumped
1420 http
->al
->ssl
.bumpMode
= bumpMode
; // inherited from bumped connection
1424 // If we have not decided yet, decide whether to bump now.
1426 // Bumping here can only start with a CONNECT request on a bumping port
1427 // (bumping of intercepted SSL conns is decided before we get 1st request).
1428 // We also do not bump redirected CONNECT requests.
1429 if (http
->request
->method
!= Http::METHOD_CONNECT
|| http
->redirect
.status
||
1430 !Config
.accessList
.ssl_bump
||
1431 !http
->getConn()->port
->flags
.tunnelSslBumping
) {
1432 http
->al
->ssl
.bumpMode
= Ssl::bumpEnd
; // SslBump does not apply; log -
1433 debugs(85, 5, HERE
<< "cannot SslBump this request");
1437 // Do not bump during authentication: clients would not proxy-authenticate
1438 // if we delay a 407 response and respond with 200 OK to CONNECT.
1439 if (error
&& error
->httpStatus
== Http::scProxyAuthenticationRequired
) {
1440 http
->al
->ssl
.bumpMode
= Ssl::bumpEnd
; // SslBump does not apply; log -
1441 debugs(85, 5, HERE
<< "no SslBump during proxy authentication");
1446 debugs(85, 5, "SslBump applies. Force bump action on error " << errorTypeName(error
->type
));
1447 http
->sslBumpNeed(Ssl::bumpBump
);
1448 http
->al
->ssl
.bumpMode
= Ssl::bumpBump
;
1452 debugs(85, 5, HERE
<< "SslBump possible, checking ACL");
1454 ACLFilledChecklist
*aclChecklist
= clientAclChecklistCreate(Config
.accessList
.ssl_bump
, http
);
1455 aclChecklist
->nonBlockingCheck(sslBumpAccessCheckDoneWrapper
, this);
1460 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1461 * as ACLFilledChecklist callback
1464 sslBumpAccessCheckDoneWrapper(Acl::Answer answer
, void *data
)
1466 ClientRequestContext
*calloutContext
= static_cast<ClientRequestContext
*>(data
);
1468 if (!calloutContext
->httpStateIsValid())
1470 calloutContext
->sslBumpAccessCheckDone(answer
);
1474 ClientRequestContext::sslBumpAccessCheckDone(const Acl::Answer
&answer
)
1476 if (!httpStateIsValid())
1479 const Ssl::BumpMode bumpMode
= answer
.allowed() ?
1480 static_cast<Ssl::BumpMode
>(answer
.kind
) : Ssl::bumpSplice
;
1481 http
->sslBumpNeed(bumpMode
); // for processRequest() to bump if needed
1482 http
->al
->ssl
.bumpMode
= bumpMode
; // for logging
1484 if (bumpMode
== Ssl::bumpTerminate
) {
1485 const Comm::ConnectionPointer clientConn
= http
->getConn() ? http
->getConn()->clientConnection
: nullptr;
1486 if (Comm::IsConnOpen(clientConn
)) {
1487 debugs(85, 3, "closing after Ssl::bumpTerminate ");
1488 clientConn
->close();
1498 * Identify requests that do not go through the store and client side stream
1499 * and forward them to the appropriate location. All other requests, request
1503 ClientHttpRequest::processRequest()
1505 debugs(85, 4, request
->method
<< ' ' << uri
);
1507 const bool untouchedConnect
= request
->method
== Http::METHOD_CONNECT
&& !redirect
.status
;
1510 if (untouchedConnect
&& sslBumpNeeded()) {
1511 assert(!request
->flags
.forceTunnel
);
1517 if (untouchedConnect
|| request
->flags
.forceTunnel
) {
1518 getConn()->stopReading(); // tunnels read for themselves
1527 ClientHttpRequest::httpStart()
1529 PROF_start(httpStart
);
1530 // XXX: Re-initializes rather than updates. Should not be needed at all.
1531 logType
.update(LOG_TAG_NONE
);
1532 debugs(85, 4, logType
.c_str() << " for '" << uri
<< "'");
1534 /* no one should have touched this */
1535 assert(out
.offset
== 0);
1536 /* Use the Stream Luke */
1537 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->data
;
1538 clientStreamRead(node
, this, node
->readBuffer
);
1539 PROF_stop(httpStart
);
1545 ClientHttpRequest::sslBumpNeed(Ssl::BumpMode mode
)
1547 debugs(83, 3, HERE
<< "sslBump required: "<< Ssl::bumpMode(mode
));
1548 sslBumpNeed_
= mode
;
1551 // called when comm_write has completed
1553 SslBumpEstablish(const Comm::ConnectionPointer
&, char *, size_t, Comm::Flag errflag
, int, void *data
)
1555 ClientHttpRequest
*r
= static_cast<ClientHttpRequest
*>(data
);
1556 debugs(85, 5, HERE
<< "responded to CONNECT: " << r
<< " ? " << errflag
);
1558 assert(r
&& cbdataReferenceValid(r
));
1559 r
->sslBumpEstablish(errflag
);
1563 ClientHttpRequest::sslBumpEstablish(Comm::Flag errflag
)
1565 // Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up
1566 if (errflag
== Comm::ERR_CLOSING
)
1570 debugs(85, 3, HERE
<< "CONNECT response failure in SslBump: " << errflag
);
1571 getConn()->clientConnection
->close();
1576 // Preserve authentication info for the ssl-bumped request
1577 if (request
->auth_user_request
!= NULL
)
1578 getConn()->setAuth(request
->auth_user_request
, "SSL-bumped CONNECT");
1581 assert(sslBumpNeeded());
1582 getConn()->switchToHttps(this, sslBumpNeed_
);
1586 ClientHttpRequest::sslBumpStart()
1588 debugs(85, 5, HERE
<< "Confirming " << Ssl::bumpMode(sslBumpNeed_
) <<
1589 "-bumped CONNECT tunnel on FD " << getConn()->clientConnection
);
1590 getConn()->sslBumpMode
= sslBumpNeed_
;
1592 AsyncCall::Pointer bumpCall
= commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1593 CommIoCbPtrFun(&SslBumpEstablish
, this));
1595 if (request
->flags
.interceptTproxy
|| request
->flags
.intercepted
) {
1596 CommIoCbParams
¶ms
= GetCommParams
<CommIoCbParams
>(bumpCall
);
1597 params
.flag
= Comm::OK
;
1598 params
.conn
= getConn()->clientConnection
;
1599 ScheduleCallHere(bumpCall
);
1603 al
->reply
= HttpReply::MakeConnectionEstablished();
1605 const auto mb
= al
->reply
->pack();
1606 // send an HTTP 200 response to kick client SSL negotiation
1607 // TODO: Unify with tunnel.cc and add a Server(?) header
1608 Comm::Write(getConn()->clientConnection
, mb
, bumpCall
);
1615 ClientHttpRequest::updateError(const Error
&error
)
1618 request
->error
.update(error
);
1620 al
->updateError(error
);
1624 ClientHttpRequest::gotEnough() const
1626 // TODO: See also (and unify with) clientReplyContext::storeNotOKTransferDone()
1627 int64_t contentLength
=
1628 memObject()->baseReply().bodySize(request
->method
);
1629 assert(contentLength
>= 0);
1631 if (out
.offset
< contentLength
)
1638 ClientHttpRequest::storeEntry(StoreEntry
*newEntry
)
1644 ClientHttpRequest::loggingEntry(StoreEntry
*newEntry
)
1647 loggingEntry_
->unlock("ClientHttpRequest::loggingEntry");
1649 loggingEntry_
= newEntry
;
1652 loggingEntry_
->lock("ClientHttpRequest::loggingEntry");
1656 ClientHttpRequest::initRequest(HttpRequest
*aRequest
)
1658 assignRequest(aRequest
);
1659 if (const auto csd
= getConn()) {
1660 if (!csd
->notes()->empty())
1661 request
->notes()->appendNewOnly(csd
->notes().getRaw());
1663 // al is created in the constructor
1666 al
->request
= request
;
1667 HTTPMSGLOCK(al
->request
);
1668 al
->syncNotes(request
);
1673 ClientHttpRequest::resetRequest(HttpRequest
*newRequest
)
1675 assert(request
!= newRequest
);
1677 assignRequest(newRequest
);
1679 uri
= SBufToCstring(request
->effectiveRequestUri());
1683 ClientHttpRequest::assignRequest(HttpRequest
*newRequest
)
1687 const_cast<HttpRequest
*&>(request
) = newRequest
;
1688 HTTPMSGLOCK(request
);
1689 setLogUriToRequestUri();
1693 ClientHttpRequest::clearRequest()
1695 HttpRequest
*oldRequest
= request
;
1696 HTTPMSGUNLOCK(oldRequest
);
1697 const_cast<HttpRequest
*&>(request
) = nullptr;
1698 absorbLogUri(nullptr);
1702 * doCallouts() - This function controls the order of "callout"
1703 * executions, including non-blocking access control checks, the
1704 * redirector, and ICAP. Previously, these callouts were chained
1705 * together such that "clientAccessCheckDone()" would call
1706 * "clientRedirectStart()" and so on.
1708 * The ClientRequestContext (aka calloutContext) class holds certain
1709 * state data for the callout/callback operations. Previously
1710 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1711 * for a short time. ClientRequestContext would then delete itself
1712 * and pass control back to ClientHttpRequest when all callouts
1715 * This caused some problems for ICAP because we want to make the
1716 * ICAP callout after checking ACLs, but before checking the no_cache
1717 * list. We can't stuff the ICAP state into the ClientRequestContext
1718 * class because we still need the ICAP state after ClientRequestContext
1721 * Note that ClientRequestContext is created before the first call
1724 * If one of the callouts notices that ClientHttpRequest is no
1725 * longer valid, it should call cbdataReferenceDone() so that
1726 * ClientHttpRequest's reference count goes to zero and it will get
1727 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1729 * Note that we set the _done flags here before actually starting
1730 * the callout. This is strictly for convenience.
1733 tos_t
aclMapTOS (acl_tos
* head
, ACLChecklist
* ch
);
1734 Ip::NfMarkConfig
aclFindNfMarkConfig (acl_nfmark
* head
, ACLChecklist
* ch
);
1737 ClientHttpRequest::doCallouts()
1739 assert(calloutContext
);
1741 if (!calloutContext
->error
) {
1742 // CVE-2009-0801: verify the Host: header is consistent with other known details.
1743 if (!calloutContext
->host_header_verify_done
) {
1744 debugs(83, 3, HERE
<< "Doing calloutContext->hostHeaderVerify()");
1745 calloutContext
->host_header_verify_done
= true;
1746 calloutContext
->hostHeaderVerify();
1750 if (!calloutContext
->http_access_done
) {
1751 debugs(83, 3, HERE
<< "Doing calloutContext->clientAccessCheck()");
1752 calloutContext
->http_access_done
= true;
1753 calloutContext
->clientAccessCheck();
1758 if (!calloutContext
->adaptation_acl_check_done
) {
1759 calloutContext
->adaptation_acl_check_done
= true;
1760 if (Adaptation::AccessCheck::Start(
1761 Adaptation::methodReqmod
, Adaptation::pointPreCache
,
1762 request
, NULL
, calloutContext
->http
->al
, this))
1763 return; // will call callback
1767 if (!calloutContext
->redirect_done
) {
1768 calloutContext
->redirect_done
= true;
1770 if (Config
.Program
.redirect
) {
1771 debugs(83, 3, HERE
<< "Doing calloutContext->clientRedirectStart()");
1772 calloutContext
->redirect_state
= REDIRECT_PENDING
;
1773 calloutContext
->clientRedirectStart();
1778 if (!calloutContext
->adapted_http_access_done
) {
1779 debugs(83, 3, HERE
<< "Doing calloutContext->clientAccessCheck2()");
1780 calloutContext
->adapted_http_access_done
= true;
1781 calloutContext
->clientAccessCheck2();
1785 if (!calloutContext
->store_id_done
) {
1786 calloutContext
->store_id_done
= true;
1788 if (Config
.Program
.store_id
) {
1789 debugs(83, 3,"Doing calloutContext->clientStoreIdStart()");
1790 calloutContext
->store_id_state
= REDIRECT_PENDING
;
1791 calloutContext
->clientStoreIdStart();
1796 if (!calloutContext
->interpreted_req_hdrs
) {
1797 debugs(83, 3, HERE
<< "Doing clientInterpretRequestHeaders()");
1798 calloutContext
->interpreted_req_hdrs
= 1;
1799 clientInterpretRequestHeaders(this);
1802 if (!calloutContext
->no_cache_done
) {
1803 calloutContext
->no_cache_done
= true;
1805 if (Config
.accessList
.noCache
&& request
->flags
.cachable
) {
1806 debugs(83, 3, HERE
<< "Doing calloutContext->checkNoCache()");
1807 calloutContext
->checkNoCache();
1811 } // if !calloutContext->error
1813 // Set appropriate MARKs and CONNMARKs if needed.
1814 if (getConn() && Comm::IsConnOpen(getConn()->clientConnection
)) {
1815 ACLFilledChecklist
ch(nullptr, request
, nullptr);
1816 ch
.al
= calloutContext
->http
->al
;
1817 ch
.src_addr
= request
->client_addr
;
1818 ch
.my_addr
= request
->my_addr
;
1819 ch
.syncAle(request
, log_uri
);
1821 if (!calloutContext
->toClientMarkingDone
) {
1822 calloutContext
->toClientMarkingDone
= true;
1823 tos_t tos
= aclMapTOS(Ip::Qos::TheConfig
.tosToClient
, &ch
);
1825 Ip::Qos::setSockTos(getConn()->clientConnection
, tos
);
1827 const auto packetMark
= aclFindNfMarkConfig(Ip::Qos::TheConfig
.nfmarkToClient
, &ch
);
1828 if (!packetMark
.isEmpty())
1829 Ip::Qos::setSockNfmark(getConn()->clientConnection
, packetMark
.mark
);
1831 const auto connmark
= aclFindNfMarkConfig(Ip::Qos::TheConfig
.nfConnmarkToClient
, &ch
);
1832 if (!connmark
.isEmpty())
1833 Ip::Qos::setNfConnmark(getConn()->clientConnection
, Ip::Qos::dirAccepted
, connmark
);
1838 // Even with calloutContext->error, we call sslBumpAccessCheck() to decide
1839 // whether SslBump applies to this transaction. If it applies, we will
1840 // attempt to bump the client to serve the error.
1841 if (!calloutContext
->sslBumpCheckDone
) {
1842 calloutContext
->sslBumpCheckDone
= true;
1843 if (calloutContext
->sslBumpAccessCheck())
1845 /* else no ssl bump required*/
1849 if (calloutContext
->error
) {
1850 // XXX: prformance regression. c_str() reallocates
1851 SBuf
storeUriBuf(request
->storeId());
1852 const char *storeUri
= storeUriBuf
.c_str();
1853 StoreEntry
*e
= storeCreateEntry(storeUri
, storeUri
, request
->flags
, request
->method
);
1855 if (sslBumpNeeded()) {
1856 // We have to serve an error, so bump the client first.
1857 sslBumpNeed(Ssl::bumpClientFirst
);
1858 // set final error but delay sending until we bump
1859 Ssl::ServerBump
*srvBump
= new Ssl::ServerBump(this, e
, Ssl::bumpClientFirst
);
1860 errorAppendEntry(e
, calloutContext
->error
);
1861 calloutContext
->error
= NULL
;
1862 getConn()->setServerBump(srvBump
);
1863 e
->unlock("ClientHttpRequest::doCallouts+sslBumpNeeded");
1867 // send the error to the client now
1868 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
1869 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1870 assert (repContext
);
1871 repContext
->setReplyToStoreEntry(e
, "immediate SslBump error");
1872 errorAppendEntry(e
, calloutContext
->error
);
1873 calloutContext
->error
= NULL
;
1874 if (calloutContext
->readNextRequest
&& getConn())
1875 getConn()->flags
.readMore
= true; // resume any pipeline reads.
1876 node
= (clientStreamNode
*)client_stream
.tail
->data
;
1877 clientStreamRead(node
, this, node
->readBuffer
);
1878 e
->unlock("ClientHttpRequest::doCallouts-sslBumpNeeded");
1883 cbdataReferenceDone(calloutContext
->http
);
1884 delete calloutContext
;
1885 calloutContext
= NULL
;
1888 headersLog(0, 1, request
->method
, request
);
1891 debugs(83, 3, HERE
<< "calling processRequest()");
1895 Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
1897 ih
->logType
= logType
;
1902 ClientHttpRequest::setLogUriToRequestUri()
1905 const auto canonicalUri
= request
->canonicalCleanUrl();
1906 absorbLogUri(xstrndup(canonicalUri
, MAX_URL
));
1910 ClientHttpRequest::setLogUriToRawUri(const char *rawUri
, const HttpRequestMethod
&method
)
1913 // Should(!request);
1915 // TODO: SBuf() performance regression, fix by converting rawUri to SBuf
1916 char *canonicalUri
= urlCanonicalCleanWithoutRequest(SBuf(rawUri
), method
, AnyP::UriScheme());
1918 absorbLogUri(AnyP::Uri::cleanup(canonicalUri
));
1920 char *cleanedRawUri
= AnyP::Uri::cleanup(rawUri
);
1921 al
->setVirginUrlForMissingRequest(SBuf(cleanedRawUri
));
1922 xfree(cleanedRawUri
);
1926 ClientHttpRequest::absorbLogUri(char *aUri
)
1929 const_cast<char *&>(log_uri
) = aUri
;
1933 ClientHttpRequest::setErrorUri(const char *aUri
)
1937 // Should(!request);
1939 uri
= xstrdup(aUri
);
1940 // TODO: SBuf() performance regression, fix by converting setErrorUri() parameter to SBuf
1941 const SBuf
errorUri(aUri
);
1942 const auto canonicalUri
= urlCanonicalCleanWithoutRequest(errorUri
, HttpRequestMethod(), AnyP::UriScheme());
1943 absorbLogUri(xstrndup(canonicalUri
, MAX_URL
));
1945 al
->setVirginUrlForMissingRequest(errorUri
);
1948 // XXX: This should not be a _request_ method. Move range_iter elsewhere.
1950 ClientHttpRequest::prepPartialResponseGeneration()
1953 assert(request
->range
);
1955 range_iter
.pos
= request
->range
->begin();
1956 range_iter
.end
= request
->range
->end();
1957 range_iter
.debt_size
= 0;
1958 const auto multipart
= request
->range
->specs
.size() > 1;
1960 range_iter
.boundary
= rangeBoundaryStr();
1961 range_iter
.valid
= true; // TODO: Remove.
1962 range_iter
.updateSpec(); // TODO: Refactor to initialize rather than update.
1964 assert(range_iter
.pos
!= range_iter
.end
);
1965 const auto &firstRange
= *range_iter
.pos
;
1967 out
.offset
= firstRange
->offset
;
1969 return multipart
? mRangeCLen() : firstRange
->length
;
1973 /// Initiate an asynchronous adaptation transaction which will call us back.
1975 ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer
&g
)
1977 debugs(85, 3, HERE
<< "adaptation needed for " << this);
1978 assert(!virginHeadSource
);
1979 assert(!adaptedBodySource
);
1980 virginHeadSource
= initiateAdaptation(
1981 new Adaptation::Iterator(request
, NULL
, al
, g
));
1983 // we could try to guess whether we can bypass this adaptation
1984 // initiation failure, but it should not really happen
1985 Must(initiated(virginHeadSource
));
1989 ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer
&answer
)
1991 assert(cbdataReferenceValid(this)); // indicates bug
1992 clearAdaptation(virginHeadSource
);
1993 assert(!adaptedBodySource
);
1995 switch (answer
.kind
) {
1996 case Adaptation::Answer::akForward
:
1997 handleAdaptedHeader(const_cast<Http::Message
*>(answer
.message
.getRaw()));
2000 case Adaptation::Answer::akBlock
:
2001 handleAdaptationBlock(answer
);
2004 case Adaptation::Answer::akError
: {
2005 static const auto d
= MakeNamedErrorDetail("CLT_REQMOD_ABORT");
2006 handleAdaptationFailure(d
, !answer
.final
);
2013 ClientHttpRequest::handleAdaptedHeader(Http::Message
*msg
)
2017 if (HttpRequest
*new_req
= dynamic_cast<HttpRequest
*>(msg
)) {
2018 // update the new message to flag whether URL re-writing was done on it
2019 if (request
->effectiveRequestUri() != new_req
->effectiveRequestUri())
2020 new_req
->flags
.redirected
= true;
2021 resetRequest(new_req
);
2022 assert(request
->method
.id());
2023 } else if (HttpReply
*new_rep
= dynamic_cast<HttpReply
*>(msg
)) {
2024 debugs(85,3,HERE
<< "REQMOD reply is HTTP reply");
2026 // subscribe to receive reply body
2027 if (new_rep
->body_pipe
!= NULL
) {
2028 adaptedBodySource
= new_rep
->body_pipe
;
2029 int consumer_ok
= adaptedBodySource
->setConsumerIfNotLate(this);
2030 assert(consumer_ok
);
2033 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
2034 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2036 repContext
->createStoreEntry(request
->method
, request
->flags
);
2038 request_satisfaction_mode
= true;
2039 request_satisfaction_offset
= 0;
2040 storeEntry()->replaceHttpReply(new_rep
);
2041 storeEntry()->timestampsSet();
2043 al
->reply
= new_rep
;
2045 if (!adaptedBodySource
) // no body
2046 storeEntry()->complete();
2047 clientGetMoreData(node
, this);
2050 // we are done with getting headers (but may be receiving body)
2051 clearAdaptation(virginHeadSource
);
2053 if (!request_satisfaction_mode
)
2058 ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer
&answer
)
2060 static const auto d
= MakeNamedErrorDetail("REQMOD_BLOCK");
2061 request
->detailError(ERR_ACCESS_DENIED
, d
);
2062 AclMatchedName
= answer
.ruleId
.termedBuf();
2063 assert(calloutContext
);
2064 calloutContext
->clientAccessCheckDone(ACCESS_DENIED
);
2065 AclMatchedName
= NULL
;
2069 ClientHttpRequest::resumeBodyStorage()
2071 if (!adaptedBodySource
)
2074 noteMoreBodyDataAvailable(adaptedBodySource
);
2078 ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
2080 assert(request_satisfaction_mode
);
2081 assert(adaptedBodySource
!= NULL
);
2083 if (size_t contentSize
= adaptedBodySource
->buf().contentSize()) {
2084 const size_t spaceAvailable
= storeEntry()->bytesWanted(Range
<size_t>(0,contentSize
));
2086 if (spaceAvailable
< contentSize
) {
2087 // No or partial body data consuming
2088 typedef NullaryMemFunT
<ClientHttpRequest
> Dialer
;
2089 AsyncCall::Pointer call
= asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage",
2090 Dialer(this, &ClientHttpRequest::resumeBodyStorage
));
2091 storeEntry()->deferProducer(call
);
2094 if (!spaceAvailable
)
2097 if (spaceAvailable
< contentSize
)
2098 contentSize
= spaceAvailable
;
2100 BodyPipeCheckout
bpc(*adaptedBodySource
);
2101 const StoreIOBuffer
ioBuf(&bpc
.buf
, request_satisfaction_offset
, contentSize
);
2102 storeEntry()->write(ioBuf
);
2103 // assume StoreEntry::write() writes the entire ioBuf
2104 request_satisfaction_offset
+= ioBuf
.length
;
2105 bpc
.buf
.consume(contentSize
);
2109 if (adaptedBodySource
->exhausted())
2110 endRequestSatisfaction();
2111 // else wait for more body data
2115 ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer
)
2117 assert(!virginHeadSource
);
2118 // should we end request satisfaction now?
2119 if (adaptedBodySource
!= NULL
&& adaptedBodySource
->exhausted())
2120 endRequestSatisfaction();
2124 ClientHttpRequest::endRequestSatisfaction()
2126 debugs(85,4, HERE
<< this << " ends request satisfaction");
2127 assert(request_satisfaction_mode
);
2128 stopConsumingFrom(adaptedBodySource
);
2130 // TODO: anything else needed to end store entry formation correctly?
2131 storeEntry()->complete();
2135 ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer
)
2137 assert(!virginHeadSource
);
2138 stopConsumingFrom(adaptedBodySource
);
2140 debugs(85,3, HERE
<< "REQMOD body production failed");
2141 if (request_satisfaction_mode
) { // too late to recover or serve an error
2142 static const auto d
= MakeNamedErrorDetail("CLT_REQMOD_RESP_BODY");
2143 request
->detailError(ERR_ICAP_FAILURE
, d
);
2144 const Comm::ConnectionPointer c
= getConn()->clientConnection
;
2145 Must(Comm::IsConnOpen(c
));
2146 c
->close(); // drastic, but we may be writing a response already
2148 static const auto d
= MakeNamedErrorDetail("CLT_REQMOD_REQ_BODY");
2149 handleAdaptationFailure(d
);
2154 ClientHttpRequest::handleAdaptationFailure(const ErrorDetail::Pointer
&errDetail
, bool bypassable
)
2156 debugs(85,3, HERE
<< "handleAdaptationFailure(" << bypassable
<< ")");
2158 const bool usedStore
= storeEntry() && !storeEntry()->isEmpty();
2159 const bool usedPipe
= request
->body_pipe
!= NULL
&&
2160 request
->body_pipe
->consumedSize() > 0;
2162 if (bypassable
&& !usedStore
&& !usedPipe
) {
2163 debugs(85,3, HERE
<< "ICAP REQMOD callout failed, bypassing: " << calloutContext
);
2169 debugs(85,3, HERE
<< "ICAP REQMOD callout failed, responding with error");
2171 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
2172 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2175 calloutsError(ERR_ICAP_FAILURE
, errDetail
);
2182 ClientHttpRequest::callException(const std::exception
&ex
)
2184 if (const auto clientConn
= getConn() ? getConn()->clientConnection
: nullptr) {
2185 if (Comm::IsConnOpen(clientConn
)) {
2186 debugs(85, 3, "closing after exception: " << ex
.what());
2187 clientConn
->close(); // initiate orderly top-to-bottom cleanup
2191 debugs(85, DBG_IMPORTANT
, "ClientHttpRequest exception without connection. Ignoring " << ex
.what());
2192 // XXX: Normally, we mustStop() but we cannot do that here because it is
2193 // likely to leave Http::Stream and ConnStateData with a dangling http
2194 // pointer. See r13480 or XXX in Http::Stream class description.
2198 // XXX: modify and use with ClientRequestContext::clientAccessCheckDone too.
2200 ClientHttpRequest::calloutsError(const err_type error
, const ErrorDetail::Pointer
&errDetail
)
2202 // The original author of the code also wanted to pass an errno to
2203 // setReplyToError, but it seems unlikely that the errno reflects the
2204 // true cause of the error at this point, so I did not pass it.
2205 if (calloutContext
) {
2206 ConnStateData
* c
= getConn();
2207 calloutContext
->error
= clientBuildError(error
, Http::scInternalServerError
,
2208 nullptr, c
, request
, al
);
2210 calloutContext
->error
->auth_user_request
=
2211 c
!= NULL
&& c
->getAuth() != NULL
? c
->getAuth() : request
->auth_user_request
;
2213 calloutContext
->error
->detailError(errDetail
);
2214 calloutContext
->readNextRequest
= true;
2216 c
->expectNoForwarding();
2218 //else if(calloutContext == NULL) is it possible?