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 33 Client-side Routines */
12 \defgroup ClientSide Client-Side Logics
14 \section cserrors Errors and client side
16 \par Problem the first:
17 * the store entry is no longer authoritative on the
18 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
19 * of client_side_reply.c.
20 * Problem the second: resources are wasted if we delay in cleaning up.
21 * Problem the third we can't depend on a connection close to clean up.
23 \par Nice thing the first:
24 * Any step in the stream can callback with data
25 * representing an error.
26 * Nice thing the second: once you stop requesting reads from upstream,
27 * upstream can be stopped too.
30 * Error has a callback mechanism to hand over a membuf
31 * with the error content. The failing node pushes that back as the
32 * reply. Can this be generalised to reduce duplicate efforts?
33 * A: Possibly. For now, only one location uses this.
34 * How to deal with pre-stream errors?
35 * Tell client_side_reply that we *want* an error page before any
36 * stream calls occur. Then we simply read as normal.
39 \section pconn_logic Persistent connection logic:
42 * requests (httpClientRequest structs) get added to the connection
43 * list, with the current one being chr
46 * The request is *immediately* kicked off, and data flows through
47 * to clientSocketRecipient.
50 * If the data that arrives at clientSocketRecipient is not for the current
51 * request, clientSocketRecipient simply returns, without requesting more
52 * data, or sending it.
55 * ConnStateData::kick() will then detect the presence of data in
56 * the next ClientHttpRequest, and will send it, restablishing the
61 #include "acl/FilledChecklist.h"
62 #include "anyp/PortCfg.h"
63 #include "base/Subscription.h"
64 #include "base/TextException.h"
65 #include "CachePeer.h"
66 #include "client_db.h"
67 #include "client_side.h"
68 #include "client_side_reply.h"
69 #include "client_side_request.h"
70 #include "ClientRequestContext.h"
71 #include "clientStream.h"
73 #include "comm/Connection.h"
74 #include "comm/Loops.h"
75 #include "comm/Read.h"
76 #include "comm/TcpAcceptor.h"
77 #include "comm/Write.h"
78 #include "CommCalls.h"
79 #include "errorpage.h"
82 #include "fqdncache.h"
86 #include "helper/Reply.h"
88 #include "http/one/RequestParser.h"
89 #include "http/one/TeChunkedParser.h"
90 #include "http/Stream.h"
91 #include "HttpHdrContRange.h"
92 #include "HttpHeaderTools.h"
93 #include "HttpReply.h"
94 #include "HttpRequest.h"
95 #include "ident/Config.h"
96 #include "ident/Ident.h"
98 #include "ipc/FdNotes.h"
99 #include "ipc/StartListening.h"
100 #include "log/access_log.h"
102 #include "MemObject.h"
103 #include "mime_header.h"
104 #include "parser/Tokenizer.h"
105 #include "profiler/Profiler.h"
107 #include "security/NegotiationHistory.h"
108 #include "servers/forward.h"
109 #include "SquidConfig.h"
110 #include "SquidTime.h"
111 #include "StatCounters.h"
112 #include "StatHist.h"
114 #include "TimeOrTag.h"
119 #include "auth/UserRequest.h"
122 #include "ClientInfo.h"
126 #include "ssl/context_storage.h"
127 #include "ssl/gadgets.h"
128 #include "ssl/helper.h"
129 #include "ssl/ProxyCerts.h"
130 #include "ssl/ServerBump.h"
131 #include "ssl/support.h"
134 // for tvSubUsec() which should be in SquidTime.h
142 #define comm_close comm_lingering_close
145 /// dials clientListenerConnectionOpened call
146 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
149 typedef void (*Handler
)(AnyP::PortCfgPointer
&portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
150 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfgPointer
&aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
151 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
153 virtual void print(std::ostream
&os
) const {
155 ", " << FdNote(portTypeNote
) << " port=" << (void*)&portCfg
<< ')';
158 virtual bool canDial(AsyncCall
&) const { return true; }
159 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
165 AnyP::PortCfgPointer portCfg
; ///< from HttpPortList
166 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
167 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
170 static void clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
172 static IOACB httpAccept
;
174 static IOACB httpsAccept
;
176 static CTCB clientLifetimeTimeout
;
178 static IDCB clientIdentDone
;
180 static int clientIsContentLengthValid(HttpRequest
* r
);
181 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
183 static void clientUpdateStatHistCounters(const LogTags
&logType
, int svc_time
);
184 static void clientUpdateStatCounters(const LogTags
&logType
);
185 static void clientUpdateHierCounters(HierarchyLogEntry
*);
186 static bool clientPingHasFinished(ping_data
const *aPing
);
187 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
188 static void ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest
, ConnStateData
* conn
);
190 char *skipLeadingSpace(char *aString
);
194 clientIdentDone(const char *ident
, void *data
)
196 ConnStateData
*conn
= (ConnStateData
*)data
;
197 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
202 clientUpdateStatCounters(const LogTags
&logType
)
204 ++statCounter
.client_http
.requests
;
206 if (logType
.isTcpHit())
207 ++statCounter
.client_http
.hits
;
209 if (logType
.oldType
== LOG_TCP_HIT
)
210 ++statCounter
.client_http
.disk_hits
;
211 else if (logType
.oldType
== LOG_TCP_MEM_HIT
)
212 ++statCounter
.client_http
.mem_hits
;
216 clientUpdateStatHistCounters(const LogTags
&logType
, int svc_time
)
218 statCounter
.client_http
.allSvcTime
.count(svc_time
);
220 * The idea here is not to be complete, but to get service times
221 * for only well-defined types. For example, we don't include
222 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
223 * (we *tried* to validate it, but failed).
226 switch (logType
.oldType
) {
228 case LOG_TCP_REFRESH_UNMODIFIED
:
229 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
232 case LOG_TCP_IMS_HIT
:
233 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
238 case LOG_TCP_MEM_HIT
:
240 case LOG_TCP_OFFLINE_HIT
:
241 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
246 case LOG_TCP_CLIENT_REFRESH_MISS
:
247 statCounter
.client_http
.missSvcTime
.count(svc_time
);
251 /* make compiler warnings go away */
257 clientPingHasFinished(ping_data
const *aPing
)
259 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
266 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
270 switch (someEntry
->code
) {
271 #if USE_CACHE_DIGESTS
276 ++ statCounter
.cd
.times_used
;
284 case FIRST_PARENT_MISS
:
286 case CLOSEST_PARENT_MISS
:
287 ++ statCounter
.icp
.times_used
;
288 i
= &someEntry
->ping
;
290 if (clientPingHasFinished(i
))
291 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
294 ++ statCounter
.icp
.query_timeouts
;
301 ++ statCounter
.netdb
.times_used
;
311 ClientHttpRequest::updateCounters()
313 clientUpdateStatCounters(logType
);
315 if (request
->errType
!= ERR_NONE
)
316 ++ statCounter
.client_http
.errors
;
318 clientUpdateStatHistCounters(logType
,
319 tvSubMsec(al
->cache
.start_time
, current_time
));
321 clientUpdateHierCounters(&request
->hier
);
325 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
328 assert(aLogEntry
!= NULL
);
330 if (Config
.onoff
.log_mime_hdrs
) {
333 request
->header
.packInto(&mb
);
334 //This is the request after adaptation or redirection
335 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
337 // the virgin request is saved to aLogEntry->request
338 if (aLogEntry
->request
) {
340 aLogEntry
->request
->header
.packInto(&mb
);
341 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
345 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
348 ah
->lastMeta
.packInto(&mb
);
349 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
357 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
359 ih
->processingTime(aLogEntry
->icap
.processingTime
);
362 aLogEntry
->http
.method
= request
->method
;
363 aLogEntry
->http
.version
= request
->http_ver
;
364 aLogEntry
->hier
= request
->hier
;
365 if (request
->content_length
> 0) // negative when no body or unknown length
366 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
367 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
369 // Adapted request, if any, inherits and then collects all the stats, but
370 // the virgin request gets logged instead; copy the stats to log them.
371 // TODO: avoid losses by keeping these stats in a shared history object?
372 if (aLogEntry
->request
) {
373 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
374 aLogEntry
->request
->errType
= request
->errType
;
375 aLogEntry
->request
->errDetail
= request
->errDetail
;
380 ClientHttpRequest::logRequest()
382 if (!out
.size
&& logType
.oldType
== LOG_TAG_NONE
)
383 debugs(33, 5, "logging half-baked transaction: " << log_uri
);
385 al
->icp
.opcode
= ICP_INVALID
;
387 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
390 al
->http
.code
= al
->reply
->sline
.status();
391 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
392 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
393 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
394 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
397 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
399 if (loggingEntry() && loggingEntry()->mem_obj
&& loggingEntry()->objectLen() >= 0)
400 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
402 al
->http
.clientRequestSz
.header
= req_sz
;
403 al
->http
.clientReplySz
.header
= out
.headers_sz
;
404 // XXX: calculate without payload encoding or headers !!
405 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
407 al
->cache
.highOffset
= out
.offset
;
409 al
->cache
.code
= logType
;
411 tvSub(al
->cache
.trTime
, al
->cache
.start_time
, current_time
);
414 prepareLogWithRequestDetails(request
, al
);
416 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
417 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
421 /* This is broken. Fails if the connection has been closed. Needs
422 * to snarf the ssl details some place earlier..
424 if (getConn() != NULL
)
425 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
429 /* Add notes (if we have a request to annotate) */
431 // The al->notes and request->notes must point to the same object.
432 (void)SyncNotes(*al
, *request
);
433 for (auto i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
434 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
435 NotePairs
¬es
= SyncNotes(*al
, *request
);
436 notes
.add((*i
)->key
.termedBuf(), value
);
437 debugs(33, 3, (*i
)->key
.termedBuf() << " " << value
);
442 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
444 checklist
.reply
= al
->reply
;
445 HTTPMSGLOCK(checklist
.reply
);
449 HTTPMSGUNLOCK(al
->adapted_request
);
450 al
->adapted_request
= request
;
451 HTTPMSGLOCK(al
->adapted_request
);
453 accessLogLog(al
, &checklist
);
455 bool updatePerformanceCounters
= true;
456 if (Config
.accessList
.stats_collection
) {
457 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
459 statsCheck
.reply
= al
->reply
;
460 HTTPMSGLOCK(statsCheck
.reply
);
462 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
465 if (updatePerformanceCounters
) {
469 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
470 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
475 ClientHttpRequest::freeResources()
479 safe_free(redirect
.location
);
480 range_iter
.boundary
.clean();
481 HTTPMSGUNLOCK(request
);
483 if (client_stream
.tail
)
484 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
488 httpRequestFree(void *data
)
490 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
491 assert(http
!= NULL
);
495 /* This is a handler normally called by comm_close() */
496 void ConnStateData::connStateClosed(const CommCloseCbParams
&)
498 deleteThis("ConnStateData::connStateClosed");
503 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
507 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
513 // clobered with self-pointer
514 // NP: something nasty is going on in Squid, but harmless.
516 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
521 * Connection-auth relies on a single set of credentials being preserved
522 * for all requests on a connection once they have been setup.
523 * There are several things which need to happen to preserve security
524 * when connection-auth credentials change unexpectedly or are unset.
526 * 1) auth helper released from any active state
528 * They can only be reserved by a handshake process which this
529 * connection can now never complete.
530 * This prevents helpers hanging when their connections close.
532 * 2) pinning is expected to be removed and server conn closed
534 * The upstream link is authenticated with the same credentials.
535 * Expecting the same level of consistency we should have received.
536 * This prevents upstream being faced with multiple or missing
537 * credentials after authentication.
538 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
539 * we just trigger that cleanup here via comm_reset_close() or
540 * ConnStateData::stopReceiving()
542 * 3) the connection needs to close.
544 * This prevents attackers injecting requests into a connection,
545 * or gateways wrongly multiplexing users into a single connection.
547 * When credentials are missing closure needs to follow an auth
548 * challenge for best recovery by the client.
550 * When credentials change there is nothing we can do but abort as
551 * fast as possible. Sending TCP RST instead of an HTTP response
552 * is the best-case action.
555 // clobbered with nul-pointer
557 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
558 auth_
->releaseAuthServer();
560 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
561 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
562 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
563 stopReceiving("connection-auth removed");
567 // clobbered with alternative credentials
569 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
570 auth_
->releaseAuthServer();
572 // this is a fatal type of problem.
573 // Close the connection immediately with TCP RST to abort all traffic flow
574 comm_reset_close(clientConnection
);
582 // cleans up before destructor is called
584 ConnStateData::swanSong()
586 debugs(33, 2, HERE
<< clientConnection
);
587 flags
.readMore
= false;
588 DeregisterRunner(this);
589 if (clientConnection
!= NULL
)
590 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
591 pipeline
.terminateAll(0);
593 unpinConnection(true);
595 Server::swanSong(); // closes the client connection
598 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
599 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
602 flags
.swanSang
= true;
606 ConnStateData::isOpen() const
608 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
609 Comm::IsConnOpen(clientConnection
) &&
610 !fd_table
[clientConnection
->fd
].closing();
613 ConnStateData::~ConnStateData()
615 debugs(33, 3, HERE
<< clientConnection
);
618 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
621 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
623 if (bodyPipe
!= NULL
)
624 stopProducingFor(bodyPipe
, false);
626 delete bodyParser
; // TODO: pool
629 delete sslServerBump
;
634 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
635 * This is the client-side persistent connection flag. We need
636 * to set this relatively early in the request processing
637 * to handle hacks for broken servers and clients.
640 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
642 HttpRequest
*request
= http
->request
;
644 debugs(33, 3, "http_ver = " << request
->http_ver
);
645 debugs(33, 3, "method = " << request
->method
);
647 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
648 request
->flags
.proxyKeepalive
= request
->persistent();
651 /// checks body length of non-chunked requests
653 clientIsContentLengthValid(HttpRequest
* r
)
655 // No Content-Length means this request just has no body, but conflicting
656 // Content-Lengths mean a message framing error (RFC 7230 Section 3.3.3 #4).
657 if (r
->header
.conflictingContentLength())
660 switch (r
->method
.id()) {
662 case Http::METHOD_GET
:
664 case Http::METHOD_HEAD
:
665 /* We do not want to see a request entity on GET/HEAD requests */
666 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
669 /* For other types of requests we don't care */
677 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
679 if (Config
.maxRequestBodySize
&&
680 bodyLength
> Config
.maxRequestBodySize
)
681 return 1; /* too large */
687 ClientHttpRequest::multipartRangeRequest() const
689 return request
->multipartRangeRequest();
693 clientPackTermBound(String boundary
, MemBuf
*mb
)
695 mb
->appendf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
696 debugs(33, 6, "buf offset: " << mb
->size
);
700 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
702 HttpHeader
hdr(hoReply
);
707 debugs(33, 5, "appending boundary: " << boundary
);
708 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
709 mb
->appendf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
711 /* stuff the header with required entries and pack it */
713 if (rep
->header
.has(Http::HdrType::CONTENT_TYPE
))
714 hdr
.putStr(Http::HdrType::CONTENT_TYPE
, rep
->header
.getStr(Http::HdrType::CONTENT_TYPE
));
716 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
721 /* append <crlf> (we packed a header, not a reply) */
722 mb
->append("\r\n", 2);
725 /** returns expected content length for multi-range replies
726 * note: assumes that httpHdrRangeCanonize has already been called
727 * warning: assumes that HTTP headers for individual ranges at the
728 * time of the actuall assembly will be exactly the same as
729 * the headers when clientMRangeCLen() is called */
731 ClientHttpRequest::mRangeCLen()
739 HttpHdrRange::iterator pos
= request
->range
->begin();
741 while (pos
!= request
->range
->end()) {
742 /* account for headers for this range */
744 clientPackRangeHdr(memObject()->getReply(),
745 *pos
, range_iter
.boundary
, &mb
);
748 /* account for range content */
749 clen
+= (*pos
)->length
;
751 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
755 /* account for the terminating boundary */
758 clientPackTermBound(range_iter
.boundary
, &mb
);
768 * generates a "unique" boundary string for multipart responses
769 * the caller is responsible for cleaning the string */
771 ClientHttpRequest::rangeBoundaryStr() const
774 String
b(APP_FULLNAME
);
776 key
= storeEntry()->getMD5Text();
777 b
.append(key
, strlen(key
));
782 * Write a chunk of data to a client socket. If the reply is present,
783 * send the reply headers down the wire too, and clean them up when
786 * The request is one backed by a connection, not an internal request.
787 * data context is not NULL
788 * There are no more entries in the stream chain.
791 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
792 HttpReply
* rep
, StoreIOBuffer receivedData
)
794 // dont tryt to deliver if client already ABORTED
795 if (!http
->getConn() || !cbdataReferenceValid(http
->getConn()))
798 // If it is not connectionless and connection is closed return
799 if (!http
->getConn()->connectionless() && !Comm::IsConnOpen(http
->getConn()->clientConnection
))
803 /* Test preconditions */
804 assert(node
!= NULL
);
805 PROF_start(clientSocketRecipient
);
806 /* TODO: handle this rather than asserting
807 * - it should only ever happen if we cause an abort and
808 * the callback chain loops back to here, so we can simply return.
809 * However, that itself shouldn't happen, so it stays as an assert for now.
811 assert(cbdataReferenceValid(node
));
812 assert(node
->node
.next
== NULL
);
813 Http::StreamPointer context
= dynamic_cast<Http::Stream
*>(node
->data
.getRaw());
814 assert(context
!= NULL
);
816 /* TODO: check offset is what we asked for */
818 // TODO: enforces HTTP/1 MUST on pipeline order, but is irrelevant to HTTP/2
819 if (context
!= http
->getConn()->pipeline
.front())
820 context
->deferRecipientForLater(node
, rep
, receivedData
);
822 http
->getConn()->handleReply(rep
, receivedData
);
824 PROF_stop(clientSocketRecipient
);
828 * Called when a downstream node is no longer interested in
829 * our data. As we are a terminal node, this means on aborts
833 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
835 /* Test preconditions */
836 assert(node
!= NULL
);
837 /* TODO: handle this rather than asserting
838 * - it should only ever happen if we cause an abort and
839 * the callback chain loops back to here, so we can simply return.
840 * However, that itself shouldn't happen, so it stays as an assert for now.
842 assert(cbdataReferenceValid(node
));
843 /* Set null by ContextFree */
844 assert(node
->node
.next
== NULL
);
845 /* this is the assert discussed above */
846 assert(NULL
== dynamic_cast<Http::Stream
*>(node
->data
.getRaw()));
847 /* We are only called when the client socket shutsdown.
848 * Tell the prev pipeline member we're finished
850 clientStreamDetach(node
, http
);
854 ConnStateData::readNextRequest()
856 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
858 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
860 * Set the timeout BEFORE calling readSomeData().
862 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
863 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
864 TimeoutDialer
, this, ConnStateData::requestTimeout
);
865 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
868 /** Please don't do anything with the FD past here! */
872 ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest
, ConnStateData
* conn
)
874 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
876 /** If the client stream is waiting on a socket write to occur, then */
878 if (deferredRequest
->flags
.deferred
) {
879 /** NO data is allowed to have been sent. */
880 assert(deferredRequest
->http
->out
.size
== 0);
882 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
883 deferredRequest
->http
,
884 deferredRequest
->deferredparams
.rep
,
885 deferredRequest
->deferredparams
.queuedBuffer
);
888 /** otherwise, the request is still active in a callbacksomewhere,
894 ConnStateData::kick()
896 if (!Comm::IsConnOpen(clientConnection
)) {
897 debugs(33, 2, clientConnection
<< " Connection was closed");
901 if (pinning
.pinned
&& !Comm::IsConnOpen(pinning
.serverConnection
)) {
902 debugs(33, 2, clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
903 clientConnection
->close();
908 * We are done with the response, and we are either still receiving request
909 * body (early response!) or have already stopped receiving anything.
911 * If we are still receiving, then clientParseRequest() below will fail.
912 * (XXX: but then we will call readNextRequest() which may succeed and
913 * execute a smuggled request as we are not done with the current request).
915 * If we stopped because we got everything, then try the next request.
917 * If we stopped receiving because of an error, then close now to avoid
918 * getting stuck and to prevent accidental request smuggling.
921 if (const char *reason
= stoppedReceiving()) {
922 debugs(33, 3, "closing for earlier request error: " << reason
);
923 clientConnection
->close();
928 * Attempt to parse a request from the request buffer.
929 * If we've been fed a pipelined request it may already
930 * be in our read buffer.
933 * This needs to fall through - if we're unlucky and parse the _last_ request
934 * from our read buffer we may never re-register for another client read.
937 if (clientParseRequests()) {
938 debugs(33, 3, clientConnection
<< ": parsed next request from buffer");
942 * Either we need to kick-start another read or, if we have
943 * a half-closed connection, kill it after the last request.
944 * This saves waiting for half-closed connections to finished being
945 * half-closed _AND_ then, sometimes, spending "Timeout" time in
946 * the keepalive "Waiting for next request" state.
948 if (commIsHalfClosed(clientConnection
->fd
) && pipeline
.empty()) {
949 debugs(33, 3, "half-closed client with no pending requests, closing");
950 clientConnection
->close();
955 * At this point we either have a parsed request (which we've
956 * kicked off the processing for) or not. If we have a deferred
957 * request (parsed but deferred for pipeling processing reasons)
958 * then look at processing it. If not, simply kickstart
961 Http::StreamPointer deferredRequest
= pipeline
.front();
962 if (deferredRequest
!= nullptr) {
963 debugs(33, 3, clientConnection
<< ": calling PushDeferredIfNeeded");
964 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, this);
965 } else if (flags
.readMore
) {
966 debugs(33, 3, clientConnection
<< ": calling readNextRequest()");
969 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
970 debugs(33, DBG_IMPORTANT
, MYNAME
<< "abandoning " << clientConnection
);
975 ConnStateData::stopSending(const char *error
)
977 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
978 "; old receiving error: " <<
979 (stoppedReceiving() ? stoppedReceiving_
: "none"));
981 if (const char *oldError
= stoppedSending()) {
982 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
983 return; // nothing has changed as far as this connection is concerned
985 stoppedSending_
= error
;
987 if (!stoppedReceiving()) {
988 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
989 debugs(33, 5, HERE
<< "must still read " << expecting
<<
990 " request body bytes with " << inBuf
.length() << " unused");
991 return; // wait for the request receiver to finish reading
995 clientConnection
->close();
999 ConnStateData::afterClientWrite(size_t size
)
1001 if (pipeline
.empty())
1004 auto ctx
= pipeline
.front();
1006 statCounter
.client_http
.kbytes_out
+= size
;
1007 if (ctx
->http
->logType
.isTcpHit())
1008 statCounter
.client_http
.hit_kbytes_out
+= size
;
1010 ctx
->writeComplete(size
);
1014 ConnStateData::abortRequestParsing(const char *const uri
)
1016 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1017 http
->req_sz
= inBuf
.length();
1018 http
->uri
= xstrdup(uri
);
1019 setLogUri (http
, uri
);
1020 auto *context
= new Http::Stream(clientConnection
, http
);
1021 StoreIOBuffer tempBuffer
;
1022 tempBuffer
.data
= context
->reqbuf
;
1023 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1024 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1025 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1026 clientSocketDetach
, context
, tempBuffer
);
1031 ConnStateData::startShutdown()
1033 // RegisteredRunner API callback - Squid has been shut down
1035 // if connection is idle terminate it now,
1036 // otherwise wait for grace period to end
1037 if (pipeline
.empty())
1042 ConnStateData::endingShutdown()
1044 // RegisteredRunner API callback - Squid shutdown grace period is over
1046 // force the client connection to close immediately
1047 // swanSong() in the close handler will cleanup.
1048 if (Comm::IsConnOpen(clientConnection
))
1049 clientConnection
->close();
1051 // deregister now to ensure finalShutdown() does not kill us prematurely.
1052 // fd_table purge will cleanup if close handler was not fast enough.
1053 DeregisterRunner(this);
1057 skipLeadingSpace(char *aString
)
1059 char *result
= aString
;
1061 while (xisspace(*aString
))
1068 * 'end' defaults to NULL for backwards compatibility
1069 * remove default value if we ever get rid of NULL-terminated
1073 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1076 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1080 for (; end
> uriAndHTTPVersion
; --end
) {
1081 if (*end
== '\n' || *end
== '\r')
1084 if (xisspace(*end
)) {
1085 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1096 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1098 safe_free(http
->log_uri
);
1101 // The uri is already clean just dump it.
1102 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1105 switch (Config
.uri_whitespace
) {
1106 case URI_WHITESPACE_ALLOW
:
1107 flags
|= RFC1738_ESCAPE_NOSPACE
;
1109 case URI_WHITESPACE_ENCODE
:
1110 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1111 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1114 case URI_WHITESPACE_CHOP
: {
1115 flags
|= RFC1738_ESCAPE_NOSPACE
;
1116 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1117 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1118 int pos
= strcspn(http
->log_uri
, w_space
);
1119 http
->log_uri
[pos
] = '\0';
1123 case URI_WHITESPACE_DENY
:
1124 case URI_WHITESPACE_STRIP
:
1127 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1131 if (!xisspace(*t
)) {
1138 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
1147 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1149 int vhost
= conn
->port
->vhost
;
1150 int vport
= conn
->port
->vport
;
1151 static char ipbuf
[MAX_IPSTRLEN
];
1153 http
->flags
.accel
= true;
1155 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1157 static const SBuf
cache_object("cache_object://");
1158 if (hp
->requestUri().startsWith(cache_object
))
1159 return; /* already in good shape */
1161 // XXX: re-use proper URL parser for this
1162 SBuf url
= hp
->requestUri(); // use full provided URI if we abort
1163 do { // use a loop so we can break out of it
1164 ::Parser::Tokenizer
tok(url
);
1165 if (tok
.skip('/')) // origin-form URL already.
1168 if (conn
->port
->vhost
)
1169 return; /* already in good shape */
1171 // skip the URI scheme
1172 static const CharacterSet uriScheme
= CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1173 static const SBuf
uriSchemeEnd("://");
1174 if (!tok
.skipAll(uriScheme
) || !tok
.skip(uriSchemeEnd
))
1177 // skip the authority segment
1178 // RFC 3986 complex nested ABNF for "authority" boils down to this:
1179 static const CharacterSet authority
= CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
1180 CharacterSet::HEXDIG
+ CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1181 if (!tok
.skipAll(authority
))
1184 static const SBuf
slashUri("/");
1185 const SBuf t
= tok
.remaining();
1188 else if (t
[0]=='/') // looks like path
1190 else if (t
[0]=='?' || t
[0]=='#') { // looks like query or fragment. fix '/'
1193 } // else do nothing. invalid path
1197 #if SHOULD_REJECT_UNKNOWN_URLS
1198 // reject URI which are not well-formed even after the processing above
1199 if (url
.isEmpty() || url
[0] != '/') {
1200 hp
->parseStatusCode
= Http::scBadRequest
;
1201 return conn
->abortRequestParsing("error:invalid-request");
1206 vport
= http
->getConn()->clientConnection
->local
.port();
1208 const bool switchedToHttps
= conn
->switchedToHttps();
1209 const bool tryHostHeader
= vhost
|| switchedToHttps
;
1211 if (tryHostHeader
&& (host
= hp
->getHeaderField("Host"))) {
1212 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
1217 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
1218 strncpy(thost
, host
, (t
-host
));
1219 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
1222 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
1225 } // else nothing to alter port-wise.
1226 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+ strlen(host
);
1227 http
->uri
= (char *)xcalloc(url_sz
, 1);
1228 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
, AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(url
));
1229 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
1230 } else if (conn
->port
->defaultsite
/* && !vhost */) {
1231 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
1232 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1233 strlen(conn
->port
->defaultsite
);
1234 http
->uri
= (char *)xcalloc(url_sz
, 1);
1238 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
1240 snprintf(http
->uri
, url_sz
, "%s://%s%s" SQUIDSBUFPH
,
1241 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
1242 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
1243 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
1244 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
1245 /* Put the local socket IP address as the hostname, with whatever vport we found */
1246 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1247 http
->uri
= (char *)xcalloc(url_sz
, 1);
1248 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1249 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
1250 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(),
1251 ipbuf
, vport
, SQUIDSBUFPRINT(url
));
1252 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
1257 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1259 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
1260 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
1261 return; /* already in good shape */
1263 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1265 if (const char *host
= hp
->getHeaderField("Host")) {
1266 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1268 http
->uri
= (char *)xcalloc(url_sz
, 1);
1269 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
,
1270 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(hp
->requestUri()));
1271 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
1273 /* Put the local socket IP address as the hostname. */
1274 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1275 http
->uri
= (char *)xcalloc(url_sz
, 1);
1276 static char ipbuf
[MAX_IPSTRLEN
];
1277 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1278 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
1279 AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).c_str(),
1280 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SQUIDSBUFPRINT(hp
->requestUri()));
1281 debugs(33, 5, "TRANSPARENT REWRITE: " << http
->uri
);
1285 /** Parse an HTTP request
1287 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
1288 * to 1 if the request was correctly parsed.
1289 * \param[in] csd a ConnStateData. The caller must make sure it is not null
1290 * \param[in] hp an Http1::RequestParser
1291 * \param[out] mehtod_p will be set as a side-effect of the parsing.
1292 * Pointed-to value will be set to Http::METHOD_NONE in case of
1294 * \param[out] http_ver will be set as a side-effect of the parsing
1295 * \return NULL on incomplete requests,
1296 * a Http::Stream on success or failure.
1299 parseHttpRequest(ConnStateData
*csd
, const Http1::RequestParserPointer
&hp
)
1301 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
1303 const bool parsedOk
= hp
->parse(csd
->inBuf
);
1305 if (csd
->port
->flags
.isIntercepted() && Config
.accessList
.on_unsupported_protocol
)
1306 csd
->preservedClientData
= csd
->inBuf
;
1307 // sync the buffers after parsing.
1308 csd
->inBuf
= hp
->remaining();
1310 if (hp
->needsMoreData()) {
1311 debugs(33, 5, "Incomplete request, waiting for end of request line");
1316 if (hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
|| hp
->parseStatusCode
== Http::scUriTooLong
)
1317 return csd
->abortRequestParsing("error:request-too-large");
1319 return csd
->abortRequestParsing("error:invalid-request");
1323 /* We know the whole request is in parser now */
1324 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
1325 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
1326 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
1330 /* deny CONNECT via accelerated ports */
1331 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
1332 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
1333 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1334 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1335 return csd
->abortRequestParsing("error:method-not-allowed");
1338 /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific
1339 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
1340 * If seen it signals a broken client or proxy has corrupted the traffic.
1342 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
1343 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
1344 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1345 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1346 return csd
->abortRequestParsing("error:method-not-allowed");
1349 if (hp
->method() == Http::METHOD_NONE
) {
1350 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1351 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1352 return csd
->abortRequestParsing("error:unsupported-request-method");
1355 // Process headers after request line
1356 debugs(33, 3, "complete request received. " <<
1357 "prefix_sz = " << hp
->messageHeaderSize() <<
1358 ", request-line-size=" << hp
->firstLineSize() <<
1359 ", mime-header-size=" << hp
->headerBlockSize() <<
1360 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
1362 /* Ok, all headers are received */
1363 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
1365 http
->req_sz
= hp
->messageHeaderSize();
1366 Http::Stream
*result
= new Http::Stream(csd
->clientConnection
, http
);
1368 StoreIOBuffer tempBuffer
;
1369 tempBuffer
.data
= result
->reqbuf
;
1370 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1372 ClientStreamData newServer
= new clientReplyContext(http
);
1373 ClientStreamData newClient
= result
;
1374 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1375 clientReplyStatus
, newServer
, clientSocketRecipient
,
1376 clientSocketDetach
, newClient
, tempBuffer
);
1379 debugs(33,5, "Prepare absolute URL from " <<
1380 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
1381 /* Rewrite the URL in transparent or accelerator mode */
1382 /* NP: there are several cases to traverse here:
1383 * - standard mode (forward proxy)
1384 * - transparent mode (TPROXY)
1385 * - transparent mode with failures
1386 * - intercept mode (NAT)
1387 * - intercept mode with failures
1388 * - accelerator mode (reverse proxy)
1389 * - internal relative-URL
1390 * - mixed combos of the above with internal URL
1391 * - remote interception with PROXY protocol
1392 * - remote reverse-proxy with PROXY protocol
1394 if (csd
->transparent()) {
1395 /* intercept or transparent mode, properly working with no failures */
1396 prepareTransparentURL(csd
, http
, hp
);
1398 } else if (internalCheck(hp
->requestUri())) { // NP: only matches relative-URI
1399 /* internal URL mode */
1400 /* prepend our name & port */
1401 http
->uri
= xstrdup(internalLocalUri(NULL
, hp
->requestUri()));
1402 // We just re-wrote the URL. Must replace the Host: header.
1403 // But have not parsed there yet!! flag for local-only handling.
1404 http
->flags
.internal
= true;
1406 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
1407 /* accelerator mode */
1408 prepareAcceleratedURL(csd
, http
, hp
);
1412 /* No special rewrites have been applied above, use the
1413 * requested url. may be rewritten later, so make extra room */
1414 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
1415 http
->uri
= (char *)xcalloc(url_sz
, 1);
1416 SBufToCstring(http
->uri
, hp
->requestUri());
1419 result
->flags
.parsed_ok
= 1;
1424 ConnStateData::connFinishedWithConn(int size
)
1427 if (pipeline
.empty() && inBuf
.isEmpty()) {
1428 /* no current or pending requests */
1429 debugs(33, 4, HERE
<< clientConnection
<< " closed");
1431 } else if (!Config
.onoff
.half_closed_clients
) {
1432 /* admin doesn't want to support half-closed client sockets */
1433 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
1434 pipeline
.terminateAll(0);
1443 ConnStateData::consumeInput(const size_t byteCount
)
1445 assert(byteCount
> 0 && byteCount
<= inBuf
.length());
1446 inBuf
.consume(byteCount
);
1447 debugs(33, 5, "inBuf has " << inBuf
.length() << " unused bytes");
1451 ConnStateData::clientAfterReadingRequests()
1453 // Were we expecting to read more request body from half-closed connection?
1454 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
1455 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
1456 clientConnection
->close();
1465 ConnStateData::quitAfterError(HttpRequest
*request
)
1467 // From HTTP p.o.v., we do not have to close after every error detected
1468 // at the client-side, but many such errors do require closure and the
1469 // client-side code is bad at handling errors so we play it safe.
1471 request
->flags
.proxyKeepalive
= false;
1472 flags
.readMore
= false;
1473 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
1477 bool ConnStateData::serveDelayedError(Http::Stream
*context
)
1479 ClientHttpRequest
*http
= context
->http
;
1484 assert(sslServerBump
->entry
);
1485 // Did we create an error entry while processing CONNECT?
1486 if (!sslServerBump
->entry
->isEmpty()) {
1487 quitAfterError(http
->request
);
1489 // Get the saved error entry and send it to the client by replacing the
1490 // ClientHttpRequest store entry with it.
1491 clientStreamNode
*node
= context
->getClientReplyContext();
1492 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1494 debugs(33, 5, "Responding with delated error for " << http
->uri
);
1495 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
1497 // save the original request for logging purposes
1498 if (!context
->http
->al
->request
) {
1499 context
->http
->al
->request
= http
->request
;
1500 HTTPMSGLOCK(context
->http
->al
->request
);
1503 // Get error details from the fake certificate-peeking request.
1504 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
1505 context
->pullData();
1509 // In bump-server-first mode, we have not necessarily seen the intended
1510 // server name at certificate-peeking time. Check for domain mismatch now,
1511 // when we can extract the intended name from the bumped HTTP request.
1512 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
1513 HttpRequest
*request
= http
->request
;
1514 if (!Ssl::checkX509ServerValidity(srvCert
, request
->url
.host())) {
1515 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
1516 "does not match domainname " << request
->url
.host());
1518 bool allowDomainMismatch
= false;
1519 if (Config
.ssl_client
.cert_error
) {
1520 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
1521 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
1522 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
1523 delete check
.sslErrors
;
1524 check
.sslErrors
= NULL
;
1527 if (!allowDomainMismatch
) {
1528 quitAfterError(request
);
1530 clientStreamNode
*node
= context
->getClientReplyContext();
1531 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1532 assert (repContext
);
1534 // Fill the server IP and hostname for error page generation.
1535 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
1536 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->url
.host());
1538 // Create an error object and fill it
1539 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
1540 err
->src_addr
= clientConnection
->remote
;
1541 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
1542 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
1544 err
->detail
= errDetail
;
1545 // Save the original request for logging purposes.
1546 if (!context
->http
->al
->request
) {
1547 context
->http
->al
->request
= request
;
1548 HTTPMSGLOCK(context
->http
->al
->request
);
1550 repContext
->setReplyToError(request
->method
, err
);
1551 assert(context
->http
->out
.offset
== 0);
1552 context
->pullData();
1560 #endif // USE_OPENSSL
1563 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
1564 * or false otherwise
1567 clientTunnelOnError(ConnStateData
*conn
, Http::Stream
*context
, HttpRequest
*request
, const HttpRequestMethod
& method
, err_type requestError
, Http::StatusCode errStatusCode
, const char *requestErrorBytes
)
1569 if (conn
->port
->flags
.isIntercepted() &&
1570 Config
.accessList
.on_unsupported_protocol
&& conn
->pipeline
.nrequests
<= 1) {
1571 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
, NULL
);
1572 checklist
.requestErrorType
= requestError
;
1573 checklist
.src_addr
= conn
->clientConnection
->remote
;
1574 checklist
.my_addr
= conn
->clientConnection
->local
;
1575 checklist
.conn(conn
);
1576 allow_t answer
= checklist
.fastCheck();
1577 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
1578 debugs(33, 3, "Request will be tunneled to server");
1580 // XXX: Either the context is finished() or it should stay queued.
1581 // The below may leak client streams BodyPipe objects. BUT, we need
1582 // to check if client-streams detatch is safe to do here (finished() will detatch).
1583 assert(conn
->pipeline
.front() == context
); // XXX: still assumes HTTP/1 semantics
1584 conn
->pipeline
.popMe(Http::StreamPointer(context
));
1586 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
1587 conn
->fakeAConnectRequest("unknown-protocol", conn
->preservedClientData
);
1590 debugs(33, 3, "Continue with returning the error: " << requestError
);
1595 conn
->quitAfterError(request
);
1596 clientStreamNode
*node
= context
->getClientReplyContext();
1597 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1598 assert (repContext
);
1600 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
1602 assert(context
->http
->out
.offset
== 0);
1603 context
->pullData();
1604 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
1609 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
1613 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
1614 * to here because calling comm_reset_close() causes http to
1615 * be freed before accessing.
1617 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
1618 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
1619 conn
->flags
.readMore
= false;
1620 comm_reset_close(conn
->clientConnection
);
1625 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, Http::Stream
*context
)
1627 ClientHttpRequest
*http
= context
->http
;
1628 bool chunked
= false;
1629 bool mustReplyToOptions
= false;
1630 bool unsupportedTe
= false;
1631 bool expectBody
= false;
1633 // We already have the request parsed and checked, so we
1634 // only need to go through the final body/conn setup to doCallouts().
1635 assert(http
->request
);
1636 HttpRequest::Pointer request
= http
->request
;
1638 // temporary hack to avoid splitting this huge function with sensitive code
1639 const bool isFtp
= !hp
;
1641 // Some blobs below are still HTTP-specific, but we would have to rewrite
1642 // this entire function to remove them from the FTP code path. Connection
1643 // setup and body_pipe preparation blobs are needed for FTP.
1645 request
->clientConnectionManager
= conn
;
1647 request
->flags
.accelerated
= http
->flags
.accel
;
1648 request
->flags
.sslBumped
=conn
->switchedToHttps();
1649 if (!conn
->connectionless()) {
1650 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
1651 // TODO: decouple http->flags.accel from request->flags.sslBumped
1652 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
1653 !conn
->port
->allow_direct
: 0;
1654 request
->sources
|= isFtp
? HttpMsg::srcFtp
:
1655 ((request
->flags
.sslBumped
|| conn
->port
->transport
.protocol
== AnyP::PROTO_HTTPS
) ? HttpMsg::srcHttps
: HttpMsg::srcHttp
);
1658 if (request
->flags
.sslBumped
) {
1659 if (conn
->getAuth() != NULL
)
1660 request
->auth_user_request
= conn
->getAuth();
1665 * If transparent or interception mode is working clone the transparent and interception flags
1666 * from the port settings to the request.
1668 if (http
->clientConnection
!= NULL
) {
1669 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
1670 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
1671 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
1672 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
1673 if (Config
.accessList
.spoof_client_ip
) {
1674 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
1675 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
1678 request
->flags
.spoofClientIp
= true;
1680 request
->flags
.spoofClientIp
= false;
1683 if (internalCheck(request
->url
.path())) {
1684 if (internalHostnameIs(request
->url
.host()) && request
->url
.port() == getMyPort()) {
1685 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true));
1686 http
->flags
.internal
= true;
1687 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->url
.path())) {
1688 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (global_internal_static on)");
1689 request
->url
.setScheme(AnyP::PROTO_HTTP
);
1690 request
->url
.host(internalHostname());
1691 request
->url
.port(getMyPort());
1692 http
->flags
.internal
= true;
1694 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (not this proxy)");
1697 request
->flags
.internal
= http
->flags
.internal
;
1698 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
1699 if (!conn
->connectionless()) {
1700 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
1701 #if FOLLOW_X_FORWARDED_FOR
1702 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
1703 // not a details about teh TCP connection itself
1704 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
1705 #endif /* FOLLOW_X_FORWARDED_FOR */
1706 request
->my_addr
= conn
->clientConnection
->local
;
1707 request
->myportname
= conn
->port
->name
;
1711 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
1712 // for now Squid only supports HTTP requests
1713 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
1714 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
1715 request
->http_ver
.major
= http_ver
.major
;
1716 request
->http_ver
.minor
= http_ver
.minor
;
1719 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
1720 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
1721 request
->clientConnectionManager
= conn
;
1723 if (request
->header
.chunked()) {
1725 } else if (request
->header
.has(Http::HdrType::TRANSFER_ENCODING
)) {
1726 const String te
= request
->header
.getList(Http::HdrType::TRANSFER_ENCODING
);
1727 // HTTP/1.1 requires chunking to be the last encoding if there is one
1728 unsupportedTe
= te
.size() && te
!= "identity";
1729 } // else implied identity coding
1731 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
1732 (request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0);
1733 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
1734 clientStreamNode
*node
= context
->getClientReplyContext();
1735 conn
->quitAfterError(request
.getRaw());
1736 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1737 assert (repContext
);
1738 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
1739 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1740 assert(context
->http
->out
.offset
== 0);
1741 context
->pullData();
1742 clientProcessRequestFinished(conn
, request
);
1746 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
1747 clientStreamNode
*node
= context
->getClientReplyContext();
1748 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1749 assert (repContext
);
1750 conn
->quitAfterError(request
.getRaw());
1751 repContext
->setReplyToError(ERR_INVALID_REQ
,
1752 Http::scLengthRequired
, request
->method
, NULL
,
1753 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1754 assert(context
->http
->out
.offset
== 0);
1755 context
->pullData();
1756 clientProcessRequestFinished(conn
, request
);
1760 clientSetKeepaliveFlag(http
);
1761 // Let tunneling code be fully responsible for CONNECT requests
1762 if (http
->request
->method
== Http::METHOD_CONNECT
) {
1763 context
->mayUseConnection(true);
1764 conn
->flags
.readMore
= false;
1768 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
1769 clientProcessRequestFinished(conn
, request
);
1774 /* Do we expect a request-body? */
1775 expectBody
= chunked
|| request
->content_length
> 0;
1776 if (!context
->mayUseConnection() && expectBody
) {
1777 request
->body_pipe
= conn
->expectRequestBody(
1778 chunked
? -1 : request
->content_length
);
1780 /* Is it too large? */
1781 if (!chunked
&& // if chunked, we will check as we accumulate
1782 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
1783 clientStreamNode
*node
= context
->getClientReplyContext();
1784 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1785 assert (repContext
);
1786 conn
->quitAfterError(request
.getRaw());
1787 repContext
->setReplyToError(ERR_TOO_BIG
,
1788 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
1789 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
1790 assert(context
->http
->out
.offset
== 0);
1791 context
->pullData();
1792 clientProcessRequestFinished(conn
, request
);
1797 // We may stop producing, comm_close, and/or call setReplyToError()
1798 // below, so quit on errors to avoid http->doCallouts()
1799 if (!conn
->handleRequestBodyData()) {
1800 clientProcessRequestFinished(conn
, request
);
1804 if (!request
->body_pipe
->productionEnded()) {
1805 debugs(33, 5, "need more request body");
1806 context
->mayUseConnection(true);
1807 assert(conn
->flags
.readMore
);
1812 http
->calloutContext
= new ClientRequestContext(http
);
1816 clientProcessRequestFinished(conn
, request
);
1820 ConnStateData::pipelinePrefetchMax() const
1822 // TODO: Support pipelined requests through pinned connections.
1825 return Config
.pipeline_max_prefetch
;
1829 * Limit the number of concurrent requests.
1830 * \return true when there are available position(s) in the pipeline queue for another request.
1831 * \return false when the pipeline queue is full or disabled.
1834 ConnStateData::concurrentRequestQueueFilled() const
1836 const int existingRequestCount
= pipeline
.count();
1838 // default to the configured pipeline size.
1839 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
1841 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
1843 const int internalRequest
= 0;
1845 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
1847 // when queue filled already we cant add more.
1848 if (existingRequestCount
>= concurrentRequestLimit
) {
1849 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
1850 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
1858 * Perform proxy_protocol_access ACL tests on the client which
1859 * connected to PROXY protocol port to see if we trust the
1860 * sender enough to accept their PROXY header claim.
1863 ConnStateData::proxyProtocolValidateClient()
1865 if (!Config
.accessList
.proxyProtocol
)
1866 return proxyProtocolError("PROXY client not permitted by default ACL");
1868 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
1869 ch
.src_addr
= clientConnection
->remote
;
1870 ch
.my_addr
= clientConnection
->local
;
1873 if (ch
.fastCheck() != ACCESS_ALLOWED
)
1874 return proxyProtocolError("PROXY client not permitted by ACLs");
1880 * Perform cleanup on PROXY protocol errors.
1881 * If header parsing hits a fatal error terminate the connection,
1882 * otherwise wait for more data.
1885 ConnStateData::proxyProtocolError(const char *msg
)
1888 // This is important to know, but maybe not so much that flooding the log is okay.
1889 #if QUIET_PROXY_PROTOCOL
1890 // display the first of every 32 occurances at level 1, the others at level 2.
1891 static uint8_t hide
= 0;
1892 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
1894 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
1901 /// magic octet prefix for PROXY protocol version 1
1902 static const SBuf
Proxy1p0magic("PROXY ", 6);
1904 /// magic octet prefix for PROXY protocol version 2
1905 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
1908 * Test the connection read buffer for PROXY protocol header.
1909 * Version 1 and 2 header currently supported.
1912 ConnStateData::parseProxyProtocolHeader()
1914 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
1916 // detect and parse PROXY/2.0 protocol header
1917 if (inBuf
.startsWith(Proxy2p0magic
))
1918 return parseProxy2p0();
1920 // detect and parse PROXY/1.0 protocol header
1921 if (inBuf
.startsWith(Proxy1p0magic
))
1922 return parseProxy1p0();
1924 // detect and terminate other protocols
1925 if (inBuf
.length() >= Proxy2p0magic
.length()) {
1926 // PROXY/1.0 magic is shorter, so we know that
1927 // the input does not start with any PROXY magic
1928 return proxyProtocolError("PROXY protocol error: invalid header");
1931 // TODO: detect short non-magic prefixes earlier to avoid
1932 // waiting for more data which may never come
1934 // not enough bytes to parse yet.
1938 /// parse the PROXY/1.0 protocol header from the connection read buffer
1940 ConnStateData::parseProxy1p0()
1942 ::Parser::Tokenizer
tok(inBuf
);
1943 tok
.skip(Proxy1p0magic
);
1945 // skip to first LF (assumes it is part of CRLF)
1946 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
1948 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
1949 if (tok
.skip('\n')) {
1950 // found valid header
1951 inBuf
= tok
.remaining();
1952 needProxyProtocolHeader_
= false;
1953 // reset the tokenizer to work on found line only.
1956 return false; // no LF yet
1958 } else // protocol error only if there are more than 107 bytes prefix header
1959 return proxyProtocolError(inBuf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
1961 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
1962 if (tok
.skip(tcpName
)) {
1964 // skip TCP/IP version number
1965 static const CharacterSet
tcpVersions("TCP-version","46");
1966 if (!tok
.skipOne(tcpVersions
))
1967 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
1969 // skip SP after protocol version
1971 return proxyProtocolError("PROXY/1.0 error: missing SP");
1974 int64_t porta
, portb
;
1975 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
1977 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
1978 // leave the LF until later.
1979 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
1980 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
1981 tok
.int64(porta
) && tok
.skip(' ') &&
1985 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
1987 // parse IP and port strings
1988 Ip::Address originalClient
, originalDest
;
1990 if (!originalClient
.GetHostByName(ipa
.c_str()))
1991 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
1993 if (!originalDest
.GetHostByName(ipb
.c_str()))
1994 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
1996 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
1997 originalClient
.port(static_cast<uint16_t>(porta
));
1999 return proxyProtocolError("PROXY/1.0 error: invalid src port");
2001 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
2002 originalDest
.port(static_cast<uint16_t>(portb
));
2004 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
2006 // we have original client and destination details now
2007 // replace the client connection values
2008 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
2009 clientConnection
->local
= originalDest
;
2010 clientConnection
->remote
= originalClient
;
2011 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2012 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2013 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2015 // repeat fetch ensuring the new client FQDN can be logged
2016 if (Config
.onoff
.log_fqdn
)
2017 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2021 } else if (tok
.skip(unknown
)) {
2022 // found valid but unusable header
2026 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2031 /// parse the PROXY/2.0 protocol header from the connection read buffer
2033 ConnStateData::parseProxy2p0()
2035 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2036 if (inBuf
.length() < prefixLen
+ 4)
2037 return false; // need more bytes
2039 if ((inBuf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2040 return proxyProtocolError("PROXY/2.0 error: invalid version");
2042 const char command
= (inBuf
[prefixLen
] & 0x0F);
2043 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2044 return proxyProtocolError("PROXY/2.0 error: invalid command");
2046 const char family
= (inBuf
[prefixLen
+1] & 0xF0) >>4;
2047 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2048 return proxyProtocolError("PROXY/2.0 error: invalid family");
2050 const char proto
= (inBuf
[prefixLen
+1] & 0x0F);
2051 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2052 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2054 const char *clen
= inBuf
.rawContent() + prefixLen
+ 2;
2056 memcpy(&len
, clen
, sizeof(len
));
2059 if (inBuf
.length() < prefixLen
+ 4 + len
)
2060 return false; // need more bytes
2062 inBuf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2063 const SBuf extra
= inBuf
.consume(len
);
2064 needProxyProtocolHeader_
= false; // found successfully
2066 // LOCAL connections do nothing with the extras
2067 if (command
== 0x00/* LOCAL*/)
2071 struct { /* for TCP/UDP over IPv4, len = 12 */
2072 struct in_addr src_addr
;
2073 struct in_addr dst_addr
;
2077 struct { /* for TCP/UDP over IPv6, len = 36 */
2078 struct in6_addr src_addr
;
2079 struct in6_addr dst_addr
;
2084 struct { /* for AF_UNIX sockets, len = 216 */
2085 uint8_t src_addr
[108];
2086 uint8_t dst_addr
[108];
2092 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2094 // replace the client connection values
2095 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2098 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2099 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2100 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2101 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2102 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2103 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2106 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2107 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2108 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2109 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2110 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2111 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2113 default: // do nothing
2116 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2118 // repeat fetch ensuring the new client FQDN can be logged
2119 if (Config
.onoff
.log_fqdn
)
2120 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2126 ConnStateData::receivedFirstByte()
2128 if (receivedFirstByte_
)
2131 receivedFirstByte_
= true;
2132 // Set timeout to Config.Timeout.request
2133 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2134 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
2135 TimeoutDialer
, this, ConnStateData::requestTimeout
);
2136 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
2140 * Attempt to parse one or more requests from the input buffer.
2141 * Returns true after completing parsing of at least one request [header]. That
2142 * includes cases where parsing ended with an error (e.g., a huge request).
2145 ConnStateData::clientParseRequests()
2147 bool parsed_req
= false;
2149 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2151 // Loop while we have read bytes that are not needed for producing the body
2152 // On errors, bodyPipe may become nil, but readMore will be cleared
2153 while (!inBuf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2155 /* Don't try to parse if the buffer is empty */
2156 if (inBuf
.isEmpty())
2159 /* Limit the number of concurrent requests */
2160 if (concurrentRequestQueueFilled())
2163 // try to parse the PROXY protocol header magic bytes
2164 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
2167 if (Http::Stream
*context
= parseOneRequest()) {
2168 debugs(33, 5, clientConnection
<< ": done parsing a request");
2170 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2171 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2172 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2174 context
->registerWithConn();
2176 processParsedRequest(context
);
2178 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2180 if (context
->mayUseConnection()) {
2181 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2185 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
2186 inBuf
.length() << " < " << Config
.maxRequestHeaderSize
);
2187 Must(inBuf
.length() < Config
.maxRequestHeaderSize
);
2192 /* XXX where to 'finish' the parsing pass? */
2197 ConnStateData::afterClientRead()
2199 /* Process next request */
2200 if (pipeline
.empty())
2201 fd_note(clientConnection
->fd
, "Reading next request");
2203 if (!clientParseRequests()) {
2207 * If the client here is half closed and we failed
2208 * to parse a request, close the connection.
2209 * The above check with connFinishedWithConn() only
2210 * succeeds _if_ the buffer is empty which it won't
2211 * be if we have an incomplete request.
2212 * XXX: This duplicates ConnStateData::kick
2214 if (pipeline
.empty() && commIsHalfClosed(clientConnection
->fd
)) {
2215 debugs(33, 5, clientConnection
<< ": half-closed connection, no completed request parsed, connection closing.");
2216 clientConnection
->close();
2224 clientAfterReadingRequests();
2228 * called when new request data has been read from the socket
2230 * \retval false called comm_close or setReplyToError (the caller should bail)
2231 * \retval true we did not call comm_close or setReplyToError
2234 ConnStateData::handleReadData()
2236 // if we are reading a body, stuff data into the body pipe
2237 if (bodyPipe
!= NULL
)
2238 return handleRequestBodyData();
2243 * called when new request body data has been buffered in inBuf
2244 * may close the connection if we were closing and piped everything out
2246 * \retval false called comm_close or setReplyToError (the caller should bail)
2247 * \retval true we did not call comm_close or setReplyToError
2250 ConnStateData::handleRequestBodyData()
2252 assert(bodyPipe
!= NULL
);
2254 if (bodyParser
) { // chunked encoding
2255 if (const err_type error
= handleChunkedRequestBody()) {
2256 abortChunkedRequestBody(error
);
2259 } else { // identity encoding
2260 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
2261 const size_t putSize
= bodyPipe
->putMoreData(inBuf
.c_str(), inBuf
.length());
2263 consumeInput(putSize
);
2265 if (!bodyPipe
->mayNeedMoreData()) {
2266 // BodyPipe will clear us automagically when we produced everything
2272 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
2274 if (const char *reason
= stoppedSending()) {
2275 /* we've finished reading like good clients,
2276 * now do the close that initiateClose initiated.
2278 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
2279 clientConnection
->close();
2287 /// parses available chunked encoded body bytes, checks size, returns errors
2289 ConnStateData::handleChunkedRequestBody()
2291 debugs(33, 7, "chunked from " << clientConnection
<< ": " << inBuf
.length());
2293 try { // the parser will throw on errors
2295 if (inBuf
.isEmpty()) // nothing to do
2298 BodyPipeCheckout
bpc(*bodyPipe
);
2299 bodyParser
->setPayloadBuffer(&bpc
.buf
);
2300 const bool parsed
= bodyParser
->parse(inBuf
);
2301 inBuf
= bodyParser
->remaining(); // sync buffers
2304 // dechunk then check: the size limit applies to _dechunked_ content
2305 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
2309 finishDechunkingRequest(true);
2311 return ERR_NONE
; // nil bodyPipe implies body end for the caller
2314 // if chunk parser needs data, then the body pipe must need it too
2315 Must(!bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
2317 // if parser needs more space and we can consume nothing, we will stall
2318 Must(!bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
2319 } catch (...) { // TODO: be more specific
2320 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
2321 return ERR_INVALID_REQ
;
2324 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
2328 /// quit on errors related to chunked request body handling
2330 ConnStateData::abortChunkedRequestBody(const err_type error
)
2332 finishDechunkingRequest(false);
2334 // XXX: The code below works if we fail during initial request parsing,
2335 // but if we fail when the server connection is used already, the server may send
2336 // us its response too, causing various assertions. How to prevent that?
2337 #if WE_KNOW_HOW_TO_SEND_ERRORS
2338 Http::StreamPointer context
= pipeline
.front();
2339 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
2340 clientStreamNode
*node
= context
->getClientReplyContext();
2341 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2343 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
2344 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
2345 repContext
->setReplyToError(error
, scode
,
2346 repContext
->http
->request
->method
,
2347 repContext
->http
->uri
,
2349 repContext
->http
->request
,
2351 context
->pullData();
2353 // close or otherwise we may get stuck as nobody will notice the error?
2354 comm_reset_close(clientConnection
);
2357 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
2358 comm_reset_close(clientConnection
);
2360 flags
.readMore
= false;
2364 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
2366 // request reader may get stuck waiting for space if nobody consumes body
2367 if (bodyPipe
!= NULL
)
2368 bodyPipe
->enableAutoConsumption();
2373 /** general lifetime handler for HTTP requests */
2375 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
2377 if (!Comm::IsConnOpen(io
.conn
))
2380 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
2382 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
2383 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
2384 receivedFirstByte();
2387 } else if (!fd_table
[io
.conn
->fd
].ssl
)
2390 const HttpRequestMethod method
;
2391 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
2392 // Tunnel established. Set receivedFirstByte to avoid loop.
2393 receivedFirstByte();
2399 * Just close the connection to not confuse browsers
2400 * using persistent connections. Some browsers open
2401 * a connection and then do not use it until much
2402 * later (presumeably because the request triggering
2403 * the open has already been completed on another
2406 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
2411 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
2413 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
2414 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
2415 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
2416 http
->logType
.err
.timedout
= true;
2417 if (Comm::IsConnOpen(io
.conn
))
2421 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
2422 AsyncJob("ConnStateData"), // kids overwrite
2424 bodyParser(nullptr),
2426 sslBumpMode(Ssl::bumpEnd
),
2428 needProxyProtocolHeader_(false),
2430 switchedToHttps_(false),
2431 sslServerBump(NULL
),
2432 signAlgorithm(Ssl::algSignTrusted
),
2434 stoppedSending_(NULL
),
2435 stoppedReceiving_(NULL
)
2437 flags
.readMore
= true; // kids may overwrite
2438 flags
.swanSang
= false;
2440 pinning
.host
= NULL
;
2442 pinning
.pinned
= false;
2443 pinning
.auth
= false;
2444 pinning
.zeroReply
= false;
2445 pinning
.peer
= NULL
;
2447 // store the details required for creating more MasterXaction objects as new requests come in
2448 if (xact
->tcpClient
!= NULL
)
2449 log_addr
= xact
->tcpClient
->remote
;
2451 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
2453 // register to receive notice of Squid signal events
2454 // which may affect long persisting client connections
2455 RegisterRunner(this);
2459 ConnStateData::start()
2461 BodyProducer::start();
2462 HttpControlMsgSink::start();
2464 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
2465 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
2466 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2467 int i
= IP_PMTUDISC_DONT
;
2468 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
2469 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
2471 static bool reported
= false;
2474 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
2480 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
2481 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
2482 comm_add_close_handler(clientConnection
->fd
, call
);
2484 if (Config
.onoff
.log_fqdn
)
2485 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2488 if (Ident::TheConfig
.identLookup
) {
2489 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
2490 identChecklist
.src_addr
= clientConnection
->remote
;
2491 identChecklist
.my_addr
= clientConnection
->local
;
2492 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
2493 Ident::Start(clientConnection
, clientIdentDone
, this);
2497 clientdbEstablished(clientConnection
->remote
, 1);
2499 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
2500 if (needProxyProtocolHeader_
) {
2501 if (!proxyProtocolValidateClient()) // will close the connection on failure
2506 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
2508 if (Config
.onoff
.client_db
) {
2509 /* it was said several times that client write limiter does not work if client_db is disabled */
2511 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
2512 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
2514 // TODO: we check early to limit error response bandwith but we
2515 // should recheck when we can honor delay_pool_uses_indirect
2516 // TODO: we should also pass the port details for myportname here.
2517 ch
.src_addr
= clientConnection
->remote
;
2518 ch
.my_addr
= clientConnection
->local
;
2520 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
2522 /* pools require explicit 'allow' to assign a client into them */
2523 if (pools
[pool
].access
) {
2524 ch
.changeAcl(pools
[pool
].access
);
2525 allow_t answer
= ch
.fastCheck();
2526 if (answer
== ACCESS_ALLOWED
) {
2528 /* request client information from db after we did all checks
2529 this will save hash lookup if client failed checks */
2530 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
2533 /* put client info in FDE */
2534 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
2536 /* setup write limiter for this request */
2537 const double burst
= floor(0.5 +
2538 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
2539 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
2542 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
2549 // kids must extend to actually start doing something (e.g., reading)
2552 /** Handle a new connection on an HTTP socket. */
2554 httpAccept(const CommAcceptCbParams
¶ms
)
2556 MasterXaction::Pointer xact
= params
.xaction
;
2557 AnyP::PortCfgPointer s
= xact
->squidPort
;
2559 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2561 if (params
.flag
!= Comm::OK
) {
2562 // Its possible the call was still queued when the client disconnected
2563 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2567 debugs(33, 4, params
.conn
<< ": accepted");
2568 fd_note(params
.conn
->fd
, "client http connect");
2570 if (s
->tcp_keepalive
.enabled
)
2571 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2573 ++incoming_sockets_accepted
;
2575 // Socket is ready, setup the connection manager to start using it
2576 ConnStateData
*connState
= Http::NewServer(xact
);
2577 AsyncJob::Start(connState
); // usually async-calls readSomeData()
2582 /** Create SSL connection structure and update fd_table */
2583 static Security::SessionPtr
2584 httpsCreate(const Comm::ConnectionPointer
&conn
, Security::ContextPtr sslContext
)
2586 if (auto ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
2587 debugs(33, 5, "will negotate SSL on " << conn
);
2597 * \retval 1 on success
2598 * \retval 0 when needs more data
2599 * \retval -1 on error
2602 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
2604 int fd
= conn
->clientConnection
->fd
;
2605 auto ssl
= fd_table
[fd
].ssl
.get();
2609 if ((ret
= SSL_accept(ssl
)) <= 0) {
2610 const int xerrno
= errno
;
2611 const int ssl_error
= SSL_get_error(ssl
, ret
);
2613 switch (ssl_error
) {
2615 case SSL_ERROR_WANT_READ
:
2616 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, conn
, 0);
2619 case SSL_ERROR_WANT_WRITE
:
2620 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, conn
, 0);
2623 case SSL_ERROR_SYSCALL
:
2625 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
2627 debugs(83, (xerrno
== ECONNRESET
) ? 1 : 2, "Error negotiating SSL connection on FD " << fd
<< ": " <<
2628 (xerrno
== 0 ? ERR_error_string(ssl_error
, NULL
) : xstrerr(xerrno
)));
2632 case SSL_ERROR_ZERO_RETURN
:
2633 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
2637 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
2638 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
2639 " (" << ssl_error
<< "/" << ret
<< ")");
2648 /** negotiate an SSL connection */
2650 clientNegotiateSSL(int fd
, void *data
)
2652 ConnStateData
*conn
= (ConnStateData
*)data
;
2654 auto ssl
= fd_table
[fd
].ssl
.get();
2657 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
2658 if (ret
< 0) // An error
2659 conn
->clientConnection
->close();
2663 if (SSL_session_reused(ssl
)) {
2664 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
2665 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
2667 if (do_debug(83, 4)) {
2668 /* Write out the SSL session details.. actually the call below, but
2669 * OpenSSL headers do strange typecasts confusing GCC.. */
2670 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
2671 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
2672 PEM_ASN1_write((i2d_of_void
*)i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
2674 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
2676 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
2677 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
2678 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
2679 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
2680 * Because there are two possible usable cast, if you get an error here, try the other
2681 * commented line. */
2683 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
2684 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
2688 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
2691 /* Note: This does not automatically fflush the log file.. */
2694 debugs(83, 2, "clientNegotiateSSL: New session " <<
2695 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
2696 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
2700 // Connection established. Retrieve TLS connection parameters for logging.
2701 conn
->clientConnection
->tlsNegotiations()->fillWith(ssl
);
2703 client_cert
= SSL_get_peer_certificate(ssl
);
2705 if (client_cert
!= NULL
) {
2706 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2707 " client certificate: subject: " <<
2708 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
2710 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2711 " client certificate: issuer: " <<
2712 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
2714 X509_free(client_cert
);
2716 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
2717 " has no certificate.");
2720 #if defined(TLSEXT_NAMETYPE_host_name)
2721 if (!conn
->serverBump()) {
2722 // when in bumpClientFirst mode, get the server name from SNI
2723 if (const char *server
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))
2724 conn
->resetSslCommonName(server
);
2728 conn
->readSomeData();
2732 * If Security::ContextPtr is given, starts reading the TLS handshake.
2733 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPtr.
2736 httpsEstablish(ConnStateData
*connState
, Security::ContextPtr sslContext
)
2738 Security::SessionPtr ssl
= nullptr;
2740 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
2742 if (!sslContext
|| !(ssl
= httpsCreate(details
, sslContext
)))
2745 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2746 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
2747 connState
, ConnStateData::requestTimeout
);
2748 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
2750 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
2754 * A callback function to use with the ACLFilledChecklist callback.
2755 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
2756 * else reverts the connection to tunnel mode.
2759 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
2761 ConnStateData
*connState
= (ConnStateData
*) data
;
2763 // if the connection is closed or closing, just return.
2764 if (!connState
->isOpen())
2767 // Require both a match and a positive bump mode to work around exceptional
2768 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
2769 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
2770 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
2771 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
2773 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
2774 connState
->sslBumpMode
= Ssl::bumpNone
;
2776 connState
->fakeAConnectRequest("ssl-bump", connState
->inBuf
);
2779 /** handle a new HTTPS connection */
2781 httpsAccept(const CommAcceptCbParams
¶ms
)
2783 MasterXaction::Pointer xact
= params
.xaction
;
2784 const AnyP::PortCfgPointer s
= xact
->squidPort
;
2786 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2788 if (params
.flag
!= Comm::OK
) {
2789 // Its possible the call was still queued when the client disconnected
2790 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2794 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
2795 fd_note(params
.conn
->fd
, "client https connect");
2797 if (s
->tcp_keepalive
.enabled
) {
2798 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2800 ++incoming_sockets_accepted
;
2802 // Socket is ready, setup the connection manager to start using it
2803 ConnStateData
*connState
= Https::NewServer(xact
);
2804 AsyncJob::Start(connState
); // usually async-calls postHttpsAccept()
2808 ConnStateData::postHttpsAccept()
2810 if (port
->flags
.tunnelSslBumping
) {
2811 debugs(33, 5, "accept transparent connection: " << clientConnection
);
2813 if (!Config
.accessList
.ssl_bump
) {
2814 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
2818 // Create a fake HTTP request for ssl_bump ACL check,
2819 // using tproxy/intercept provided destination IP and port.
2820 HttpRequest
*request
= new HttpRequest();
2821 static char ip
[MAX_IPSTRLEN
];
2822 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
2823 request
->url
.host(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
2824 request
->url
.port(clientConnection
->local
.port());
2825 request
->myportname
= port
->name
;
2827 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
2828 acl_checklist
->src_addr
= clientConnection
->remote
;
2829 acl_checklist
->my_addr
= port
->s
;
2830 // Build a local AccessLogEntry to allow requiresAle() acls work
2831 acl_checklist
->al
= new AccessLogEntry
;
2832 acl_checklist
->al
->cache
.start_time
= current_time
;
2833 acl_checklist
->al
->tcpClient
= clientConnection
;
2834 acl_checklist
->al
->cache
.port
= port
;
2835 acl_checklist
->al
->cache
.caddr
= log_addr
;
2836 HTTPMSGUNLOCK(acl_checklist
->al
->request
);
2837 acl_checklist
->al
->request
= request
;
2838 HTTPMSGLOCK(acl_checklist
->al
->request
);
2839 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
2842 httpsEstablish(this, port
->secure
.staticContext
.get());
2847 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
2849 ConnStateData
* state_data
= (ConnStateData
*)(data
);
2850 state_data
->sslCrtdHandleReply(reply
);
2854 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
2857 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply
);
2861 if (reply
.result
== Helper::BrokenHelper
) {
2862 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
2863 } else if (!reply
.other().hasContent()) {
2864 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
2866 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
2867 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
2868 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
2870 if (reply
.result
!= Helper::Okay
) {
2871 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
2873 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
2874 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
2875 doPeekAndSpliceStep();
2876 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
2877 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
2879 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
2881 auto ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
2882 getSslContextDone(ctx
, true);
2888 getSslContextDone(NULL
);
2891 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
2893 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
2895 // fake certificate adaptation requires bump-server-first mode
2896 if (!sslServerBump
) {
2897 assert(port
->signingCert
.get());
2898 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2899 if (port
->signPkey
.get())
2900 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2901 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2905 // In case of an error while connecting to the secure server, use a fake
2906 // trusted certificate, with no mimicked fields and no adaptation
2907 // algorithms. There is nothing we can mimic so we want to minimize the
2908 // number of warnings the user will have to see to get to the error page.
2909 assert(sslServerBump
->entry
);
2910 if (sslServerBump
->entry
->isEmpty()) {
2911 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
2912 certProperties
.mimicCert
.resetAndLock(mimicCert
);
2914 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
2915 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
2916 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors());
2918 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
2919 // If the algorithm already set, then ignore it.
2920 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
2921 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
2922 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
2925 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
2926 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
2927 const char *param
= ca
->param
;
2929 // For parameterless CN adaptation, use hostname from the
2931 if (ca
->alg
== Ssl::algSetCommonName
) {
2933 param
= sslConnectHostOrIp
.termedBuf();
2934 certProperties
.commonName
= param
;
2935 certProperties
.setCommonName
= true;
2936 } else if (ca
->alg
== Ssl::algSetValidAfter
)
2937 certProperties
.setValidAfter
= true;
2938 else if (ca
->alg
== Ssl::algSetValidBefore
)
2939 certProperties
.setValidBefore
= true;
2941 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
2942 alg
<< " param: " << (param
? param
: "-"));
2946 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
2947 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
2948 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
2949 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
2953 } else {// if (!sslServerBump->entry->isEmpty())
2954 // Use trusted certificate for a Squid-generated error
2955 // or the user would have to add a security exception
2956 // just to see the error page. We will close the connection
2957 // so that the trust is not extended to non-Squid content.
2958 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2961 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
2963 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
2964 assert(port
->untrustedSigningCert
.get());
2965 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
2966 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
2968 assert(port
->signingCert
.get());
2969 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2971 if (port
->signPkey
.get())
2972 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2974 signAlgorithm
= certProperties
.signAlgorithm
;
2976 certProperties
.signHash
= Ssl::DefaultSignHash
;
2980 ConnStateData::getSslContextStart()
2982 // XXX starting SSL with a pipeline of requests still waiting for non-SSL replies?
2983 assert(pipeline
.count() < 2); // the CONNECT is okay for now. Anything else is a bug.
2984 pipeline
.terminateAll(0);
2985 /* careful: terminateAll(0) above frees request, host, etc. */
2987 if (port
->generateHostCertificates
) {
2988 Ssl::CertificateProperties certProperties
;
2989 buildSslCertGenerationParams(certProperties
);
2990 sslBumpCertKey
= certProperties
.dbKey().c_str();
2991 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
2993 // Disable caching for bumpPeekAndSplice mode
2994 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
2995 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
2996 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
2997 Security::ContextPtr dynCtx
= nullptr;
2998 Security::ContextPointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : nullptr;
2999 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3000 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3001 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3002 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3003 getSslContextDone(dynCtx
);
3006 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3008 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3011 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3017 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3018 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3019 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3020 request_message
.composeRequest(certProperties
);
3021 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3022 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3024 } catch (const std::exception
&e
) {
3025 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3026 "request for " << certProperties
.commonName
<<
3027 " certificate: " << e
.what() << "; will now block to " <<
3028 "generate that certificate.");
3029 // fall through to do blocking in-process generation.
3031 #endif // USE_SSL_CRTD
3033 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3034 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3035 doPeekAndSpliceStep();
3036 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3037 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3038 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3040 auto dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3041 getSslContextDone(dynCtx
, true);
3045 getSslContextDone(NULL
);
3049 ConnStateData::getSslContextDone(Security::ContextPtr sslContext
, bool isNew
)
3051 // Try to add generated ssl context to storage.
3052 if (port
->generateHostCertificates
&& isNew
) {
3054 if (signAlgorithm
== Ssl::algSignTrusted
) {
3055 // Add signing certificate to the certificates chain
3056 X509
*cert
= port
->signingCert
.get();
3057 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3058 // increase the certificate lock
3059 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3061 const int ssl_error
= ERR_get_error();
3062 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3064 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3066 //else it is self-signed or untrusted do not attrach any certificate
3068 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3069 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3071 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Security::ContextPointer(sslContext
))) {
3072 // If it is not in storage delete after using. Else storage deleted it.
3073 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3076 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3080 // If generated ssl context = NULL, try to use static ssl context.
3082 if (!port
->secure
.staticContext
) {
3083 debugs(83, DBG_IMPORTANT
, "Closing " << clientConnection
->remote
<< " as lacking TLS context");
3084 clientConnection
->close();
3087 debugs(33, 5, "Using static TLS context.");
3088 sslContext
= port
->secure
.staticContext
.get();
3092 if (!httpsCreate(clientConnection
, sslContext
))
3095 // bumped intercepted conns should already have Config.Timeout.request set
3096 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3097 // to make sure the connection does not get stuck on non-SSL clients.
3098 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3099 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3100 this, ConnStateData::requestTimeout
);
3101 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3103 // Disable the client read handler until CachePeer selection is complete
3104 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3105 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3106 switchedToHttps_
= true;
3110 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3112 assert(!switchedToHttps_
);
3114 sslConnectHostOrIp
= request
->url
.host();
3115 resetSslCommonName(request
->url
.host());
3117 // We are going to read new request
3118 flags
.readMore
= true;
3119 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3121 // keep version major.minor details the same.
3122 // but we are now performing the HTTPS handshake traffic
3123 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
3125 // If sslServerBump is set, then we have decided to deny CONNECT
3126 // and now want to switch to SSL to send the error to the client
3127 // without even peeking at the origin server certificate.
3128 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3129 request
->flags
.sslPeek
= true;
3130 sslServerBump
= new Ssl::ServerBump(request
);
3132 // will call httpsPeeked() with certificate and connection, eventually
3133 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3135 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
3136 request
->flags
.sslPeek
= true;
3137 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
3138 startPeekAndSplice();
3142 // otherwise, use sslConnectHostOrIp
3143 getSslContextStart();
3147 ConnStateData::spliceOnError(const err_type err
)
3149 if (Config
.accessList
.on_unsupported_protocol
) {
3150 assert(serverBump());
3151 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
3152 checklist
.requestErrorType
= err
;
3153 checklist
.conn(this);
3154 allow_t answer
= checklist
.fastCheck();
3155 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
3163 /** negotiate an SSL connection */
3165 clientPeekAndSpliceSSL(int fd
, void *data
)
3167 ConnStateData
*conn
= (ConnStateData
*)data
;
3168 auto ssl
= fd_table
[fd
].ssl
.get();
3170 debugs(83, 5, "Start peek and splice on FD " << fd
);
3173 if ((ret
= Squid_SSL_accept(conn
, clientPeekAndSpliceSSL
)) < 0)
3174 debugs(83, 2, "SSL_accept failed.");
3176 BIO
*b
= SSL_get_rbio(ssl
);
3178 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3180 const err_type err
= bio
->noSslClient() ? ERR_PROTOCOL_UNKNOWN
: ERR_SECURE_ACCEPT_FAIL
;
3181 if (!conn
->spliceOnError(err
))
3182 conn
->clientConnection
->close();
3186 if (!bio
->rBufData().isEmpty())
3187 conn
->receivedFirstByte();
3189 if (bio
->gotHello()) {
3190 if (conn
->serverBump()) {
3191 Ssl::Bio::sslFeatures
const &features
= bio
->receivedHelloFeatures();
3192 if (!features
.serverName
.isEmpty()) {
3193 conn
->serverBump()->clientSni
= features
.serverName
;
3194 conn
->resetSslCommonName(features
.serverName
.c_str());
3198 debugs(83, 5, "I got hello. Start forwarding the request!!! ");
3199 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3200 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
3201 conn
->startPeekAndSpliceDone();
3206 void ConnStateData::startPeekAndSplice()
3208 // will call httpsPeeked() with certificate and connection, eventually
3209 auto unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
3210 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
3212 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
3215 // commSetConnTimeout() was called for this request before we switched.
3216 // Fix timeout to request_start_timeout
3217 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3218 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3219 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3220 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
3221 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
3222 // a bumbed "connect" request on non transparent port.
3223 receivedFirstByte_
= false;
3225 // Disable the client read handler until CachePeer selection is complete
3226 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3227 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientPeekAndSpliceSSL
, this, 0);
3228 switchedToHttps_
= true;
3230 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3231 BIO
*b
= SSL_get_rbio(ssl
);
3232 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3236 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
3238 ConnStateData
*connState
= (ConnStateData
*) data
;
3240 // if the connection is closed or closing, just return.
3241 if (!connState
->isOpen())
3244 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
3245 assert(connState
->serverBump());
3246 Ssl::BumpMode bumpAction
;
3247 if (answer
== ACCESS_ALLOWED
) {
3248 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
3250 bumpAction
= Ssl::bumpSplice
;
3252 connState
->serverBump()->act
.step2
= bumpAction
;
3253 connState
->sslBumpMode
= bumpAction
;
3255 if (bumpAction
== Ssl::bumpTerminate
) {
3256 connState
->clientConnection
->close();
3257 } else if (bumpAction
!= Ssl::bumpSplice
) {
3258 connState
->startPeekAndSpliceDone();
3260 connState
->splice();
3264 ConnStateData::splice()
3266 // normally we can splice here, because we just got client hello message
3267 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3269 //retrieve received TLS client information
3270 clientConnection
->tlsNegotiations()->fillWith(ssl
);
3272 BIO
*b
= SSL_get_rbio(ssl
);
3273 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3274 SBuf
const &rbuf
= bio
->rBufData();
3275 debugs(83,5, "Bio for " << clientConnection
<< " read " << rbuf
.length() << " helo bytes");
3277 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
3278 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
3280 if (transparent()) {
3281 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
3282 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
3283 transferProtocol
= Http::ProtocolVersion();
3284 fakeAConnectRequest("intercepted TLS spliced", rbuf
);
3286 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
3288 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
3289 transferProtocol
= Http::ProtocolVersion();
3290 // inBuf still has the "CONNECT ..." request data, reset it to SSL hello message
3292 Http::StreamPointer context
= pipeline
.front();
3293 ClientHttpRequest
*http
= context
->http
;
3299 ConnStateData::startPeekAndSpliceDone()
3301 // This is the Step2 of the SSL bumping
3302 assert(sslServerBump
);
3303 Http::StreamPointer context
= pipeline
.front();
3304 ClientHttpRequest
*http
= context
? context
->http
: NULL
;
3306 if (sslServerBump
->step
== Ssl::bumpStep1
) {
3307 sslServerBump
->step
= Ssl::bumpStep2
;
3308 // Run a accessList check to check if want to splice or continue bumping
3310 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
3311 acl_checklist
->al
= http
? http
->al
: NULL
;
3312 //acl_checklist->src_addr = params.conn->remote;
3313 //acl_checklist->my_addr = s->s;
3314 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpNone
));
3315 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpClientFirst
));
3316 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpServerFirst
));
3317 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
3321 FwdState::Start(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw(), http
? http
->al
: NULL
);
3325 ConnStateData::doPeekAndSpliceStep()
3327 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3328 BIO
*b
= SSL_get_rbio(ssl
);
3330 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3332 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
3335 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
3336 switchedToHttps_
= true;
3340 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3342 Must(sslServerBump
!= NULL
);
3344 if (Comm::IsConnOpen(serverConnection
)) {
3345 pinConnection(serverConnection
, NULL
, NULL
, false);
3347 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3349 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3351 // copy error detail from bump-server-first request to CONNECT request
3352 if (!pipeline
.empty() && pipeline
.front()->http
!= nullptr && pipeline
.front()->http
->request
)
3353 pipeline
.front()->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3356 getSslContextStart();
3359 #endif /* USE_OPENSSL */
3362 ConnStateData::fakeAConnectRequest(const char *reason
, const SBuf
&payload
)
3364 // fake a CONNECT request to force connState to tunnel
3367 if (serverBump() && !serverBump()->clientSni
.isEmpty()) {
3368 connectHost
.assign(serverBump()->clientSni
);
3369 if (clientConnection
->local
.port() > 0)
3370 connectHost
.appendf(":%d",clientConnection
->local
.port());
3374 static char ip
[MAX_IPSTRLEN
];
3375 connectHost
.assign(clientConnection
->local
.toUrl(ip
, sizeof(ip
)));
3377 // Pre-pend this fake request to the TLS bits already in the buffer
3379 retStr
.append("CONNECT ");
3380 retStr
.append(connectHost
);
3381 retStr
.append(" HTTP/1.1\r\nHost: ");
3382 retStr
.append(connectHost
);
3383 retStr
.append("\r\n\r\n");
3384 retStr
.append(payload
);
3386 bool ret
= handleReadData();
3388 ret
= clientParseRequests();
3391 debugs(33, 2, "Failed to start fake CONNECT request for " << reason
<< " connection: " << clientConnection
);
3392 clientConnection
->close();
3396 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3398 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3400 if (!Comm::IsConnOpen(c
)) {
3401 Must(NHttpSockets
> 0); // we tried to open some
3402 --NHttpSockets
; // there will be fewer sockets than planned
3403 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3405 if (!NHttpSockets
) // we could not open any listen sockets at all
3406 fatalf("Unable to open %s",FdNote(portType
));
3413 /// find any unused HttpSockets[] slot and store fd there or return false
3415 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
3418 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
3419 if ((found
= HttpSockets
[i
] < 0))
3420 HttpSockets
[i
] = conn
->fd
;
3426 clientHttpConnectionsOpen(void)
3428 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3429 const char *scheme
= AnyP::UriScheme(s
->transport
.protocol
).c_str();
3431 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
3432 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many '" << scheme
<< "_port' lines.");
3433 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
3438 if (s
->flags
.tunnelSslBumping
) {
3439 if (!Config
.accessList
.ssl_bump
) {
3440 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme
<< "_port " << s
->s
);
3441 s
->flags
.tunnelSslBumping
= false;
3443 if (!s
->secure
.staticContext
&& !s
->generateHostCertificates
) {
3444 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at " << scheme
<< "_port " << s
->s
<< " due to TLS initialization failure.");
3445 s
->flags
.tunnelSslBumping
= false;
3446 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
)
3447 s
->secure
.encryptTransport
= false;
3449 if (s
->flags
.tunnelSslBumping
) {
3450 // Create ssl_ctx cache for this port.
3451 auto sz
= s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
;
3452 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, sz
);
3456 if (s
->secure
.encryptTransport
&& !s
->secure
.staticContext
) {
3457 debugs(1, DBG_CRITICAL
, "ERROR: Ignoring " << scheme
<< "_port " << s
->s
<< " due to TLS context initialization failure.");
3462 // Fill out a Comm::Connection which IPC will open as a listener for us
3463 // then pass back when active so we can start a TcpAcceptor subscription.
3464 s
->listenConn
= new Comm::Connection
;
3465 s
->listenConn
->local
= s
->s
;
3467 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3468 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3470 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3471 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
) {
3472 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
3473 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
3474 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3476 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
3477 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
3478 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
3481 } else if (s
->transport
.protocol
== AnyP::PROTO_HTTPS
) {
3482 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
3483 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
3484 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3486 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
3487 ListeningStartedDialer(&clientListenerConnectionOpened
,
3488 s
, Ipc::fdnHttpsSocket
, sub
));
3489 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
3493 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
3499 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
3501 // Fill out a Comm::Connection which IPC will open as a listener for us
3502 port
->listenConn
= new Comm::Connection
;
3503 port
->listenConn
->local
= port
->s
;
3504 port
->listenConn
->flags
=
3506 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3507 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3509 // route new connections to subCall
3510 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3511 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3512 AsyncCall::Pointer listenCall
=
3513 asyncCall(33, 2, "clientListenerConnectionOpened",
3514 ListeningStartedDialer(&clientListenerConnectionOpened
,
3515 port
, fdNote
, sub
));
3516 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
3518 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
3519 HttpSockets
[NHttpSockets
] = -1;
3523 /// process clientHttpConnectionsOpen result
3525 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
3529 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
3532 Must(Comm::IsConnOpen(s
->listenConn
));
3534 // TCP: setup a job to handle accept() with subscribed handler
3535 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
3537 debugs(1, DBG_IMPORTANT
, "Accepting " <<
3538 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
3539 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
3540 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
3541 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
3542 << FdNote(portTypeNote
) << " connections at "
3545 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
3549 clientOpenListenSockets(void)
3551 clientHttpConnectionsOpen();
3552 Ftp::StartListening();
3554 if (NHttpSockets
< 1)
3555 fatal("No HTTP, HTTPS, or FTP ports configured");
3559 clientConnectionsClose()
3561 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3562 if (s
->listenConn
!= NULL
) {
3563 debugs(1, DBG_IMPORTANT
, "Closing HTTP(S) port " << s
->listenConn
->local
);
3564 s
->listenConn
->close();
3565 s
->listenConn
= NULL
;
3569 Ftp::StopListening();
3571 // TODO see if we can drop HttpSockets array entirely */
3572 for (int i
= 0; i
< NHttpSockets
; ++i
) {
3573 HttpSockets
[i
] = -1;
3580 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
3582 const char *vary
= request
->vary_headers
;
3583 int has_vary
= entry
->getReply()->header
.has(Http::HdrType::VARY
);
3584 #if X_ACCELERATOR_VARY
3587 entry
->getReply()->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
3590 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
3592 /* Oops... something odd is going on here.. */
3593 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
3594 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3595 safe_free(request
->vary_headers
);
3600 /* This is not a varying object */
3604 /* virtual "vary" object found. Calculate the vary key and
3605 * continue the search
3607 vary
= httpMakeVaryMark(request
, entry
->getReply());
3610 request
->vary_headers
= xstrdup(vary
);
3613 /* Ouch.. we cannot handle this kind of variance */
3614 /* XXX This cannot really happen, but just to be complete */
3619 vary
= httpMakeVaryMark(request
, entry
->getReply());
3622 request
->vary_headers
= xstrdup(vary
);
3626 /* Ouch.. we cannot handle this kind of variance */
3627 /* XXX This cannot really happen, but just to be complete */
3629 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
3632 /* Oops.. we have already been here and still haven't
3633 * found the requested variant. Bail out
3635 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
3636 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3642 ACLFilledChecklist
*
3643 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
3645 ConnStateData
* conn
= http
->getConn();
3646 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
3647 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
3650 * hack for ident ACL. It needs to get full addresses, and a place to store
3651 * the ident result on persistent connections...
3653 /* connection oriented auth also needs these two lines for it's operation. */
3658 ConnStateData::transparent() const
3660 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
3664 ConnStateData::expectRequestBody(int64_t size
)
3666 bodyPipe
= new BodyPipe(this);
3668 bodyPipe
->setBodySize(size
);
3670 startDechunkingRequest();
3675 ConnStateData::mayNeedToReadMoreBody() const
3678 return 0; // request without a body or read/produced all body bytes
3680 if (!bodyPipe
->bodySizeKnown())
3681 return -1; // probably need to read more, but we cannot be sure
3683 const int64_t needToProduce
= bodyPipe
->unproducedSize();
3684 const int64_t haveAvailable
= static_cast<int64_t>(inBuf
.length());
3686 if (needToProduce
<= haveAvailable
)
3687 return 0; // we have read what we need (but are waiting for pipe space)
3689 return needToProduce
- haveAvailable
;
3693 ConnStateData::stopReceiving(const char *error
)
3695 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
3696 "; old sending error: " <<
3697 (stoppedSending() ? stoppedSending_
: "none"));
3699 if (const char *oldError
= stoppedReceiving()) {
3700 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
3701 return; // nothing has changed as far as this connection is concerned
3704 stoppedReceiving_
= error
;
3706 if (const char *sendError
= stoppedSending()) {
3707 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
3708 clientConnection
->close();
3713 ConnStateData::expectNoForwarding()
3715 if (bodyPipe
!= NULL
) {
3716 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
3717 bodyPipe
->expectNoConsumption();
3721 /// initialize dechunking state
3723 ConnStateData::startDechunkingRequest()
3725 Must(bodyPipe
!= NULL
);
3726 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
3727 assert(!bodyParser
);
3728 bodyParser
= new Http1::TeChunkedParser
;
3731 /// put parsed content into input buffer and clean up
3733 ConnStateData::finishDechunkingRequest(bool withSuccess
)
3735 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
3737 if (bodyPipe
!= NULL
) {
3738 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
3739 BodyPipe::Pointer myPipe
= bodyPipe
;
3740 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
3741 Must(!bodyPipe
); // we rely on it being nil after we are done with body
3743 Must(myPipe
->bodySizeKnown());
3744 Http::StreamPointer context
= pipeline
.front();
3745 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
3746 context
->http
->request
->setContentLength(myPipe
->bodySize());
3754 // XXX: this is an HTTP/1-only operation
3756 ConnStateData::sendControlMsg(HttpControlMsg msg
)
3759 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
3763 // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them
3764 if (!pipeline
.empty()) {
3765 HttpReply::Pointer
rep(msg
.reply
);
3767 // remember the callback
3768 cbControlMsgSent
= msg
.cbSuccess
;
3770 typedef CommCbMemFunT
<HttpControlMsgSink
, CommIoCbParams
> Dialer
;
3771 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, HttpControlMsgSink::wroteControlMsg
);
3773 writeControlMsgAndCall(rep
.getRaw(), call
);
3777 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
3778 clientConnection
->close();
3781 /// Our close handler called by Comm when the pinned connection is closed
3783 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
3785 // FwdState might repin a failed connection sooner than this close
3786 // callback is called for the failed connection.
3787 assert(pinning
.serverConnection
== io
.conn
);
3788 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
3789 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
3790 pinning
.serverConnection
->noteClosure();
3791 unpinConnection(false);
3793 if (sawZeroReply
&& clientConnection
!= NULL
) {
3794 debugs(33, 3, "Closing client connection on pinned zero reply.");
3795 clientConnection
->close();
3801 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
3803 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
3804 pinning
.serverConnection
->fd
!= pinServer
->fd
)
3805 pinNewConnection(pinServer
, request
, aPeer
, auth
);
3808 startPinnedConnectionMonitoring();
3812 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
3814 unpinConnection(true); // closes pinned connection, if any, and resets fields
3816 pinning
.serverConnection
= pinServer
;
3818 debugs(33, 3, HERE
<< pinning
.serverConnection
);
3820 Must(pinning
.serverConnection
!= NULL
);
3822 // when pinning an SSL bumped connection, the request may be NULL
3823 const char *pinnedHost
= "[unknown]";
3825 pinning
.host
= xstrdup(request
->url
.host());
3826 pinning
.port
= request
->url
.port();
3827 pinnedHost
= pinning
.host
;
3829 pinning
.port
= pinServer
->remote
.port();
3831 pinning
.pinned
= true;
3833 pinning
.peer
= cbdataReference(aPeer
);
3834 pinning
.auth
= auth
;
3835 char stmp
[MAX_IPSTRLEN
];
3836 char desc
[FD_DESC_SZ
];
3837 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
3838 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
3839 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
3840 clientConnection
->fd
);
3841 fd_note(pinning
.serverConnection
->fd
, desc
);
3843 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3844 pinning
.closeHandler
= JobCallback(33, 5,
3845 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
3846 // remember the pinned connection so that cb does not unpin a fresher one
3847 typedef CommCloseCbParams Params
;
3848 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
3849 params
.conn
= pinning
.serverConnection
;
3850 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
3853 /// [re]start monitoring pinned connection for peer closures so that we can
3854 /// propagate them to an _idle_ client pinned to that peer
3856 ConnStateData::startPinnedConnectionMonitoring()
3858 if (pinning
.readHandler
!= NULL
)
3859 return; // already monitoring
3861 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
3862 pinning
.readHandler
= JobCallback(33, 3,
3863 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
3864 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
3868 ConnStateData::stopPinnedConnectionMonitoring()
3870 if (pinning
.readHandler
!= NULL
) {
3871 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
3872 pinning
.readHandler
= NULL
;
3878 ConnStateData::handleIdleClientPinnedTlsRead()
3880 // A ready-for-reading connection means that the TLS server either closed
3881 // the connection, sent us some unexpected HTTP data, or started TLS
3882 // renegotiations. We should close the connection except for the last case.
3884 Must(pinning
.serverConnection
!= nullptr);
3885 auto ssl
= fd_table
[pinning
.serverConnection
->fd
].ssl
.get();
3890 const int readResult
= SSL_read(ssl
, buf
, sizeof(buf
));
3892 if (readResult
> 0 || SSL_pending(ssl
) > 0) {
3893 debugs(83, 2, pinning
.serverConnection
<< " TLS application data read");
3897 switch(const int error
= SSL_get_error(ssl
, readResult
)) {
3898 case SSL_ERROR_WANT_WRITE
:
3899 debugs(83, DBG_IMPORTANT
, pinning
.serverConnection
<< " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection");
3900 // fall through to restart monitoring, for now
3901 case SSL_ERROR_NONE
:
3902 case SSL_ERROR_WANT_READ
:
3903 startPinnedConnectionMonitoring();
3907 debugs(83, 2, pinning
.serverConnection
<< " TLS error: " << error
);
3916 /// Our read handler called by Comm when the server either closes an idle pinned connection or
3917 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
3919 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
3921 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
3923 if (io
.flag
== Comm::ERR_CLOSING
)
3924 return; // close handler will clean up
3926 Must(pinning
.serverConnection
== io
.conn
);
3929 if (handleIdleClientPinnedTlsRead())
3933 const bool clientIsIdle
= pipeline
.empty();
3935 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
3936 io
.size
<< (clientIsIdle
? " with idle client" : ""));
3938 pinning
.serverConnection
->close();
3940 // If we are still sending data to the client, do not close now. When we are done sending,
3941 // ConnStateData::kick() checks pinning.serverConnection and will close.
3942 // However, if we are idle, then we must close to inform the idle client and minimize races.
3943 if (clientIsIdle
&& clientConnection
!= NULL
)
3944 clientConnection
->close();
3947 const Comm::ConnectionPointer
3948 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
3950 debugs(33, 7, HERE
<< pinning
.serverConnection
);
3953 if (!Comm::IsConnOpen(pinning
.serverConnection
))
3955 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->url
.host()) != 0)
3957 else if (request
&& pinning
.port
!= request
->url
.port())
3959 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
3961 else if (aPeer
!= pinning
.peer
)
3965 /* The pinning info is not safe, remove any pinning info */
3966 unpinConnection(true);
3969 return pinning
.serverConnection
;
3972 Comm::ConnectionPointer
3973 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
3975 debugs(33, 7, pinning
.serverConnection
);
3976 if (validatePinnedConnection(request
, aPeer
) != NULL
)
3977 stopPinnedConnectionMonitoring();
3979 return pinning
.serverConnection
; // closed if validation failed
3983 ConnStateData::unpinConnection(const bool andClose
)
3985 debugs(33, 3, HERE
<< pinning
.serverConnection
);
3988 cbdataReferenceDone(pinning
.peer
);
3990 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
3991 if (pinning
.closeHandler
!= NULL
) {
3992 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
3993 pinning
.closeHandler
= NULL
;
3996 stopPinnedConnectionMonitoring();
3998 // close the server side socket if requested
4000 pinning
.serverConnection
->close();
4001 pinning
.serverConnection
= NULL
;
4004 safe_free(pinning
.host
);
4006 pinning
.zeroReply
= false;
4008 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4009 * connection has gone away */