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
->GetHost());
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
));
121 Connection() : len (0), buf ((char *)xmalloc(SQUID_TCP_SO_RCVBUF
)), size_ptr(NULL
), delayedLoops(0),
122 readPending(NULL
), readPendingFunc(NULL
) {}
126 int bytesWanted(int lower
=0, int upper
= INT_MAX
) const;
127 void bytesIn(int const &);
130 void setDelayId(DelayId
const &);
133 void error(int const xerrno
);
134 int debugLevelForError(int const xerrno
) const;
135 /// handles a non-I/O error associated with this Connection
136 void logicError(const char *errMsg
);
138 void dataSent (size_t amount
);
141 int64_t *size_ptr
; /* pointer to size in an ConnStateData for logging */
143 Comm::ConnectionPointer conn
; ///< The currently connected connection.
144 uint8_t delayedLoops
; ///< how many times a read on this connection has been postponed.
146 // XXX: make these an AsyncCall when event API can handle them
147 TunnelStateData
*readPending
;
148 EVH
*readPendingFunc
;
157 Connection client
, server
;
158 int *status_ptr
; ///< pointer for logging HTTP status
159 LogTags
*logTag_ptr
; ///< pointer for logging Squid processing code
160 MemBuf
*connectRespBuf
; ///< accumulates peer CONNECT response when we need it
161 bool connectReqWriting
; ///< whether we are writing a CONNECT request to a peer
162 SBuf preReadClientData
;
164 void copyRead(Connection
&from
, IOCB
*completion
);
166 /// continue to set up connection to a peer, going async for SSL peers
167 void connectToPeer();
171 /// Gives PeerConnector access to Answer in the TunnelStateData callback dialer.
172 class MyAnswerDialer
: public CallDialer
, public Ssl::PeerConnector::CbDialer
175 typedef void (TunnelStateData::*Method
)(Security::EncryptorAnswer
&);
177 MyAnswerDialer(Method method
, TunnelStateData
*tunnel
):
178 method_(method
), tunnel_(tunnel
), answer_() {}
181 virtual bool canDial(AsyncCall
&call
) { return tunnel_
.valid(); }
182 void dial(AsyncCall
&call
) { ((&(*tunnel_
))->*method_
)(answer_
); }
183 virtual void print(std::ostream
&os
) const {
184 os
<< '(' << tunnel_
.get() << ", " << answer_
<< ')';
187 /* Ssl::PeerConnector::CbDialer API */
188 virtual Security::EncryptorAnswer
&answer() { return answer_
; }
192 CbcPointer
<TunnelStateData
> tunnel_
;
193 Security::EncryptorAnswer answer_
;
197 /// callback handler after connection setup (including any encryption)
198 void connectedToPeer(Security::EncryptorAnswer
&answer
);
201 bool keepGoingAfterRead(size_t len
, Comm::Flag errcode
, int xerrno
, Connection
&from
, Connection
&to
);
202 void copy(size_t len
, Connection
&from
, Connection
&to
, IOCB
*);
203 void handleConnectResponse(const size_t chunkSize
);
204 void readServer(char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
);
205 void readClient(char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
);
206 void writeClientDone(char *buf
, size_t len
, Comm::Flag flag
, int xerrno
);
207 void writeServerDone(char *buf
, size_t len
, Comm::Flag flag
, int xerrno
);
209 static void ReadConnectResponseDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
);
210 void readConnectResponseDone(char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
);
211 void copyClientBytes();
214 static const char *const conn_established
= "HTTP/1.1 200 Connection established\r\n\r\n";
216 static CNCB tunnelConnectDone
;
217 static ERCB tunnelErrorComplete
;
218 static CLCB tunnelServerClosed
;
219 static CLCB tunnelClientClosed
;
220 static CTCB tunnelTimeout
;
221 static PSC tunnelPeerSelectComplete
;
222 static EVH tunnelDelayedClientRead
;
223 static EVH tunnelDelayedServerRead
;
224 static void tunnelConnected(const Comm::ConnectionPointer
&server
, void *);
225 static void tunnelRelayConnectRequest(const Comm::ConnectionPointer
&server
, void *);
228 tunnelServerClosed(const CommCloseCbParams
¶ms
)
230 TunnelStateData
*tunnelState
= (TunnelStateData
*)params
.data
;
231 debugs(26, 3, HERE
<< tunnelState
->server
.conn
);
232 tunnelState
->server
.conn
= NULL
;
234 if (tunnelState
->request
!= NULL
)
235 tunnelState
->request
->hier
.stopPeerClock(false);
237 if (tunnelState
->noConnections()) {
242 if (!tunnelState
->server
.len
) {
243 tunnelState
->client
.conn
->close();
249 tunnelClientClosed(const CommCloseCbParams
¶ms
)
251 TunnelStateData
*tunnelState
= (TunnelStateData
*)params
.data
;
252 debugs(26, 3, HERE
<< tunnelState
->client
.conn
);
253 tunnelState
->client
.conn
= NULL
;
255 if (tunnelState
->noConnections()) {
260 if (!tunnelState
->client
.len
) {
261 tunnelState
->server
.conn
->close();
266 TunnelStateData::TunnelStateData() :
272 connectRespBuf(NULL
),
273 connectReqWriting(false)
275 debugs(26, 3, "TunnelStateData constructed this=" << this);
276 client
.readPendingFunc
= &tunnelDelayedClientRead
;
277 server
.readPendingFunc
= &tunnelDelayedServerRead
;
280 TunnelStateData::~TunnelStateData()
282 debugs(26, 3, "TunnelStateData destructed this=" << this);
283 assert(noConnections());
285 serverDestinations
.clear();
286 delete connectRespBuf
;
289 TunnelStateData::Connection::~Connection()
292 eventDelete(readPendingFunc
, readPending
);
298 TunnelStateData::Connection::bytesWanted(int lowerbound
, int upperbound
) const
301 return delayId
.bytesWanted(lowerbound
, upperbound
);
309 TunnelStateData::Connection::bytesIn(int const &count
)
311 debugs(26, 3, HERE
<< "len=" << len
<< " + count=" << count
);
313 delayId
.bytesIn(count
);
320 TunnelStateData::Connection::debugLevelForError(int const xerrno
) const
324 if (xerrno
== ECONNRESET
)
329 if (ignoreErrno(xerrno
))
335 /* Read from server side and queue it for writing to the client */
337 TunnelStateData::ReadServer(const Comm::ConnectionPointer
&c
, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
)
339 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
340 assert(cbdataReferenceValid(tunnelState
));
341 debugs(26, 3, HERE
<< c
);
343 tunnelState
->readServer(buf
, len
, errcode
, xerrno
);
347 TunnelStateData::readServer(char *, size_t len
, Comm::Flag errcode
, int xerrno
)
349 debugs(26, 3, HERE
<< server
.conn
<< ", read " << len
<< " bytes, err=" << errcode
);
350 server
.delayedLoops
=0;
353 * Bail out early on Comm::ERR_CLOSING
354 * - close handlers will tidy up for us
357 if (errcode
== Comm::ERR_CLOSING
)
362 kb_incr(&(statCounter
.server
.all
.kbytes_in
), len
);
363 kb_incr(&(statCounter
.server
.other
.kbytes_in
), len
);
366 if (keepGoingAfterRead(len
, errcode
, xerrno
, server
, client
))
367 copy(len
, server
, client
, WriteClientDone
);
370 /// Called when we read [a part of] CONNECT response from the peer
372 TunnelStateData::readConnectResponseDone(char *, size_t len
, Comm::Flag errcode
, int xerrno
)
374 debugs(26, 3, server
.conn
<< ", read " << len
<< " bytes, err=" << errcode
);
375 assert(waitingForConnectResponse());
377 if (errcode
== Comm::ERR_CLOSING
)
381 connectRespBuf
->appended(len
);
383 kb_incr(&(statCounter
.server
.all
.kbytes_in
), len
);
384 kb_incr(&(statCounter
.server
.other
.kbytes_in
), len
);
387 if (keepGoingAfterRead(len
, errcode
, xerrno
, server
, client
))
388 handleConnectResponse(len
);
391 /* Read from client side and queue it for writing to the server */
393 TunnelStateData::ReadConnectResponseDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
)
395 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
396 assert (cbdataReferenceValid (tunnelState
));
398 tunnelState
->readConnectResponseDone(buf
, len
, errcode
, xerrno
);
401 /// Parses [possibly incomplete] CONNECT response and reacts to it.
402 /// If the tunnel is being closed or more response data is needed, returns false.
403 /// Otherwise, the caller should handle the remaining read data, if any.
405 TunnelStateData::handleConnectResponse(const size_t chunkSize
)
407 assert(waitingForConnectResponse());
409 // Ideally, client and server should use MemBuf or better, but current code
410 // never accumulates more than one read when shoveling data (XXX) so it does
411 // not need to deal with MemBuf complexity. To keep it simple, we use a
412 // dedicated MemBuf for accumulating CONNECT responses. TODO: When shoveling
413 // is optimized, reuse server.buf for CONNEC response accumulation instead.
415 /* mimic the basic parts of HttpStateData::processReplyHeader() */
417 Http::StatusCode parseErr
= Http::scNone
;
418 const bool eof
= !chunkSize
;
419 connectRespBuf
->terminate(); // HttpMsg::parse requires terminated string
420 const bool parsed
= rep
.parse(connectRespBuf
->content(), connectRespBuf
->contentSize(), eof
, &parseErr
);
422 if (parseErr
> 0) { // unrecoverable parsing error
423 server
.logicError("malformed CONNECT response from peer");
431 if (!connectRespBuf
->hasSpace()) {
432 server
.logicError("huge CONNECT response from peer");
437 readConnectResponse();
441 // CONNECT response was successfully parsed
442 *status_ptr
= rep
.sline
.status();
444 // bail if we did not get an HTTP 200 (Connection Established) response
445 if (rep
.sline
.status() != Http::scOkay
) {
446 server
.logicError("unsupported CONNECT response status code");
450 if (rep
.hdr_sz
< connectRespBuf
->contentSize()) {
451 // preserve bytes that the server already sent after the CONNECT response
452 server
.len
= connectRespBuf
->contentSize() - rep
.hdr_sz
;
453 memcpy(server
.buf
, connectRespBuf
->content()+rep
.hdr_sz
, server
.len
);
455 // reset; delay pools were using this field to throttle CONNECT response
459 delete connectRespBuf
;
460 connectRespBuf
= NULL
;
461 connectExchangeCheckpoint();
465 TunnelStateData::Connection::logicError(const char *errMsg
)
467 debugs(50, 3, conn
<< " closing on error: " << errMsg
);
472 TunnelStateData::Connection::error(int const xerrno
)
474 /* XXX fixme xstrerror and xerrno... */
477 debugs(50, debugLevelForError(xerrno
), HERE
<< conn
<< ": read/write failure: " << xstrerror());
479 if (!ignoreErrno(xerrno
))
483 /* Read from client side and queue it for writing to the server */
485 TunnelStateData::ReadClient(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag errcode
, int xerrno
, void *data
)
487 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
488 assert (cbdataReferenceValid (tunnelState
));
490 tunnelState
->readClient(buf
, len
, errcode
, xerrno
);
494 TunnelStateData::readClient(char *, size_t len
, Comm::Flag errcode
, int xerrno
)
496 debugs(26, 3, HERE
<< client
.conn
<< ", read " << len
<< " bytes, err=" << errcode
);
497 client
.delayedLoops
=0;
500 * Bail out early on Comm::ERR_CLOSING
501 * - close handlers will tidy up for us
504 if (errcode
== Comm::ERR_CLOSING
)
509 kb_incr(&(statCounter
.client_http
.kbytes_in
), len
);
512 if (keepGoingAfterRead(len
, errcode
, xerrno
, client
, server
))
513 copy(len
, client
, server
, WriteServerDone
);
516 /// Updates state after reading from client or server.
517 /// Returns whether the caller should use the data just read.
519 TunnelStateData::keepGoingAfterRead(size_t len
, Comm::Flag errcode
, int xerrno
, Connection
&from
, Connection
&to
)
521 debugs(26, 3, HERE
<< "from={" << from
.conn
<< "}, to={" << to
.conn
<< "}");
523 /* I think this is to prevent free-while-in-a-callback behaviour
525 * from.conn->close() / to.conn->close() done here trigger close callbacks which may free TunnelStateData
527 const CbcPointer
<TunnelStateData
> safetyLock(this);
529 /* Bump the source connection read timeout on any activity */
530 if (Comm::IsConnOpen(from
.conn
)) {
531 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
532 CommTimeoutCbPtrFun(tunnelTimeout
, this));
533 commSetConnTimeout(from
.conn
, Config
.Timeout
.read
, timeoutCall
);
536 /* Bump the dest connection read timeout on any activity */
537 /* see Bug 3659: tunnels can be weird, with very long one-way transfers */
538 if (Comm::IsConnOpen(to
.conn
)) {
539 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
540 CommTimeoutCbPtrFun(tunnelTimeout
, this));
541 commSetConnTimeout(to
.conn
, Config
.Timeout
.read
, timeoutCall
);
546 else if (len
== 0 || !Comm::IsConnOpen(to
.conn
)) {
547 debugs(26, 3, HERE
<< "Nothing to write or client gone. Terminate the tunnel.");
550 /* Only close the remote end if we've finished queueing data to it */
551 if (from
.len
== 0 && Comm::IsConnOpen(to
.conn
) ) {
554 } else if (cbdataReferenceValid(this)) {
562 TunnelStateData::copy(size_t len
, Connection
&from
, Connection
&to
, IOCB
*completion
)
564 debugs(26, 3, HERE
<< "Schedule Write");
565 AsyncCall::Pointer call
= commCbCall(5,5, "TunnelBlindCopyWriteHandler",
566 CommIoCbPtrFun(completion
, this));
567 Comm::Write(to
.conn
, from
.buf
, len
, call
, NULL
);
570 /* Writes data from the client buffer to the server side */
572 TunnelStateData::WriteServerDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag flag
, int xerrno
, void *data
)
574 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
575 assert (cbdataReferenceValid (tunnelState
));
577 tunnelState
->writeServerDone(buf
, len
, flag
, xerrno
);
581 TunnelStateData::writeServerDone(char *, size_t len
, Comm::Flag flag
, int xerrno
)
583 debugs(26, 3, HERE
<< server
.conn
<< ", " << len
<< " bytes written, flag=" << flag
);
586 if (flag
!= Comm::OK
) {
587 if (flag
!= Comm::ERR_CLOSING
) {
588 debugs(26, 4, HERE
<< "calling TunnelStateData::server.error(" << xerrno
<<")");
589 server
.error(xerrno
); // may call comm_close
596 debugs(26, 4, HERE
<< "No read input. Closing server connection.");
597 server
.conn
->close();
602 kb_incr(&(statCounter
.server
.all
.kbytes_out
), len
);
603 kb_incr(&(statCounter
.server
.other
.kbytes_out
), len
);
604 client
.dataSent(len
);
606 /* If the other end has closed, so should we */
607 if (!Comm::IsConnOpen(client
.conn
)) {
608 debugs(26, 4, HERE
<< "Client gone away. Shutting down server connection.");
609 server
.conn
->close();
613 const CbcPointer
<TunnelStateData
> safetyLock(this); /* ??? should be locked by the caller... */
615 if (cbdataReferenceValid(this))
619 /* Writes data from the server buffer to the client side */
621 TunnelStateData::WriteClientDone(const Comm::ConnectionPointer
&, char *buf
, size_t len
, Comm::Flag flag
, int xerrno
, void *data
)
623 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
624 assert (cbdataReferenceValid (tunnelState
));
626 tunnelState
->writeClientDone(buf
, len
, flag
, xerrno
);
630 TunnelStateData::Connection::dataSent(size_t amount
)
632 debugs(26, 3, HERE
<< "len=" << len
<< " - amount=" << amount
);
633 assert(amount
== (size_t)len
);
635 /* increment total object size */
642 TunnelStateData::writeClientDone(char *, size_t len
, Comm::Flag flag
, int xerrno
)
644 debugs(26, 3, HERE
<< client
.conn
<< ", " << len
<< " bytes written, flag=" << flag
);
647 if (flag
!= Comm::OK
) {
648 if (flag
!= Comm::ERR_CLOSING
) {
649 debugs(26, 4, HERE
<< "Closing client connection due to comm flags.");
650 client
.error(xerrno
); // may call comm_close
657 debugs(26, 4, HERE
<< "Closing client connection due to 0 byte read.");
658 client
.conn
->close();
663 kb_incr(&(statCounter
.client_http
.kbytes_out
), len
);
664 server
.dataSent(len
);
666 /* If the other end has closed, so should we */
667 if (!Comm::IsConnOpen(server
.conn
)) {
668 debugs(26, 4, HERE
<< "Server has gone away. Terminating client connection.");
669 client
.conn
->close();
673 CbcPointer
<TunnelStateData
> safetyLock(this); /* ??? should be locked by the caller... */
675 if (cbdataReferenceValid(this))
676 copyRead(server
, ReadServer
);
680 tunnelTimeout(const CommTimeoutCbParams
&io
)
682 TunnelStateData
*tunnelState
= static_cast<TunnelStateData
*>(io
.data
);
683 debugs(26, 3, HERE
<< io
.conn
);
684 /* Temporary lock to protect our own feets (comm_close -> tunnelClientClosed -> Free) */
685 CbcPointer
<TunnelStateData
> safetyLock(tunnelState
);
687 tunnelState
->client
.closeIfOpen();
688 tunnelState
->server
.closeIfOpen();
692 TunnelStateData::Connection::closeIfOpen()
694 if (Comm::IsConnOpen(conn
))
699 tunnelDelayedClientRead(void *data
)
704 TunnelStateData
*tunnel
= static_cast<TunnelStateData
*>(data
);
705 tunnel
->client
.readPending
= NULL
;
706 static uint64_t counter
=0;
707 debugs(26, 7, "Client read(2) delayed " << ++counter
<< " times");
708 tunnel
->copyRead(tunnel
->client
, TunnelStateData::ReadClient
);
712 tunnelDelayedServerRead(void *data
)
717 TunnelStateData
*tunnel
= static_cast<TunnelStateData
*>(data
);
718 tunnel
->server
.readPending
= NULL
;
719 static uint64_t counter
=0;
720 debugs(26, 7, "Server read(2) delayed " << ++counter
<< " times");
721 tunnel
->copyRead(tunnel
->server
, TunnelStateData::ReadServer
);
725 TunnelStateData::copyRead(Connection
&from
, IOCB
*completion
)
727 assert(from
.len
== 0);
728 // If only the minimum permitted read size is going to be attempted
729 // then we schedule an event to try again in a few I/O cycles.
730 // Allow at least 1 byte to be read every (0.3*10) seconds.
731 int bw
= from
.bytesWanted(1, SQUID_TCP_SO_RCVBUF
);
732 if (bw
== 1 && ++from
.delayedLoops
< 10) {
733 from
.readPending
= this;
734 eventAdd("tunnelDelayedServerRead", from
.readPendingFunc
, from
.readPending
, 0.3, true);
738 AsyncCall::Pointer call
= commCbCall(5,4, "TunnelBlindCopyReadHandler",
739 CommIoCbPtrFun(completion
, this));
740 comm_read(from
.conn
, from
.buf
, bw
, call
);
744 TunnelStateData::readConnectResponse()
746 assert(waitingForConnectResponse());
748 AsyncCall::Pointer call
= commCbCall(5,4, "readConnectResponseDone",
749 CommIoCbPtrFun(ReadConnectResponseDone
, this));
750 comm_read(server
.conn
, connectRespBuf
->space(),
751 server
.bytesWanted(1, connectRespBuf
->spaceSize()), call
);
755 TunnelStateData::copyClientBytes()
757 if (preReadClientData
.length()) {
758 size_t copyBytes
= preReadClientData
.length() > SQUID_TCP_SO_RCVBUF
? SQUID_TCP_SO_RCVBUF
: preReadClientData
.length();
759 memcpy(client
.buf
, preReadClientData
.rawContent(), copyBytes
);
760 preReadClientData
.consume(copyBytes
);
761 client
.bytesIn(copyBytes
);
762 if (keepGoingAfterRead(copyBytes
, Comm::OK
, 0, client
, server
))
763 copy(copyBytes
, client
, server
, TunnelStateData::WriteServerDone
);
765 copyRead(client
, ReadClient
);
769 * Set the HTTP status for this request and sets the read handlers for client
770 * and server side connections.
773 tunnelStartShoveling(TunnelStateData
*tunnelState
)
775 assert(!tunnelState
->waitingForConnectExchange());
776 *tunnelState
->status_ptr
= Http::scOkay
;
777 if (tunnelState
->logTag_ptr
)
778 *tunnelState
->logTag_ptr
= LOG_TCP_TUNNEL
;
779 if (cbdataReferenceValid(tunnelState
)) {
781 // Shovel any payload already pushed into reply buffer by the server response
782 if (!tunnelState
->server
.len
)
783 tunnelState
->copyRead(tunnelState
->server
, TunnelStateData::ReadServer
);
785 debugs(26, DBG_DATA
, "Tunnel server PUSH Payload: \n" << Raw("", tunnelState
->server
.buf
, tunnelState
->server
.len
) << "\n----------");
786 tunnelState
->copy(tunnelState
->server
.len
, tunnelState
->server
, tunnelState
->client
, TunnelStateData::WriteClientDone
);
789 if (tunnelState
->http
.valid() && tunnelState
->http
->getConn() && !tunnelState
->http
->getConn()->in
.buf
.isEmpty()) {
790 struct ConnStateData::In
*in
= &tunnelState
->http
->getConn()->in
;
791 debugs(26, DBG_DATA
, "Tunnel client PUSH Payload: \n" << in
->buf
<< "\n----------");
792 tunnelState
->preReadClientData
.append(in
->buf
);
793 in
->buf
.consume(); // ConnStateData buffer accounting after the shuffle.
795 tunnelState
->copyClientBytes();
800 * All the pieces we need to write to client and/or server connection
802 * Call the tunnelStartShoveling to start the blind pump.
805 tunnelConnectedWriteDone(const Comm::ConnectionPointer
&conn
, char *, size_t, Comm::Flag flag
, int, void *data
)
807 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
808 debugs(26, 3, HERE
<< conn
<< ", flag=" << flag
);
810 if (flag
!= Comm::OK
) {
811 *tunnelState
->status_ptr
= Http::scInternalServerError
;
812 tunnelErrorComplete(conn
->fd
, data
, 0);
816 tunnelStartShoveling(tunnelState
);
819 /// Called when we are done writing CONNECT request to a peer.
821 tunnelConnectReqWriteDone(const Comm::ConnectionPointer
&conn
, char *, size_t, Comm::Flag flag
, int, void *data
)
823 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
824 debugs(26, 3, conn
<< ", flag=" << flag
);
825 assert(tunnelState
->waitingForConnectRequest());
827 if (flag
!= Comm::OK
) {
828 *tunnelState
->status_ptr
= Http::scInternalServerError
;
829 tunnelErrorComplete(conn
->fd
, data
, 0);
833 tunnelState
->connectReqWriting
= false;
834 tunnelState
->connectExchangeCheckpoint();
838 TunnelStateData::connectExchangeCheckpoint()
840 if (waitingForConnectResponse()) {
841 debugs(26, 5, "still reading CONNECT response on " << server
.conn
);
842 } else if (waitingForConnectRequest()) {
843 debugs(26, 5, "still writing CONNECT request on " << server
.conn
);
845 assert(!waitingForConnectExchange());
846 debugs(26, 3, "done with CONNECT exchange on " << server
.conn
);
847 tunnelConnected(server
.conn
, this);
852 * handle the write completion from a proxy request to an upstream origin
855 tunnelConnected(const Comm::ConnectionPointer
&server
, void *data
)
857 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
858 debugs(26, 3, HERE
<< server
<< ", tunnelState=" << tunnelState
);
860 if (!tunnelState
->clientExpectsConnectResponse())
861 tunnelStartShoveling(tunnelState
); // ssl-bumped connection, be quiet
863 AsyncCall::Pointer call
= commCbCall(5,5, "tunnelConnectedWriteDone",
864 CommIoCbPtrFun(tunnelConnectedWriteDone
, tunnelState
));
865 Comm::Write(tunnelState
->client
.conn
, conn_established
, strlen(conn_established
), call
, NULL
);
870 tunnelErrorComplete(int fd
/*const Comm::ConnectionPointer &*/, void *data
, size_t)
872 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
873 debugs(26, 3, HERE
<< "FD " << fd
);
874 assert(tunnelState
!= NULL
);
875 /* temporary lock to save our own feets (comm_close -> tunnelClientClosed -> Free) */
876 CbcPointer
<TunnelStateData
> safetyLock(tunnelState
);
878 if (Comm::IsConnOpen(tunnelState
->client
.conn
))
879 tunnelState
->client
.conn
->close();
881 if (Comm::IsConnOpen(tunnelState
->server
.conn
))
882 tunnelState
->server
.conn
->close();
886 tunnelConnectDone(const Comm::ConnectionPointer
&conn
, Comm::Flag status
, int xerrno
, void *data
)
888 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
890 if (status
!= Comm::OK
) {
891 debugs(26, 4, HERE
<< conn
<< ", comm failure recovery.");
892 /* At this point only the TCP handshake has failed. no data has been passed.
893 * we are allowed to re-try the TCP-level connection to alternate IPs for CONNECT.
895 tunnelState
->serverDestinations
.erase(tunnelState
->serverDestinations
.begin());
896 if (status
!= Comm::TIMEOUT
&& tunnelState
->serverDestinations
.size() > 0) {
897 /* Try another IP of this destination host */
898 GetMarkingsToServer(tunnelState
->request
.getRaw(), *tunnelState
->serverDestinations
[0]);
899 debugs(26, 4, HERE
<< "retry with : " << tunnelState
->serverDestinations
[0]);
900 AsyncCall::Pointer call
= commCbCall(26,3, "tunnelConnectDone", CommConnectCbPtrFun(tunnelConnectDone
, tunnelState
));
901 Comm::ConnOpener
*cs
= new Comm::ConnOpener(tunnelState
->serverDestinations
[0], call
, Config
.Timeout
.connect
);
902 cs
->setHost(tunnelState
->url
);
905 debugs(26, 4, HERE
<< "terminate with error.");
906 ErrorState
*err
= new ErrorState(ERR_CONNECT_FAIL
, Http::scServiceUnavailable
, tunnelState
->request
.getRaw());
907 *tunnelState
->status_ptr
= Http::scServiceUnavailable
;
908 err
->xerrno
= xerrno
;
909 // on timeout is this still: err->xerrno = ETIMEDOUT;
910 err
->port
= conn
->remote
.port();
911 err
->callback
= tunnelErrorComplete
;
912 err
->callback_data
= tunnelState
;
913 errorSend(tunnelState
->client
.conn
, err
);
914 if (tunnelState
->request
!= NULL
)
915 tunnelState
->request
->hier
.stopPeerClock(false);
921 /* no point using the delayIsNoDelay stuff since tunnel is nice and simple */
922 if (conn
->getPeer() && conn
->getPeer()->options
.no_delay
)
923 tunnelState
->server
.setDelayId(DelayId());
926 tunnelState
->request
->hier
.note(conn
, tunnelState
->getHost());
928 tunnelState
->server
.conn
= conn
;
929 tunnelState
->request
->peer_host
= conn
->getPeer() ? conn
->getPeer()->host
: NULL
;
930 comm_add_close_handler(conn
->fd
, tunnelServerClosed
, tunnelState
);
932 debugs(26, 4, HERE
<< "determine post-connect handling pathway.");
933 if (conn
->getPeer()) {
934 tunnelState
->request
->peer_login
= conn
->getPeer()->login
;
935 tunnelState
->request
->flags
.proxying
= !(conn
->getPeer()->options
.originserver
);
937 tunnelState
->request
->peer_login
= NULL
;
938 tunnelState
->request
->flags
.proxying
= false;
941 if (tunnelState
->request
->flags
.proxying
)
942 tunnelState
->connectToPeer();
944 tunnelConnected(conn
, tunnelState
);
947 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
948 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
949 commSetConnTimeout(conn
, Config
.Timeout
.read
, timeoutCall
);
953 tunnelStart(ClientHttpRequest
* http
, int64_t * size_ptr
, int *status_ptr
, const AccessLogEntryPointer
&al
)
956 /* Create state structure. */
957 TunnelStateData
*tunnelState
= NULL
;
958 ErrorState
*err
= NULL
;
959 HttpRequest
*request
= http
->request
;
960 char *url
= http
->uri
;
963 * client_addr.isNoAddr() indicates this is an "internal" request
964 * from peer_digest.c, asn.c, netdb.c, etc and should always
965 * be allowed. yuck, I know.
968 if (Config
.accessList
.miss
&& !request
->client_addr
.isNoAddr()) {
970 * Check if this host is allowed to fetch MISSES from us (miss_access)
971 * default is to allow.
973 ACLFilledChecklist
ch(Config
.accessList
.miss
, request
, NULL
);
974 ch
.src_addr
= request
->client_addr
;
975 ch
.my_addr
= request
->my_addr
;
976 if (ch
.fastCheck() == ACCESS_DENIED
) {
977 debugs(26, 4, HERE
<< "MISS access forbidden.");
978 err
= new ErrorState(ERR_FORWARDING_DENIED
, Http::scForbidden
, request
);
979 *status_ptr
= Http::scForbidden
;
980 errorSend(http
->getConn()->clientConnection
, err
);
985 debugs(26, 3, request
->method
<< ' ' << url
<< ' ' << request
->http_ver
);
986 ++statCounter
.server
.all
.requests
;
987 ++statCounter
.server
.other
.requests
;
989 tunnelState
= new TunnelStateData
;
991 tunnelState
->server
.setDelayId(DelayId::DelayClient(http
));
993 tunnelState
->url
= xstrdup(url
);
994 tunnelState
->request
= request
;
995 tunnelState
->server
.size_ptr
= size_ptr
;
996 tunnelState
->status_ptr
= status_ptr
;
997 tunnelState
->logTag_ptr
= &http
->logType
;
998 tunnelState
->client
.conn
= http
->getConn()->clientConnection
;
999 tunnelState
->http
= http
;
1000 tunnelState
->al
= al
;
1002 comm_add_close_handler(tunnelState
->client
.conn
->fd
,
1006 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
1007 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
1008 commSetConnTimeout(tunnelState
->client
.conn
, Config
.Timeout
.lifetime
, timeoutCall
);
1010 peerSelect(&(tunnelState
->serverDestinations
), request
, al
,
1012 tunnelPeerSelectComplete
,
1017 TunnelStateData::connectToPeer()
1020 if (CachePeer
*p
= server
.conn
->getPeer()) {
1021 if (p
->secure
.encryptTransport
) {
1022 AsyncCall::Pointer callback
= asyncCall(5,4,
1023 "TunnelStateData::ConnectedToPeer",
1024 MyAnswerDialer(&TunnelStateData::connectedToPeer
, this));
1025 Ssl::PeerConnector
*connector
=
1026 new Ssl::PeerConnector(request
, server
.conn
, client
.conn
, callback
);
1027 AsyncJob::Start(connector
); // will call our callback
1033 Security::EncryptorAnswer nil
;
1034 connectedToPeer(nil
);
1038 TunnelStateData::connectedToPeer(Security::EncryptorAnswer
&answer
)
1040 if (ErrorState
*error
= answer
.error
.get()) {
1041 *status_ptr
= error
->httpStatus
;
1042 error
->callback
= tunnelErrorComplete
;
1043 error
->callback_data
= this;
1044 errorSend(client
.conn
, error
);
1045 answer
.error
.clear(); // preserve error for errorSendComplete()
1049 tunnelRelayConnectRequest(server
.conn
, this);
1053 tunnelRelayConnectRequest(const Comm::ConnectionPointer
&srv
, void *data
)
1055 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
1056 assert(!tunnelState
->waitingForConnectExchange());
1057 HttpHeader
hdr_out(hoRequest
);
1058 HttpStateFlags flags
;
1059 debugs(26, 3, HERE
<< srv
<< ", tunnelState=" << tunnelState
);
1060 memset(&flags
, '\0', sizeof(flags
));
1061 flags
.proxying
= tunnelState
->request
->flags
.proxying
;
1064 mb
.Printf("CONNECT %s HTTP/1.1\r\n", tunnelState
->url
);
1065 HttpStateData::httpBuildRequestHeader(tunnelState
->request
.getRaw(),
1066 NULL
, /* StoreEntry */
1067 tunnelState
->al
, /* AccessLogEntry */
1070 hdr_out
.packInto(&mb
);
1072 mb
.append("\r\n", 2);
1074 debugs(11, 2, "Tunnel Server REQUEST: " << tunnelState
->server
.conn
<< ":\n----------\n" <<
1075 Raw("tunnelRelayConnectRequest", mb
.content(), mb
.contentSize()) << "\n----------");
1077 if (tunnelState
->clientExpectsConnectResponse()) {
1078 // hack: blindly tunnel peer response (to our CONNECT request) to the client as ours.
1079 AsyncCall::Pointer writeCall
= commCbCall(5,5, "tunnelConnectedWriteDone",
1080 CommIoCbPtrFun(tunnelConnectedWriteDone
, tunnelState
));
1081 Comm::Write(srv
, &mb
, writeCall
);
1083 // we have to eat the connect response from the peer (so that the client
1084 // does not see it) and only then start shoveling data to the client
1085 AsyncCall::Pointer writeCall
= commCbCall(5,5, "tunnelConnectReqWriteDone",
1086 CommIoCbPtrFun(tunnelConnectReqWriteDone
,
1088 Comm::Write(srv
, &mb
, writeCall
);
1089 tunnelState
->connectReqWriting
= true;
1091 tunnelState
->connectRespBuf
= new MemBuf
;
1092 // SQUID_TCP_SO_RCVBUF: we should not accumulate more than regular I/O buffer
1093 // can hold since any CONNECT response leftovers have to fit into server.buf.
1094 // 2*SQUID_TCP_SO_RCVBUF: HttpMsg::parse() zero-terminates, which uses space.
1095 tunnelState
->connectRespBuf
->init(SQUID_TCP_SO_RCVBUF
, 2*SQUID_TCP_SO_RCVBUF
);
1096 tunnelState
->readConnectResponse();
1098 assert(tunnelState
->waitingForConnectExchange());
1101 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
1102 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
1103 commSetConnTimeout(srv
, Config
.Timeout
.read
, timeoutCall
);
1107 tunnelPeerSelectComplete(Comm::ConnectionList
*peer_paths
, ErrorState
*err
, void *data
)
1109 TunnelStateData
*tunnelState
= (TunnelStateData
*)data
;
1111 if (peer_paths
== NULL
|| peer_paths
->size() < 1) {
1112 debugs(26, 3, HERE
<< "No paths found. Aborting CONNECT");
1114 err
= new ErrorState(ERR_CANNOT_FORWARD
, Http::scServiceUnavailable
, tunnelState
->request
.getRaw());
1116 *tunnelState
->status_ptr
= err
->httpStatus
;
1117 err
->callback
= tunnelErrorComplete
;
1118 err
->callback_data
= tunnelState
;
1119 errorSend(tunnelState
->client
.conn
, err
);
1124 GetMarkingsToServer(tunnelState
->request
.getRaw(), *tunnelState
->serverDestinations
[0]);
1126 if (tunnelState
->request
!= NULL
)
1127 tunnelState
->request
->hier
.startPeerClock();
1129 debugs(26, 3, HERE
<< "paths=" << peer_paths
->size() << ", p[0]={" << (*peer_paths
)[0] << "}, serverDest[0]={" <<
1130 tunnelState
->serverDestinations
[0] << "}");
1132 AsyncCall::Pointer call
= commCbCall(26,3, "tunnelConnectDone", CommConnectCbPtrFun(tunnelConnectDone
, tunnelState
));
1133 Comm::ConnOpener
*cs
= new Comm::ConnOpener(tunnelState
->serverDestinations
[0], call
, Config
.Timeout
.connect
);
1134 cs
->setHost(tunnelState
->url
);
1135 AsyncJob::Start(cs
);
1138 CBDATA_CLASS_INIT(TunnelStateData
);
1141 TunnelStateData::noConnections() const
1143 return !Comm::IsConnOpen(server
.conn
) && !Comm::IsConnOpen(client
.conn
);
1148 TunnelStateData::Connection::setDelayId(DelayId
const &newDelay
)
1157 switchToTunnel(HttpRequest
*request
, Comm::ConnectionPointer
&clientConn
, Comm::ConnectionPointer
&srvConn
)
1159 debugs(26,5, "Revert to tunnel FD " << clientConn
->fd
<< " with FD " << srvConn
->fd
);
1160 /* Create state structure. */
1161 TunnelStateData
*tunnelState
= NULL
;
1162 const char *url
= urlCanonical(request
);
1164 debugs(26, 3, request
->method
<< " " << url
<< " " << request
->http_ver
);
1165 ++statCounter
.server
.all
.requests
;
1166 ++statCounter
.server
.other
.requests
;
1168 tunnelState
= new TunnelStateData
;
1169 tunnelState
->url
= xstrdup(url
);
1170 tunnelState
->request
= request
;
1171 tunnelState
->server
.size_ptr
= NULL
; //Set later if ClientSocketContext is available
1173 // Temporary static variable to store the unneeded for our case status code
1174 static int status_code
= 0;
1175 tunnelState
->status_ptr
= &status_code
;
1176 tunnelState
->client
.conn
= clientConn
;
1178 ConnStateData
*conn
;
1179 if ((conn
= request
->clientConnectionManager
.get())) {
1180 ClientSocketContext::Pointer context
= conn
->getCurrentContext();
1181 if (context
!= NULL
&& context
->http
!= NULL
) {
1182 tunnelState
->logTag_ptr
= &context
->http
->logType
;
1183 tunnelState
->server
.size_ptr
= &context
->http
->out
.size
;
1186 /* no point using the delayIsNoDelay stuff since tunnel is nice and simple */
1187 if (srvConn
->getPeer() && srvConn
->getPeer()->options
.no_delay
)
1188 tunnelState
->server
.setDelayId(DelayId::DelayClient(context
->http
));
1193 comm_add_close_handler(tunnelState
->client
.conn
->fd
,
1197 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
1198 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
1199 commSetConnTimeout(tunnelState
->client
.conn
, Config
.Timeout
.lifetime
, timeoutCall
);
1200 fd_table
[clientConn
->fd
].read_method
= &default_read_method
;
1201 fd_table
[clientConn
->fd
].write_method
= &default_write_method
;
1203 tunnelState
->request
->hier
.note(srvConn
, tunnelState
->getHost());
1205 tunnelState
->server
.conn
= srvConn
;
1206 tunnelState
->request
->peer_host
= srvConn
->getPeer() ? srvConn
->getPeer()->host
: NULL
;
1207 comm_add_close_handler(srvConn
->fd
, tunnelServerClosed
, tunnelState
);
1209 debugs(26, 4, "determine post-connect handling pathway.");
1210 if (srvConn
->getPeer()) {
1211 tunnelState
->request
->peer_login
= srvConn
->getPeer()->login
;
1212 tunnelState
->request
->flags
.proxying
= !(srvConn
->getPeer()->options
.originserver
);
1214 tunnelState
->request
->peer_login
= NULL
;
1215 tunnelState
->request
->flags
.proxying
= false;
1218 timeoutCall
= commCbCall(5, 4, "tunnelTimeout",
1219 CommTimeoutCbPtrFun(tunnelTimeout
, tunnelState
));
1220 commSetConnTimeout(srvConn
, Config
.Timeout
.read
, timeoutCall
);
1221 fd_table
[srvConn
->fd
].read_method
= &default_read_method
;
1222 fd_table
[srvConn
->fd
].write_method
= &default_write_method
;
1224 SSL
*ssl
= fd_table
[srvConn
->fd
].ssl
;
1226 BIO
*b
= SSL_get_rbio(ssl
);
1227 Ssl::ServerBio
*srvBio
= static_cast<Ssl::ServerBio
*>(b
->ptr
);
1228 const MemBuf
&buf
= srvBio
->rBufData();
1230 AsyncCall::Pointer call
= commCbCall(5,5, "tunnelConnectedWriteDone",
1231 CommIoCbPtrFun(tunnelConnectedWriteDone
, tunnelState
));
1232 Comm::Write(tunnelState
->client
.conn
, buf
.content(), buf
.contentSize(), call
, NULL
);
1234 #endif //USE_OPENSSL