2 * Copyright (C) 1996-2015 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 26 Secure Sockets Layer Proxy */
12 #include "acl/FilledChecklist.h"
13 #include "base/CbcPointer.h"
14 #include "CachePeer.h"
16 #include "client_side.h"
17 #include "client_side_request.h"
19 #include "comm/Connection.h"
20 #include "comm/ConnOpener.h"
21 #include "comm/Read.h"
22 #include "comm/Write.h"
23 #include "errorpage.h"
28 #include "HttpRequest.h"
29 #include "HttpStateFlags.h"
30 #include "ip/QosConfig.h"
33 #include "PeerSelectState.h"
35 #include "SquidConfig.h"
36 #include "SquidTime.h"
37 #include "StatCounters.h"
40 #include "ssl/PeerConnector.h"
41 #include "ssl/ServerBump.h"
43 #include "security/EncryptorAnswer.h"
54 * TunnelStateData is the state engine performing the tasks for
55 * setup of a TCP tunnel from an existing open client FD to a server
56 * then shuffling binary data between the resulting FD pair.
59 * TODO 1: implement a read/write API on ConnStateData to send/receive blocks
60 * of pre-formatted data. Then we can use that as the client side of the tunnel
61 * instead of re-implementing it here and occasionally getting the ConnStateData
62 * read/write state wrong.
64 * TODO 2: then convert this into a AsyncJob, possibly a child of 'Server'
68 CBDATA_CLASS(TunnelStateData
);
73 TunnelStateData(const TunnelStateData
&); // do not implement
74 TunnelStateData
&operator =(const TunnelStateData
&); // do not implement
77 static void ReadClient(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
);
78 static void ReadServer(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
);
79 static void WriteClientDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag flag
, int xerrno
, void *data
);
80 static void WriteServerDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag flag
, int xerrno
, void *data
);
82 /// Starts reading peer response to our CONNECT request.
83 void readConnectResponse();
85 /// Called when we may be done handling a CONNECT exchange with the peer.
86 void connectExchangeCheckpoint();
88 bool noConnections() const;
90 CbcPointer
<ClientHttpRequest
> http
;
91 HttpRequest::Pointer request
;
92 AccessLogEntryPointer al
;
93 Comm::ConnectionList serverDestinations
;
95 const char * getHost() const {
96 return (server
.conn
!= NULL
&& server
.conn
->getPeer() ? server
.conn
->getPeer()->host
: request
->url
.host());
99 /// Whether we are writing a CONNECT request to a peer.
100 bool waitingForConnectRequest() const { return connectReqWriting
; }
101 /// Whether we are reading a CONNECT response from a peer.
102 bool waitingForConnectResponse() const { return connectRespBuf
; }
103 /// Whether we are waiting for the CONNECT request/response exchange with the peer.
104 bool waitingForConnectExchange() const { return waitingForConnectRequest() || waitingForConnectResponse(); }
106 /// Whether the client sent a CONNECT request to us.
107 bool clientExpectsConnectResponse() const {
109 // We are bumping and we had already send "OK CONNECTED"
110 if (http
.valid() && http
->getConn() && http
->getConn()->serverBump() && http
->getConn()->serverBump()->step
> Ssl::bumpStep1
)
113 return !(request
!= NULL
&&
114 (request
->flags
.interceptTproxy
|| request
->flags
.intercepted
));
117 /// Sends "502 Bad Gateway" error response to the client,
118 /// if it is waiting for Squid CONNECT response, closing connections.
119 void informUserOfPeerError(const char *errMsg
, size_t);
125 Connection() : len (0), buf ((char *)xmalloc(SQUID_TCP_SO_RCVBUF
)), size_ptr(NULL
), delayedLoops(0),
126 readPending(NULL
), readPendingFunc(NULL
) {}
130 int bytesWanted(int lower
=0, int upper
= INT_MAX
) const;
131 void bytesIn(int const &);
134 void setDelayId(DelayId
const &);
137 void error(int const xerrno
);
138 int debugLevelForError(int const xerrno
) const;
140 void dataSent (size_t amount
);
141 /// writes 'b' buffer, setting the 'writer' member to 'callback'.
142 void write(const char *b
, int size
, AsyncCall::Pointer
&callback
, FREE
* free_func
);
145 AsyncCall::Pointer writer
; ///< pending Comm::Write callback
146 uint64_t *size_ptr
; /* pointer to size in an ConnStateData for logging */
148 Comm::ConnectionPointer conn
; ///< The currently connected connection.
149 uint8_t delayedLoops
; ///< how many times a read on this connection has been postponed.
151 // XXX: make these an AsyncCall when event API can handle them
152 TunnelStateData
*readPending
;
153 EVH
*readPendingFunc
;
162 Connection client
, server
;
163 int *status_ptr
; ///< pointer for logging HTTP status
164 LogTags
*logTag_ptr
; ///< pointer for logging Squid processing code
165 MemBuf
*connectRespBuf
; ///< accumulates peer CONNECT response when we need it
166 bool connectReqWriting
; ///< whether we are writing a CONNECT request to a peer
167 SBuf preReadClientData
;
168 time_t started
; ///< when this tunnel was initiated.
170 void copyRead(Connection
&from
, IOCB
*completion
);
172 /// continue to set up connection to a peer, going async for SSL peers
173 void connectToPeer();
177 /// Gives PeerConnector access to Answer in the TunnelStateData callback dialer.
178 class MyAnswerDialer
: public CallDialer
, public Ssl::PeerConnector::CbDialer
181 typedef void (TunnelStateData::*Method
)(Security::EncryptorAnswer
&);
183 MyAnswerDialer(Method method
, TunnelStateData
*tunnel
):
184 method_(method
), tunnel_(tunnel
), answer_() {}
187 virtual bool canDial(AsyncCall
&call
) { return tunnel_
.valid(); }
188 void dial(AsyncCall
&call
) { ((&(*tunnel_
))->*method_
)(answer_
); }
189 virtual void print(std::ostream
&os
) const {
190 os
<< '(' << tunnel_
.get() << ", " << answer_
<< ')';
193 /* Ssl::PeerConnector::CbDialer API */
194 virtual Security::EncryptorAnswer
&answer() { return answer_
; }
198 CbcPointer
<TunnelStateData
> tunnel_
;
199 Security::EncryptorAnswer answer_
;
203 /// callback handler after connection setup (including any encryption)
204 void connectedToPeer(Security::EncryptorAnswer
&answer
);
207 bool keepGoingAfterRead(size_t len
, Comm::Flag errcode
, int xerrno
, Connection
&from
, Connection
&to
);
208 void copy(size_t len
, Connection
&from
, Connection
&to
, IOCB
*);
209 void handleConnectResponse(const size_t chunkSize
);
210 void readServer(char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
);
211 void readClient(char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
);
212 void writeClientDone(char *buf
, size_t len
, Comm::Flag flag
, int xerrno
);
213 void writeServerDone(char *buf
, size_t len
, Comm::Flag flag
, int xerrno
);
215 static void ReadConnectResponseDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
);
216 void readConnectResponseDone(char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
);
217 void copyClientBytes();
220 static const char *const conn_established
= "HTTP/1.1 200 Connection established\r\n\r\n";
222 static CNCB tunnelConnectDone
;
223 static ERCB tunnelErrorComplete
;
224 static CLCB tunnelServerClosed
;
225 static CLCB tunnelClientClosed
;
226 static CTCB tunnelTimeout
;
227 static PSC tunnelPeerSelectComplete
;
228 static EVH tunnelDelayedClientRead
;
229 static EVH tunnelDelayedServerRead
;
230 static void tunnelConnected(const Comm::ConnectionPointer
&server
, void *);
231 static void tunnelRelayConnectRequest(const Comm::ConnectionPointer
&server
, void *);
234 tunnelServerClosed(const CommCloseCbParams
¶ms
)
236 TunnelStateData
*tunnelState
= (TunnelStateData
*)params
.data
;
237 debugs(26, 3, HERE
<< tunnelState
->server
.conn
);
238 tunnelState
->server
.conn
= NULL
;
239 tunnelState
->server
.writer
= NULL
;
241 if (tunnelState
->request
!= NULL
)
242 tunnelState
->request
->hier
.stopPeerClock(false);
244 if (tunnelState
->noConnections()) {
249 if (!tunnelState
->client
.writer
) {
250 tunnelState
->client
.conn
->close();
256 tunnelClientClosed(const CommCloseCbParams
¶ms
)
258 TunnelStateData
*tunnelState
= (TunnelStateData
*)params
.data
;
259 debugs(26, 3, HERE
<< tunnelState
->client
.conn
);
260 tunnelState
->client
.conn
= NULL
;
261 tunnelState
->client
.writer
= NULL
;
263 if (tunnelState
->noConnections()) {
268 if (!tunnelState
->server
.writer
) {
269 tunnelState
->server
.conn
->close();
274 TunnelStateData::TunnelStateData() :
280 connectRespBuf(NULL
),
281 connectReqWriting(false),
282 started(squid_curtime
)
284 debugs(26, 3, "TunnelStateData constructed this=" << this);
285 client
.readPendingFunc
= &tunnelDelayedClientRead
;
286 server
.readPendingFunc
= &tunnelDelayedServerRead
;
289 TunnelStateData::~TunnelStateData()
291 debugs(26, 3, "TunnelStateData destructed this=" << this);
292 assert(noConnections());
294 serverDestinations
.clear();
295 delete connectRespBuf
;
298 TunnelStateData::Connection::~Connection()
301 eventDelete(readPendingFunc
, readPending
);
307 TunnelStateData::Connection::bytesWanted(int lowerbound
, int upperbound
) const
310 return delayId
.bytesWanted(lowerbound
, upperbound
);
318 TunnelStateData::Connection::bytesIn(int const &count
)
320 debugs(26, 3, HERE
<< "len=" << len
<< " + count=" << count
);
322 delayId
.bytesIn(count
);
329 TunnelStateData::Connection::debugLevelForError(int const xerrno
) const
333 if (xerrno
== ECONNRESET
)
338 if (ignoreErrno(xerrno
))
344 /* Read from server side and queue it for writing to the client */
346 TunnelStateData::ReadServer(const Comm::ConnectionPointer
&c
, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
)
348 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
349 assert(cbdataReferenceValid(tunnelState
));
350 debugs(26, 3, HERE
<< c
);
352 tunnelState
->readServer(buf
, len
, errcode
, xerrno
);
356 TunnelStateData::readServer(char *, size_t len
, Comm::Flag errcode
, int xerrno
)
358 debugs(26, 3, HERE
<< server
.conn
<< ", read " << len
<< " bytes, err=" << errcode
);
359 server
.delayedLoops
=0;
362 * Bail out early on Comm::ERR_CLOSING
363 * - close handlers will tidy up for us
366 if (errcode
== Comm::ERR_CLOSING
)
371 statCounter
.server
.all
.kbytes_in
+= len
;
372 statCounter
.server
.other
.kbytes_in
+= len
;
375 if (keepGoingAfterRead(len
, errcode
, xerrno
, server
, client
))
376 copy(len
, server
, client
, WriteClientDone
);
379 /// Called when we read [a part of] CONNECT response from the peer
381 TunnelStateData::readConnectResponseDone(char *, size_t len
, Comm::Flag errcode
, int xerrno
)
383 debugs(26, 3, server
.conn
<< ", read " << len
<< " bytes, err=" << errcode
);
384 assert(waitingForConnectResponse());
386 if (errcode
== Comm::ERR_CLOSING
)
390 connectRespBuf
->appended(len
);
392 statCounter
.server
.all
.kbytes_in
+= len
;
393 statCounter
.server
.other
.kbytes_in
+= len
;
396 if (keepGoingAfterRead(len
, errcode
, xerrno
, server
, client
))
397 handleConnectResponse(len
);
401 TunnelStateData::informUserOfPeerError(const char *errMsg
, const size_t sz
)
406 *logTag_ptr
= LOG_TCP_TUNNEL
;
408 if (!clientExpectsConnectResponse()) {
409 // closing the connection is the best we can do here
410 debugs(50, 3, server
.conn
<< " closing on error: " << errMsg
);
411 server
.conn
->close();
415 // if we have no reply suitable to relay, use 502 Bad Gateway
416 if (!sz
|| sz
> static_cast<size_t>(connectRespBuf
->contentSize())) {
417 ErrorState
*err
= new ErrorState(ERR_CONNECT_FAIL
, Http::scBadGateway
, request
.getRaw());
418 *status_ptr
= Http::scBadGateway
;
419 err
->callback
= tunnelErrorComplete
;
420 err
->callback_data
= this;
421 errorSend(http
->getConn()->clientConnection
, err
);
425 // if we need to send back the server response. write its headers to the client
427 memcpy(server
.buf
, connectRespBuf
->content(), server
.len
);
428 copy(server
.len
, server
, client
, TunnelStateData::WriteClientDone
);
429 // then close the server FD to prevent any relayed keep-alive causing CVE-2015-5400
430 server
.closeIfOpen();
433 /* Read from client side and queue it for writing to the server */
435 TunnelStateData::ReadConnectResponseDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
)
437 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
438 assert (cbdataReferenceValid (tunnelState
));
440 tunnelState
->readConnectResponseDone(buf
, len
, errcode
, xerrno
);
443 /// Parses [possibly incomplete] CONNECT response and reacts to it.
444 /// If the tunnel is being closed or more response data is needed, returns false.
445 /// Otherwise, the caller should handle the remaining read data, if any.
447 TunnelStateData::handleConnectResponse(const size_t chunkSize
)
449 assert(waitingForConnectResponse());
451 // Ideally, client and server should use MemBuf or better, but current code
452 // never accumulates more than one read when shoveling data (XXX) so it does
453 // not need to deal with MemBuf complexity. To keep it simple, we use a
454 // dedicated MemBuf for accumulating CONNECT responses. TODO: When shoveling
455 // is optimized, reuse server.buf for CONNEC response accumulation instead.
457 /* mimic the basic parts of HttpStateData::processReplyHeader() */
459 Http::StatusCode parseErr
= Http::scNone
;
460 const bool eof
= !chunkSize
;
461 connectRespBuf
->terminate(); // HttpMsg::parse requires terminated string
462 const bool parsed
= rep
.parse(connectRespBuf
->content(), connectRespBuf
->contentSize(), eof
, &parseErr
);
464 if (parseErr
> 0) { // unrecoverable parsing error
465 informUserOfPeerError("malformed CONNECT response from peer", 0);
473 if (!connectRespBuf
->hasSpace()) {
474 informUserOfPeerError("huge CONNECT response from peer", 0);
479 readConnectResponse();
483 // CONNECT response was successfully parsed
484 *status_ptr
= rep
.sline
.status();
486 // we need to relay the 401/407 responses when login=PASS(THRU)
487 const char *pwd
= server
.conn
->getPeer()->login
;
488 const bool relay
= pwd
&& (strcmp(pwd
, "PASS") != 0 || strcmp(pwd
, "PASSTHRU") != 0) &&
489 (*status_ptr
== Http::scProxyAuthenticationRequired
||
490 *status_ptr
== Http::scUnauthorized
);
492 // bail if we did not get an HTTP 200 (Connection Established) response
493 if (rep
.sline
.status() != Http::scOkay
) {
494 // if we ever decide to reuse the peer connection, we must extract the error response first
495 informUserOfPeerError("unsupported CONNECT response status code", (relay
? rep
.hdr_sz
: 0));
499 if (rep
.hdr_sz
< connectRespBuf
->contentSize()) {
500 // preserve bytes that the server already sent after the CONNECT response
501 server
.len
= connectRespBuf
->contentSize() - rep
.hdr_sz
;
502 memcpy(server
.buf
, connectRespBuf
->content()+rep
.hdr_sz
, server
.len
);
504 // reset; delay pools were using this field to throttle CONNECT response
508 delete connectRespBuf
;
509 connectRespBuf
= NULL
;
510 connectExchangeCheckpoint();
514 TunnelStateData::Connection::error(int const xerrno
)
516 /* XXX fixme xstrerror and xerrno... */
519 debugs(50, debugLevelForError(xerrno
), HERE
<< conn
<< ": read/write failure: " << xstrerror());
521 if (!ignoreErrno(xerrno
))
525 /* Read from client side and queue it for writing to the server */
527 TunnelStateData::ReadClient(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
)
529 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
530 assert (cbdataReferenceValid (tunnelState
));
532 tunnelState
->readClient(buf
, len
, errcode
, xerrno
);
536 TunnelStateData::readClient(char *, size_t len
, Comm::Flag errcode
, int xerrno
)
538 debugs(26, 3, HERE
<< client
.conn
<< ", read " << len
<< " bytes, err=" << errcode
);
539 client
.delayedLoops
=0;
542 * Bail out early on Comm::ERR_CLOSING
543 * - close handlers will tidy up for us
546 if (errcode
== Comm::ERR_CLOSING
)
551 statCounter
.client_http
.kbytes_in
+= len
;
554 if (keepGoingAfterRead(len
, errcode
, xerrno
, client
, server
))
555 copy(len
, client
, server
, WriteServerDone
);
558 /// Updates state after reading from client or server.
559 /// Returns whether the caller should use the data just read.
561 TunnelStateData::keepGoingAfterRead(size_t len
, Comm::Flag errcode
, int xerrno
, Connection
&from
, Connection
&to
)
563 debugs(26, 3, HERE
<< "from={" << from
.conn
<< "}, to={" << to
.conn
<< "}");
565 /* I think this is to prevent free-while-in-a-callback behaviour
567 * from.conn->close() / to.conn->close() done here trigger close callbacks which may free TunnelStateData
569 const CbcPointer
<TunnelStateData
> safetyLock(this);
571 /* Bump the source connection read timeout on any activity */
572 if (Comm::IsConnOpen(from
.conn
)) {
573 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
574 CommTimeoutCbPtrFun(tunnelTimeout
, this));
575 commSetConnTimeout(from
.conn
, Config
.Timeout
.read
, timeoutCall
);
578 /* Bump the dest connection read timeout on any activity */
579 /* see Bug 3659: tunnels can be weird, with very long one-way transfers */
580 if (Comm::IsConnOpen(to
.conn
)) {
581 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
582 CommTimeoutCbPtrFun(tunnelTimeout
, this));
583 commSetConnTimeout(to
.conn
, Config
.Timeout
.read
, timeoutCall
);
588 else if (len
== 0 || !Comm::IsConnOpen(to
.conn
)) {
589 debugs(26, 3, HERE
<< "Nothing to write or client gone. Terminate the tunnel.");
592 /* Only close the remote end if we've finished queueing data to it */
593 if (from
.len
== 0 && Comm::IsConnOpen(to
.conn
) ) {
596 } else if (cbdataReferenceValid(this)) {
604 TunnelStateData::copy(size_t len
, Connection
&from
, Connection
&to
, IOCB
*completion
)
606 debugs(26, 3, HERE
<< "Schedule Write");
607 AsyncCall::Pointer call
= commCbCall(5,5, "TunnelBlindCopyWriteHandler",
608 CommIoCbPtrFun(completion
, this));
609 to
.write(from
.buf
, len
, call
, NULL
);
612 /* Writes data from the client buffer to the server side */
614 TunnelStateData::WriteServerDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag flag
, int xerrno
, void *data
)
616 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
617 assert (cbdataReferenceValid (tunnelState
));
618 tunnelState
->server
.writer
= NULL
;
620 tunnelState
->writeServerDone(buf
, len
, flag
, xerrno
);
624 TunnelStateData::writeServerDone(char *, size_t len
, Comm::Flag flag
, int xerrno
)
626 debugs(26, 3, HERE
<< server
.conn
<< ", " << len
<< " bytes written, flag=" << flag
);
629 if (flag
!= Comm::OK
) {
630 if (flag
!= Comm::ERR_CLOSING
) {
631 debugs(26, 4, HERE
<< "calling TunnelStateData::server.error(" << xerrno
<<")");
632 server
.error(xerrno
); // may call comm_close
639 debugs(26, 4, HERE
<< "No read input. Closing server connection.");
640 server
.conn
->close();
645 statCounter
.server
.all
.kbytes_out
+= len
;
646 statCounter
.server
.other
.kbytes_out
+= len
;
647 client
.dataSent(len
);
649 /* If the other end has closed, so should we */
650 if (!Comm::IsConnOpen(client
.conn
)) {
651 debugs(26, 4, HERE
<< "Client gone away. Shutting down server connection.");
652 server
.conn
->close();
656 const CbcPointer
<TunnelStateData
> safetyLock(this); /* ??? should be locked by the caller... */
658 if (cbdataReferenceValid(this))
662 /* Writes data from the server buffer to the client side */
664 TunnelStateData::WriteClientDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag flag
, int xerrno
, void *data
)
666 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
667 assert (cbdataReferenceValid (tunnelState
));
668 tunnelState
->client
.writer
= NULL
;
670 tunnelState
->writeClientDone(buf
, len
, flag
, xerrno
);
674 TunnelStateData::Connection::dataSent(size_t amount
)
676 debugs(26, 3, HERE
<< "len=" << len
<< " - amount=" << amount
);
677 assert(amount
== (size_t)len
);
679 /* increment total object size */
686 TunnelStateData::Connection::write(const char *b
, int size
, AsyncCall::Pointer
&callback
, FREE
* free_func
)
689 Comm::Write(conn
, b
, size
, callback
, free_func
);
693 TunnelStateData::writeClientDone(char *, size_t len
, Comm::Flag flag
, int xerrno
)
695 debugs(26, 3, HERE
<< client
.conn
<< ", " << len
<< " bytes written, flag=" << flag
);
698 if (flag
!= Comm::OK
) {
699 if (flag
!= Comm::ERR_CLOSING
) {
700 debugs(26, 4, HERE
<< "Closing client connection due to comm flags.");
701 client
.error(xerrno
); // may call comm_close
708 debugs(26, 4, HERE
<< "Closing client connection due to 0 byte read.");
709 client
.conn
->close();
714 statCounter
.client_http
.kbytes_out
+= len
;
715 server
.dataSent(len
);
717 /* If the other end has closed, so should we */
718 if (!Comm::IsConnOpen(server
.conn
)) {
719 debugs(26, 4, HERE
<< "Server has gone away. Terminating client connection.");
720 client
.conn
->close();
724 CbcPointer
<TunnelStateData
> safetyLock(this); /* ??? should be locked by the caller... */
726 if (cbdataReferenceValid(this))
727 copyRead(server
, ReadServer
);
731 tunnelTimeout(const CommTimeoutCbParams
&io
)
733 TunnelStateData
*tunnelState
= static_cast<TunnelStateData
*>(io
.data
);
734 debugs(26, 3, HERE
<< io
.conn
);
735 /* Temporary lock to protect our own feets (comm_close -> tunnelClientClosed -> Free) */
736 CbcPointer
<TunnelStateData
> safetyLock(tunnelState
);
738 tunnelState
->client
.closeIfOpen();
739 tunnelState
->server
.closeIfOpen();
743 TunnelStateData::Connection::closeIfOpen()
745 if (Comm::IsConnOpen(conn
))
750 tunnelDelayedClientRead(void *data
)
755 TunnelStateData
*tunnel
= static_cast<TunnelStateData
*>(data
);
756 tunnel
->client
.readPending
= NULL
;
757 static uint64_t counter
=0;
758 debugs(26, 7, "Client read(2) delayed " << ++counter
<< " times");
759 tunnel
->copyRead(tunnel
->client
, TunnelStateData::ReadClient
);
763 tunnelDelayedServerRead(void *data
)
768 TunnelStateData
*tunnel
= static_cast<TunnelStateData
*>(data
);
769 tunnel
->server
.readPending
= NULL
;
770 static uint64_t counter
=0;
771 debugs(26, 7, "Server read(2) delayed " << ++counter
<< " times");
772 tunnel
->copyRead(tunnel
->server
, TunnelStateData::ReadServer
);
776 TunnelStateData::copyRead(Connection
&from
, IOCB
*completion
)
778 assert(from
.len
== 0);
779 // If only the minimum permitted read size is going to be attempted
780 // then we schedule an event to try again in a few I/O cycles.
781 // Allow at least 1 byte to be read every (0.3*10) seconds.
782 int bw
= from
.bytesWanted(1, SQUID_TCP_SO_RCVBUF
);
783 if (bw
== 1 && ++from
.delayedLoops
< 10) {
784 from
.readPending
= this;
785 eventAdd("tunnelDelayedServerRead", from
.readPendingFunc
, from
.readPending
, 0.3, true);
789 AsyncCall::Pointer call
= commCbCall(5,4, "TunnelBlindCopyReadHandler",
790 CommIoCbPtrFun(completion
, this));
791 comm_read(from
.conn
, from
.buf
, bw
, call
);
795 TunnelStateData::readConnectResponse()
797 assert(waitingForConnectResponse());
799 AsyncCall::Pointer call
= commCbCall(5,4, "readConnectResponseDone",
800 CommIoCbPtrFun(ReadConnectResponseDone
, this));
801 comm_read(server
.conn
, connectRespBuf
->space(),
802 server
.bytesWanted(1, connectRespBuf
->spaceSize()), call
);
806 TunnelStateData::copyClientBytes()
808 if (preReadClientData
.length()) {
809 size_t copyBytes
= preReadClientData
.length() > SQUID_TCP_SO_RCVBUF
? SQUID_TCP_SO_RCVBUF
: preReadClientData
.length();
810 memcpy(client
.buf
, preReadClientData
.rawContent(), copyBytes
);
811 preReadClientData
.consume(copyBytes
);
812 client
.bytesIn(copyBytes
);
813 if (keepGoingAfterRead(copyBytes
, Comm::OK
, 0, client
, server
))
814 copy(copyBytes
, client
, server
, TunnelStateData::WriteServerDone
);
816 copyRead(client
, ReadClient
);
820 * Set the HTTP status for this request and sets the read handlers for client
821 * and server side connections.
824 tunnelStartShoveling(TunnelStateData
*tunnelState
)
826 assert(!tunnelState
->waitingForConnectExchange());
827 *tunnelState
->status_ptr
= Http::scOkay
;
828 if (tunnelState
->logTag_ptr
)
829 *tunnelState
->logTag_ptr
= LOG_TCP_TUNNEL
;
830 if (cbdataReferenceValid(tunnelState
)) {
832 // Shovel any payload already pushed into reply buffer by the server response
833 if (!tunnelState
->server
.len
)
834 tunnelState
->copyRead(tunnelState
->server
, TunnelStateData::ReadServer
);
836 debugs(26, DBG_DATA
, "Tunnel server PUSH Payload: \n" << Raw("", tunnelState
->server
.buf
, tunnelState
->server
.len
) << "\n----------");
837 tunnelState
->copy(tunnelState
->server
.len
, tunnelState
->server
, tunnelState
->client
, TunnelStateData::WriteClientDone
);
840 if (tunnelState
->http
.valid() && tunnelState
->http
->getConn() && !tunnelState
->http
->getConn()->inBuf
.isEmpty()) {
841 SBuf
* const in
= &tunnelState
->http
->getConn()->inBuf
;
842 debugs(26, DBG_DATA
, "Tunnel client PUSH Payload: \n" << *in
<< "\n----------");
843 tunnelState
->preReadClientData
.append(*in
);
844 in
->consume(); // ConnStateData buffer accounting after the shuffle.
846 tunnelState
->copyClientBytes();
851 * All the pieces we need to write to client and/or server connection
853 * Call the tunnelStartShoveling to start the blind pump.
856 tunnelConnectedWriteDone(const Comm::ConnectionPointer
&conn
, char *, size_t, Comm::Flag flag
, int, void *data
)
858 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
859 debugs(26, 3, HERE
<< conn
<< ", flag=" << flag
);
860 tunnelState
->client
.writer
= NULL
;
862 if (flag
!= Comm::OK
) {
863 *tunnelState
->status_ptr
= Http::scInternalServerError
;
864 tunnelErrorComplete(conn
->fd
, data
, 0);
868 tunnelStartShoveling(tunnelState
);
871 /// Called when we are done writing CONNECT request to a peer.
873 tunnelConnectReqWriteDone(const Comm::ConnectionPointer
&conn
, char *, size_t, Comm::Flag flag
, int, void *data
)
875 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
876 debugs(26, 3, conn
<< ", flag=" << flag
);
877 tunnelState
->server
.writer
= NULL
;
878 assert(tunnelState
->waitingForConnectRequest());
880 if (flag
!= Comm::OK
) {
881 *tunnelState
->status_ptr
= Http::scInternalServerError
;
882 tunnelErrorComplete(conn
->fd
, data
, 0);
886 tunnelState
->connectReqWriting
= false;
887 tunnelState
->connectExchangeCheckpoint();
891 TunnelStateData::connectExchangeCheckpoint()
893 if (waitingForConnectResponse()) {
894 debugs(26, 5, "still reading CONNECT response on " << server
.conn
);
895 } else if (waitingForConnectRequest()) {
896 debugs(26, 5, "still writing CONNECT request on " << server
.conn
);
898 assert(!waitingForConnectExchange());
899 debugs(26, 3, "done with CONNECT exchange on " << server
.conn
);
900 tunnelConnected(server
.conn
, this);
905 * handle the write completion from a proxy request to an upstream origin
908 tunnelConnected(const Comm::ConnectionPointer
&server
, void *data
)
910 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
911 debugs(26, 3, HERE
<< server
<< ", tunnelState=" << tunnelState
);
913 if (!tunnelState
->clientExpectsConnectResponse())
914 tunnelStartShoveling(tunnelState
); // ssl-bumped connection, be quiet
916 AsyncCall::Pointer call
= commCbCall(5,5, "tunnelConnectedWriteDone",
917 CommIoCbPtrFun(tunnelConnectedWriteDone
, tunnelState
));
918 tunnelState
->client
.write(conn_established
, strlen(conn_established
), call
, NULL
);
923 tunnelErrorComplete(int fd
/*const Comm::ConnectionPointer &*/, void *data
, size_t)
925 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
926 debugs(26, 3, HERE
<< "FD " << fd
);
927 assert(tunnelState
!= NULL
);
928 /* temporary lock to save our own feets (comm_close -> tunnelClientClosed -> Free) */
929 CbcPointer
<TunnelStateData
> safetyLock(tunnelState
);
931 if (Comm::IsConnOpen(tunnelState
->client
.conn
))
932 tunnelState
->client
.conn
->close();
934 if (Comm::IsConnOpen(tunnelState
->server
.conn
))
935 tunnelState
->server
.conn
->close();
939 tunnelConnectDone(const Comm::ConnectionPointer
&conn
, Comm::Flag status
, int xerrno
, void *data
)
941 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
943 if (status
!= Comm::OK
) {
944 debugs(26, 4, HERE
<< conn
<< ", comm failure recovery.");
945 /* At this point only the TCP handshake has failed. no data has been passed.
946 * we are allowed to re-try the TCP-level connection to alternate IPs for CONNECT.
948 debugs(26, 4, "removing server 1 of " << tunnelState
->serverDestinations
.size() <<
949 " from destinations (" << tunnelState
->serverDestinations
[0] << ")");
950 tunnelState
->serverDestinations
.erase(tunnelState
->serverDestinations
.begin());
951 time_t fwdTimeout
= tunnelState
->started
+ Config
.Timeout
.forward
;
952 if (fwdTimeout
> squid_curtime
&& tunnelState
->serverDestinations
.size() > 0) {
953 // find remaining forward_timeout available for this attempt
954 fwdTimeout
-= squid_curtime
;
955 if (fwdTimeout
> Config
.Timeout
.connect
)
956 fwdTimeout
= Config
.Timeout
.connect
;
957 /* Try another IP of this destination host */
958 GetMarkingsToServer(tunnelState
->request
.getRaw(), *tunnelState
->serverDestinations
[0]);
959 debugs(26, 4, HERE
<< "retry with : " << tunnelState
->serverDestinations
[0]);
960 AsyncCall::Pointer call
= commCbCall(26,3, "tunnelConnectDone", CommConnectCbPtrFun(tunnelConnectDone
, tunnelState
));
961 Comm::ConnOpener
*cs
= new Comm::ConnOpener(tunnelState
->serverDestinations
[0], call
, fwdTimeout
);
962 cs
->setHost(tunnelState
->url
);
965 debugs(26, 4, HERE
<< "terminate with error.");
966 ErrorState
*err
= new ErrorState(ERR_CONNECT_FAIL
, Http::scServiceUnavailable
, tunnelState
->request
.getRaw());
967 *tunnelState
->status_ptr
= Http::scServiceUnavailable
;
968 err
->xerrno
= xerrno
;
969 // on timeout is this still: err->xerrno = ETIMEDOUT;
970 err
->port
= conn
->remote
.port();
971 err
->callback
= tunnelErrorComplete
;
972 err
->callback_data
= tunnelState
;
973 errorSend(tunnelState
->client
.conn
, err
);
974 if (tunnelState
->request
!= NULL
)
975 tunnelState
->request
->hier
.stopPeerClock(false);
981 /* no point using the delayIsNoDelay stuff since tunnel is nice and simple */
982 if (conn
->getPeer() && conn
->getPeer()->options
.no_delay
)
983 tunnelState
->server
.setDelayId(DelayId());
986 tunnelState
->request
->hier
.note(conn
, tunnelState
->getHost());
988 tunnelState
->server
.conn
= conn
;
989 tunnelState
->request
->peer_host
= conn
->getPeer() ? conn
->getPeer()->host
: NULL
;
990 comm_add_close_handler(conn
->fd
, tunnelServerClosed
, tunnelState
);
992 debugs(26, 4, HERE
<< "determine post-connect handling pathway.");
993 if (conn
->getPeer()) {
994 tunnelState
->request
->peer_login
= conn
->getPeer()->login
;
995 tunnelState
->request
->peer_domain
= conn
->getPeer()->domain
;
996 tunnelState
->request
->flags
.proxying
= !(conn
->getPeer()->options
.originserver
);
998 tunnelState
->request
->peer_login
= NULL
;
999 tunnelState
->request
->peer_domain
= NULL
;
1000 tunnelState
->request
->flags
.proxying
= false;
1003 if (tunnelState
->request
->flags
.proxying
)
1004 tunnelState
->connectToPeer();
1006 tunnelConnected(conn
, tunnelState
);
1009 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
1010 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
1011 commSetConnTimeout(conn
, Config
.Timeout
.read
, timeoutCall
);
1015 tunnelStart(ClientHttpRequest
* http
)
1017 debugs(26, 3, HERE
);
1018 /* Create state structure. */
1019 TunnelStateData
*tunnelState
= NULL
;
1020 ErrorState
*err
= NULL
;
1021 HttpRequest
*request
= http
->request
;
1022 char *url
= http
->uri
;
1025 * client_addr.isNoAddr() indicates this is an "internal" request
1026 * from peer_digest.c, asn.c, netdb.c, etc and should always
1027 * be allowed. yuck, I know.
1030 if (Config
.accessList
.miss
&& !request
->client_addr
.isNoAddr()) {
1032 * Check if this host is allowed to fetch MISSES from us (miss_access)
1033 * default is to allow.
1035 ACLFilledChecklist
ch(Config
.accessList
.miss
, request
, NULL
);
1036 ch
.src_addr
= request
->client_addr
;
1037 ch
.my_addr
= request
->my_addr
;
1038 if (ch
.fastCheck() == ACCESS_DENIED
) {
1039 debugs(26, 4, HERE
<< "MISS access forbidden.");
1040 err
= new ErrorState(ERR_FORWARDING_DENIED
, Http::scForbidden
, request
);
1041 http
->al
->http
.code
= Http::scForbidden
;
1042 errorSend(http
->getConn()->clientConnection
, err
);
1047 debugs(26, 3, request
->method
<< ' ' << url
<< ' ' << request
->http_ver
);
1048 ++statCounter
.server
.all
.requests
;
1049 ++statCounter
.server
.other
.requests
;
1051 tunnelState
= new TunnelStateData
;
1053 tunnelState
->server
.setDelayId(DelayId::DelayClient(http
));
1055 tunnelState
->url
= xstrdup(url
);
1056 tunnelState
->request
= request
;
1057 tunnelState
->server
.size_ptr
= &http
->out
.size
;
1058 tunnelState
->client
.size_ptr
= &http
->al
->http
.clientRequestSz
.payloadData
;
1059 tunnelState
->status_ptr
= &http
->al
->http
.code
;
1060 tunnelState
->logTag_ptr
= &http
->logType
;
1061 tunnelState
->client
.conn
= http
->getConn()->clientConnection
;
1062 tunnelState
->http
= http
;
1063 tunnelState
->al
= http
->al
;
1064 //tunnelState->started is set in TunnelStateData ctor
1066 comm_add_close_handler(tunnelState
->client
.conn
->fd
,
1070 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
1071 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
1072 commSetConnTimeout(tunnelState
->client
.conn
, Config
.Timeout
.lifetime
, timeoutCall
);
1074 peerSelect(&(tunnelState
->serverDestinations
), request
, http
->al
,
1076 tunnelPeerSelectComplete
,
1081 TunnelStateData::connectToPeer()
1084 if (CachePeer
*p
= server
.conn
->getPeer()) {
1085 if (p
->secure
.encryptTransport
) {
1086 AsyncCall::Pointer callback
= asyncCall(5,4,
1087 "TunnelStateData::ConnectedToPeer",
1088 MyAnswerDialer(&TunnelStateData::connectedToPeer
, this));
1089 Ssl::BlindPeerConnector
*connector
=
1090 new Ssl::BlindPeerConnector(request
, server
.conn
, callback
);
1091 AsyncJob::Start(connector
); // will call our callback
1097 Security::EncryptorAnswer nil
;
1098 connectedToPeer(nil
);
1102 TunnelStateData::connectedToPeer(Security::EncryptorAnswer
&answer
)
1104 if (ErrorState
*error
= answer
.error
.get()) {
1105 *status_ptr
= error
->httpStatus
;
1106 error
->callback
= tunnelErrorComplete
;
1107 error
->callback_data
= this;
1108 errorSend(client
.conn
, error
);
1109 answer
.error
.clear(); // preserve error for errorSendComplete()
1113 tunnelRelayConnectRequest(server
.conn
, this);
1117 tunnelRelayConnectRequest(const Comm::ConnectionPointer
&srv
, void *data
)
1119 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
1120 assert(!tunnelState
->waitingForConnectExchange());
1121 HttpHeader
hdr_out(hoRequest
);
1122 HttpStateFlags flags
;
1123 debugs(26, 3, HERE
<< srv
<< ", tunnelState=" << tunnelState
);
1124 memset(&flags
, '\0', sizeof(flags
));
1125 flags
.proxying
= tunnelState
->request
->flags
.proxying
;
1128 mb
.appendf("CONNECT %s HTTP/1.1\r\n", tunnelState
->url
);
1129 HttpStateData::httpBuildRequestHeader(tunnelState
->request
.getRaw(),
1130 NULL
, /* StoreEntry */
1131 tunnelState
->al
, /* AccessLogEntry */
1134 hdr_out
.packInto(&mb
);
1136 mb
.append("\r\n", 2);
1138 debugs(11, 2, "Tunnel Server REQUEST: " << tunnelState
->server
.conn
<<
1139 ":\n----------\n" << mb
.buf
<< "\n----------");
1141 AsyncCall::Pointer writeCall
= commCbCall(5,5, "tunnelConnectReqWriteDone",
1142 CommIoCbPtrFun(tunnelConnectReqWriteDone
,
1145 tunnelState
->server
.write(mb
.buf
, mb
.size
, writeCall
, mb
.freeFunc());
1146 tunnelState
->connectReqWriting
= true;
1148 tunnelState
->connectRespBuf
= new MemBuf
;
1149 // SQUID_TCP_SO_RCVBUF: we should not accumulate more than regular I/O buffer
1150 // can hold since any CONNECT response leftovers have to fit into server.buf.
1151 // 2*SQUID_TCP_SO_RCVBUF: HttpMsg::parse() zero-terminates, which uses space.
1152 tunnelState
->connectRespBuf
->init(SQUID_TCP_SO_RCVBUF
, 2*SQUID_TCP_SO_RCVBUF
);
1153 tunnelState
->readConnectResponse();
1155 assert(tunnelState
->waitingForConnectExchange());
1157 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
1158 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
1159 commSetConnTimeout(srv
, Config
.Timeout
.read
, timeoutCall
);
1163 tunnelPeerSelectComplete(Comm::ConnectionList
*peer_paths
, ErrorState
*err
, void *data
)
1165 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
1167 if (peer_paths
== NULL
|| peer_paths
->size() < 1) {
1168 debugs(26, 3, HERE
<< "No paths found. Aborting CONNECT");
1170 err
= new ErrorState(ERR_CANNOT_FORWARD
, Http::scServiceUnavailable
, tunnelState
->request
.getRaw());
1172 *tunnelState
->status_ptr
= err
->httpStatus
;
1173 err
->callback
= tunnelErrorComplete
;
1174 err
->callback_data
= tunnelState
;
1175 errorSend(tunnelState
->client
.conn
, err
);
1180 GetMarkingsToServer(tunnelState
->request
.getRaw(), *tunnelState
->serverDestinations
[0]);
1182 if (tunnelState
->request
!= NULL
)
1183 tunnelState
->request
->hier
.startPeerClock();
1185 debugs(26, 3, HERE
<< "paths=" << peer_paths
->size() << ", p[0]={" << (*peer_paths
)[0] << "}, serverDest[0]={" <<
1186 tunnelState
->serverDestinations
[0] << "}");
1188 AsyncCall::Pointer call
= commCbCall(26,3, "tunnelConnectDone", CommConnectCbPtrFun(tunnelConnectDone
, tunnelState
));
1189 Comm::ConnOpener
*cs
= new Comm::ConnOpener(tunnelState
->serverDestinations
[0], call
, Config
.Timeout
.connect
);
1190 cs
->setHost(tunnelState
->url
);
1191 AsyncJob::Start(cs
);
1194 CBDATA_CLASS_INIT(TunnelStateData
);
1197 TunnelStateData::noConnections() const
1199 return !Comm::IsConnOpen(server
.conn
) && !Comm::IsConnOpen(client
.conn
);
1204 TunnelStateData::Connection::setDelayId(DelayId
const &newDelay
)
1213 switchToTunnel(HttpRequest
*request
, Comm::ConnectionPointer
&clientConn
, Comm::ConnectionPointer
&srvConn
)
1215 debugs(26,5, "Revert to tunnel FD " << clientConn
->fd
<< " with FD " << srvConn
->fd
);
1216 /* Create state structure. */
1217 TunnelStateData
*tunnelState
= NULL
;
1218 const SBuf
url(request
->effectiveRequestUri());
1220 debugs(26, 3, request
->method
<< " " << url
<< " " << request
->http_ver
);
1221 ++statCounter
.server
.all
.requests
;
1222 ++statCounter
.server
.other
.requests
;
1224 tunnelState
= new TunnelStateData
;
1225 tunnelState
->url
= SBufToCstring(url
);
1226 tunnelState
->request
= request
;
1227 tunnelState
->server
.size_ptr
= NULL
; //Set later if ClientSocketContext is available
1229 // Temporary static variable to store the unneeded for our case status code
1230 static int status_code
= 0;
1231 tunnelState
->status_ptr
= &status_code
;
1232 tunnelState
->client
.conn
= clientConn
;
1234 ConnStateData
*conn
;
1235 if ((conn
= request
->clientConnectionManager
.get())) {
1236 ClientSocketContext::Pointer context
= conn
->pipeline
.front());
1237 if (context
!= nullptr && context
->http
!= nullptr) {
1238 tunnelState
->logTag_ptr
= &context
->http
->logType
;
1239 tunnelState
->server
.size_ptr
= &context
->http
->out
.size
;
1242 /* no point using the delayIsNoDelay stuff since tunnel is nice and simple */
1243 if (srvConn
->getPeer() && srvConn
->getPeer()->options
.no_delay
)
1244 tunnelState
->server
.setDelayId(DelayId::DelayClient(context
->http
));
1249 comm_add_close_handler(tunnelState
->client
.conn
->fd
,
1253 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
1254 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
1255 commSetConnTimeout(tunnelState
->client
.conn
, Config
.Timeout
.lifetime
, timeoutCall
);
1256 fd_table
[clientConn
->fd
].read_method
= &default_read_method
;
1257 fd_table
[clientConn
->fd
].write_method
= &default_write_method
;
1259 tunnelState
->request
->hier
.note(srvConn
, tunnelState
->getHost());
1261 tunnelState
->server
.conn
= srvConn
;
1262 tunnelState
->request
->peer_host
= srvConn
->getPeer() ? srvConn
->getPeer()->host
: NULL
;
1263 comm_add_close_handler(srvConn
->fd
, tunnelServerClosed
, tunnelState
);
1265 debugs(26, 4, "determine post-connect handling pathway.");
1266 if (srvConn
->getPeer()) {
1267 tunnelState
->request
->peer_login
= srvConn
->getPeer()->login
;
1268 tunnelState
->request
->peer_domain
= srvConn
->getPeer()->domain
;
1269 tunnelState
->request
->flags
.proxying
= !(srvConn
->getPeer()->options
.originserver
);
1271 tunnelState
->request
->peer_login
= NULL
;
1272 tunnelState
->request
->peer_domain
= NULL
;
1273 tunnelState
->request
->flags
.proxying
= false;
1276 timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
1277 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
1278 commSetConnTimeout(srvConn
, Config
.Timeout
.read
, timeoutCall
);
1279 fd_table
[srvConn
->fd
].read_method
= &default_read_method
;
1280 fd_table
[srvConn
->fd
].write_method
= &default_write_method
;
1282 auto ssl
= fd_table
[srvConn
->fd
].ssl
;
1284 BIO
*b
= SSL_get_rbio(ssl
);
1285 Ssl::ServerBio
*srvBio
= static_cast<Ssl::ServerBio
*>(b
->ptr
);
1286 const MemBuf
&buf
= srvBio
->rBufData();
1288 AsyncCall::Pointer call
= commCbCall(5,5, "tunnelConnectedWriteDone",
1289 CommIoCbPtrFun(tunnelConnectedWriteDone
, tunnelState
));
1290 tunnelState
->client
.write(buf
.content(), buf
.contentSize(), call
, NULL
);
1292 #endif //USE_OPENSSL