2 * Copyright (C) 1996-2016 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 17 Request Forwarding */
12 #include "AccessLogEntry.h"
13 #include "acl/Address.h"
14 #include "acl/FilledChecklist.h"
15 #include "acl/Gadgets.h"
16 #include "anyp/PortCfg.h"
17 #include "CacheManager.h"
18 #include "CachePeer.h"
19 #include "client_side.h"
20 #include "clients/forward.h"
21 #include "comm/Connection.h"
22 #include "comm/ConnOpener.h"
23 #include "comm/Loops.h"
24 #include "CommCalls.h"
25 #include "errorpage.h"
32 #include "hier_code.h"
34 #include "http/Stream.h"
35 #include "HttpReply.h"
36 #include "HttpRequest.h"
37 #include "icmp/net_db.h"
39 #include "ip/Intercept.h"
40 #include "ip/QosConfig.h"
42 #include "MemObject.h"
43 #include "mgr/Registration.h"
44 #include "neighbors.h"
46 #include "PeerPoolMgr.h"
47 #include "PeerSelectState.h"
48 #include "security/BlindPeerConnector.h"
49 #include "SquidConfig.h"
50 #include "SquidTime.h"
51 #include "ssl/PeekingPeerConnector.h"
53 #include "StoreClient.h"
57 #include "ssl/cert_validate_message.h"
58 #include "ssl/Config.h"
59 #include "ssl/ErrorDetail.h"
60 #include "ssl/helper.h"
61 #include "ssl/ServerBump.h"
62 #include "ssl/support.h"
64 #include "security/EncryptorAnswer.h"
69 static PSC fwdPeerSelectionCompleteWrapper
;
70 static CLCB fwdServerClosedWrapper
;
71 static CNCB fwdConnectDoneWrapper
;
75 #define MAX_FWD_STATS_IDX 9
76 static int FwdReplyCodes
[MAX_FWD_STATS_IDX
+ 1][Http::scInvalidHeader
+ 1];
78 static PconnPool
*fwdPconnPool
= new PconnPool("server-peers", NULL
);
79 CBDATA_CLASS_INIT(FwdState
);
81 class FwdStatePeerAnswerDialer
: public CallDialer
, public Security::PeerConnector::CbDialer
84 typedef void (FwdState::*Method
)(Security::EncryptorAnswer
&);
86 FwdStatePeerAnswerDialer(Method method
, FwdState
*fwd
):
87 method_(method
), fwd_(fwd
), answer_() {}
90 virtual bool canDial(AsyncCall
&call
) { return fwd_
.valid(); }
91 void dial(AsyncCall
&call
) { ((&(*fwd_
))->*method_
)(answer_
); }
92 virtual void print(std::ostream
&os
) const {
93 os
<< '(' << fwd_
.get() << ", " << answer_
<< ')';
96 /* Security::PeerConnector::CbDialer API */
97 virtual Security::EncryptorAnswer
&answer() { return answer_
; }
101 CbcPointer
<FwdState
> fwd_
;
102 Security::EncryptorAnswer answer_
;
106 FwdState::abort(void* d
)
108 FwdState
* fwd
= (FwdState
*)d
;
109 Pointer tmp
= fwd
; // Grab a temporary pointer to keep the object alive during our scope.
111 if (Comm::IsConnOpen(fwd
->serverConnection())) {
112 fwd
->closeServerConnection("store entry aborted");
114 debugs(17, 7, HERE
<< "store entry aborted; no connection to close");
116 fwd
->serverDestinations
.clear();
121 FwdState::closeServerConnection(const char *reason
)
123 debugs(17, 3, "because " << reason
<< "; " << serverConn
);
124 comm_remove_close_handler(serverConn
->fd
, closeHandler
);
126 fwdPconnPool
->noteUses(fd_table
[serverConn
->fd
].pconn
.uses
);
130 /**** PUBLIC INTERFACE ********************************************************/
132 FwdState::FwdState(const Comm::ConnectionPointer
&client
, StoreEntry
* e
, HttpRequest
* r
, const AccessLogEntryPointer
&alp
):
138 start_t(squid_curtime
),
140 pconnRace(raceImpossible
)
142 debugs(17, 2, "Forwarding client request " << client
<< ", url=" << e
->url());
143 HTTPMSGLOCK(request
);
144 serverDestinations
.reserve(Config
.forward_max_tries
);
146 EBIT_SET(e
->flags
, ENTRY_FWD_HDR_WAIT
);
147 flags
.connected_okay
= false;
148 flags
.dont_retry
= false;
149 flags
.forward_completed
= false;
150 debugs(17, 3, "FwdState constructed, this=" << this);
153 // Called once, right after object creation, when it is safe to set self
154 void FwdState::start(Pointer aSelf
)
156 // Protect ourselves from being destroyed when the only Server pointing
157 // to us is gone (while we expect to talk to more Servers later).
158 // Once we set self, we are responsible for clearing it when we do not
159 // expect to talk to any servers.
160 self
= aSelf
; // refcounted
162 // We hope that either the store entry aborts or peer is selected.
163 // Otherwise we are going to leak our object.
165 // Ftp::Relay needs to preserve control connection on data aborts
166 // so it registers its own abort handler that calls ours when needed.
167 if (!request
->flags
.ftpNative
)
168 entry
->registerAbort(FwdState::abort
, this);
170 #if STRICT_ORIGINAL_DST
171 // Bug 3243: CVE 2009-0801
172 // Bypass of browser same-origin access control in intercepted communication
173 // To resolve this we must force DIRECT and only to the original client destination.
174 const bool isIntercepted
= request
&& !request
->flags
.redirected
&& (request
->flags
.intercepted
|| request
->flags
.interceptTproxy
);
175 const bool useOriginalDst
= Config
.onoff
.client_dst_passthru
|| (request
&& !request
->flags
.hostVerified
);
176 if (isIntercepted
&& useOriginalDst
) {
177 selectPeerForIntercepted();
178 // 3.2 does not suppro re-wrapping inside CONNECT.
179 // our only alternative is to fake destination "found" and continue with the forwarding.
180 startConnectionOrFail();
185 // do full route options selection
186 peerSelect(&serverDestinations
, request
, al
, entry
, fwdPeerSelectionCompleteWrapper
, this);
189 #if STRICT_ORIGINAL_DST
190 /// bypasses peerSelect() when dealing with intercepted requests
192 FwdState::selectPeerForIntercepted()
194 // use pinned connection if available
195 Comm::ConnectionPointer p
;
196 if (ConnStateData
*client
= request
->pinnedConnection()) {
197 p
= client
->validatePinnedConnection(request
, NULL
);
198 if (Comm::IsConnOpen(p
)) {
199 /* duplicate peerSelectPinned() effects */
200 p
->peerType
= PINNED
;
201 entry
->ping_status
= PING_DONE
; /* Skip ICP */
203 debugs(17, 3, "reusing a pinned conn: " << *p
);
204 serverDestinations
.push_back(p
);
206 debugs(17,2, "Pinned connection is not valid: " << p
);
207 ErrorState
*anErr
= new ErrorState(ERR_ZERO_SIZE_OBJECT
, Http::scServiceUnavailable
, request
);
210 // Either use the valid pinned connection or fail if it is invalid.
214 // use client original destination as second preferred choice
215 p
= new Comm::Connection();
216 p
->peerType
= ORIGINAL_DST
;
217 p
->remote
= clientConn
->local
;
218 getOutgoingAddress(request
, p
);
220 debugs(17, 3, HERE
<< "using client original destination: " << *p
);
221 serverDestinations
.push_back(p
);
226 FwdState::completed()
228 if (flags
.forward_completed
) {
229 debugs(17, DBG_IMPORTANT
, HERE
<< "FwdState::completed called on a completed request! Bad!");
233 flags
.forward_completed
= true;
235 request
->hier
.stopPeerClock(false);
237 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
238 debugs(17, 3, HERE
<< "entry aborted");
242 #if URL_CHECKSUM_DEBUG
244 entry
->mem_obj
->checkUrlChecksum();
247 if (entry
->store_status
== STORE_PENDING
) {
248 if (entry
->isEmpty()) {
249 if (!err
) // we quit (e.g., fd closed) before an error or content
250 fail(new ErrorState(ERR_READ_ERROR
, Http::scBadGateway
, request
));
252 errorAppendEntry(entry
, err
);
255 if (request
->flags
.sslPeek
&& request
->clientConnectionManager
.valid()) {
256 CallJobHere1(17, 4, request
->clientConnectionManager
, ConnStateData
,
257 ConnStateData::httpsPeeked
, Comm::ConnectionPointer(NULL
));
261 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
263 entry
->releaseRequest();
267 if (storePendingNClients(entry
) > 0)
268 assert(!EBIT_TEST(entry
->flags
, ENTRY_FWD_HDR_WAIT
));
272 FwdState::~FwdState()
274 debugs(17, 3, "FwdState destructor start");
276 if (! flags
.forward_completed
)
281 HTTPMSGUNLOCK(request
);
285 entry
->unregisterAbort();
287 entry
->unlock("FwdState");
291 if (calls
.connector
!= NULL
) {
292 calls
.connector
->cancel("FwdState destructed");
293 calls
.connector
= NULL
;
296 if (Comm::IsConnOpen(serverConn
))
297 closeServerConnection("~FwdState");
299 serverDestinations
.clear();
301 debugs(17, 3, "FwdState destructed, this=" << this);
305 * This is the entry point for client-side to start forwarding
306 * a transaction. It is a static method that may or may not
307 * allocate a FwdState.
310 FwdState::Start(const Comm::ConnectionPointer
&clientConn
, StoreEntry
*entry
, HttpRequest
*request
, const AccessLogEntryPointer
&al
)
313 * client_addr == no_addr indicates this is an "internal" request
314 * from peer_digest.c, asn.c, netdb.c, etc and should always
315 * be allowed. yuck, I know.
318 if ( Config
.accessList
.miss
&& !request
->client_addr
.isNoAddr() &&
319 !request
->flags
.internal
&& request
->url
.getScheme() != AnyP::PROTO_CACHE_OBJECT
) {
321 * Check if this host is allowed to fetch MISSES from us (miss_access).
322 * Intentionally replace the src_addr automatically selected by the checklist code
323 * we do NOT want the indirect client address to be tested here.
325 ACLFilledChecklist
ch(Config
.accessList
.miss
, request
, NULL
);
326 ch
.src_addr
= request
->client_addr
;
327 if (ch
.fastCheck() == ACCESS_DENIED
) {
329 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
, 1);
331 if (page_id
== ERR_NONE
)
332 page_id
= ERR_FORWARDING_DENIED
;
334 ErrorState
*anErr
= new ErrorState(page_id
, Http::scForbidden
, request
);
335 errorAppendEntry(entry
, anErr
); // frees anErr
340 debugs(17, 3, HERE
<< "'" << entry
->url() << "'");
342 * This seems like an odd place to bind mem_obj and request.
343 * Might want to assert that request is NULL at this point
345 entry
->mem_obj
->request
= request
;
346 HTTPMSGLOCK(entry
->mem_obj
->request
);
347 #if URL_CHECKSUM_DEBUG
349 entry
->mem_obj
->checkUrlChecksum();
354 ErrorState
*anErr
= new ErrorState(ERR_SHUTTING_DOWN
, Http::scServiceUnavailable
, request
);
355 errorAppendEntry(entry
, anErr
); // frees anErr
359 if (request
->flags
.internal
) {
360 debugs(17, 2, "calling internalStart() due to request flag");
361 internalStart(clientConn
, request
, entry
);
365 switch (request
->url
.getScheme()) {
367 case AnyP::PROTO_CACHE_OBJECT
:
368 debugs(17, 2, "calling CacheManager due to request scheme " << request
->url
.getScheme());
369 CacheManager::GetInstance()->Start(clientConn
, request
, entry
);
372 case AnyP::PROTO_URN
:
373 urnStart(request
, entry
);
377 FwdState::Pointer fwd
= new FwdState(clientConn
, entry
, request
, al
);
386 FwdState::fwdStart(const Comm::ConnectionPointer
&clientConn
, StoreEntry
*entry
, HttpRequest
*request
)
388 // Hides AccessLogEntry.h from code that does not supply ALE anyway.
389 Start(clientConn
, entry
, request
, NULL
);
393 FwdState::startConnectionOrFail()
395 debugs(17, 3, HERE
<< entry
->url());
397 if (serverDestinations
.size() > 0) {
398 // Ditch error page if it was created before.
399 // A new one will be created if there's another problem
403 // Update the logging information about this new server connection.
404 // Done here before anything else so the errors get logged for
405 // this server link regardless of what happens when connecting to it.
406 // IF sucessfuly connected this top destination will become the serverConnection().
407 syncHierNote(serverDestinations
[0], request
->url
.host());
408 request
->clearError();
412 debugs(17, 3, HERE
<< "Connection failed: " << entry
->url());
414 ErrorState
*anErr
= new ErrorState(ERR_CANNOT_FORWARD
, Http::scInternalServerError
, request
);
416 } // else use actual error from last connection attempt
417 self
= NULL
; // refcounted
422 FwdState::fail(ErrorState
* errorState
)
424 debugs(17, 3, err_type_str
[errorState
->type
] << " \"" << Http::StatusCodeString(errorState
->httpStatus
) << "\"\n\t" << entry
->url());
429 if (!errorState
->request
) {
430 errorState
->request
= request
;
431 HTTPMSGLOCK(errorState
->request
);
434 if (err
->type
!= ERR_ZERO_SIZE_OBJECT
)
437 if (pconnRace
== racePossible
) {
438 debugs(17, 5, HERE
<< "pconn race happened");
439 pconnRace
= raceHappened
;
442 if (ConnStateData
*pinned_connection
= request
->pinnedConnection()) {
443 pinned_connection
->pinning
.zeroReply
= true;
444 flags
.dont_retry
= true; // we want to propagate failure to the client
445 debugs(17, 4, "zero reply on pinned connection");
450 * Frees fwdState without closing FD or generating an abort
453 FwdState::unregister(Comm::ConnectionPointer
&conn
)
455 debugs(17, 3, HERE
<< entry
->url() );
456 assert(serverConnection() == conn
);
457 assert(Comm::IsConnOpen(conn
));
458 comm_remove_close_handler(conn
->fd
, closeHandler
);
463 // \deprecated use unregister(Comm::ConnectionPointer &conn) instead
465 FwdState::unregister(int fd
)
467 debugs(17, 3, HERE
<< entry
->url() );
468 assert(fd
== serverConnection()->fd
);
469 unregister(serverConn
);
473 * FooClient modules call fwdComplete() when they are done
474 * downloading an object. Then, we either 1) re-forward the
475 * request somewhere else if needed, or 2) call storeComplete()
481 debugs(17, 3, HERE
<< entry
->url() << "\n\tstatus " << entry
->getReply()->sline
.status());
482 #if URL_CHECKSUM_DEBUG
484 entry
->mem_obj
->checkUrlChecksum();
487 logReplyStatus(n_tries
, entry
->getReply()->sline
.status());
490 debugs(17, 3, HERE
<< "re-forwarding " << entry
->getReply()->sline
.status() << " " << entry
->url());
492 if (Comm::IsConnOpen(serverConn
))
493 unregister(serverConn
);
497 // drop the last path off the selection list. try the next one.
498 serverDestinations
.erase(serverDestinations
.begin());
499 startConnectionOrFail();
502 if (Comm::IsConnOpen(serverConn
))
503 debugs(17, 3, HERE
<< "server FD " << serverConnection()->fd
<< " not re-forwarding status " << entry
->getReply()->sline
.status());
505 debugs(17, 3, HERE
<< "server (FD closed) not re-forwarding status " << entry
->getReply()->sline
.status());
506 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
509 if (!Comm::IsConnOpen(serverConn
))
512 self
= NULL
; // refcounted
516 /**** CALLBACK WRAPPERS ************************************************************/
519 fwdPeerSelectionCompleteWrapper(Comm::ConnectionList
*, ErrorState
*err
, void *data
)
521 FwdState
*fwd
= (FwdState
*) data
;
524 fwd
->startConnectionOrFail();
528 fwdServerClosedWrapper(const CommCloseCbParams
¶ms
)
530 FwdState
*fwd
= (FwdState
*)params
.data
;
531 fwd
->serverClosed(params
.fd
);
535 fwdConnectDoneWrapper(const Comm::ConnectionPointer
&conn
, Comm::Flag status
, int xerrno
, void *data
)
537 FwdState
*fwd
= (FwdState
*) data
;
538 fwd
->connectDone(conn
, status
, xerrno
);
541 /**** PRIVATE *****************************************************************/
544 * FwdState::checkRetry
546 * Return TRUE if the request SHOULD be retried. This method is
547 * called when the HTTP connection fails, or when the connection
548 * is closed before reading the end of HTTP headers from the server.
551 FwdState::checkRetry()
556 if (!self
) { // we have aborted before the server called us back
557 debugs(17, 5, HERE
<< "not retrying because of earlier abort");
558 // we will be destroyed when the server clears its Pointer to us
562 if (entry
->store_status
!= STORE_PENDING
)
565 if (!entry
->isEmpty())
568 if (n_tries
> Config
.forward_max_tries
)
571 if (squid_curtime
- start_t
> Config
.Timeout
.forward
)
574 if (flags
.dont_retry
)
577 if (request
->bodyNibbled())
580 // NP: not yet actually connected anywhere. retry is safe.
581 if (!flags
.connected_okay
)
584 if (!checkRetriable())
590 /// Whether we may try sending this request again after a failure.
592 FwdState::checkRetriable()
594 // Optimize: A compliant proxy may retry PUTs, but Squid lacks the [rather
595 // complicated] code required to protect the PUT request body from being
596 // nibbled during the first try. Thus, Squid cannot retry some PUTs today.
597 if (request
->body_pipe
!= NULL
)
600 // RFC2616 9.1 Safe and Idempotent Methods
601 return (request
->method
.isHttpSafe() || request
->method
.isIdempotent());
605 FwdState::serverClosed(int fd
)
607 // XXX: fd is often -1 here
608 debugs(17, 2, "FD " << fd
<< " " << entry
->url() << " after " <<
609 (fd
>= 0 ? fd_table
[fd
].pconn
.uses
: -1) << " requests");
610 if (fd
>= 0 && serverConnection()->fd
== fd
)
611 fwdPconnPool
->noteUses(fd_table
[fd
].pconn
.uses
);
616 FwdState::retryOrBail()
619 debugs(17, 3, HERE
<< "re-forwarding (" << n_tries
<< " tries, " << (squid_curtime
- start_t
) << " secs)");
620 // we should retry the same destination if it failed due to pconn race
621 if (pconnRace
== raceHappened
)
622 debugs(17, 4, HERE
<< "retrying the same destination");
624 serverDestinations
.erase(serverDestinations
.begin()); // last one failed. try another.
625 startConnectionOrFail();
629 // TODO: should we call completed() here and move doneWithRetries there?
632 request
->hier
.stopPeerClock(false);
634 if (self
!= NULL
&& !err
&& shutting_down
&& entry
->isEmpty()) {
635 ErrorState
*anErr
= new ErrorState(ERR_SHUTTING_DOWN
, Http::scServiceUnavailable
, request
);
636 errorAppendEntry(entry
, anErr
);
639 self
= NULL
; // refcounted
642 // If the Server quits before nibbling at the request body, the body sender
643 // will not know (so that we can retry). Call this if we will not retry. We
644 // will notify the sender so that it does not get stuck waiting for space.
646 FwdState::doneWithRetries()
648 if (request
&& request
->body_pipe
!= NULL
)
649 request
->body_pipe
->expectNoConsumption();
652 // called by the server that failed after calling unregister()
654 FwdState::handleUnregisteredServerEnd()
656 debugs(17, 2, HERE
<< "self=" << self
<< " err=" << err
<< ' ' << entry
->url());
657 assert(!Comm::IsConnOpen(serverConn
));
662 FwdState::connectDone(const Comm::ConnectionPointer
&conn
, Comm::Flag status
, int xerrno
)
664 if (status
!= Comm::OK
) {
665 ErrorState
*const anErr
= makeConnectingError(ERR_CONNECT_FAIL
);
666 anErr
->xerrno
= xerrno
;
669 /* it might have been a timeout with a partially open link */
672 peerConnectFailed(conn
->getPeer());
681 debugs(17, 3, HERE
<< serverConnection() << ": '" << entry
->url() << "'" );
683 closeHandler
= comm_add_close_handler(serverConnection()->fd
, fwdServerClosedWrapper
, this);
685 if (!request
->flags
.pinned
) {
686 const CachePeer
*p
= serverConnection()->getPeer();
687 const bool peerWantsTls
= p
&& p
->secure
.encryptTransport
;
688 // userWillTlsToPeerForUs assumes CONNECT == HTTPS
689 const bool userWillTlsToPeerForUs
= p
&& p
->options
.originserver
&&
690 request
->method
== Http::METHOD_CONNECT
;
691 const bool needTlsToPeer
= peerWantsTls
&& !userWillTlsToPeerForUs
;
692 const bool needTlsToOrigin
= !p
&& request
->url
.getScheme() == AnyP::PROTO_HTTPS
;
693 if (needTlsToPeer
|| needTlsToOrigin
|| request
->flags
.sslPeek
) {
694 HttpRequest::Pointer requestPointer
= request
;
695 AsyncCall::Pointer callback
= asyncCall(17,4,
696 "FwdState::ConnectedToPeer",
697 FwdStatePeerAnswerDialer(&FwdState::connectedToPeer
, this));
698 // Use positive timeout when less than one second is left.
699 const time_t sslNegotiationTimeout
= max(static_cast<time_t>(1), timeLeft());
700 Security::PeerConnector
*connector
= nullptr;
702 if (request
->flags
.sslPeek
)
703 connector
= new Ssl::PeekingPeerConnector(requestPointer
, serverConnection(), clientConn
, callback
, al
, sslNegotiationTimeout
);
706 connector
= new Security::BlindPeerConnector(requestPointer
, serverConnection(), callback
, al
, sslNegotiationTimeout
);
707 AsyncJob::Start(connector
); // will call our callback
712 // if not encrypting just run the post-connect actions
713 Security::EncryptorAnswer nil
;
714 connectedToPeer(nil
);
718 FwdState::connectedToPeer(Security::EncryptorAnswer
&answer
)
720 if (ErrorState
*error
= answer
.error
.get()) {
722 answer
.error
.clear(); // preserve error for errorSendComplete()
723 if (CachePeer
*p
= serverConnection()->getPeer())
724 peerConnectFailed(p
);
725 serverConnection()->close();
729 if (answer
.tunneled
) {
730 // TODO: When ConnStateData establishes tunnels, its state changes
731 // [in ways that may affect logging?]. Consider informing
732 // ConnStateData about our tunnel or otherwise unifying tunnel
733 // establishment [side effects].
734 unregister(serverConn
); // async call owns it now
735 complete(); // destroys us
739 // should reach ConnStateData before the dispatched Client job starts
740 CallJobHere1(17, 4, request
->clientConnectionManager
, ConnStateData
,
741 ConnStateData::notePeerConnection
, serverConnection());
743 if (serverConnection()->getPeer())
744 peerConnectSucceded(serverConnection()->getPeer());
746 flags
.connected_okay
= true;
751 FwdState::connectTimeout(int fd
)
753 debugs(17, 2, "fwdConnectTimeout: FD " << fd
<< ": '" << entry
->url() << "'" );
754 assert(serverDestinations
[0] != NULL
);
755 assert(fd
== serverDestinations
[0]->fd
);
757 if (entry
->isEmpty()) {
758 ErrorState
*anErr
= new ErrorState(ERR_CONNECT_FAIL
, Http::scGatewayTimeout
, request
);
759 anErr
->xerrno
= ETIMEDOUT
;
762 /* This marks the peer DOWN ... */
763 if (serverDestinations
[0]->getPeer())
764 peerConnectFailed(serverDestinations
[0]->getPeer());
767 if (Comm::IsConnOpen(serverDestinations
[0])) {
768 serverDestinations
[0]->close();
773 FwdState::timeLeft() const
775 /* connection timeout */
777 if (serverDestinations
[0]->getPeer()) {
778 ctimeout
= serverDestinations
[0]->getPeer()->connect_timeout
> 0 ?
779 serverDestinations
[0]->getPeer()->connect_timeout
: Config
.Timeout
.peer_connect
;
781 ctimeout
= Config
.Timeout
.connect
;
784 /* calculate total forwarding timeout ??? */
785 int ftimeout
= Config
.Timeout
.forward
- (squid_curtime
- start_t
);
789 if (ftimeout
< ctimeout
)
790 return (time_t)ftimeout
;
792 return (time_t)ctimeout
;
795 /// called when serverConn is set to an _open_ to-peer connection
797 FwdState::syncWithServerConn(const char *host
)
799 if (Ip::Qos::TheConfig
.isAclTosActive())
800 Ip::Qos::setSockTos(serverConn
, GetTosToServer(request
));
803 if (Ip::Qos::TheConfig
.isAclNfmarkActive())
804 Ip::Qos::setSockNfmark(serverConn
, GetNfmarkToServer(request
));
807 syncHierNote(serverConn
, host
);
811 FwdState::syncHierNote(const Comm::ConnectionPointer
&server
, const char *host
)
814 request
->hier
.note(server
, host
);
816 al
->hier
.note(server
, host
);
820 * Called after forwarding path selection (via peer select) has taken place
821 * and whenever forwarding needs to attempt a new connection (routing failover).
822 * We have a vector of possible localIP->remoteIP paths now ready to start being connected.
825 FwdState::connectStart()
827 assert(serverDestinations
.size() > 0);
829 debugs(17, 3, "fwdConnectStart: " << entry
->url());
831 request
->hier
.startPeerClock();
833 // Do not fowrward bumped connections to parent proxy unless it is an
835 if (serverDestinations
[0]->getPeer() && !serverDestinations
[0]->getPeer()->options
.originserver
&& request
->flags
.sslBumped
) {
836 debugs(50, 4, "fwdConnectStart: Ssl bumped connections through parent proxy are not allowed");
837 ErrorState
*anErr
= new ErrorState(ERR_CANNOT_FORWARD
, Http::scServiceUnavailable
, request
);
839 self
= NULL
; // refcounted
843 request
->flags
.pinned
= false; // XXX: what if the ConnStateData set this to flag existing credentials?
844 // XXX: answer: the peer selection *should* catch it and give us only the pinned peer. so we reverse the =0 step below.
845 // XXX: also, logs will now lie if pinning is broken and leads to an error message.
846 if (serverDestinations
[0]->peerType
== PINNED
) {
847 ConnStateData
*pinned_connection
= request
->pinnedConnection();
848 debugs(17,7, "pinned peer connection: " << pinned_connection
);
849 // pinned_connection may become nil after a pconn race
850 serverConn
= pinned_connection
? pinned_connection
->borrowPinnedConnection(request
, serverDestinations
[0]->getPeer()) : nullptr;
851 if (Comm::IsConnOpen(serverConn
)) {
852 flags
.connected_okay
= true;
854 request
->flags
.pinned
= true;
856 if (pinned_connection
->pinnedAuth())
857 request
->flags
.auth
= true;
859 closeHandler
= comm_add_close_handler(serverConn
->fd
, fwdServerClosedWrapper
, this);
861 syncWithServerConn(pinned_connection
->pinning
.host
);
863 // the server may close the pinned connection before this request
864 pconnRace
= racePossible
;
869 // Pinned connection failure.
870 debugs(17,2,HERE
<< "Pinned connection failed: " << pinned_connection
);
871 ErrorState
*anErr
= new ErrorState(ERR_ZERO_SIZE_OBJECT
, Http::scServiceUnavailable
, request
);
873 self
= NULL
; // refcounted
877 // Use pconn to avoid opening a new connection.
878 const char *host
= NULL
;
879 if (!serverDestinations
[0]->getPeer())
880 host
= request
->url
.host();
882 Comm::ConnectionPointer temp
;
883 // Avoid pconns after races so that the same client does not suffer twice.
884 // This does not increase the total number of connections because we just
885 // closed the connection that failed the race. And re-pinning assumes this.
886 if (pconnRace
!= raceHappened
)
887 temp
= pconnPop(serverDestinations
[0], host
);
889 const bool openedPconn
= Comm::IsConnOpen(temp
);
890 pconnRace
= openedPconn
? racePossible
: raceImpossible
;
892 // if we found an open persistent connection to use. use it.
895 flags
.connected_okay
= true;
896 debugs(17, 3, HERE
<< "reusing pconn " << serverConnection());
899 closeHandler
= comm_add_close_handler(serverConnection()->fd
, fwdServerClosedWrapper
, this);
901 syncWithServerConn(request
->url
.host());
907 // We will try to open a new connection, possibly to the same destination.
908 // We reset serverDestinations[0] in case we are using it again because
909 // ConnOpener modifies its destination argument.
910 serverDestinations
[0]->local
.port(0);
913 #if URL_CHECKSUM_DEBUG
914 entry
->mem_obj
->checkUrlChecksum();
917 GetMarkingsToServer(request
, *serverDestinations
[0]);
919 calls
.connector
= commCbCall(17,3, "fwdConnectDoneWrapper", CommConnectCbPtrFun(fwdConnectDoneWrapper
, this));
920 Comm::ConnOpener
*cs
= new Comm::ConnOpener(serverDestinations
[0], calls
.connector
, timeLeft());
929 debugs(17, 3, clientConn
<< ": Fetching " << request
->method
<< ' ' << entry
->url());
931 * Assert that server_fd is set. This is to guarantee that fwdState
932 * is attached to something and will be deallocated when server_fd
935 assert(Comm::IsConnOpen(serverConn
));
937 fd_note(serverConnection()->fd
, entry
->url());
939 fd_table
[serverConnection()->fd
].noteUse();
941 /*assert(!EBIT_TEST(entry->flags, ENTRY_DISPATCHED)); */
942 assert(entry
->ping_status
!= PING_WAITING
);
944 assert(entry
->locked());
946 EBIT_SET(entry
->flags
, ENTRY_DISPATCHED
);
948 netdbPingSite(request
->url
.host());
950 /* Retrieves remote server TOS or MARK value, and stores it as part of the
951 * original client request FD object. It is later used to forward
952 * remote server's TOS/MARK in the response to the client in case of a MISS.
954 if (Ip::Qos::TheConfig
.isHitNfmarkActive()) {
955 if (Comm::IsConnOpen(clientConn
) && Comm::IsConnOpen(serverConnection())) {
956 fde
* clientFde
= &fd_table
[clientConn
->fd
]; // XXX: move the fd_table access into Ip::Qos
957 /* Get the netfilter mark for the connection */
958 Ip::Qos::getNfmarkFromServer(serverConnection(), clientFde
);
963 /* Bug 2537: The TOS forward part of QOS only applies to patched Linux kernels. */
964 if (Ip::Qos::TheConfig
.isHitTosActive()) {
965 if (Comm::IsConnOpen(clientConn
)) {
966 fde
* clientFde
= &fd_table
[clientConn
->fd
]; // XXX: move the fd_table access into Ip::Qos
967 /* Get the TOS value for the packet */
968 Ip::Qos::getTosFromServer(serverConnection(), clientFde
);
974 if (request
->flags
.sslPeek
) {
975 CallJobHere1(17, 4, request
->clientConnectionManager
, ConnStateData
,
976 ConnStateData::httpsPeeked
, serverConnection());
977 unregister(serverConn
); // async call owns it now
978 complete(); // destroys us
983 if (serverConnection()->getPeer() != NULL
) {
984 ++ serverConnection()->getPeer()->stats
.fetches
;
985 request
->peer_login
= serverConnection()->getPeer()->login
;
986 request
->peer_domain
= serverConnection()->getPeer()->domain
;
987 request
->flags
.auth_no_keytab
= serverConnection()->getPeer()->options
.auth_no_keytab
;
990 assert(!request
->flags
.sslPeek
);
991 request
->peer_login
= NULL
;
992 request
->peer_domain
= NULL
;
993 request
->flags
.auth_no_keytab
= 0;
995 switch (request
->url
.getScheme()) {
997 case AnyP::PROTO_HTTPS
:
1001 case AnyP::PROTO_HTTP
:
1005 case AnyP::PROTO_GOPHER
:
1009 case AnyP::PROTO_FTP
:
1010 if (request
->flags
.ftpNative
)
1011 Ftp::StartRelay(this);
1013 Ftp::StartGateway(this);
1016 case AnyP::PROTO_CACHE_OBJECT
:
1018 case AnyP::PROTO_URN
:
1019 fatal_dump("Should never get here");
1022 case AnyP::PROTO_WHOIS
:
1026 case AnyP::PROTO_WAIS
: /* Not implemented */
1029 debugs(17, DBG_IMPORTANT
, "WARNING: Cannot retrieve '" << entry
->url() << "'.");
1030 ErrorState
*anErr
= new ErrorState(ERR_UNSUP_REQ
, Http::scBadRequest
, request
);
1032 // Set the dont_retry flag because this is not a transient (network) error.
1033 flags
.dont_retry
= true;
1034 if (Comm::IsConnOpen(serverConn
)) {
1035 serverConn
->close();
1043 * FwdState::reforward
1045 * returns TRUE if the transaction SHOULD be re-forwarded to the
1046 * next choice in the serverDestinations list. This method is called when
1047 * peer communication completes normally, or experiences
1048 * some error after receiving the end of HTTP headers.
1051 FwdState::reforward()
1053 StoreEntry
*e
= entry
;
1055 if (EBIT_TEST(e
->flags
, ENTRY_ABORTED
)) {
1056 debugs(17, 3, HERE
<< "entry aborted");
1060 assert(e
->store_status
== STORE_PENDING
);
1062 #if URL_CHECKSUM_DEBUG
1064 e
->mem_obj
->checkUrlChecksum();
1067 debugs(17, 3, HERE
<< e
->url() << "?" );
1069 if (!EBIT_TEST(e
->flags
, ENTRY_FWD_HDR_WAIT
)) {
1070 debugs(17, 3, HERE
<< "No, ENTRY_FWD_HDR_WAIT isn't set");
1074 if (n_tries
> Config
.forward_max_tries
)
1077 if (request
->bodyNibbled())
1080 if (serverDestinations
.size() <= 1) {
1081 // NP: <= 1 since total count includes the recently failed one.
1082 debugs(17, 3, HERE
<< "No alternative forwarding paths left");
1086 const Http::StatusCode s
= e
->getReply()->sline
.status();
1087 debugs(17, 3, HERE
<< "status " << s
);
1088 return reforwardableStatus(s
);
1092 * Create "503 Service Unavailable" or "504 Gateway Timeout" error depending
1093 * on whether this is a validation request. RFC 2616 says that we MUST reply
1094 * with "504 Gateway Timeout" if validation fails and cached reply has
1095 * proxy-revalidate, must-revalidate or s-maxage Cache-Control directive.
1098 FwdState::makeConnectingError(const err_type type
) const
1100 return new ErrorState(type
, request
->flags
.needValidation
?
1101 Http::scGatewayTimeout
: Http::scServiceUnavailable
, request
);
1105 fwdStats(StoreEntry
* s
)
1109 storeAppendPrintf(s
, "Status");
1111 for (j
= 1; j
< MAX_FWD_STATS_IDX
; ++j
) {
1112 storeAppendPrintf(s
, "\ttry#%d", j
);
1115 storeAppendPrintf(s
, "\n");
1117 for (i
= 0; i
<= (int) Http::scInvalidHeader
; ++i
) {
1118 if (FwdReplyCodes
[0][i
] == 0)
1121 storeAppendPrintf(s
, "%3d", i
);
1123 for (j
= 0; j
<= MAX_FWD_STATS_IDX
; ++j
) {
1124 storeAppendPrintf(s
, "\t%d", FwdReplyCodes
[j
][i
]);
1127 storeAppendPrintf(s
, "\n");
1131 /**** STATIC MEMBER FUNCTIONS *************************************************/
1134 FwdState::reforwardableStatus(const Http::StatusCode s
) const
1138 case Http::scBadGateway
:
1140 case Http::scGatewayTimeout
:
1143 case Http::scForbidden
:
1145 case Http::scInternalServerError
:
1147 case Http::scNotImplemented
:
1149 case Http::scServiceUnavailable
:
1150 return Config
.retry
.onerror
;
1160 * Decide where details need to be gathered to correctly describe a persistent connection.
1162 * - the address/port details about this link
1163 * - domain name of server at other end of this link (either peer or requested host)
1166 FwdState::pconnPush(Comm::ConnectionPointer
&conn
, const char *domain
)
1168 if (conn
->getPeer()) {
1169 fwdPconnPool
->push(conn
, NULL
);
1171 fwdPconnPool
->push(conn
, domain
);
1175 Comm::ConnectionPointer
1176 FwdState::pconnPop(const Comm::ConnectionPointer
&dest
, const char *domain
)
1178 bool retriable
= checkRetriable();
1179 if (!retriable
&& Config
.accessList
.serverPconnForNonretriable
) {
1180 ACLFilledChecklist
ch(Config
.accessList
.serverPconnForNonretriable
, request
, NULL
);
1181 retriable
= (ch
.fastCheck() == ACCESS_ALLOWED
);
1183 // always call shared pool first because we need to close an idle
1184 // connection there if we have to use a standby connection.
1185 Comm::ConnectionPointer conn
= fwdPconnPool
->pop(dest
, domain
, retriable
);
1186 if (!Comm::IsConnOpen(conn
)) {
1187 // either there was no pconn to pop or this is not a retriable xaction
1188 if (CachePeer
*peer
= dest
->getPeer()) {
1189 if (peer
->standby
.pool
)
1190 conn
= peer
->standby
.pool
->pop(dest
, domain
, true);
1193 return conn
; // open, closed, or nil
1197 FwdState::initModule()
1199 RegisterWithCacheManager();
1203 FwdState::RegisterWithCacheManager(void)
1205 Mgr::RegisterAction("forward", "Request Forwarding Statistics", fwdStats
, 0, 1);
1209 FwdState::logReplyStatus(int tries
, const Http::StatusCode status
)
1211 if (status
> Http::scInvalidHeader
)
1216 if (tries
> MAX_FWD_STATS_IDX
)
1217 tries
= MAX_FWD_STATS_IDX
;
1219 ++ FwdReplyCodes
[tries
][status
];
1222 /**** PRIVATE NON-MEMBER FUNCTIONS ********************************************/
1226 * Formerly static, but now used by client_side_request.cc
1228 /// Checks for a TOS value to apply depending on the ACL
1230 aclMapTOS(acl_tos
* head
, ACLChecklist
* ch
)
1232 for (acl_tos
*l
= head
; l
; l
= l
->next
) {
1233 if (!l
->aclList
|| ch
->fastCheck(l
->aclList
) == ACCESS_ALLOWED
)
1240 /// Checks for a netfilter mark value to apply depending on the ACL
1242 aclMapNfmark(acl_nfmark
* head
, ACLChecklist
* ch
)
1244 for (acl_nfmark
*l
= head
; l
; l
= l
->next
) {
1245 if (!l
->aclList
|| ch
->fastCheck(l
->aclList
) == ACCESS_ALLOWED
)
1253 getOutgoingAddress(HttpRequest
* request
, Comm::ConnectionPointer conn
)
1255 // skip if an outgoing address is already set.
1256 if (!conn
->local
.isAnyAddr()) return;
1258 // ensure that at minimum the wildcard local matches remote protocol
1259 if (conn
->remote
.isIPv4())
1260 conn
->local
.setIPv4();
1262 // maybe use TPROXY client address
1263 if (request
&& request
->flags
.spoofClientIp
) {
1264 if (!conn
->getPeer() || !conn
->getPeer()->options
.no_tproxy
) {
1265 #if FOLLOW_X_FORWARDED_FOR && LINUX_NETFILTER
1266 if (Config
.onoff
.tproxy_uses_indirect_client
)
1267 conn
->local
= request
->indirect_client_addr
;
1270 conn
->local
= request
->client_addr
;
1271 // some flags need setting on the socket to use this address
1272 conn
->flags
|= COMM_DOBIND
;
1273 conn
->flags
|= COMM_TRANSPARENT
;
1276 // else no tproxy today ...
1279 if (!Config
.accessList
.outgoing_address
) {
1280 return; // anything will do.
1283 ACLFilledChecklist
ch(NULL
, request
, NULL
);
1284 ch
.dst_peer_name
= conn
->getPeer() ? conn
->getPeer()->name
: NULL
;
1285 ch
.dst_addr
= conn
->remote
;
1287 // TODO use the connection details in ACL.
1288 // needs a bit of rework in ACLFilledChecklist to use Comm::Connection instead of ConnStateData
1290 for (Acl::Address
*l
= Config
.accessList
.outgoing_address
; l
; l
= l
->next
) {
1292 /* check if the outgoing address is usable to the destination */
1293 if (conn
->remote
.isIPv4() != l
->addr
.isIPv4()) continue;
1295 /* check ACLs for this outgoing address */
1296 if (!l
->aclList
|| ch
.fastCheck(l
->aclList
) == ACCESS_ALLOWED
) {
1297 conn
->local
= l
->addr
;
1304 GetTosToServer(HttpRequest
* request
)
1306 ACLFilledChecklist
ch(NULL
, request
, NULL
);
1307 return aclMapTOS(Ip::Qos::TheConfig
.tosToServer
, &ch
);
1311 GetNfmarkToServer(HttpRequest
* request
)
1313 ACLFilledChecklist
ch(NULL
, request
, NULL
);
1314 return aclMapNfmark(Ip::Qos::TheConfig
.nfmarkToServer
, &ch
);
1318 GetMarkingsToServer(HttpRequest
* request
, Comm::Connection
&conn
)
1320 // Get the server side TOS and Netfilter mark to be set on the connection.
1321 if (Ip::Qos::TheConfig
.isAclTosActive()) {
1322 conn
.tos
= GetTosToServer(request
);
1323 debugs(17, 3, "from " << conn
.local
<< " tos " << int(conn
.tos
));
1326 #if SO_MARK && USE_LIBCAP
1327 conn
.nfmark
= GetNfmarkToServer(request
);
1328 debugs(17, 3, "from " << conn
.local
<< " netfilter mark " << conn
.nfmark
);