2 * Copyright (C) 1996-2020 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 "SquidConfig.h"
55 #include "SquidTime.h"
61 #include "auth/UserRequest.h"
64 #include "adaptation/AccessCheck.h"
65 #include "adaptation/Answer.h"
66 #include "adaptation/Iterator.h"
67 #include "adaptation/Service.h"
69 #include "adaptation/icap/History.h"
73 #include "ssl/ServerBump.h"
74 #include "ssl/support.h"
78 #define comm_close comm_lingering_close
81 static const char *const crlf
= "\r\n";
83 #if FOLLOW_X_FORWARDED_FOR
84 static void clientFollowXForwardedForCheck(Acl::Answer answer
, void *data
);
85 #endif /* FOLLOW_X_FORWARDED_FOR */
87 ErrorState
*clientBuildError(err_type
, Http::StatusCode
, char const *url
, const ConnStateData
*, HttpRequest
*, const AccessLogEntry::Pointer
&);
89 CBDATA_CLASS_INIT(ClientRequestContext
);
93 static void clientAccessCheckDoneWrapper(Acl::Answer
, void *);
95 static void sslBumpAccessCheckDoneWrapper(Acl::Answer
, void *);
97 static int clientHierarchical(ClientHttpRequest
* http
);
98 static void clientInterpretRequestHeaders(ClientHttpRequest
* http
);
99 static HLPCB clientRedirectDoneWrapper
;
100 static HLPCB clientStoreIdDoneWrapper
;
101 static void checkNoCacheDoneWrapper(Acl::Answer
, void *);
102 SQUIDCEXTERN CSR clientGetMoreData
;
103 SQUIDCEXTERN CSS clientReplyStatus
;
104 SQUIDCEXTERN CSD clientReplyDetach
;
105 static void checkFailureRatio(err_type
, hier_code
);
107 ClientRequestContext::~ClientRequestContext()
110 * Release our "lock" on our parent, ClientHttpRequest, if we
115 cbdataReferenceDone(http
);
118 debugs(85,3, "ClientRequestContext destructed, this=" << this);
121 ClientRequestContext::ClientRequestContext(ClientHttpRequest
*anHttp
) :
122 http(cbdataReference(anHttp
)),
124 redirect_state(REDIRECT_NONE
),
125 store_id_state(REDIRECT_NONE
),
126 host_header_verify_done(false),
127 http_access_done(false),
128 adapted_http_access_done(false),
130 adaptation_acl_check_done(false),
132 redirect_done(false),
133 store_id_done(false),
134 no_cache_done(false),
135 interpreted_req_hdrs(false),
136 toClientMarkingDone(false),
138 sslBumpCheckDone(false),
141 readNextRequest(false)
143 debugs(85, 3, "ClientRequestContext constructed, this=" << this);
146 CBDATA_CLASS_INIT(ClientHttpRequest
);
148 ClientHttpRequest::ClientHttpRequest(ConnStateData
* aConn
) :
150 AsyncJob("ClientHttpRequest"),
156 calloutContext(NULL
),
157 maxReplyBodySize_(0),
160 conn_(cbdataReference(aConn
))
162 , sslBumpNeed_(Ssl::bumpEnd
)
165 , request_satisfaction_mode(false)
166 , request_satisfaction_offset(0)
169 al
= new AccessLogEntry
;
170 CodeContext::Reset(al
);
171 al
->cache
.start_time
= current_time
;
173 al
->tcpClient
= clientConnection
= aConn
->clientConnection
;
174 al
->cache
.port
= aConn
->port
;
175 al
->cache
.caddr
= aConn
->log_addr
;
176 al
->proxyProtocolHeader
= aConn
->proxyProtocolHeader();
177 al
->updateError(aConn
->bareError
);
180 if (aConn
->clientConnection
!= NULL
&& aConn
->clientConnection
->isOpen()) {
181 if (auto ssl
= fd_table
[aConn
->clientConnection
->fd
].ssl
.get())
182 al
->cache
.sslClientCert
.resetWithoutLocking(SSL_get_peer_certificate(ssl
));
186 dlinkAdd(this, &active
, &ClientActiveRequests
);
190 * returns true if client specified that the object must come from the cache
191 * without contacting origin server
194 ClientHttpRequest::onlyIfCached()const
197 return request
->cache_control
&&
198 request
->cache_control
->hasOnlyIfCached();
202 * This function is designed to serve a fairly specific purpose.
203 * Occasionally our vBNS-connected caches can talk to each other, but not
204 * the rest of the world. Here we try to detect frequent failures which
205 * make the cache unusable (e.g. DNS lookup and connect() failures). If
206 * the failure:success ratio goes above 1.0 then we go into "hit only"
207 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
208 * will only fetch HITs from us if they are using the ICP protocol. We
209 * stay in this mode for 5 minutes.
211 * Duane W., Sept 16, 1996
214 checkFailureRatio(err_type etype
, hier_code hcode
)
216 // Can be set at compile time with -D compiler flag
217 #ifndef FAILURE_MODE_TIME
218 #define FAILURE_MODE_TIME 300
221 if (hcode
== HIER_NONE
)
224 // don't bother when ICP is disabled.
225 if (Config
.Port
.icp
<= 0)
228 static double magic_factor
= 100.0;
232 n_good
= magic_factor
/ (1.0 + request_failure_ratio
);
234 n_bad
= magic_factor
- n_good
;
240 case ERR_CONNECT_FAIL
:
241 case ERR_SECURE_CONNECT_FAIL
:
251 request_failure_ratio
= n_bad
/ n_good
;
253 if (hit_only_mode_until
> squid_curtime
)
256 if (request_failure_ratio
< 1.0)
259 debugs(33, DBG_CRITICAL
, "WARNING: Failure Ratio at "<< std::setw(4)<<
260 std::setprecision(3) << request_failure_ratio
);
262 debugs(33, DBG_CRITICAL
, "WARNING: ICP going into HIT-only mode for " <<
263 FAILURE_MODE_TIME
/ 60 << " minutes...");
265 hit_only_mode_until
= squid_curtime
+ FAILURE_MODE_TIME
;
267 request_failure_ratio
= 0.8; /* reset to something less than 1.0 */
270 ClientHttpRequest::~ClientHttpRequest()
272 debugs(33, 3, "httpRequestFree: " << uri
);
273 PROF_start(httpRequestFree
);
275 // Even though freeResources() below may destroy the request,
276 // we no longer set request->body_pipe to NULL here
277 // because we did not initiate that pipe (ConnStateData did)
279 /* the ICP check here was erroneous
280 * - StoreEntry::releaseRequest was always called if entry was valid
288 checkFailureRatio(request
->error
.category
, al
->hier
.code
);
293 announceInitiatorAbort(virginHeadSource
);
295 if (adaptedBodySource
!= NULL
)
296 stopConsumingFrom(adaptedBodySource
);
300 delete calloutContext
;
302 clientConnection
= NULL
;
305 cbdataReferenceDone(conn_
);
307 /* moving to the next connection is handled by the context free */
308 dlinkDelete(&active
, &ClientActiveRequests
);
310 PROF_stop(httpRequestFree
);
314 * Create a request and kick it off
319 * TODO: Pass in the buffers to be used in the initial Read request, as they are
320 * determined by the user
323 clientBeginRequest(const HttpRequestMethod
& method
, char const *url
, CSCB
* streamcallback
,
324 CSD
* streamdetach
, ClientStreamData streamdata
, HttpHeader
const *header
,
325 char *tailbuf
, size_t taillen
, const MasterXaction::Pointer
&mx
)
328 ClientHttpRequest
*http
= new ClientHttpRequest(NULL
);
329 HttpRequest
*request
;
330 StoreIOBuffer tempBuffer
;
331 if (http
->al
!= NULL
)
332 http
->al
->cache
.start_time
= current_time
;
333 /* this is only used to adjust the connection offset in client_side.c */
335 tempBuffer
.length
= taillen
;
336 tempBuffer
.data
= tailbuf
;
337 /* client stream setup */
338 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
339 clientReplyStatus
, new clientReplyContext(http
), streamcallback
,
340 streamdetach
, streamdata
, tempBuffer
);
341 /* make it visible in the 'current acctive requests list' */
343 /* internal requests only makes sense in an
344 * accelerator today. TODO: accept flags ? */
345 http
->flags
.accel
= true;
346 /* allow size for url rewriting */
347 url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
348 http
->uri
= (char *)xcalloc(url_sz
, 1);
349 strcpy(http
->uri
, url
); // XXX: polluting http->uri before parser validation
351 request
= HttpRequest::FromUrlXXX(http
->uri
, mx
, method
);
353 debugs(85, 5, "Invalid URL: " << http
->uri
);
358 * now update the headers in request with our supplied headers.
359 * HttpRequest::FromUrl() should return a blank header set, but
360 * we use Update to be sure of correctness.
363 request
->header
.update(header
);
365 /* http struct now ready */
368 * build new header list *? TODO
370 request
->flags
.accelerated
= http
->flags
.accel
;
372 /* this is an internally created
373 * request, not subject to acceleration
374 * target overrides */
375 // TODO: detect and handle internal requests of internal objects?
377 /* Internally created requests cannot have bodies today */
378 request
->content_length
= 0;
380 request
->client_addr
.setNoAddr();
382 #if FOLLOW_X_FORWARDED_FOR
383 request
->indirect_client_addr
.setNoAddr();
384 #endif /* FOLLOW_X_FORWARDED_FOR */
386 request
->my_addr
.setNoAddr(); /* undefined for internal requests */
388 request
->my_addr
.port(0);
390 request
->http_ver
= Http::ProtocolVersion();
392 http
->initRequest(request
);
394 /* optional - skip the access check ? */
395 http
->calloutContext
= new ClientRequestContext(http
);
397 http
->calloutContext
->http_access_done
= false;
399 http
->calloutContext
->redirect_done
= true;
401 http
->calloutContext
->no_cache_done
= true;
409 ClientRequestContext::httpStateIsValid()
411 ClientHttpRequest
*http_
= http
;
413 if (cbdataReferenceValid(http_
))
418 cbdataReferenceDone(http_
);
423 #if FOLLOW_X_FORWARDED_FOR
425 * clientFollowXForwardedForCheck() checks the content of X-Forwarded-For:
426 * against the followXFF ACL, or cleans up and passes control to
427 * clientAccessCheck().
429 * The trust model here is a little ambiguous. So to clarify the logic:
430 * - we may always use the direct client address as the client IP.
431 * - these trust tests merey tell whether we trust given IP enough to believe the
432 * IP string which it appended to the X-Forwarded-For: header.
433 * - if at any point we don't trust what an IP adds we stop looking.
434 * - at that point the current contents of indirect_client_addr are the value set
435 * by the last previously trusted IP.
436 * ++ indirect_client_addr contains the remote direct client from the trusted peers viewpoint.
439 clientFollowXForwardedForCheck(Acl::Answer answer
, void *data
)
441 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
443 if (!calloutContext
->httpStateIsValid())
446 ClientHttpRequest
*http
= calloutContext
->http
;
447 HttpRequest
*request
= http
->request
;
449 if (answer
.allowed() && request
->x_forwarded_for_iterator
.size() != 0) {
452 * Remove the last comma-delimited element from the
453 * x_forwarded_for_iterator and use it to repeat the cycle.
456 const char *asciiaddr
;
459 p
= request
->x_forwarded_for_iterator
.termedBuf();
460 l
= request
->x_forwarded_for_iterator
.size();
463 * XXX x_forwarded_for_iterator should really be a list of
464 * IP addresses, but it's a String instead. We have to
465 * walk backwards through the String, biting off the last
466 * comma-delimited part each time. As long as the data is in
467 * a String, we should probably implement and use a variant of
468 * strListGetItem() that walks backwards instead of forwards
469 * through a comma-separated list. But we don't even do that;
470 * we just do the work in-line here.
472 /* skip trailing space and commas */
473 while (l
> 0 && (p
[l
-1] == ',' || xisspace(p
[l
-1])))
475 request
->x_forwarded_for_iterator
.cut(l
);
476 /* look for start of last item in list */
477 while (l
> 0 && ! (p
[l
-1] == ',' || xisspace(p
[l
-1])))
480 if ((addr
= asciiaddr
)) {
481 request
->indirect_client_addr
= addr
;
482 request
->x_forwarded_for_iterator
.cut(l
);
483 calloutContext
->acl_checklist
= clientAclChecklistCreate(Config
.accessList
.followXFF
, http
);
484 if (!Config
.onoff
.acl_uses_indirect_client
) {
485 /* override the default src_addr tested if we have to go deeper than one level into XFF */
486 Filled(calloutContext
->acl_checklist
)->src_addr
= request
->indirect_client_addr
;
488 calloutContext
->acl_checklist
->nonBlockingCheck(clientFollowXForwardedForCheck
, data
);
493 /* clean up, and pass control to clientAccessCheck */
494 if (Config
.onoff
.log_uses_indirect_client
) {
496 * Ensure that the access log shows the indirect client
497 * instead of the direct client.
499 http
->al
->cache
.caddr
= request
->indirect_client_addr
;
500 if (ConnStateData
*conn
= http
->getConn())
501 conn
->log_addr
= request
->indirect_client_addr
;
503 request
->x_forwarded_for_iterator
.clean();
504 request
->flags
.done_follow_x_forwarded_for
= true;
506 if (answer
.conflicted()) {
507 debugs(28, DBG_CRITICAL
, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request
->indirect_client_addr
);
510 /* process actual access ACL as normal. */
511 calloutContext
->clientAccessCheck();
513 #endif /* FOLLOW_X_FORWARDED_FOR */
516 hostHeaderIpVerifyWrapper(const ipcache_addrs
* ia
, const Dns::LookupDetails
&dns
, void *data
)
518 ClientRequestContext
*c
= static_cast<ClientRequestContext
*>(data
);
519 c
->hostHeaderIpVerify(ia
, dns
);
523 ClientRequestContext::hostHeaderIpVerify(const ipcache_addrs
* ia
, const Dns::LookupDetails
&dns
)
525 Comm::ConnectionPointer clientConn
= http
->getConn()->clientConnection
;
527 // note the DNS details for the transaction stats.
528 http
->request
->recordLookup(dns
);
530 // Is the NAT destination IP in DNS?
531 if (ia
&& ia
->have(clientConn
->local
)) {
532 debugs(85, 3, "validate IP " << clientConn
->local
<< " possible from Host:");
533 http
->request
->flags
.hostVerified
= true;
537 debugs(85, 3, HERE
<< "FAIL: validate IP " << clientConn
->local
<< " possible from Host:");
538 hostHeaderVerifyFailed("local IP", "any domain IP");
542 ClientRequestContext::hostHeaderVerifyFailed(const char *A
, const char *B
)
544 // IP address validation for Host: failed. Admin wants to ignore them.
545 // NP: we do not yet handle CONNECT tunnels well, so ignore for them
546 if (!Config
.onoff
.hostStrictVerify
&& http
->request
->method
!= Http::METHOD_CONNECT
) {
547 debugs(85, 3, "SECURITY ALERT: Host header forgery detected on " << http
->getConn()->clientConnection
<<
548 " (" << A
<< " does not match " << B
<< ") on URL: " << http
->request
->effectiveRequestUri());
550 // NP: it is tempting to use 'flags.noCache' but that is all about READing cache data.
551 // The problems here are about WRITE for new cache content, which means flags.cachable
552 http
->request
->flags
.cachable
= false; // MUST NOT cache (for now)
553 // XXX: when we have updated the cache key to base on raw-IP + URI this cacheable limit can go.
554 http
->request
->flags
.hierarchical
= false; // MUST NOT pass to peers (for now)
555 // XXX: when we have sorted out the best way to relay requests properly to peers this hierarchical limit can go.
560 debugs(85, DBG_IMPORTANT
, "SECURITY ALERT: Host header forgery detected on " <<
561 http
->getConn()->clientConnection
<< " (" << A
<< " does not match " << B
<< ")");
562 if (const char *ua
= http
->request
->header
.getStr(Http::HdrType::USER_AGENT
))
563 debugs(85, DBG_IMPORTANT
, "SECURITY ALERT: By user agent: " << ua
);
564 debugs(85, DBG_IMPORTANT
, "SECURITY ALERT: on URL: " << http
->request
->effectiveRequestUri());
566 // IP address validation for Host: failed. reject the connection.
567 clientStreamNode
*node
= (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
568 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
570 repContext
->setReplyToError(ERR_CONFLICT_HOST
, Http::scConflict
,
571 http
->request
->method
, NULL
,
576 http
->getConn() != NULL
&& http
->getConn()->getAuth() != NULL
?
577 http
->getConn()->getAuth() : http
->request
->auth_user_request
);
581 node
= (clientStreamNode
*)http
->client_stream
.tail
->data
;
582 clientStreamRead(node
, http
, node
->readBuffer
);
586 ClientRequestContext::hostHeaderVerify()
588 // Require a Host: header.
589 const char *host
= http
->request
->header
.getStr(Http::HdrType::HOST
);
592 // TODO: dump out the HTTP/1.1 error about missing host header.
593 // otherwise this is fine, can't forge a header value when its not even set.
594 debugs(85, 3, HERE
<< "validate skipped with no Host: header present.");
599 if (http
->request
->flags
.internal
) {
600 // TODO: kill this when URL handling allows partial URLs out of accel mode
601 // and we no longer screw with the URL just to add our internal host there
602 debugs(85, 6, HERE
<< "validate skipped due to internal composite URL.");
607 // Locate if there is a port attached, strip ready for IP lookup
608 char *portStr
= NULL
;
609 char *hostB
= xstrdup(host
);
611 if (host
[0] == '[') {
613 portStr
= strchr(hostB
, ']');
614 if (portStr
&& *(++portStr
) != ':') {
618 // Domain or IPv4 literal with port
619 portStr
= strrchr(hostB
, ':');
624 *portStr
= '\0'; // strip the ':'
625 if (*(++portStr
) != '\0') {
627 int64_t ret
= strtoll(portStr
, &end
, 10);
628 if (end
== portStr
|| *end
!= '\0' || ret
< 1 || ret
> 0xFFFF) {
629 // invalid port details. Replace the ':'
633 port
= (ret
& 0xFFFF);
637 debugs(85, 3, "validate host=" << host
<< ", port=" << port
<< ", portStr=" << (portStr
?portStr
:"NULL"));
638 if (http
->request
->flags
.intercepted
|| http
->request
->flags
.interceptTproxy
) {
639 // verify the Host: port (if any) matches the apparent destination
640 if (portStr
&& port
!= http
->getConn()->clientConnection
->local
.port()) {
641 debugs(85, 3, "FAIL on validate port " << http
->getConn()->clientConnection
->local
.port() <<
642 " matches Host: port " << port
<< " (" << portStr
<< ")");
643 hostHeaderVerifyFailed("intercepted port", portStr
);
645 // XXX: match the scheme default port against the apparent destination
647 // verify the destination DNS is one of the Host: headers IPs
648 ipcache_nbgethostbyname(host
, hostHeaderIpVerifyWrapper
, this);
650 } else if (!Config
.onoff
.hostStrictVerify
) {
651 debugs(85, 3, "validate skipped.");
653 } else if (strlen(host
) != strlen(http
->request
->url
.host())) {
654 // Verify forward-proxy requested URL domain matches the Host: header
655 debugs(85, 3, "FAIL on validate URL domain length " << http
->request
->url
.host() << " matches Host: " << host
);
656 hostHeaderVerifyFailed(host
, http
->request
->url
.host());
657 } else if (matchDomainName(host
, http
->request
->url
.host()) != 0) {
658 // Verify forward-proxy requested URL domain matches the Host: header
659 debugs(85, 3, "FAIL on validate URL domain " << http
->request
->url
.host() << " matches Host: " << host
);
660 hostHeaderVerifyFailed(host
, http
->request
->url
.host());
661 } else if (portStr
&& port
!= http
->request
->url
.port()) {
662 // Verify forward-proxy requested URL domain matches the Host: header
663 debugs(85, 3, "FAIL on validate URL port " << http
->request
->url
.port() << " matches Host: port " << portStr
);
664 hostHeaderVerifyFailed("URL port", portStr
);
665 } else if (!portStr
&& http
->request
->method
!= Http::METHOD_CONNECT
&& http
->request
->url
.port() != http
->request
->url
.getScheme().defaultPort()) {
666 // Verify forward-proxy requested URL domain matches the Host: header
667 // Special case: we don't have a default-port to check for CONNECT. Assume URL is correct.
668 debugs(85, 3, "FAIL on validate URL port " << http
->request
->url
.port() << " matches Host: default port " << http
->request
->url
.getScheme().defaultPort());
669 hostHeaderVerifyFailed("URL port", "default port");
672 debugs(85, 3, "validate passed.");
673 http
->request
->flags
.hostVerified
= true;
679 /* This is the entry point for external users of the client_side routines */
681 ClientRequestContext::clientAccessCheck()
683 #if FOLLOW_X_FORWARDED_FOR
684 if (!http
->request
->flags
.doneFollowXff() &&
685 Config
.accessList
.followXFF
&&
686 http
->request
->header
.has(Http::HdrType::X_FORWARDED_FOR
)) {
688 /* we always trust the direct client address for actual use */
689 http
->request
->indirect_client_addr
= http
->request
->client_addr
;
690 http
->request
->indirect_client_addr
.port(0);
692 /* setup the XFF iterator for processing */
693 http
->request
->x_forwarded_for_iterator
= http
->request
->header
.getList(Http::HdrType::X_FORWARDED_FOR
);
695 /* begin by checking to see if we trust direct client enough to walk XFF */
696 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.followXFF
, http
);
697 acl_checklist
->nonBlockingCheck(clientFollowXForwardedForCheck
, this);
702 if (Config
.accessList
.http
) {
703 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.http
, http
);
704 acl_checklist
->nonBlockingCheck(clientAccessCheckDoneWrapper
, this);
706 debugs(0, DBG_CRITICAL
, "No http_access configuration found. This will block ALL traffic");
707 clientAccessCheckDone(ACCESS_DENIED
);
712 * Identical in operation to clientAccessCheck() but performed later using different configured ACL list.
713 * The default here is to allow all. Since the earlier http_access should do a default deny all.
714 * This check is just for a last-minute denial based on adapted request headers.
717 ClientRequestContext::clientAccessCheck2()
719 if (Config
.accessList
.adapted_http
) {
720 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.adapted_http
, http
);
721 acl_checklist
->nonBlockingCheck(clientAccessCheckDoneWrapper
, this);
723 debugs(85, 2, HERE
<< "No adapted_http_access configuration. default: ALLOW");
724 clientAccessCheckDone(ACCESS_ALLOWED
);
729 clientAccessCheckDoneWrapper(Acl::Answer answer
, void *data
)
731 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
733 if (!calloutContext
->httpStateIsValid())
736 calloutContext
->clientAccessCheckDone(answer
);
740 ClientRequestContext::clientAccessCheckDone(const Acl::Answer
&answer
)
742 acl_checklist
= NULL
;
744 Http::StatusCode status
;
745 debugs(85, 2, "The request " << http
->request
->method
<< ' ' <<
746 http
->uri
<< " is " << answer
<<
747 "; last ACL checked: " << (AclMatchedName
? AclMatchedName
: "[none]"));
750 char const *proxy_auth_msg
= "<null>";
751 if (http
->getConn() != NULL
&& http
->getConn()->getAuth() != NULL
)
752 proxy_auth_msg
= http
->getConn()->getAuth()->denyMessage("<null>");
753 else if (http
->request
->auth_user_request
!= NULL
)
754 proxy_auth_msg
= http
->request
->auth_user_request
->denyMessage("<null>");
757 if (!answer
.allowed()) {
758 // auth has a grace period where credentials can be expired but okay not to challenge.
760 /* Send an auth challenge or error */
761 // XXX: do we still need aclIsProxyAuth() ?
762 bool auth_challenge
= (answer
== ACCESS_AUTH_REQUIRED
|| aclIsProxyAuth(AclMatchedName
));
763 debugs(85, 5, "Access Denied: " << http
->uri
);
764 debugs(85, 5, "AclMatchedName = " << (AclMatchedName
? AclMatchedName
: "<null>"));
767 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg
? proxy_auth_msg
: "<null>"));
771 * NOTE: get page_id here, based on AclMatchedName because if
772 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
773 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
776 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, answer
!= ACCESS_AUTH_REQUIRED
);
778 http
->logType
.update(LOG_TCP_DENIED
);
780 if (auth_challenge
) {
782 if (http
->request
->flags
.sslBumped
) {
783 /*SSL Bumped request, authentication is not possible*/
784 status
= Http::scForbidden
;
785 } else if (!http
->flags
.accel
) {
786 /* Proxy authorisation needed */
787 status
= Http::scProxyAuthenticationRequired
;
789 /* WWW authorisation needed */
790 status
= Http::scUnauthorized
;
793 // need auth, but not possible to do.
794 status
= Http::scForbidden
;
796 if (page_id
== ERR_NONE
)
797 page_id
= ERR_CACHE_ACCESS_DENIED
;
799 status
= Http::scForbidden
;
801 if (page_id
== ERR_NONE
)
802 page_id
= ERR_ACCESS_DENIED
;
805 error
= clientBuildError(page_id
, status
, nullptr, http
->getConn(), http
->request
, http
->al
);
808 error
->auth_user_request
=
809 http
->getConn() != NULL
&& http
->getConn()->getAuth() != NULL
?
810 http
->getConn()->getAuth() : http
->request
->auth_user_request
;
813 readNextRequest
= true;
816 /* ACCESS_ALLOWED continues here ... */
818 http
->uri
= SBufToCstring(http
->request
->effectiveRequestUri());
824 ClientHttpRequest::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer g
)
826 debugs(93,3,HERE
<< this << " adaptationAclCheckDone called");
829 Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
831 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
) {
832 ih
->rfc931
= getConn()->clientConnection
->rfc931
;
834 if (getConn()->clientConnection
->isOpen()) {
835 ih
->ssluser
= sslGetUserEmail(fd_table
[getConn()->clientConnection
->fd
].ssl
.get());
839 ih
->log_uri
= log_uri
;
845 debugs(85,3, HERE
<< "no adaptation needed");
856 clientRedirectAccessCheckDone(Acl::Answer answer
, void *data
)
858 ClientRequestContext
*context
= (ClientRequestContext
*)data
;
859 ClientHttpRequest
*http
= context
->http
;
860 context
->acl_checklist
= NULL
;
862 if (answer
.allowed())
863 redirectStart(http
, clientRedirectDoneWrapper
, context
);
865 Helper::Reply
const nilReply(Helper::Error
);
866 context
->clientRedirectDone(nilReply
);
871 ClientRequestContext::clientRedirectStart()
873 debugs(33, 5, HERE
<< "'" << http
->uri
<< "'");
874 http
->al
->syncNotes(http
->request
);
875 if (Config
.accessList
.redirector
) {
876 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.redirector
, http
);
877 acl_checklist
->nonBlockingCheck(clientRedirectAccessCheckDone
, this);
879 redirectStart(http
, clientRedirectDoneWrapper
, this);
883 * This methods handles Access checks result of StoreId access list.
884 * Will handle as "ERR" (no change) in a case Access is not allowed.
887 clientStoreIdAccessCheckDone(Acl::Answer answer
, void *data
)
889 ClientRequestContext
*context
= static_cast<ClientRequestContext
*>(data
);
890 ClientHttpRequest
*http
= context
->http
;
891 context
->acl_checklist
= NULL
;
893 if (answer
.allowed())
894 storeIdStart(http
, clientStoreIdDoneWrapper
, context
);
896 debugs(85, 3, "access denied expected ERR reply handling: " << answer
);
897 Helper::Reply
const nilReply(Helper::Error
);
898 context
->clientStoreIdDone(nilReply
);
903 * Start locating an alternative storage ID string (if any) from admin
904 * configured helper program. This is an asynchronous operation terminating in
905 * ClientRequestContext::clientStoreIdDone() when completed.
908 ClientRequestContext::clientStoreIdStart()
910 debugs(33, 5,"'" << http
->uri
<< "'");
912 if (Config
.accessList
.store_id
) {
913 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.store_id
, http
);
914 acl_checklist
->nonBlockingCheck(clientStoreIdAccessCheckDone
, this);
916 storeIdStart(http
, clientStoreIdDoneWrapper
, this);
920 clientHierarchical(ClientHttpRequest
* http
)
922 HttpRequest
*request
= http
->request
;
923 HttpRequestMethod method
= request
->method
;
925 // intercepted requests MUST NOT (yet) be sent to peers unless verified
926 if (!request
->flags
.hostVerified
&& (request
->flags
.intercepted
|| request
->flags
.interceptTproxy
))
930 * IMS needs a private key, so we can use the hierarchy for IMS only if our
931 * neighbors support private keys
934 if (request
->flags
.ims
&& !neighbors_do_private_keys
)
938 * This is incorrect: authenticating requests can be sent via a hierarchy
939 * (they can even be cached if the correct headers are set on the reply)
941 if (request
->flags
.auth
)
944 if (method
== Http::METHOD_TRACE
)
947 if (method
!= Http::METHOD_GET
)
950 if (request
->flags
.loopDetected
)
953 if (request
->url
.getScheme() == AnyP::PROTO_HTTP
)
954 return method
.respMaybeCacheable();
956 if (request
->url
.getScheme() == AnyP::PROTO_GOPHER
)
957 return gopherCachable(request
);
959 if (request
->url
.getScheme() == AnyP::PROTO_CACHE_OBJECT
)
966 clientCheckPinning(ClientHttpRequest
* http
)
968 HttpRequest
*request
= http
->request
;
969 HttpHeader
*req_hdr
= &request
->header
;
970 ConnStateData
*http_conn
= http
->getConn();
972 /* Internal requests such as those from ESI includes may be without
973 * a client connection
978 request
->flags
.connectionAuthDisabled
= http_conn
->port
->connection_auth_disabled
;
979 if (!request
->flags
.connectionAuthDisabled
) {
980 if (Comm::IsConnOpen(http_conn
->pinning
.serverConnection
)) {
981 if (http_conn
->pinning
.auth
) {
982 request
->flags
.connectionAuth
= true;
983 request
->flags
.auth
= true;
985 request
->flags
.connectionProxyAuth
= true;
987 // These should already be linked correctly.
988 assert(request
->clientConnectionManager
== http_conn
);
992 /* check if connection auth is used, and flag as candidate for pinning
994 * Note: we may need to set flags.connectionAuth even if the connection
995 * is already pinned if it was pinned earlier due to proxy auth
997 if (!request
->flags
.connectionAuth
) {
998 if (req_hdr
->has(Http::HdrType::AUTHORIZATION
) || req_hdr
->has(Http::HdrType::PROXY_AUTHORIZATION
)) {
999 HttpHeaderPos pos
= HttpHeaderInitPos
;
1002 while ((e
= req_hdr
->getEntry(&pos
))) {
1003 if (e
->id
== Http::HdrType::AUTHORIZATION
|| e
->id
== Http::HdrType::PROXY_AUTHORIZATION
) {
1004 const char *value
= e
->value
.rawBuf();
1005 if (strncasecmp(value
, "NTLM ", 5) == 0
1007 strncasecmp(value
, "Negotiate ", 10) == 0
1009 strncasecmp(value
, "Kerberos ", 9) == 0) {
1010 if (e
->id
== Http::HdrType::AUTHORIZATION
) {
1011 request
->flags
.connectionAuth
= true;
1014 request
->flags
.connectionProxyAuth
= true;
1020 if (may_pin
&& !request
->pinnedConnection()) {
1021 // These should already be linked correctly. Just need the ServerConnection to pinn.
1022 assert(request
->clientConnectionManager
== http_conn
);
1029 clientInterpretRequestHeaders(ClientHttpRequest
* http
)
1031 HttpRequest
*request
= http
->request
;
1032 HttpHeader
*req_hdr
= &request
->header
;
1033 bool no_cache
= false;
1035 request
->imslen
= -1;
1036 request
->ims
= req_hdr
->getTime(Http::HdrType::IF_MODIFIED_SINCE
);
1038 if (request
->ims
> 0)
1039 request
->flags
.ims
= true;
1041 if (!request
->flags
.ignoreCc
) {
1042 if (request
->cache_control
) {
1043 if (request
->cache_control
->hasNoCache())
1046 // RFC 2616: treat Pragma:no-cache as if it was Cache-Control:no-cache when Cache-Control is missing
1047 } else if (req_hdr
->has(Http::HdrType::PRAGMA
))
1048 no_cache
= req_hdr
->hasListMember(Http::HdrType::PRAGMA
,"no-cache",',');
1051 if (request
->method
== Http::METHOD_OTHER
) {
1056 #if USE_HTTP_VIOLATIONS
1058 if (Config
.onoff
.reload_into_ims
)
1059 request
->flags
.nocacheHack
= true;
1060 else if (refresh_nocache_hack
)
1061 request
->flags
.nocacheHack
= true;
1065 request
->flags
.noCache
= true;
1068 /* ignore range header in non-GETs or non-HEADs */
1069 if (request
->method
== Http::METHOD_GET
|| request
->method
== Http::METHOD_HEAD
) {
1070 // XXX: initialize if we got here without HttpRequest::parseHeader()
1071 if (!request
->range
)
1072 request
->range
= req_hdr
->getRange();
1074 if (request
->range
) {
1075 request
->flags
.isRanged
= true;
1076 clientStreamNode
*node
= (clientStreamNode
*)http
->client_stream
.tail
->data
;
1077 /* XXX: This is suboptimal. We should give the stream the range set,
1078 * and thereby let the top of the stream set the offset when the
1079 * size becomes known. As it is, we will end up requesting from 0
1080 * for evey -X range specification.
1081 * RBC - this may be somewhat wrong. We should probably set the range
1082 * iter up at this point.
1084 node
->readBuffer
.offset
= request
->range
->lowestOffset(0);
1085 http
->range_iter
.pos
= request
->range
->begin();
1086 http
->range_iter
.end
= request
->range
->end();
1087 http
->range_iter
.valid
= true;
1091 /* Only HEAD and GET requests permit a Range or Request-Range header.
1092 * If these headers appear on any other type of request, delete them now.
1095 req_hdr
->delById(Http::HdrType::RANGE
);
1096 req_hdr
->delById(Http::HdrType::REQUEST_RANGE
);
1097 request
->ignoreRange("neither HEAD nor GET");
1100 if (req_hdr
->has(Http::HdrType::AUTHORIZATION
))
1101 request
->flags
.auth
= true;
1103 clientCheckPinning(http
);
1105 if (!request
->url
.userInfo().isEmpty())
1106 request
->flags
.auth
= true;
1108 if (req_hdr
->has(Http::HdrType::VIA
)) {
1109 String s
= req_hdr
->getList(Http::HdrType::VIA
);
1111 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
1112 * Note ThisCache2 has a space prepended to the hostname so we don't
1113 * accidentally match super-domains.
1116 if (strListIsSubstr(&s
, ThisCache2
, ',')) {
1117 request
->flags
.loopDetected
= true;
1121 fvdbCountVia(s
.termedBuf());
1128 // headers only relevant to reverse-proxy
1129 if (request
->flags
.accelerated
) {
1130 // check for a cdn-info member with a cdn-id matching surrogate_id
1131 // XXX: HttpHeader::hasListMember() does not handle OWS around ";" yet
1132 if (req_hdr
->hasListMember(Http::HdrType::CDN_LOOP
, Config
.Accel
.surrogate_id
, ','))
1133 request
->flags
.loopDetected
= true;
1136 if (request
->flags
.loopDetected
) {
1137 debugObj(33, DBG_IMPORTANT
, "WARNING: Forwarding loop detected for:\n",
1138 request
, (ObjPackMethod
) & httpRequestPack
);
1143 if (req_hdr
->has(Http::HdrType::X_FORWARDED_FOR
)) {
1144 String s
= req_hdr
->getList(Http::HdrType::X_FORWARDED_FOR
);
1145 fvdbCountForw(s
.termedBuf());
1151 request
->flags
.cachable
= http
->request
->maybeCacheable();
1153 if (clientHierarchical(http
))
1154 request
->flags
.hierarchical
= true;
1156 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
1157 (request
->flags
.noCache
? "SET" : "NOT SET"));
1158 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
1159 (request
->flags
.cachable
? "SET" : "NOT SET"));
1160 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
1161 (request
->flags
.hierarchical
? "SET" : "NOT SET"));
1166 clientRedirectDoneWrapper(void *data
, const Helper::Reply
&result
)
1168 ClientRequestContext
*calloutContext
= (ClientRequestContext
*)data
;
1170 if (!calloutContext
->httpStateIsValid())
1173 calloutContext
->clientRedirectDone(result
);
1177 clientStoreIdDoneWrapper(void *data
, const Helper::Reply
&result
)
1179 ClientRequestContext
*calloutContext
= (ClientRequestContext
*)data
;
1181 if (!calloutContext
->httpStateIsValid())
1184 calloutContext
->clientStoreIdDone(result
);
1188 ClientRequestContext::clientRedirectDone(const Helper::Reply
&reply
)
1190 HttpRequest
*old_request
= http
->request
;
1191 debugs(85, 5, HERE
<< "'" << http
->uri
<< "' result=" << reply
);
1192 assert(redirect_state
== REDIRECT_PENDING
);
1193 redirect_state
= REDIRECT_DONE
;
1195 // Put helper response Notes into the transaction state record (ALE) eventually
1196 // do it early to ensure that no matter what the outcome the notes are present.
1198 http
->al
->syncNotes(old_request
);
1200 UpdateRequestNotes(http
->getConn(), *old_request
, reply
.notes
);
1202 switch (reply
.result
) {
1203 case Helper::TimedOut
:
1204 if (Config
.onUrlRewriteTimeout
.action
!= toutActBypass
) {
1205 static const auto d
= MakeNamedErrorDetail("REDIRECTOR_TIMEDOUT");
1206 http
->calloutsError(ERR_GATEWAY_FAILURE
, d
);
1207 debugs(85, DBG_IMPORTANT
, "ERROR: URL rewrite helper: Timedout");
1211 case Helper::Unknown
:
1213 // Handler in redirect.cc should have already mapped Unknown
1214 // IF it contained valid entry for the old URL-rewrite helper protocol
1215 debugs(85, DBG_IMPORTANT
, "ERROR: URL rewrite helper returned invalid result code. Wrong helper? " << reply
);
1218 case Helper::BrokenHelper
:
1219 debugs(85, DBG_IMPORTANT
, "ERROR: URL rewrite helper: " << reply
);
1223 // no change to be done.
1226 case Helper::Okay
: {
1227 // #1: redirect with a specific status code OK status=NNN url="..."
1228 // #2: redirect with a default status code OK url="..."
1229 // #3: re-write the URL OK rewrite-url="..."
1231 const char *statusNote
= reply
.notes
.findFirst("status");
1232 const char *urlNote
= reply
.notes
.findFirst("url");
1234 if (urlNote
!= NULL
) {
1235 // HTTP protocol redirect to be done.
1237 // TODO: change default redirect status for appropriate requests
1238 // Squid defaults to 302 status for now for better compatibility with old clients.
1239 // HTTP/1.0 client should get 302 (Http::scFound)
1240 // HTTP/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect)
1241 // HTTP/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther)
1242 Http::StatusCode status
= Http::scFound
;
1243 if (statusNote
!= NULL
) {
1244 const char * result
= statusNote
;
1245 status
= static_cast<Http::StatusCode
>(atoi(result
));
1248 if (status
== Http::scMovedPermanently
1249 || status
== Http::scFound
1250 || status
== Http::scSeeOther
1251 || status
== Http::scPermanentRedirect
1252 || status
== Http::scTemporaryRedirect
) {
1253 http
->redirect
.status
= status
;
1254 http
->redirect
.location
= xstrdup(urlNote
);
1255 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
1257 debugs(85, DBG_CRITICAL
, "ERROR: URL-rewrite produces invalid " << status
<< " redirect Location: " << urlNote
);
1260 // URL-rewrite wanted. Ew.
1261 urlNote
= reply
.notes
.findFirst("rewrite-url");
1263 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1264 if (urlNote
!= NULL
&& strcmp(urlNote
, http
->uri
)) {
1266 if (tmpUrl
.parse(old_request
->method
, SBuf(urlNote
))) {
1267 HttpRequest
*new_request
= old_request
->clone();
1268 new_request
->url
= tmpUrl
;
1269 debugs(61, 2, "URL-rewriter diverts URL from " << old_request
->effectiveRequestUri() << " to " << new_request
->effectiveRequestUri());
1271 // update the new request to flag the re-writing was done on it
1272 new_request
->flags
.redirected
= true;
1274 // unlink bodypipe from the old request. Not needed there any longer.
1275 if (old_request
->body_pipe
!= NULL
) {
1276 old_request
->body_pipe
= NULL
;
1277 debugs(61,2, HERE
<< "URL-rewriter diverts body_pipe " << new_request
->body_pipe
<<
1278 " from request " << old_request
<< " to " << new_request
);
1281 http
->resetRequest(new_request
);
1282 old_request
= nullptr;
1284 debugs(85, DBG_CRITICAL
, "ERROR: URL-rewrite produces invalid request: " <<
1285 old_request
->method
<< " " << urlNote
<< " " << old_request
->http_ver
);
1293 /* XXX PIPELINE: This is inaccurate during pipelining */
1295 if (http
->getConn() != NULL
&& Comm::IsConnOpen(http
->getConn()->clientConnection
))
1296 fd_note(http
->getConn()->clientConnection
->fd
, http
->uri
);
1304 * This method handles the different replies from StoreID helper.
1307 ClientRequestContext::clientStoreIdDone(const Helper::Reply
&reply
)
1309 HttpRequest
*old_request
= http
->request
;
1310 debugs(85, 5, "'" << http
->uri
<< "' result=" << reply
);
1311 assert(store_id_state
== REDIRECT_PENDING
);
1312 store_id_state
= REDIRECT_DONE
;
1314 // Put helper response Notes into the transaction state record (ALE) eventually
1315 // do it early to ensure that no matter what the outcome the notes are present.
1317 http
->al
->syncNotes(old_request
);
1319 UpdateRequestNotes(http
->getConn(), *old_request
, reply
.notes
);
1321 switch (reply
.result
) {
1322 case Helper::Unknown
:
1324 // Handler in redirect.cc should have already mapped Unknown
1325 // IF it contained valid entry for the old helper protocol
1326 debugs(85, DBG_IMPORTANT
, "ERROR: storeID helper returned invalid result code. Wrong helper? " << reply
);
1329 case Helper::TimedOut
:
1330 // Timeouts for storeID are not implemented
1331 case Helper::BrokenHelper
:
1332 debugs(85, DBG_IMPORTANT
, "ERROR: storeID helper: " << reply
);
1336 // no change to be done.
1339 case Helper::Okay
: {
1340 const char *urlNote
= reply
.notes
.findFirst("store-id");
1342 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
1343 if (urlNote
!= NULL
&& strcmp(urlNote
, http
->uri
) ) {
1344 // Debug section required for some very specific cases.
1345 debugs(85, 9, "Setting storeID with: " << urlNote
);
1346 http
->request
->store_id
= urlNote
;
1347 http
->store_id
= urlNote
;
1356 /** Test cache allow/deny configuration
1357 * Sets flags.cachable=1 if caching is not denied.
1360 ClientRequestContext::checkNoCache()
1362 if (Config
.accessList
.noCache
) {
1363 acl_checklist
= clientAclChecklistCreate(Config
.accessList
.noCache
, http
);
1364 acl_checklist
->nonBlockingCheck(checkNoCacheDoneWrapper
, this);
1366 /* unless otherwise specified, we try to cache. */
1367 checkNoCacheDone(ACCESS_ALLOWED
);
1372 checkNoCacheDoneWrapper(Acl::Answer answer
, void *data
)
1374 ClientRequestContext
*calloutContext
= (ClientRequestContext
*) data
;
1376 if (!calloutContext
->httpStateIsValid())
1379 calloutContext
->checkNoCacheDone(answer
);
1383 ClientRequestContext::checkNoCacheDone(const Acl::Answer
&answer
)
1385 acl_checklist
= NULL
;
1386 if (answer
.denied()) {
1387 http
->request
->flags
.noCache
= true; // do not read reply from cache
1388 http
->request
->flags
.cachable
= false; // do not store reply into cache
1395 ClientRequestContext::sslBumpAccessCheck()
1397 if (!http
->getConn()) {
1398 http
->al
->ssl
.bumpMode
= Ssl::bumpEnd
; // SslBump does not apply; log -
1402 const Ssl::BumpMode bumpMode
= http
->getConn()->sslBumpMode
;
1403 if (http
->request
->flags
.forceTunnel
) {
1404 debugs(85, 5, "not needed; already decided to tunnel " << http
->getConn());
1405 if (bumpMode
!= Ssl::bumpEnd
)
1406 http
->al
->ssl
.bumpMode
= bumpMode
; // inherited from bumped connection
1410 // If SSL connection tunneling or bumping decision has been made, obey it.
1411 if (bumpMode
!= Ssl::bumpEnd
) {
1412 debugs(85, 5, HERE
<< "SslBump already decided (" << bumpMode
<<
1413 "), " << "ignoring ssl_bump for " << http
->getConn());
1415 // We need the following "if" for transparently bumped TLS connection,
1416 // because in this case we are running ssl_bump access list before
1417 // the doCallouts runs. It can be removed after the bug #4340 fixed.
1418 // We do not want to proceed to bumping steps:
1419 // - if the TLS connection with the client is already established
1420 // because we are accepting normal HTTP requests on TLS port,
1421 // or because of the client-first bumping mode
1422 // - When the bumping is already started
1423 if (!http
->getConn()->switchedToHttps() &&
1424 !http
->getConn()->serverBump())
1425 http
->sslBumpNeed(bumpMode
); // for processRequest() to bump if needed and not already bumped
1426 http
->al
->ssl
.bumpMode
= bumpMode
; // inherited from bumped connection
1430 // If we have not decided yet, decide whether to bump now.
1432 // Bumping here can only start with a CONNECT request on a bumping port
1433 // (bumping of intercepted SSL conns is decided before we get 1st request).
1434 // We also do not bump redirected CONNECT requests.
1435 if (http
->request
->method
!= Http::METHOD_CONNECT
|| http
->redirect
.status
||
1436 !Config
.accessList
.ssl_bump
||
1437 !http
->getConn()->port
->flags
.tunnelSslBumping
) {
1438 http
->al
->ssl
.bumpMode
= Ssl::bumpEnd
; // SslBump does not apply; log -
1439 debugs(85, 5, HERE
<< "cannot SslBump this request");
1443 // Do not bump during authentication: clients would not proxy-authenticate
1444 // if we delay a 407 response and respond with 200 OK to CONNECT.
1445 if (error
&& error
->httpStatus
== Http::scProxyAuthenticationRequired
) {
1446 http
->al
->ssl
.bumpMode
= Ssl::bumpEnd
; // SslBump does not apply; log -
1447 debugs(85, 5, HERE
<< "no SslBump during proxy authentication");
1452 debugs(85, 5, "SslBump applies. Force bump action on error " << errorTypeName(error
->type
));
1453 http
->sslBumpNeed(Ssl::bumpBump
);
1454 http
->al
->ssl
.bumpMode
= Ssl::bumpBump
;
1458 debugs(85, 5, HERE
<< "SslBump possible, checking ACL");
1460 ACLFilledChecklist
*aclChecklist
= clientAclChecklistCreate(Config
.accessList
.ssl_bump
, http
);
1461 aclChecklist
->nonBlockingCheck(sslBumpAccessCheckDoneWrapper
, this);
1466 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1467 * as ACLFilledChecklist callback
1470 sslBumpAccessCheckDoneWrapper(Acl::Answer answer
, void *data
)
1472 ClientRequestContext
*calloutContext
= static_cast<ClientRequestContext
*>(data
);
1474 if (!calloutContext
->httpStateIsValid())
1476 calloutContext
->sslBumpAccessCheckDone(answer
);
1480 ClientRequestContext::sslBumpAccessCheckDone(const Acl::Answer
&answer
)
1482 if (!httpStateIsValid())
1485 const Ssl::BumpMode bumpMode
= answer
.allowed() ?
1486 static_cast<Ssl::BumpMode
>(answer
.kind
) : Ssl::bumpSplice
;
1487 http
->sslBumpNeed(bumpMode
); // for processRequest() to bump if needed
1488 http
->al
->ssl
.bumpMode
= bumpMode
; // for logging
1490 if (bumpMode
== Ssl::bumpTerminate
) {
1491 const Comm::ConnectionPointer clientConn
= http
->getConn() ? http
->getConn()->clientConnection
: nullptr;
1492 if (Comm::IsConnOpen(clientConn
)) {
1493 debugs(85, 3, "closing after Ssl::bumpTerminate ");
1494 clientConn
->close();
1504 * Identify requests that do not go through the store and client side stream
1505 * and forward them to the appropriate location. All other requests, request
1509 ClientHttpRequest::processRequest()
1511 debugs(85, 4, request
->method
<< ' ' << uri
);
1513 const bool untouchedConnect
= request
->method
== Http::METHOD_CONNECT
&& !redirect
.status
;
1516 if (untouchedConnect
&& sslBumpNeeded()) {
1517 assert(!request
->flags
.forceTunnel
);
1523 if (untouchedConnect
|| request
->flags
.forceTunnel
) {
1524 getConn()->stopReading(); // tunnels read for themselves
1533 ClientHttpRequest::httpStart()
1535 PROF_start(httpStart
);
1536 // XXX: Re-initializes rather than updates. Should not be needed at all.
1537 logType
.update(LOG_TAG_NONE
);
1538 debugs(85, 4, logType
.c_str() << " for '" << uri
<< "'");
1540 /* no one should have touched this */
1541 assert(out
.offset
== 0);
1542 /* Use the Stream Luke */
1543 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->data
;
1544 clientStreamRead(node
, this, node
->readBuffer
);
1545 PROF_stop(httpStart
);
1551 ClientHttpRequest::sslBumpNeed(Ssl::BumpMode mode
)
1553 debugs(83, 3, HERE
<< "sslBump required: "<< Ssl::bumpMode(mode
));
1554 sslBumpNeed_
= mode
;
1557 // called when comm_write has completed
1559 SslBumpEstablish(const Comm::ConnectionPointer
&, char *, size_t, Comm::Flag errflag
, int, void *data
)
1561 ClientHttpRequest
*r
= static_cast<ClientHttpRequest
*>(data
);
1562 debugs(85, 5, HERE
<< "responded to CONNECT: " << r
<< " ? " << errflag
);
1564 assert(r
&& cbdataReferenceValid(r
));
1565 r
->sslBumpEstablish(errflag
);
1569 ClientHttpRequest::sslBumpEstablish(Comm::Flag errflag
)
1571 // Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up
1572 if (errflag
== Comm::ERR_CLOSING
)
1576 debugs(85, 3, HERE
<< "CONNECT response failure in SslBump: " << errflag
);
1577 getConn()->clientConnection
->close();
1582 // Preserve authentication info for the ssl-bumped request
1583 if (request
->auth_user_request
!= NULL
)
1584 getConn()->setAuth(request
->auth_user_request
, "SSL-bumped CONNECT");
1587 assert(sslBumpNeeded());
1588 getConn()->switchToHttps(this, sslBumpNeed_
);
1592 ClientHttpRequest::sslBumpStart()
1594 debugs(85, 5, HERE
<< "Confirming " << Ssl::bumpMode(sslBumpNeed_
) <<
1595 "-bumped CONNECT tunnel on FD " << getConn()->clientConnection
);
1596 getConn()->sslBumpMode
= sslBumpNeed_
;
1598 AsyncCall::Pointer bumpCall
= commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1599 CommIoCbPtrFun(&SslBumpEstablish
, this));
1601 if (request
->flags
.interceptTproxy
|| request
->flags
.intercepted
) {
1602 CommIoCbParams
¶ms
= GetCommParams
<CommIoCbParams
>(bumpCall
);
1603 params
.flag
= Comm::OK
;
1604 params
.conn
= getConn()->clientConnection
;
1605 ScheduleCallHere(bumpCall
);
1609 al
->reply
= HttpReply::MakeConnectionEstablished();
1611 const auto mb
= al
->reply
->pack();
1612 // send an HTTP 200 response to kick client SSL negotiation
1613 // TODO: Unify with tunnel.cc and add a Server(?) header
1614 Comm::Write(getConn()->clientConnection
, mb
, bumpCall
);
1621 ClientHttpRequest::updateError(const Error
&error
)
1624 request
->error
.update(error
);
1626 al
->updateError(error
);
1630 ClientHttpRequest::gotEnough() const
1632 // TODO: See also (and unify with) clientReplyContext::storeNotOKTransferDone()
1633 int64_t contentLength
=
1634 memObject()->baseReply().bodySize(request
->method
);
1635 assert(contentLength
>= 0);
1637 if (out
.offset
< contentLength
)
1644 ClientHttpRequest::storeEntry(StoreEntry
*newEntry
)
1650 ClientHttpRequest::loggingEntry(StoreEntry
*newEntry
)
1653 loggingEntry_
->unlock("ClientHttpRequest::loggingEntry");
1655 loggingEntry_
= newEntry
;
1658 loggingEntry_
->lock("ClientHttpRequest::loggingEntry");
1662 ClientHttpRequest::initRequest(HttpRequest
*aRequest
)
1664 assignRequest(aRequest
);
1665 if (const auto csd
= getConn()) {
1666 if (!csd
->notes()->empty())
1667 request
->notes()->appendNewOnly(csd
->notes().getRaw());
1669 // al is created in the constructor
1672 al
->request
= request
;
1673 HTTPMSGLOCK(al
->request
);
1674 al
->syncNotes(request
);
1679 ClientHttpRequest::resetRequest(HttpRequest
*newRequest
)
1681 assert(request
!= newRequest
);
1683 assignRequest(newRequest
);
1685 uri
= SBufToCstring(request
->effectiveRequestUri());
1689 ClientHttpRequest::assignRequest(HttpRequest
*newRequest
)
1693 const_cast<HttpRequest
*&>(request
) = newRequest
;
1694 HTTPMSGLOCK(request
);
1695 setLogUriToRequestUri();
1699 ClientHttpRequest::clearRequest()
1701 HttpRequest
*oldRequest
= request
;
1702 HTTPMSGUNLOCK(oldRequest
);
1703 const_cast<HttpRequest
*&>(request
) = nullptr;
1704 absorbLogUri(nullptr);
1708 * doCallouts() - This function controls the order of "callout"
1709 * executions, including non-blocking access control checks, the
1710 * redirector, and ICAP. Previously, these callouts were chained
1711 * together such that "clientAccessCheckDone()" would call
1712 * "clientRedirectStart()" and so on.
1714 * The ClientRequestContext (aka calloutContext) class holds certain
1715 * state data for the callout/callback operations. Previously
1716 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1717 * for a short time. ClientRequestContext would then delete itself
1718 * and pass control back to ClientHttpRequest when all callouts
1721 * This caused some problems for ICAP because we want to make the
1722 * ICAP callout after checking ACLs, but before checking the no_cache
1723 * list. We can't stuff the ICAP state into the ClientRequestContext
1724 * class because we still need the ICAP state after ClientRequestContext
1727 * Note that ClientRequestContext is created before the first call
1730 * If one of the callouts notices that ClientHttpRequest is no
1731 * longer valid, it should call cbdataReferenceDone() so that
1732 * ClientHttpRequest's reference count goes to zero and it will get
1733 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1735 * Note that we set the _done flags here before actually starting
1736 * the callout. This is strictly for convenience.
1739 tos_t
aclMapTOS (acl_tos
* head
, ACLChecklist
* ch
);
1740 Ip::NfMarkConfig
aclFindNfMarkConfig (acl_nfmark
* head
, ACLChecklist
* ch
);
1743 ClientHttpRequest::doCallouts()
1745 assert(calloutContext
);
1747 if (!calloutContext
->error
) {
1748 // CVE-2009-0801: verify the Host: header is consistent with other known details.
1749 if (!calloutContext
->host_header_verify_done
) {
1750 debugs(83, 3, HERE
<< "Doing calloutContext->hostHeaderVerify()");
1751 calloutContext
->host_header_verify_done
= true;
1752 calloutContext
->hostHeaderVerify();
1756 if (!calloutContext
->http_access_done
) {
1757 debugs(83, 3, HERE
<< "Doing calloutContext->clientAccessCheck()");
1758 calloutContext
->http_access_done
= true;
1759 calloutContext
->clientAccessCheck();
1764 if (!calloutContext
->adaptation_acl_check_done
) {
1765 calloutContext
->adaptation_acl_check_done
= true;
1766 if (Adaptation::AccessCheck::Start(
1767 Adaptation::methodReqmod
, Adaptation::pointPreCache
,
1768 request
, NULL
, calloutContext
->http
->al
, this))
1769 return; // will call callback
1773 if (!calloutContext
->redirect_done
) {
1774 calloutContext
->redirect_done
= true;
1776 if (Config
.Program
.redirect
) {
1777 debugs(83, 3, HERE
<< "Doing calloutContext->clientRedirectStart()");
1778 calloutContext
->redirect_state
= REDIRECT_PENDING
;
1779 calloutContext
->clientRedirectStart();
1784 if (!calloutContext
->adapted_http_access_done
) {
1785 debugs(83, 3, HERE
<< "Doing calloutContext->clientAccessCheck2()");
1786 calloutContext
->adapted_http_access_done
= true;
1787 calloutContext
->clientAccessCheck2();
1791 if (!calloutContext
->store_id_done
) {
1792 calloutContext
->store_id_done
= true;
1794 if (Config
.Program
.store_id
) {
1795 debugs(83, 3,"Doing calloutContext->clientStoreIdStart()");
1796 calloutContext
->store_id_state
= REDIRECT_PENDING
;
1797 calloutContext
->clientStoreIdStart();
1802 if (!calloutContext
->interpreted_req_hdrs
) {
1803 debugs(83, 3, HERE
<< "Doing clientInterpretRequestHeaders()");
1804 calloutContext
->interpreted_req_hdrs
= 1;
1805 clientInterpretRequestHeaders(this);
1808 if (!calloutContext
->no_cache_done
) {
1809 calloutContext
->no_cache_done
= true;
1811 if (Config
.accessList
.noCache
&& request
->flags
.cachable
) {
1812 debugs(83, 3, HERE
<< "Doing calloutContext->checkNoCache()");
1813 calloutContext
->checkNoCache();
1817 } // if !calloutContext->error
1819 // Set appropriate MARKs and CONNMARKs if needed.
1820 if (getConn() && Comm::IsConnOpen(getConn()->clientConnection
)) {
1821 ACLFilledChecklist
ch(nullptr, request
, nullptr);
1822 ch
.al
= calloutContext
->http
->al
;
1823 ch
.src_addr
= request
->client_addr
;
1824 ch
.my_addr
= request
->my_addr
;
1825 ch
.syncAle(request
, log_uri
);
1827 if (!calloutContext
->toClientMarkingDone
) {
1828 calloutContext
->toClientMarkingDone
= true;
1829 tos_t tos
= aclMapTOS(Ip::Qos::TheConfig
.tosToClient
, &ch
);
1831 Ip::Qos::setSockTos(getConn()->clientConnection
, tos
);
1833 const auto packetMark
= aclFindNfMarkConfig(Ip::Qos::TheConfig
.nfmarkToClient
, &ch
);
1834 if (!packetMark
.isEmpty())
1835 Ip::Qos::setSockNfmark(getConn()->clientConnection
, packetMark
.mark
);
1837 const auto connmark
= aclFindNfMarkConfig(Ip::Qos::TheConfig
.nfConnmarkToClient
, &ch
);
1838 if (!connmark
.isEmpty())
1839 Ip::Qos::setNfConnmark(getConn()->clientConnection
, Ip::Qos::dirAccepted
, connmark
);
1844 // Even with calloutContext->error, we call sslBumpAccessCheck() to decide
1845 // whether SslBump applies to this transaction. If it applies, we will
1846 // attempt to bump the client to serve the error.
1847 if (!calloutContext
->sslBumpCheckDone
) {
1848 calloutContext
->sslBumpCheckDone
= true;
1849 if (calloutContext
->sslBumpAccessCheck())
1851 /* else no ssl bump required*/
1855 if (calloutContext
->error
) {
1856 // XXX: prformance regression. c_str() reallocates
1857 SBuf
storeUriBuf(request
->storeId());
1858 const char *storeUri
= storeUriBuf
.c_str();
1859 StoreEntry
*e
= storeCreateEntry(storeUri
, storeUri
, request
->flags
, request
->method
);
1861 if (sslBumpNeeded()) {
1862 // We have to serve an error, so bump the client first.
1863 sslBumpNeed(Ssl::bumpClientFirst
);
1864 // set final error but delay sending until we bump
1865 Ssl::ServerBump
*srvBump
= new Ssl::ServerBump(this, e
, Ssl::bumpClientFirst
);
1866 errorAppendEntry(e
, calloutContext
->error
);
1867 calloutContext
->error
= NULL
;
1868 getConn()->setServerBump(srvBump
);
1869 e
->unlock("ClientHttpRequest::doCallouts+sslBumpNeeded");
1873 // send the error to the client now
1874 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
1875 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1876 assert (repContext
);
1877 repContext
->setReplyToStoreEntry(e
, "immediate SslBump error");
1878 errorAppendEntry(e
, calloutContext
->error
);
1879 calloutContext
->error
= NULL
;
1880 if (calloutContext
->readNextRequest
&& getConn())
1881 getConn()->flags
.readMore
= true; // resume any pipeline reads.
1882 node
= (clientStreamNode
*)client_stream
.tail
->data
;
1883 clientStreamRead(node
, this, node
->readBuffer
);
1884 e
->unlock("ClientHttpRequest::doCallouts-sslBumpNeeded");
1889 cbdataReferenceDone(calloutContext
->http
);
1890 delete calloutContext
;
1891 calloutContext
= NULL
;
1894 headersLog(0, 1, request
->method
, request
);
1897 debugs(83, 3, HERE
<< "calling processRequest()");
1901 Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
1903 ih
->logType
= logType
;
1908 ClientHttpRequest::setLogUriToRequestUri()
1911 const auto canonicalUri
= request
->canonicalCleanUrl();
1912 absorbLogUri(xstrndup(canonicalUri
, MAX_URL
));
1916 ClientHttpRequest::setLogUriToRawUri(const char *rawUri
, const HttpRequestMethod
&method
)
1919 // Should(!request);
1921 // TODO: SBuf() performance regression, fix by converting rawUri to SBuf
1922 char *canonicalUri
= urlCanonicalCleanWithoutRequest(SBuf(rawUri
), method
, AnyP::UriScheme());
1924 absorbLogUri(AnyP::Uri::cleanup(canonicalUri
));
1926 char *cleanedRawUri
= AnyP::Uri::cleanup(rawUri
);
1927 al
->setVirginUrlForMissingRequest(SBuf(cleanedRawUri
));
1928 xfree(cleanedRawUri
);
1932 ClientHttpRequest::absorbLogUri(char *aUri
)
1935 const_cast<char *&>(log_uri
) = aUri
;
1939 ClientHttpRequest::setErrorUri(const char *aUri
)
1943 // Should(!request);
1945 uri
= xstrdup(aUri
);
1946 // TODO: SBuf() performance regression, fix by converting setErrorUri() parameter to SBuf
1947 const SBuf
errorUri(aUri
);
1948 const auto canonicalUri
= urlCanonicalCleanWithoutRequest(errorUri
, HttpRequestMethod(), AnyP::UriScheme());
1949 absorbLogUri(xstrndup(canonicalUri
, MAX_URL
));
1951 al
->setVirginUrlForMissingRequest(errorUri
);
1955 /// Initiate an asynchronous adaptation transaction which will call us back.
1957 ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer
&g
)
1959 debugs(85, 3, HERE
<< "adaptation needed for " << this);
1960 assert(!virginHeadSource
);
1961 assert(!adaptedBodySource
);
1962 virginHeadSource
= initiateAdaptation(
1963 new Adaptation::Iterator(request
, NULL
, al
, g
));
1965 // we could try to guess whether we can bypass this adaptation
1966 // initiation failure, but it should not really happen
1967 Must(initiated(virginHeadSource
));
1971 ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer
&answer
)
1973 assert(cbdataReferenceValid(this)); // indicates bug
1974 clearAdaptation(virginHeadSource
);
1975 assert(!adaptedBodySource
);
1977 switch (answer
.kind
) {
1978 case Adaptation::Answer::akForward
:
1979 handleAdaptedHeader(const_cast<Http::Message
*>(answer
.message
.getRaw()));
1982 case Adaptation::Answer::akBlock
:
1983 handleAdaptationBlock(answer
);
1986 case Adaptation::Answer::akError
: {
1987 static const auto d
= MakeNamedErrorDetail("CLT_REQMOD_ABORT");
1988 handleAdaptationFailure(d
, !answer
.final
);
1995 ClientHttpRequest::handleAdaptedHeader(Http::Message
*msg
)
1999 if (HttpRequest
*new_req
= dynamic_cast<HttpRequest
*>(msg
)) {
2000 // update the new message to flag whether URL re-writing was done on it
2001 if (request
->effectiveRequestUri() != new_req
->effectiveRequestUri())
2002 new_req
->flags
.redirected
= true;
2003 resetRequest(new_req
);
2004 assert(request
->method
.id());
2005 } else if (HttpReply
*new_rep
= dynamic_cast<HttpReply
*>(msg
)) {
2006 debugs(85,3,HERE
<< "REQMOD reply is HTTP reply");
2008 // subscribe to receive reply body
2009 if (new_rep
->body_pipe
!= NULL
) {
2010 adaptedBodySource
= new_rep
->body_pipe
;
2011 int consumer_ok
= adaptedBodySource
->setConsumerIfNotLate(this);
2012 assert(consumer_ok
);
2015 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
2016 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2018 repContext
->createStoreEntry(request
->method
, request
->flags
);
2020 request_satisfaction_mode
= true;
2021 request_satisfaction_offset
= 0;
2022 storeEntry()->replaceHttpReply(new_rep
);
2023 storeEntry()->timestampsSet();
2025 al
->reply
= new_rep
;
2027 if (!adaptedBodySource
) // no body
2028 storeEntry()->complete();
2029 clientGetMoreData(node
, this);
2032 // we are done with getting headers (but may be receiving body)
2033 clearAdaptation(virginHeadSource
);
2035 if (!request_satisfaction_mode
)
2040 ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer
&answer
)
2042 static const auto d
= MakeNamedErrorDetail("REQMOD_BLOCK");
2043 request
->detailError(ERR_ACCESS_DENIED
, d
);
2044 AclMatchedName
= answer
.ruleId
.termedBuf();
2045 assert(calloutContext
);
2046 calloutContext
->clientAccessCheckDone(ACCESS_DENIED
);
2047 AclMatchedName
= NULL
;
2051 ClientHttpRequest::resumeBodyStorage()
2053 if (!adaptedBodySource
)
2056 noteMoreBodyDataAvailable(adaptedBodySource
);
2060 ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer
)
2062 assert(request_satisfaction_mode
);
2063 assert(adaptedBodySource
!= NULL
);
2065 if (size_t contentSize
= adaptedBodySource
->buf().contentSize()) {
2066 const size_t spaceAvailable
= storeEntry()->bytesWanted(Range
<size_t>(0,contentSize
));
2068 if (spaceAvailable
< contentSize
) {
2069 // No or partial body data consuming
2070 typedef NullaryMemFunT
<ClientHttpRequest
> Dialer
;
2071 AsyncCall::Pointer call
= asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage",
2072 Dialer(this, &ClientHttpRequest::resumeBodyStorage
));
2073 storeEntry()->deferProducer(call
);
2076 if (!spaceAvailable
)
2079 if (spaceAvailable
< contentSize
)
2080 contentSize
= spaceAvailable
;
2082 BodyPipeCheckout
bpc(*adaptedBodySource
);
2083 const StoreIOBuffer
ioBuf(&bpc
.buf
, request_satisfaction_offset
, contentSize
);
2084 storeEntry()->write(ioBuf
);
2085 // assume StoreEntry::write() writes the entire ioBuf
2086 request_satisfaction_offset
+= ioBuf
.length
;
2087 bpc
.buf
.consume(contentSize
);
2091 if (adaptedBodySource
->exhausted())
2092 endRequestSatisfaction();
2093 // else wait for more body data
2097 ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer
)
2099 assert(!virginHeadSource
);
2100 // should we end request satisfaction now?
2101 if (adaptedBodySource
!= NULL
&& adaptedBodySource
->exhausted())
2102 endRequestSatisfaction();
2106 ClientHttpRequest::endRequestSatisfaction()
2108 debugs(85,4, HERE
<< this << " ends request satisfaction");
2109 assert(request_satisfaction_mode
);
2110 stopConsumingFrom(adaptedBodySource
);
2112 // TODO: anything else needed to end store entry formation correctly?
2113 storeEntry()->complete();
2117 ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer
)
2119 assert(!virginHeadSource
);
2120 stopConsumingFrom(adaptedBodySource
);
2122 debugs(85,3, HERE
<< "REQMOD body production failed");
2123 if (request_satisfaction_mode
) { // too late to recover or serve an error
2124 static const auto d
= MakeNamedErrorDetail("CLT_REQMOD_RESP_BODY");
2125 request
->detailError(ERR_ICAP_FAILURE
, d
);
2126 const Comm::ConnectionPointer c
= getConn()->clientConnection
;
2127 Must(Comm::IsConnOpen(c
));
2128 c
->close(); // drastic, but we may be writing a response already
2130 static const auto d
= MakeNamedErrorDetail("CLT_REQMOD_REQ_BODY");
2131 handleAdaptationFailure(d
);
2136 ClientHttpRequest::handleAdaptationFailure(const ErrorDetail::Pointer
&errDetail
, bool bypassable
)
2138 debugs(85,3, HERE
<< "handleAdaptationFailure(" << bypassable
<< ")");
2140 const bool usedStore
= storeEntry() && !storeEntry()->isEmpty();
2141 const bool usedPipe
= request
->body_pipe
!= NULL
&&
2142 request
->body_pipe
->consumedSize() > 0;
2144 if (bypassable
&& !usedStore
&& !usedPipe
) {
2145 debugs(85,3, HERE
<< "ICAP REQMOD callout failed, bypassing: " << calloutContext
);
2151 debugs(85,3, HERE
<< "ICAP REQMOD callout failed, responding with error");
2153 clientStreamNode
*node
= (clientStreamNode
*)client_stream
.tail
->prev
->data
;
2154 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2157 calloutsError(ERR_ICAP_FAILURE
, errDetail
);
2164 ClientHttpRequest::callException(const std::exception
&ex
)
2166 if (const auto clientConn
= getConn() ? getConn()->clientConnection
: nullptr) {
2167 if (Comm::IsConnOpen(clientConn
)) {
2168 debugs(85, 3, "closing after exception: " << ex
.what());
2169 clientConn
->close(); // initiate orderly top-to-bottom cleanup
2173 debugs(85, DBG_IMPORTANT
, "ClientHttpRequest exception without connection. Ignoring " << ex
.what());
2174 // XXX: Normally, we mustStop() but we cannot do that here because it is
2175 // likely to leave Http::Stream and ConnStateData with a dangling http
2176 // pointer. See r13480 or XXX in Http::Stream class description.
2180 // XXX: modify and use with ClientRequestContext::clientAccessCheckDone too.
2182 ClientHttpRequest::calloutsError(const err_type error
, const ErrorDetail::Pointer
&errDetail
)
2184 // The original author of the code also wanted to pass an errno to
2185 // setReplyToError, but it seems unlikely that the errno reflects the
2186 // true cause of the error at this point, so I did not pass it.
2187 if (calloutContext
) {
2188 ConnStateData
* c
= getConn();
2189 calloutContext
->error
= clientBuildError(error
, Http::scInternalServerError
,
2190 nullptr, c
, request
, al
);
2192 calloutContext
->error
->auth_user_request
=
2193 c
!= NULL
&& c
->getAuth() != NULL
? c
->getAuth() : request
->auth_user_request
;
2195 calloutContext
->error
->detailError(errDetail
);
2196 calloutContext
->readNextRequest
= true;
2198 c
->expectNoForwarding();
2200 //else if(calloutContext == NULL) is it possible?