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
);
589 flags
.readMore
= false;
590 DeregisterRunner(this);
591 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
592 pipeline
.terminateAll(0);
594 unpinConnection(true);
596 Server::swanSong(); // closes the client connection
599 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
600 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
603 flags
.swanSang
= true;
607 ConnStateData::isOpen() const
609 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
610 Comm::IsConnOpen(clientConnection
) &&
611 !fd_table
[clientConnection
->fd
].closing();
614 ConnStateData::~ConnStateData()
616 debugs(33, 3, HERE
<< clientConnection
);
619 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
622 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
624 if (bodyPipe
!= NULL
)
625 stopProducingFor(bodyPipe
, false);
627 delete bodyParser
; // TODO: pool
630 delete sslServerBump
;
635 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
636 * This is the client-side persistent connection flag. We need
637 * to set this relatively early in the request processing
638 * to handle hacks for broken servers and clients.
641 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
643 HttpRequest
*request
= http
->request
;
645 debugs(33, 3, "http_ver = " << request
->http_ver
);
646 debugs(33, 3, "method = " << request
->method
);
648 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
649 request
->flags
.proxyKeepalive
= request
->persistent();
652 /// checks body length of non-chunked requests
654 clientIsContentLengthValid(HttpRequest
* r
)
656 // No Content-Length means this request just has no body, but conflicting
657 // Content-Lengths mean a message framing error (RFC 7230 Section 3.3.3 #4).
658 if (r
->header
.conflictingContentLength())
661 switch (r
->method
.id()) {
663 case Http::METHOD_GET
:
665 case Http::METHOD_HEAD
:
666 /* We do not want to see a request entity on GET/HEAD requests */
667 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
670 /* For other types of requests we don't care */
678 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
680 if (Config
.maxRequestBodySize
&&
681 bodyLength
> Config
.maxRequestBodySize
)
682 return 1; /* too large */
688 ClientHttpRequest::multipartRangeRequest() const
690 return request
->multipartRangeRequest();
694 clientPackTermBound(String boundary
, MemBuf
*mb
)
696 mb
->appendf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
697 debugs(33, 6, "buf offset: " << mb
->size
);
701 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
703 HttpHeader
hdr(hoReply
);
708 debugs(33, 5, "appending boundary: " << boundary
);
709 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
710 mb
->appendf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
712 /* stuff the header with required entries and pack it */
714 if (rep
->header
.has(Http::HdrType::CONTENT_TYPE
))
715 hdr
.putStr(Http::HdrType::CONTENT_TYPE
, rep
->header
.getStr(Http::HdrType::CONTENT_TYPE
));
717 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
722 /* append <crlf> (we packed a header, not a reply) */
723 mb
->append("\r\n", 2);
726 /** returns expected content length for multi-range replies
727 * note: assumes that httpHdrRangeCanonize has already been called
728 * warning: assumes that HTTP headers for individual ranges at the
729 * time of the actuall assembly will be exactly the same as
730 * the headers when clientMRangeCLen() is called */
732 ClientHttpRequest::mRangeCLen()
740 HttpHdrRange::iterator pos
= request
->range
->begin();
742 while (pos
!= request
->range
->end()) {
743 /* account for headers for this range */
745 clientPackRangeHdr(memObject()->getReply(),
746 *pos
, range_iter
.boundary
, &mb
);
749 /* account for range content */
750 clen
+= (*pos
)->length
;
752 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
756 /* account for the terminating boundary */
759 clientPackTermBound(range_iter
.boundary
, &mb
);
769 * generates a "unique" boundary string for multipart responses
770 * the caller is responsible for cleaning the string */
772 ClientHttpRequest::rangeBoundaryStr() const
775 String
b(APP_FULLNAME
);
777 key
= storeEntry()->getMD5Text();
778 b
.append(key
, strlen(key
));
783 * Write a chunk of data to a client socket. If the reply is present,
784 * send the reply headers down the wire too, and clean them up when
787 * The request is one backed by a connection, not an internal request.
788 * data context is not NULL
789 * There are no more entries in the stream chain.
792 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
793 HttpReply
* rep
, StoreIOBuffer receivedData
)
795 // dont tryt to deliver if client already ABORTED
796 if (!http
->getConn() || !cbdataReferenceValid(http
->getConn()) || !Comm::IsConnOpen(http
->getConn()->clientConnection
))
799 /* Test preconditions */
800 assert(node
!= NULL
);
801 PROF_start(clientSocketRecipient
);
802 /* TODO: handle this rather than asserting
803 * - it should only ever happen if we cause an abort and
804 * the callback chain loops back to here, so we can simply return.
805 * However, that itself shouldn't happen, so it stays as an assert for now.
807 assert(cbdataReferenceValid(node
));
808 assert(node
->node
.next
== NULL
);
809 Http::StreamPointer context
= dynamic_cast<Http::Stream
*>(node
->data
.getRaw());
810 assert(context
!= NULL
);
812 /* TODO: check offset is what we asked for */
814 // TODO: enforces HTTP/1 MUST on pipeline order, but is irrelevant to HTTP/2
815 if (context
!= http
->getConn()->pipeline
.front())
816 context
->deferRecipientForLater(node
, rep
, receivedData
);
818 http
->getConn()->handleReply(rep
, receivedData
);
820 PROF_stop(clientSocketRecipient
);
824 * Called when a downstream node is no longer interested in
825 * our data. As we are a terminal node, this means on aborts
829 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
831 /* Test preconditions */
832 assert(node
!= NULL
);
833 /* TODO: handle this rather than asserting
834 * - it should only ever happen if we cause an abort and
835 * the callback chain loops back to here, so we can simply return.
836 * However, that itself shouldn't happen, so it stays as an assert for now.
838 assert(cbdataReferenceValid(node
));
839 /* Set null by ContextFree */
840 assert(node
->node
.next
== NULL
);
841 /* this is the assert discussed above */
842 assert(NULL
== dynamic_cast<Http::Stream
*>(node
->data
.getRaw()));
843 /* We are only called when the client socket shutsdown.
844 * Tell the prev pipeline member we're finished
846 clientStreamDetach(node
, http
);
850 ConnStateData::readNextRequest()
852 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
854 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
856 * Set the timeout BEFORE calling readSomeData().
858 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
859 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
860 TimeoutDialer
, this, ConnStateData::requestTimeout
);
861 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
864 /** Please don't do anything with the FD past here! */
868 ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest
, ConnStateData
* conn
)
870 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
872 /** If the client stream is waiting on a socket write to occur, then */
874 if (deferredRequest
->flags
.deferred
) {
875 /** NO data is allowed to have been sent. */
876 assert(deferredRequest
->http
->out
.size
== 0);
878 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
879 deferredRequest
->http
,
880 deferredRequest
->deferredparams
.rep
,
881 deferredRequest
->deferredparams
.queuedBuffer
);
884 /** otherwise, the request is still active in a callbacksomewhere,
890 ConnStateData::kick()
892 if (!Comm::IsConnOpen(clientConnection
)) {
893 debugs(33, 2, clientConnection
<< " Connection was closed");
897 if (pinning
.pinned
&& !Comm::IsConnOpen(pinning
.serverConnection
)) {
898 debugs(33, 2, clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
899 clientConnection
->close();
904 * We are done with the response, and we are either still receiving request
905 * body (early response!) or have already stopped receiving anything.
907 * If we are still receiving, then clientParseRequest() below will fail.
908 * (XXX: but then we will call readNextRequest() which may succeed and
909 * execute a smuggled request as we are not done with the current request).
911 * If we stopped because we got everything, then try the next request.
913 * If we stopped receiving because of an error, then close now to avoid
914 * getting stuck and to prevent accidental request smuggling.
917 if (const char *reason
= stoppedReceiving()) {
918 debugs(33, 3, "closing for earlier request error: " << reason
);
919 clientConnection
->close();
924 * Attempt to parse a request from the request buffer.
925 * If we've been fed a pipelined request it may already
926 * be in our read buffer.
929 * This needs to fall through - if we're unlucky and parse the _last_ request
930 * from our read buffer we may never re-register for another client read.
933 if (clientParseRequests()) {
934 debugs(33, 3, clientConnection
<< ": parsed next request from buffer");
938 * Either we need to kick-start another read or, if we have
939 * a half-closed connection, kill it after the last request.
940 * This saves waiting for half-closed connections to finished being
941 * half-closed _AND_ then, sometimes, spending "Timeout" time in
942 * the keepalive "Waiting for next request" state.
944 if (commIsHalfClosed(clientConnection
->fd
) && pipeline
.empty()) {
945 debugs(33, 3, "half-closed client with no pending requests, closing");
946 clientConnection
->close();
951 * At this point we either have a parsed request (which we've
952 * kicked off the processing for) or not. If we have a deferred
953 * request (parsed but deferred for pipeling processing reasons)
954 * then look at processing it. If not, simply kickstart
957 Http::StreamPointer deferredRequest
= pipeline
.front();
958 if (deferredRequest
!= nullptr) {
959 debugs(33, 3, clientConnection
<< ": calling PushDeferredIfNeeded");
960 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, this);
961 } else if (flags
.readMore
) {
962 debugs(33, 3, clientConnection
<< ": calling readNextRequest()");
965 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
966 debugs(33, DBG_IMPORTANT
, MYNAME
<< "abandoning " << clientConnection
);
971 ConnStateData::stopSending(const char *error
)
973 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
974 "; old receiving error: " <<
975 (stoppedReceiving() ? stoppedReceiving_
: "none"));
977 if (const char *oldError
= stoppedSending()) {
978 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
979 return; // nothing has changed as far as this connection is concerned
981 stoppedSending_
= error
;
983 if (!stoppedReceiving()) {
984 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
985 debugs(33, 5, HERE
<< "must still read " << expecting
<<
986 " request body bytes with " << inBuf
.length() << " unused");
987 return; // wait for the request receiver to finish reading
991 clientConnection
->close();
995 ConnStateData::afterClientWrite(size_t size
)
997 if (pipeline
.empty())
1000 auto ctx
= pipeline
.front();
1002 statCounter
.client_http
.kbytes_out
+= size
;
1003 if (ctx
->http
->logType
.isTcpHit())
1004 statCounter
.client_http
.hit_kbytes_out
+= size
;
1006 ctx
->writeComplete(size
);
1010 ConnStateData::abortRequestParsing(const char *const uri
)
1012 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1013 http
->req_sz
= inBuf
.length();
1014 http
->uri
= xstrdup(uri
);
1015 setLogUri (http
, uri
);
1016 auto *context
= new Http::Stream(clientConnection
, http
);
1017 StoreIOBuffer tempBuffer
;
1018 tempBuffer
.data
= context
->reqbuf
;
1019 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1020 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1021 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1022 clientSocketDetach
, context
, tempBuffer
);
1027 ConnStateData::startShutdown()
1029 // RegisteredRunner API callback - Squid has been shut down
1031 // if connection is idle terminate it now,
1032 // otherwise wait for grace period to end
1033 if (pipeline
.empty())
1038 ConnStateData::endingShutdown()
1040 // RegisteredRunner API callback - Squid shutdown grace period is over
1042 // force the client connection to close immediately
1043 // swanSong() in the close handler will cleanup.
1044 if (Comm::IsConnOpen(clientConnection
))
1045 clientConnection
->close();
1047 // deregister now to ensure finalShutdown() does not kill us prematurely.
1048 // fd_table purge will cleanup if close handler was not fast enough.
1049 DeregisterRunner(this);
1053 skipLeadingSpace(char *aString
)
1055 char *result
= aString
;
1057 while (xisspace(*aString
))
1064 * 'end' defaults to NULL for backwards compatibility
1065 * remove default value if we ever get rid of NULL-terminated
1069 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1072 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1076 for (; end
> uriAndHTTPVersion
; --end
) {
1077 if (*end
== '\n' || *end
== '\r')
1080 if (xisspace(*end
)) {
1081 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1092 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1094 safe_free(http
->log_uri
);
1097 // The uri is already clean just dump it.
1098 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1101 switch (Config
.uri_whitespace
) {
1102 case URI_WHITESPACE_ALLOW
:
1103 flags
|= RFC1738_ESCAPE_NOSPACE
;
1105 case URI_WHITESPACE_ENCODE
:
1106 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1107 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1110 case URI_WHITESPACE_CHOP
: {
1111 flags
|= RFC1738_ESCAPE_NOSPACE
;
1112 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1113 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1114 int pos
= strcspn(http
->log_uri
, w_space
);
1115 http
->log_uri
[pos
] = '\0';
1119 case URI_WHITESPACE_DENY
:
1120 case URI_WHITESPACE_STRIP
:
1123 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1127 if (!xisspace(*t
)) {
1134 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
1143 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1145 int vhost
= conn
->port
->vhost
;
1146 int vport
= conn
->port
->vport
;
1147 static char ipbuf
[MAX_IPSTRLEN
];
1149 http
->flags
.accel
= true;
1151 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1153 static const SBuf
cache_object("cache_object://");
1154 if (hp
->requestUri().startsWith(cache_object
))
1155 return; /* already in good shape */
1157 // XXX: re-use proper URL parser for this
1158 SBuf url
= hp
->requestUri(); // use full provided URI if we abort
1159 do { // use a loop so we can break out of it
1160 ::Parser::Tokenizer
tok(url
);
1161 if (tok
.skip('/')) // origin-form URL already.
1164 if (conn
->port
->vhost
)
1165 return; /* already in good shape */
1167 // skip the URI scheme
1168 static const CharacterSet uriScheme
= CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1169 static const SBuf
uriSchemeEnd("://");
1170 if (!tok
.skipAll(uriScheme
) || !tok
.skip(uriSchemeEnd
))
1173 // skip the authority segment
1174 // RFC 3986 complex nested ABNF for "authority" boils down to this:
1175 static const CharacterSet authority
= CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
1176 CharacterSet::HEXDIG
+ CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1177 if (!tok
.skipAll(authority
))
1180 static const SBuf
slashUri("/");
1181 const SBuf t
= tok
.remaining();
1184 else if (t
[0]=='/') // looks like path
1186 else if (t
[0]=='?' || t
[0]=='#') { // looks like query or fragment. fix '/'
1189 } // else do nothing. invalid path
1193 #if SHOULD_REJECT_UNKNOWN_URLS
1194 // reject URI which are not well-formed even after the processing above
1195 if (url
.isEmpty() || url
[0] != '/') {
1196 hp
->parseStatusCode
= Http::scBadRequest
;
1197 return conn
->abortRequestParsing("error:invalid-request");
1202 vport
= http
->getConn()->clientConnection
->local
.port();
1204 const bool switchedToHttps
= conn
->switchedToHttps();
1205 const bool tryHostHeader
= vhost
|| switchedToHttps
;
1207 if (tryHostHeader
&& (host
= hp
->getHeaderField("Host"))) {
1208 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
1213 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
1214 strncpy(thost
, host
, (t
-host
));
1215 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
1218 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
1221 } // else nothing to alter port-wise.
1222 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+ strlen(host
);
1223 http
->uri
= (char *)xcalloc(url_sz
, 1);
1224 const SBuf
&scheme
= AnyP::UriScheme(conn
->transferProtocol
.protocol
).image();
1225 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s" SQUIDSBUFPH
, SQUIDSBUFPRINT(scheme
), host
, SQUIDSBUFPRINT(url
));
1226 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
1227 } else if (conn
->port
->defaultsite
/* && !vhost */) {
1228 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
1229 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1230 strlen(conn
->port
->defaultsite
);
1231 http
->uri
= (char *)xcalloc(url_sz
, 1);
1235 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
1237 const SBuf
&scheme
= AnyP::UriScheme(conn
->transferProtocol
.protocol
).image();
1238 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s%s" SQUIDSBUFPH
,
1239 SQUIDSBUFPRINT(scheme
), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
1240 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
1241 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
1242 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
1243 /* Put the local socket IP address as the hostname, with whatever vport we found */
1244 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1245 http
->uri
= (char *)xcalloc(url_sz
, 1);
1246 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1247 const SBuf
&scheme
= AnyP::UriScheme(conn
->transferProtocol
.protocol
).image();
1248 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s:%d" SQUIDSBUFPH
,
1249 SQUIDSBUFPRINT(scheme
), ipbuf
, vport
, SQUIDSBUFPRINT(url
));
1250 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
1255 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1257 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
1258 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
1259 return; /* already in good shape */
1261 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1263 if (const char *host
= hp
->getHeaderField("Host")) {
1264 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1266 http
->uri
= (char *)xcalloc(url_sz
, 1);
1267 const SBuf
&scheme
= AnyP::UriScheme(conn
->transferProtocol
.protocol
).image();
1268 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s" SQUIDSBUFPH
,
1269 SQUIDSBUFPRINT(scheme
), host
, SQUIDSBUFPRINT(hp
->requestUri()));
1270 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
1272 /* Put the local socket IP address as the hostname. */
1273 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1274 http
->uri
= (char *)xcalloc(url_sz
, 1);
1275 static char ipbuf
[MAX_IPSTRLEN
];
1276 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1277 const SBuf
&scheme
= AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).image();
1278 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s:%d" SQUIDSBUFPH
,
1279 SQUIDSBUFPRINT(scheme
),
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");
1317 hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
||
1318 hp
->parseStatusCode
== Http::scUriTooLong
;
1319 auto result
= csd
->abortRequestParsing(
1320 tooBig
? "error:request-too-large" : "error:invalid-request");
1321 // assume that remaining leftovers belong to this bad request
1322 csd
->consumeInput(csd
->inBuf
.length());
1327 /* We know the whole request is in parser now */
1328 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
1329 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
1330 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
1334 /* deny CONNECT via accelerated ports */
1335 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
1336 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
1337 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1338 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1339 return csd
->abortRequestParsing("error:method-not-allowed");
1342 /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific
1343 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
1344 * If seen it signals a broken client or proxy has corrupted the traffic.
1346 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
1347 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
1348 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1349 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1350 return csd
->abortRequestParsing("error:method-not-allowed");
1353 if (hp
->method() == Http::METHOD_NONE
) {
1354 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1355 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1356 return csd
->abortRequestParsing("error:unsupported-request-method");
1359 // Process headers after request line
1360 debugs(33, 3, "complete request received. " <<
1361 "prefix_sz = " << hp
->messageHeaderSize() <<
1362 ", request-line-size=" << hp
->firstLineSize() <<
1363 ", mime-header-size=" << hp
->headerBlockSize() <<
1364 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
1366 /* Ok, all headers are received */
1367 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
1369 http
->req_sz
= hp
->messageHeaderSize();
1370 Http::Stream
*result
= new Http::Stream(csd
->clientConnection
, http
);
1372 StoreIOBuffer tempBuffer
;
1373 tempBuffer
.data
= result
->reqbuf
;
1374 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1376 ClientStreamData newServer
= new clientReplyContext(http
);
1377 ClientStreamData newClient
= result
;
1378 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1379 clientReplyStatus
, newServer
, clientSocketRecipient
,
1380 clientSocketDetach
, newClient
, tempBuffer
);
1383 debugs(33,5, "Prepare absolute URL from " <<
1384 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
1385 /* Rewrite the URL in transparent or accelerator mode */
1386 /* NP: there are several cases to traverse here:
1387 * - standard mode (forward proxy)
1388 * - transparent mode (TPROXY)
1389 * - transparent mode with failures
1390 * - intercept mode (NAT)
1391 * - intercept mode with failures
1392 * - accelerator mode (reverse proxy)
1393 * - internal relative-URL
1394 * - mixed combos of the above with internal URL
1395 * - remote interception with PROXY protocol
1396 * - remote reverse-proxy with PROXY protocol
1398 if (csd
->transparent()) {
1399 /* intercept or transparent mode, properly working with no failures */
1400 prepareTransparentURL(csd
, http
, hp
);
1402 } else if (internalCheck(hp
->requestUri())) { // NP: only matches relative-URI
1403 /* internal URL mode */
1404 /* prepend our name & port */
1405 http
->uri
= xstrdup(internalLocalUri(NULL
, hp
->requestUri()));
1406 // We just re-wrote the URL. Must replace the Host: header.
1407 // But have not parsed there yet!! flag for local-only handling.
1408 http
->flags
.internal
= true;
1410 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
1411 /* accelerator mode */
1412 prepareAcceleratedURL(csd
, http
, hp
);
1416 /* No special rewrites have been applied above, use the
1417 * requested url. may be rewritten later, so make extra room */
1418 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
1419 http
->uri
= (char *)xcalloc(url_sz
, 1);
1420 SBufToCstring(http
->uri
, hp
->requestUri());
1423 result
->flags
.parsed_ok
= 1;
1428 ConnStateData::connFinishedWithConn(int size
)
1431 if (pipeline
.empty() && inBuf
.isEmpty()) {
1432 /* no current or pending requests */
1433 debugs(33, 4, HERE
<< clientConnection
<< " closed");
1435 } else if (!Config
.onoff
.half_closed_clients
) {
1436 /* admin doesn't want to support half-closed client sockets */
1437 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
1438 pipeline
.terminateAll(0);
1447 ConnStateData::consumeInput(const size_t byteCount
)
1449 assert(byteCount
> 0 && byteCount
<= inBuf
.length());
1450 inBuf
.consume(byteCount
);
1451 debugs(33, 5, "inBuf has " << inBuf
.length() << " unused bytes");
1455 ConnStateData::clientAfterReadingRequests()
1457 // Were we expecting to read more request body from half-closed connection?
1458 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
1459 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
1460 clientConnection
->close();
1469 ConnStateData::quitAfterError(HttpRequest
*request
)
1471 // From HTTP p.o.v., we do not have to close after every error detected
1472 // at the client-side, but many such errors do require closure and the
1473 // client-side code is bad at handling errors so we play it safe.
1475 request
->flags
.proxyKeepalive
= false;
1476 flags
.readMore
= false;
1477 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
1481 bool ConnStateData::serveDelayedError(Http::Stream
*context
)
1483 ClientHttpRequest
*http
= context
->http
;
1488 assert(sslServerBump
->entry
);
1489 // Did we create an error entry while processing CONNECT?
1490 if (!sslServerBump
->entry
->isEmpty()) {
1491 quitAfterError(http
->request
);
1493 // Get the saved error entry and send it to the client by replacing the
1494 // ClientHttpRequest store entry with it.
1495 clientStreamNode
*node
= context
->getClientReplyContext();
1496 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1498 debugs(33, 5, "Responding with delated error for " << http
->uri
);
1499 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
1501 // save the original request for logging purposes
1502 if (!context
->http
->al
->request
) {
1503 context
->http
->al
->request
= http
->request
;
1504 HTTPMSGLOCK(context
->http
->al
->request
);
1507 // Get error details from the fake certificate-peeking request.
1508 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
1509 context
->pullData();
1513 // In bump-server-first mode, we have not necessarily seen the intended
1514 // server name at certificate-peeking time. Check for domain mismatch now,
1515 // when we can extract the intended name from the bumped HTTP request.
1516 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
1517 HttpRequest
*request
= http
->request
;
1518 if (!Ssl::checkX509ServerValidity(srvCert
, request
->url
.host())) {
1519 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
1520 "does not match domainname " << request
->url
.host());
1522 bool allowDomainMismatch
= false;
1523 if (Config
.ssl_client
.cert_error
) {
1524 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
1525 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
1526 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
1527 delete check
.sslErrors
;
1528 check
.sslErrors
= NULL
;
1531 if (!allowDomainMismatch
) {
1532 quitAfterError(request
);
1534 clientStreamNode
*node
= context
->getClientReplyContext();
1535 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1536 assert (repContext
);
1538 // Fill the server IP and hostname for error page generation.
1539 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
1540 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->url
.host());
1542 // Create an error object and fill it
1543 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
1544 err
->src_addr
= clientConnection
->remote
;
1545 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
1546 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
1548 err
->detail
= errDetail
;
1549 // Save the original request for logging purposes.
1550 if (!context
->http
->al
->request
) {
1551 context
->http
->al
->request
= request
;
1552 HTTPMSGLOCK(context
->http
->al
->request
);
1554 repContext
->setReplyToError(request
->method
, err
);
1555 assert(context
->http
->out
.offset
== 0);
1556 context
->pullData();
1564 #endif // USE_OPENSSL
1567 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
1568 * or false otherwise
1571 clientTunnelOnError(ConnStateData
*conn
, Http::Stream
*context
, HttpRequest
*request
, const HttpRequestMethod
& method
, err_type requestError
, Http::StatusCode errStatusCode
, const char *requestErrorBytes
)
1573 if (conn
->port
->flags
.isIntercepted() &&
1574 Config
.accessList
.on_unsupported_protocol
&& conn
->pipeline
.nrequests
<= 1) {
1575 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
, NULL
);
1576 checklist
.requestErrorType
= requestError
;
1577 checklist
.src_addr
= conn
->clientConnection
->remote
;
1578 checklist
.my_addr
= conn
->clientConnection
->local
;
1579 checklist
.conn(conn
);
1580 allow_t answer
= checklist
.fastCheck();
1581 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
1582 debugs(33, 3, "Request will be tunneled to server");
1584 // XXX: Either the context is finished() or it should stay queued.
1585 // The below may leak client streams BodyPipe objects. BUT, we need
1586 // to check if client-streams detatch is safe to do here (finished() will detatch).
1587 assert(conn
->pipeline
.front() == context
); // XXX: still assumes HTTP/1 semantics
1588 conn
->pipeline
.popMe(Http::StreamPointer(context
));
1590 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
1591 return conn
->fakeAConnectRequest("unknown-protocol", conn
->preservedClientData
);
1593 debugs(33, 3, "Continue with returning the error: " << requestError
);
1598 conn
->quitAfterError(request
);
1599 clientStreamNode
*node
= context
->getClientReplyContext();
1600 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1601 assert (repContext
);
1603 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
1605 assert(context
->http
->out
.offset
== 0);
1606 context
->pullData();
1607 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
1612 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
1616 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
1617 * to here because calling comm_reset_close() causes http to
1618 * be freed before accessing.
1620 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
1621 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
1622 conn
->flags
.readMore
= false;
1623 comm_reset_close(conn
->clientConnection
);
1628 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, Http::Stream
*context
)
1630 ClientHttpRequest
*http
= context
->http
;
1631 bool chunked
= false;
1632 bool mustReplyToOptions
= false;
1633 bool unsupportedTe
= false;
1634 bool expectBody
= false;
1636 // We already have the request parsed and checked, so we
1637 // only need to go through the final body/conn setup to doCallouts().
1638 assert(http
->request
);
1639 HttpRequest::Pointer request
= http
->request
;
1641 // temporary hack to avoid splitting this huge function with sensitive code
1642 const bool isFtp
= !hp
;
1644 // Some blobs below are still HTTP-specific, but we would have to rewrite
1645 // this entire function to remove them from the FTP code path. Connection
1646 // setup and body_pipe preparation blobs are needed for FTP.
1648 request
->clientConnectionManager
= conn
;
1650 request
->flags
.accelerated
= http
->flags
.accel
;
1651 request
->flags
.sslBumped
=conn
->switchedToHttps();
1652 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
1653 // TODO: decouple http->flags.accel from request->flags.sslBumped
1654 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
1655 !conn
->port
->allow_direct
: 0;
1656 request
->sources
|= isFtp
? HttpMsg::srcFtp
:
1657 ((request
->flags
.sslBumped
|| conn
->port
->transport
.protocol
== AnyP::PROTO_HTTPS
) ? HttpMsg::srcHttps
: HttpMsg::srcHttp
);
1659 if (request
->flags
.sslBumped
) {
1660 if (conn
->getAuth() != NULL
)
1661 request
->auth_user_request
= conn
->getAuth();
1666 * If transparent or interception mode is working clone the transparent and interception flags
1667 * from the port settings to the request.
1669 if (http
->clientConnection
!= NULL
) {
1670 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
1671 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
1672 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
1673 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
1674 if (Config
.accessList
.spoof_client_ip
) {
1675 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
1676 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
1679 request
->flags
.spoofClientIp
= true;
1681 request
->flags
.spoofClientIp
= false;
1684 if (internalCheck(request
->url
.path())) {
1685 if (internalHostnameIs(request
->url
.host()) && request
->url
.port() == getMyPort()) {
1686 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true));
1687 http
->flags
.internal
= true;
1688 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->url
.path())) {
1689 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (global_internal_static on)");
1690 request
->url
.setScheme(AnyP::PROTO_HTTP
, "http");
1691 request
->url
.host(internalHostname());
1692 request
->url
.port(getMyPort());
1693 http
->flags
.internal
= true;
1695 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (not this proxy)");
1698 request
->flags
.internal
= http
->flags
.internal
;
1699 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
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
;
1710 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
1711 // for now Squid only supports HTTP requests
1712 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
1713 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
1714 request
->http_ver
.major
= http_ver
.major
;
1715 request
->http_ver
.minor
= http_ver
.minor
;
1718 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
1719 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
1720 request
->clientConnectionManager
= conn
;
1722 if (request
->header
.chunked()) {
1724 } else if (request
->header
.has(Http::HdrType::TRANSFER_ENCODING
)) {
1725 const String te
= request
->header
.getList(Http::HdrType::TRANSFER_ENCODING
);
1726 // HTTP/1.1 requires chunking to be the last encoding if there is one
1727 unsupportedTe
= te
.size() && te
!= "identity";
1728 } // else implied identity coding
1730 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
1731 (request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0);
1732 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
1733 clientStreamNode
*node
= context
->getClientReplyContext();
1734 conn
->quitAfterError(request
.getRaw());
1735 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1736 assert (repContext
);
1737 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
1738 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1739 assert(context
->http
->out
.offset
== 0);
1740 context
->pullData();
1741 clientProcessRequestFinished(conn
, request
);
1745 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
1746 clientStreamNode
*node
= context
->getClientReplyContext();
1747 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1748 assert (repContext
);
1749 conn
->quitAfterError(request
.getRaw());
1750 repContext
->setReplyToError(ERR_INVALID_REQ
,
1751 Http::scLengthRequired
, request
->method
, NULL
,
1752 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1753 assert(context
->http
->out
.offset
== 0);
1754 context
->pullData();
1755 clientProcessRequestFinished(conn
, request
);
1759 clientSetKeepaliveFlag(http
);
1760 // Let tunneling code be fully responsible for CONNECT requests
1761 if (http
->request
->method
== Http::METHOD_CONNECT
) {
1762 context
->mayUseConnection(true);
1763 conn
->flags
.readMore
= false;
1767 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
1768 clientProcessRequestFinished(conn
, request
);
1773 /* Do we expect a request-body? */
1774 expectBody
= chunked
|| request
->content_length
> 0;
1775 if (!context
->mayUseConnection() && expectBody
) {
1776 request
->body_pipe
= conn
->expectRequestBody(
1777 chunked
? -1 : request
->content_length
);
1779 /* Is it too large? */
1780 if (!chunked
&& // if chunked, we will check as we accumulate
1781 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
1782 clientStreamNode
*node
= context
->getClientReplyContext();
1783 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1784 assert (repContext
);
1785 conn
->quitAfterError(request
.getRaw());
1786 repContext
->setReplyToError(ERR_TOO_BIG
,
1787 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
1788 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
1789 assert(context
->http
->out
.offset
== 0);
1790 context
->pullData();
1791 clientProcessRequestFinished(conn
, request
);
1796 // We may stop producing, comm_close, and/or call setReplyToError()
1797 // below, so quit on errors to avoid http->doCallouts()
1798 if (!conn
->handleRequestBodyData()) {
1799 clientProcessRequestFinished(conn
, request
);
1803 if (!request
->body_pipe
->productionEnded()) {
1804 debugs(33, 5, "need more request body");
1805 context
->mayUseConnection(true);
1806 assert(conn
->flags
.readMore
);
1811 http
->calloutContext
= new ClientRequestContext(http
);
1815 clientProcessRequestFinished(conn
, request
);
1819 ConnStateData::pipelinePrefetchMax() const
1821 // TODO: Support pipelined requests through pinned connections.
1824 return Config
.pipeline_max_prefetch
;
1828 * Limit the number of concurrent requests.
1829 * \return true when there are available position(s) in the pipeline queue for another request.
1830 * \return false when the pipeline queue is full or disabled.
1833 ConnStateData::concurrentRequestQueueFilled() const
1835 const int existingRequestCount
= pipeline
.count();
1837 // default to the configured pipeline size.
1838 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
1840 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
1842 const int internalRequest
= 0;
1844 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
1846 // when queue filled already we cant add more.
1847 if (existingRequestCount
>= concurrentRequestLimit
) {
1848 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
1849 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
1857 * Perform proxy_protocol_access ACL tests on the client which
1858 * connected to PROXY protocol port to see if we trust the
1859 * sender enough to accept their PROXY header claim.
1862 ConnStateData::proxyProtocolValidateClient()
1864 if (!Config
.accessList
.proxyProtocol
)
1865 return proxyProtocolError("PROXY client not permitted by default ACL");
1867 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
1868 ch
.src_addr
= clientConnection
->remote
;
1869 ch
.my_addr
= clientConnection
->local
;
1872 if (ch
.fastCheck() != ACCESS_ALLOWED
)
1873 return proxyProtocolError("PROXY client not permitted by ACLs");
1879 * Perform cleanup on PROXY protocol errors.
1880 * If header parsing hits a fatal error terminate the connection,
1881 * otherwise wait for more data.
1884 ConnStateData::proxyProtocolError(const char *msg
)
1887 // This is important to know, but maybe not so much that flooding the log is okay.
1888 #if QUIET_PROXY_PROTOCOL
1889 // display the first of every 32 occurances at level 1, the others at level 2.
1890 static uint8_t hide
= 0;
1891 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
1893 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
1900 /// magic octet prefix for PROXY protocol version 1
1901 static const SBuf
Proxy1p0magic("PROXY ", 6);
1903 /// magic octet prefix for PROXY protocol version 2
1904 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
1907 * Test the connection read buffer for PROXY protocol header.
1908 * Version 1 and 2 header currently supported.
1911 ConnStateData::parseProxyProtocolHeader()
1913 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
1915 // detect and parse PROXY/2.0 protocol header
1916 if (inBuf
.startsWith(Proxy2p0magic
))
1917 return parseProxy2p0();
1919 // detect and parse PROXY/1.0 protocol header
1920 if (inBuf
.startsWith(Proxy1p0magic
))
1921 return parseProxy1p0();
1923 // detect and terminate other protocols
1924 if (inBuf
.length() >= Proxy2p0magic
.length()) {
1925 // PROXY/1.0 magic is shorter, so we know that
1926 // the input does not start with any PROXY magic
1927 return proxyProtocolError("PROXY protocol error: invalid header");
1930 // TODO: detect short non-magic prefixes earlier to avoid
1931 // waiting for more data which may never come
1933 // not enough bytes to parse yet.
1937 /// parse the PROXY/1.0 protocol header from the connection read buffer
1939 ConnStateData::parseProxy1p0()
1941 ::Parser::Tokenizer
tok(inBuf
);
1942 tok
.skip(Proxy1p0magic
);
1944 // skip to first LF (assumes it is part of CRLF)
1945 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
1947 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
1948 if (tok
.skip('\n')) {
1949 // found valid header
1950 inBuf
= tok
.remaining();
1951 needProxyProtocolHeader_
= false;
1952 // reset the tokenizer to work on found line only.
1955 return false; // no LF yet
1957 } else // protocol error only if there are more than 107 bytes prefix header
1958 return proxyProtocolError(inBuf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
1960 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
1961 if (tok
.skip(tcpName
)) {
1963 // skip TCP/IP version number
1964 static const CharacterSet
tcpVersions("TCP-version","46");
1965 if (!tok
.skipOne(tcpVersions
))
1966 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
1968 // skip SP after protocol version
1970 return proxyProtocolError("PROXY/1.0 error: missing SP");
1973 int64_t porta
, portb
;
1974 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
1976 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
1977 // leave the LF until later.
1978 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
1979 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
1980 tok
.int64(porta
) && tok
.skip(' ') &&
1984 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
1986 // parse IP and port strings
1987 Ip::Address originalClient
, originalDest
;
1989 if (!originalClient
.GetHostByName(ipa
.c_str()))
1990 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
1992 if (!originalDest
.GetHostByName(ipb
.c_str()))
1993 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
1995 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
1996 originalClient
.port(static_cast<uint16_t>(porta
));
1998 return proxyProtocolError("PROXY/1.0 error: invalid src port");
2000 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
2001 originalDest
.port(static_cast<uint16_t>(portb
));
2003 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
2005 // we have original client and destination details now
2006 // replace the client connection values
2007 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
2008 clientConnection
->local
= originalDest
;
2009 clientConnection
->remote
= originalClient
;
2010 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2011 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2012 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2014 // repeat fetch ensuring the new client FQDN can be logged
2015 if (Config
.onoff
.log_fqdn
)
2016 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2020 } else if (tok
.skip(unknown
)) {
2021 // found valid but unusable header
2025 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2030 /// parse the PROXY/2.0 protocol header from the connection read buffer
2032 ConnStateData::parseProxy2p0()
2034 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2035 if (inBuf
.length() < prefixLen
+ 4)
2036 return false; // need more bytes
2038 if ((inBuf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2039 return proxyProtocolError("PROXY/2.0 error: invalid version");
2041 const char command
= (inBuf
[prefixLen
] & 0x0F);
2042 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2043 return proxyProtocolError("PROXY/2.0 error: invalid command");
2045 const char family
= (inBuf
[prefixLen
+1] & 0xF0) >>4;
2046 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2047 return proxyProtocolError("PROXY/2.0 error: invalid family");
2049 const char proto
= (inBuf
[prefixLen
+1] & 0x0F);
2050 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2051 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2053 const char *clen
= inBuf
.rawContent() + prefixLen
+ 2;
2055 memcpy(&len
, clen
, sizeof(len
));
2058 if (inBuf
.length() < prefixLen
+ 4 + len
)
2059 return false; // need more bytes
2061 inBuf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2062 const SBuf extra
= inBuf
.consume(len
);
2063 needProxyProtocolHeader_
= false; // found successfully
2065 // LOCAL connections do nothing with the extras
2066 if (command
== 0x00/* LOCAL*/)
2070 struct { /* for TCP/UDP over IPv4, len = 12 */
2071 struct in_addr src_addr
;
2072 struct in_addr dst_addr
;
2076 struct { /* for TCP/UDP over IPv6, len = 36 */
2077 struct in6_addr src_addr
;
2078 struct in6_addr dst_addr
;
2083 struct { /* for AF_UNIX sockets, len = 216 */
2084 uint8_t src_addr
[108];
2085 uint8_t dst_addr
[108];
2091 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2093 // replace the client connection values
2094 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2097 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2098 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2099 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2100 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2101 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2102 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2105 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2106 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2107 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2108 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2109 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2110 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2112 default: // do nothing
2115 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2117 // repeat fetch ensuring the new client FQDN can be logged
2118 if (Config
.onoff
.log_fqdn
)
2119 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2125 ConnStateData::receivedFirstByte()
2127 if (receivedFirstByte_
)
2130 receivedFirstByte_
= true;
2131 // Set timeout to Config.Timeout.request
2132 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2133 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
2134 TimeoutDialer
, this, ConnStateData::requestTimeout
);
2135 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
2139 * Attempt to parse one or more requests from the input buffer.
2140 * Returns true after completing parsing of at least one request [header]. That
2141 * includes cases where parsing ended with an error (e.g., a huge request).
2144 ConnStateData::clientParseRequests()
2146 bool parsed_req
= false;
2148 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2150 // Loop while we have read bytes that are not needed for producing the body
2151 // On errors, bodyPipe may become nil, but readMore will be cleared
2152 while (!inBuf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2154 /* Limit the number of concurrent requests */
2155 if (concurrentRequestQueueFilled())
2158 // try to parse the PROXY protocol header magic bytes
2159 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
2162 if (Http::Stream
*context
= parseOneRequest()) {
2163 debugs(33, 5, clientConnection
<< ": done parsing a request");
2165 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2166 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2167 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2169 context
->registerWithConn();
2171 processParsedRequest(context
);
2173 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2175 if (context
->mayUseConnection()) {
2176 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2180 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
2181 inBuf
.length() << " < " << Config
.maxRequestHeaderSize
);
2182 Must(inBuf
.length() < Config
.maxRequestHeaderSize
);
2187 /* XXX where to 'finish' the parsing pass? */
2192 ConnStateData::afterClientRead()
2195 if (parsingTlsHandshake
) {
2196 parseTlsHandshake();
2201 /* Process next request */
2202 if (pipeline
.empty())
2203 fd_note(clientConnection
->fd
, "Reading next request");
2205 if (!clientParseRequests()) {
2209 * If the client here is half closed and we failed
2210 * to parse a request, close the connection.
2211 * The above check with connFinishedWithConn() only
2212 * succeeds _if_ the buffer is empty which it won't
2213 * be if we have an incomplete request.
2214 * XXX: This duplicates ConnStateData::kick
2216 if (pipeline
.empty() && commIsHalfClosed(clientConnection
->fd
)) {
2217 debugs(33, 5, clientConnection
<< ": half-closed connection, no completed request parsed, connection closing.");
2218 clientConnection
->close();
2226 clientAfterReadingRequests();
2230 * called when new request data has been read from the socket
2232 * \retval false called comm_close or setReplyToError (the caller should bail)
2233 * \retval true we did not call comm_close or setReplyToError
2236 ConnStateData::handleReadData()
2238 // if we are reading a body, stuff data into the body pipe
2239 if (bodyPipe
!= NULL
)
2240 return handleRequestBodyData();
2245 * called when new request body data has been buffered in inBuf
2246 * may close the connection if we were closing and piped everything out
2248 * \retval false called comm_close or setReplyToError (the caller should bail)
2249 * \retval true we did not call comm_close or setReplyToError
2252 ConnStateData::handleRequestBodyData()
2254 assert(bodyPipe
!= NULL
);
2256 if (bodyParser
) { // chunked encoding
2257 if (const err_type error
= handleChunkedRequestBody()) {
2258 abortChunkedRequestBody(error
);
2261 } else { // identity encoding
2262 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
2263 const size_t putSize
= bodyPipe
->putMoreData(inBuf
.c_str(), inBuf
.length());
2265 consumeInput(putSize
);
2267 if (!bodyPipe
->mayNeedMoreData()) {
2268 // BodyPipe will clear us automagically when we produced everything
2274 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
2276 if (const char *reason
= stoppedSending()) {
2277 /* we've finished reading like good clients,
2278 * now do the close that initiateClose initiated.
2280 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
2281 clientConnection
->close();
2289 /// parses available chunked encoded body bytes, checks size, returns errors
2291 ConnStateData::handleChunkedRequestBody()
2293 debugs(33, 7, "chunked from " << clientConnection
<< ": " << inBuf
.length());
2295 try { // the parser will throw on errors
2297 if (inBuf
.isEmpty()) // nothing to do
2300 BodyPipeCheckout
bpc(*bodyPipe
);
2301 bodyParser
->setPayloadBuffer(&bpc
.buf
);
2302 const bool parsed
= bodyParser
->parse(inBuf
);
2303 inBuf
= bodyParser
->remaining(); // sync buffers
2306 // dechunk then check: the size limit applies to _dechunked_ content
2307 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
2311 finishDechunkingRequest(true);
2313 return ERR_NONE
; // nil bodyPipe implies body end for the caller
2316 // if chunk parser needs data, then the body pipe must need it too
2317 Must(!bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
2319 // if parser needs more space and we can consume nothing, we will stall
2320 Must(!bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
2321 } catch (...) { // TODO: be more specific
2322 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
2323 return ERR_INVALID_REQ
;
2326 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
2330 /// quit on errors related to chunked request body handling
2332 ConnStateData::abortChunkedRequestBody(const err_type error
)
2334 finishDechunkingRequest(false);
2336 // XXX: The code below works if we fail during initial request parsing,
2337 // but if we fail when the server connection is used already, the server may send
2338 // us its response too, causing various assertions. How to prevent that?
2339 #if WE_KNOW_HOW_TO_SEND_ERRORS
2340 Http::StreamPointer context
= pipeline
.front();
2341 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
2342 clientStreamNode
*node
= context
->getClientReplyContext();
2343 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2345 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
2346 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
2347 repContext
->setReplyToError(error
, scode
,
2348 repContext
->http
->request
->method
,
2349 repContext
->http
->uri
,
2351 repContext
->http
->request
,
2353 context
->pullData();
2355 // close or otherwise we may get stuck as nobody will notice the error?
2356 comm_reset_close(clientConnection
);
2359 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
2360 comm_reset_close(clientConnection
);
2362 flags
.readMore
= false;
2366 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
2368 // request reader may get stuck waiting for space if nobody consumes body
2369 if (bodyPipe
!= NULL
)
2370 bodyPipe
->enableAutoConsumption();
2375 /** general lifetime handler for HTTP requests */
2377 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
2379 if (!Comm::IsConnOpen(io
.conn
))
2382 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
2384 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
2385 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
2386 receivedFirstByte();
2389 } else if (!fd_table
[io
.conn
->fd
].ssl
)
2392 const HttpRequestMethod method
;
2393 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
2394 // Tunnel established. Set receivedFirstByte to avoid loop.
2395 receivedFirstByte();
2401 * Just close the connection to not confuse browsers
2402 * using persistent connections. Some browsers open
2403 * a connection and then do not use it until much
2404 * later (presumeably because the request triggering
2405 * the open has already been completed on another
2408 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
2413 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
2415 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
2416 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
2417 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
2418 http
->logType
.err
.timedout
= true;
2419 if (Comm::IsConnOpen(io
.conn
))
2423 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
2424 AsyncJob("ConnStateData"), // kids overwrite
2426 bodyParser(nullptr),
2428 sslBumpMode(Ssl::bumpEnd
),
2430 needProxyProtocolHeader_(false),
2432 switchedToHttps_(false),
2433 parsingTlsHandshake(false),
2434 sslServerBump(NULL
),
2435 signAlgorithm(Ssl::algSignTrusted
),
2437 stoppedSending_(NULL
),
2438 stoppedReceiving_(NULL
)
2440 flags
.readMore
= true; // kids may overwrite
2441 flags
.swanSang
= false;
2443 pinning
.host
= NULL
;
2445 pinning
.pinned
= false;
2446 pinning
.auth
= false;
2447 pinning
.zeroReply
= false;
2448 pinning
.peer
= NULL
;
2450 // store the details required for creating more MasterXaction objects as new requests come in
2451 log_addr
= xact
->tcpClient
->remote
;
2452 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
2454 // register to receive notice of Squid signal events
2455 // which may affect long persisting client connections
2456 RegisterRunner(this);
2460 ConnStateData::start()
2462 BodyProducer::start();
2463 HttpControlMsgSink::start();
2465 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
2466 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
2467 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2468 int i
= IP_PMTUDISC_DONT
;
2469 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0) {
2471 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerr(xerrno
));
2474 static bool reported
= false;
2477 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
2483 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
2484 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
2485 comm_add_close_handler(clientConnection
->fd
, call
);
2487 if (Config
.onoff
.log_fqdn
)
2488 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2491 if (Ident::TheConfig
.identLookup
) {
2492 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
2493 identChecklist
.src_addr
= clientConnection
->remote
;
2494 identChecklist
.my_addr
= clientConnection
->local
;
2495 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
2496 Ident::Start(clientConnection
, clientIdentDone
, this);
2500 clientdbEstablished(clientConnection
->remote
, 1);
2502 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
2503 if (needProxyProtocolHeader_
) {
2504 if (!proxyProtocolValidateClient()) // will close the connection on failure
2509 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
2511 if (Config
.onoff
.client_db
) {
2512 /* it was said several times that client write limiter does not work if client_db is disabled */
2514 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
2515 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
2517 // TODO: we check early to limit error response bandwith but we
2518 // should recheck when we can honor delay_pool_uses_indirect
2519 // TODO: we should also pass the port details for myportname here.
2520 ch
.src_addr
= clientConnection
->remote
;
2521 ch
.my_addr
= clientConnection
->local
;
2523 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
2525 /* pools require explicit 'allow' to assign a client into them */
2526 if (pools
[pool
].access
) {
2527 ch
.changeAcl(pools
[pool
].access
);
2528 allow_t answer
= ch
.fastCheck();
2529 if (answer
== ACCESS_ALLOWED
) {
2531 /* request client information from db after we did all checks
2532 this will save hash lookup if client failed checks */
2533 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
2536 /* put client info in FDE */
2537 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
2539 /* setup write limiter for this request */
2540 const double burst
= floor(0.5 +
2541 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
2542 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
2545 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
2552 // kids must extend to actually start doing something (e.g., reading)
2555 /** Handle a new connection on an HTTP socket. */
2557 httpAccept(const CommAcceptCbParams
¶ms
)
2559 MasterXaction::Pointer xact
= params
.xaction
;
2560 AnyP::PortCfgPointer s
= xact
->squidPort
;
2562 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2564 if (params
.flag
!= Comm::OK
) {
2565 // Its possible the call was still queued when the client disconnected
2566 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2570 debugs(33, 4, params
.conn
<< ": accepted");
2571 fd_note(params
.conn
->fd
, "client http connect");
2573 if (s
->tcp_keepalive
.enabled
)
2574 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2576 ++incoming_sockets_accepted
;
2578 // Socket is ready, setup the connection manager to start using it
2579 auto *srv
= Http::NewServer(xact
);
2580 AsyncJob::Start(srv
); // usually async-calls readSomeData()
2585 /** Create SSL connection structure and update fd_table */
2587 httpsCreate(const Comm::ConnectionPointer
&conn
, Security::ContextPtr sslContext
)
2589 if (Ssl::CreateServer(sslContext
, conn
, "client https start")) {
2590 debugs(33, 5, "will negotate SSL on " << conn
);
2600 * \retval 1 on success
2601 * \retval 0 when needs more data
2602 * \retval -1 on error
2605 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
2607 int fd
= conn
->clientConnection
->fd
;
2608 auto ssl
= fd_table
[fd
].ssl
.get();
2612 if ((ret
= SSL_accept(ssl
)) <= 0) {
2613 const int xerrno
= errno
;
2614 const int ssl_error
= SSL_get_error(ssl
, ret
);
2616 switch (ssl_error
) {
2618 case SSL_ERROR_WANT_READ
:
2619 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, (callback
!= NULL
? conn
: NULL
), 0);
2622 case SSL_ERROR_WANT_WRITE
:
2623 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, (callback
!= NULL
? conn
: NULL
), 0);
2626 case SSL_ERROR_SYSCALL
:
2628 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
2630 debugs(83, (xerrno
== ECONNRESET
) ? 1 : 2, "Error negotiating SSL connection on FD " << fd
<< ": " <<
2631 (xerrno
== 0 ? ERR_error_string(ssl_error
, NULL
) : xstrerr(xerrno
)));
2635 case SSL_ERROR_ZERO_RETURN
:
2636 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
2640 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
2641 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
2642 " (" << ssl_error
<< "/" << ret
<< ")");
2651 /** negotiate an SSL connection */
2653 clientNegotiateSSL(int fd
, void *data
)
2655 ConnStateData
*conn
= (ConnStateData
*)data
;
2657 auto ssl
= fd_table
[fd
].ssl
.get();
2660 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
2661 if (ret
< 0) // An error
2662 conn
->clientConnection
->close();
2666 if (Security::SessionIsResumed(fd_table
[fd
].ssl
)) {
2667 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
2668 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
2670 if (Debug::Enabled(83, 4)) {
2671 /* Write out the SSL session details.. actually the call below, but
2672 * OpenSSL headers do strange typecasts confusing GCC.. */
2673 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
2674 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
2675 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
);
2677 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
2679 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
2680 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
2681 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
2682 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
2683 * Because there are two possible usable cast, if you get an error here, try the other
2684 * commented line. */
2686 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
2687 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
2691 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
2694 /* Note: This does not automatically fflush the log file.. */
2697 debugs(83, 2, "clientNegotiateSSL: New session " <<
2698 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
2699 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
2703 // Connection established. Retrieve TLS connection parameters for logging.
2704 conn
->clientConnection
->tlsNegotiations()->retrieveNegotiatedInfo(ssl
);
2706 client_cert
= SSL_get_peer_certificate(ssl
);
2708 if (client_cert
!= NULL
) {
2709 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2710 " client certificate: subject: " <<
2711 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
2713 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2714 " client certificate: issuer: " <<
2715 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
2717 X509_free(client_cert
);
2719 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
2720 " has no certificate.");
2723 #if defined(TLSEXT_NAMETYPE_host_name)
2724 if (!conn
->serverBump()) {
2725 // when in bumpClientFirst mode, get the server name from SNI
2726 if (const char *server
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))
2727 conn
->resetSslCommonName(server
);
2731 conn
->readSomeData();
2735 * If Security::ContextPtr is given, starts reading the TLS handshake.
2736 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPtr.
2739 httpsEstablish(ConnStateData
*connState
, Security::ContextPtr sslContext
)
2742 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
2744 if (!sslContext
|| !httpsCreate(details
, sslContext
))
2747 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2748 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
2749 connState
, ConnStateData::requestTimeout
);
2750 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
2752 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
2756 * A callback function to use with the ACLFilledChecklist callback.
2757 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
2758 * else reverts the connection to tunnel mode.
2761 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
2763 ConnStateData
*connState
= (ConnStateData
*) data
;
2765 // if the connection is closed or closing, just return.
2766 if (!connState
->isOpen())
2769 // Require both a match and a positive bump mode to work around exceptional
2770 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
2771 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
2772 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
2773 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
2775 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
2776 connState
->sslBumpMode
= Ssl::bumpNone
;
2778 if (!connState
->fakeAConnectRequest("ssl-bump", connState
->inBuf
))
2779 connState
->clientConnection
->close();
2782 /** handle a new HTTPS connection */
2784 httpsAccept(const CommAcceptCbParams
¶ms
)
2786 MasterXaction::Pointer xact
= params
.xaction
;
2787 const AnyP::PortCfgPointer s
= xact
->squidPort
;
2789 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2791 if (params
.flag
!= Comm::OK
) {
2792 // Its possible the call was still queued when the client disconnected
2793 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2797 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
2798 fd_note(params
.conn
->fd
, "client https connect");
2800 if (s
->tcp_keepalive
.enabled
) {
2801 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2803 ++incoming_sockets_accepted
;
2805 // Socket is ready, setup the connection manager to start using it
2806 auto *srv
= Https::NewServer(xact
);
2807 AsyncJob::Start(srv
); // usually async-calls postHttpsAccept()
2811 ConnStateData::postHttpsAccept()
2813 if (port
->flags
.tunnelSslBumping
) {
2814 debugs(33, 5, "accept transparent connection: " << clientConnection
);
2816 if (!Config
.accessList
.ssl_bump
) {
2817 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
2821 // Create a fake HTTP request for ssl_bump ACL check,
2822 // using tproxy/intercept provided destination IP and port.
2823 HttpRequest
*request
= new HttpRequest();
2824 static char ip
[MAX_IPSTRLEN
];
2825 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
2826 request
->url
.host(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
2827 request
->url
.port(clientConnection
->local
.port());
2828 request
->myportname
= port
->name
;
2830 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
2831 acl_checklist
->src_addr
= clientConnection
->remote
;
2832 acl_checklist
->my_addr
= port
->s
;
2833 // Build a local AccessLogEntry to allow requiresAle() acls work
2834 acl_checklist
->al
= new AccessLogEntry
;
2835 acl_checklist
->al
->cache
.start_time
= current_time
;
2836 acl_checklist
->al
->tcpClient
= clientConnection
;
2837 acl_checklist
->al
->cache
.port
= port
;
2838 acl_checklist
->al
->cache
.caddr
= log_addr
;
2839 HTTPMSGUNLOCK(acl_checklist
->al
->request
);
2840 acl_checklist
->al
->request
= request
;
2841 HTTPMSGLOCK(acl_checklist
->al
->request
);
2842 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
2845 httpsEstablish(this, port
->secure
.staticContext
.get());
2850 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
2852 ConnStateData
* state_data
= (ConnStateData
*)(data
);
2853 state_data
->sslCrtdHandleReply(reply
);
2857 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
2860 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply
);
2864 if (reply
.result
== Helper::BrokenHelper
) {
2865 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
2866 } else if (!reply
.other().hasContent()) {
2867 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
2869 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
2870 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
2871 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
2873 if (reply
.result
!= Helper::Okay
) {
2874 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
2876 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
2877 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
2878 doPeekAndSpliceStep();
2879 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
2880 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
2882 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
2884 SSL_CTX
*sslContext
= SSL_get_SSL_CTX(ssl
);
2885 Ssl::configureUnconfiguredSslContext(sslContext
, signAlgorithm
, *port
);
2887 auto ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
2888 getSslContextDone(ctx
, true);
2894 getSslContextDone(NULL
);
2897 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
2899 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
2901 // fake certificate adaptation requires bump-server-first mode
2902 if (!sslServerBump
) {
2903 assert(port
->signingCert
.get());
2904 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2905 if (port
->signPkey
.get())
2906 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2907 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2911 // In case of an error while connecting to the secure server, use a fake
2912 // trusted certificate, with no mimicked fields and no adaptation
2913 // algorithms. There is nothing we can mimic so we want to minimize the
2914 // number of warnings the user will have to see to get to the error page.
2915 assert(sslServerBump
->entry
);
2916 if (sslServerBump
->entry
->isEmpty()) {
2917 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
2918 certProperties
.mimicCert
.resetAndLock(mimicCert
);
2920 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
2921 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
2922 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors());
2924 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
2925 // If the algorithm already set, then ignore it.
2926 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
2927 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
2928 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
2931 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
2932 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
2933 const char *param
= ca
->param
;
2935 // For parameterless CN adaptation, use hostname from the
2937 if (ca
->alg
== Ssl::algSetCommonName
) {
2939 param
= sslConnectHostOrIp
.termedBuf();
2940 certProperties
.commonName
= param
;
2941 certProperties
.setCommonName
= true;
2942 } else if (ca
->alg
== Ssl::algSetValidAfter
)
2943 certProperties
.setValidAfter
= true;
2944 else if (ca
->alg
== Ssl::algSetValidBefore
)
2945 certProperties
.setValidBefore
= true;
2947 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
2948 alg
<< " param: " << (param
? param
: "-"));
2952 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
2953 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
2954 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
2955 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
2959 } else {// if (!sslServerBump->entry->isEmpty())
2960 // Use trusted certificate for a Squid-generated error
2961 // or the user would have to add a security exception
2962 // just to see the error page. We will close the connection
2963 // so that the trust is not extended to non-Squid content.
2964 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2967 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
2969 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
2970 assert(port
->untrustedSigningCert
.get());
2971 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
2972 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
2974 assert(port
->signingCert
.get());
2975 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2977 if (port
->signPkey
.get())
2978 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2980 signAlgorithm
= certProperties
.signAlgorithm
;
2982 certProperties
.signHash
= Ssl::DefaultSignHash
;
2986 ConnStateData::getSslContextStart()
2988 // If we are called, then CONNECT has succeeded. Finalize it.
2989 if (auto xact
= pipeline
.front()) {
2990 if (xact
->http
&& xact
->http
->request
&& xact
->http
->request
->method
== Http::METHOD_CONNECT
)
2992 // cannot proceed with encryption if requests wait for plain responses
2993 Must(pipeline
.empty());
2995 /* careful: finished() above frees request, host, etc. */
2997 if (port
->generateHostCertificates
) {
2998 Ssl::CertificateProperties certProperties
;
2999 buildSslCertGenerationParams(certProperties
);
3000 sslBumpCertKey
= certProperties
.dbKey().c_str();
3001 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3003 // Disable caching for bumpPeekAndSplice mode
3004 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
3005 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3006 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3007 Security::ContextPtr dynCtx
= nullptr;
3008 Security::ContextPointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : nullptr;
3009 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3010 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3011 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3012 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3013 getSslContextDone(dynCtx
);
3016 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3018 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3021 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3027 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3028 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3029 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3030 request_message
.composeRequest(certProperties
);
3031 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3032 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3034 } catch (const std::exception
&e
) {
3035 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3036 "request for " << certProperties
.commonName
<<
3037 " certificate: " << e
.what() << "; will now block to " <<
3038 "generate that certificate.");
3039 // fall through to do blocking in-process generation.
3041 #endif // USE_SSL_CRTD
3043 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3044 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3045 doPeekAndSpliceStep();
3046 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3047 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3048 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3050 SSL_CTX
*sslContext
= SSL_get_SSL_CTX(ssl
);
3051 Ssl::configureUnconfiguredSslContext(sslContext
, certProperties
.signAlgorithm
, *port
);
3053 auto dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3054 getSslContextDone(dynCtx
, true);
3058 getSslContextDone(NULL
);
3062 ConnStateData::getSslContextDone(Security::ContextPtr sslContext
, bool isNew
)
3064 // Try to add generated ssl context to storage.
3065 if (port
->generateHostCertificates
&& isNew
) {
3067 if (sslContext
&& (signAlgorithm
== Ssl::algSignTrusted
)) {
3068 Ssl::chainCertificatesToSSLContext(sslContext
, *port
);
3069 } else if (signAlgorithm
== Ssl::algSignTrusted
) {
3070 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain because SSL context chain is invalid!");
3072 //else it is self-signed or untrusted do not attrach any certificate
3074 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3075 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3077 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Security::ContextPointer(sslContext
))) {
3078 // If it is not in storage delete after using. Else storage deleted it.
3079 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3082 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3086 // If generated ssl context = NULL, try to use static ssl context.
3088 if (!port
->secure
.staticContext
) {
3089 debugs(83, DBG_IMPORTANT
, "Closing " << clientConnection
->remote
<< " as lacking TLS context");
3090 clientConnection
->close();
3093 debugs(33, 5, "Using static TLS context.");
3094 sslContext
= port
->secure
.staticContext
.get();
3098 if (!httpsCreate(clientConnection
, sslContext
))
3101 // bumped intercepted conns should already have Config.Timeout.request set
3102 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3103 // to make sure the connection does not get stuck on non-SSL clients.
3104 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3105 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3106 this, ConnStateData::requestTimeout
);
3107 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3109 switchedToHttps_
= true;
3111 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3112 BIO
*b
= SSL_get_rbio(ssl
);
3113 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3114 bio
->setReadBufData(inBuf
);
3116 clientNegotiateSSL(clientConnection
->fd
, this);
3120 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3122 assert(!switchedToHttps_
);
3124 sslConnectHostOrIp
= request
->url
.host();
3125 resetSslCommonName(request
->url
.host());
3127 // We are going to read new request
3128 flags
.readMore
= true;
3129 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3131 // keep version major.minor details the same.
3132 // but we are now performing the HTTPS handshake traffic
3133 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
3135 // If sslServerBump is set, then we have decided to deny CONNECT
3136 // and now want to switch to SSL to send the error to the client
3137 // without even peeking at the origin server certificate.
3138 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3139 request
->flags
.sslPeek
= true;
3140 sslServerBump
= new Ssl::ServerBump(request
);
3141 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
3142 request
->flags
.sslPeek
= true;
3143 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
3146 // commSetConnTimeout() was called for this request before we switched.
3147 // Fix timeout to request_start_timeout
3148 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3149 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3150 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3151 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
3152 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
3153 // a bumbed "connect" request on non transparent port.
3154 receivedFirstByte_
= false;
3155 // Get more data to peek at Tls
3156 parsingTlsHandshake
= true;
3161 ConnStateData::parseTlsHandshake()
3163 Must(parsingTlsHandshake
);
3165 assert(!inBuf
.isEmpty());
3166 receivedFirstByte();
3167 fd_note(clientConnection
->fd
, "Parsing TLS handshake");
3169 bool unsupportedProtocol
= false;
3171 if (!tlsParser
.parseHello(inBuf
)) {
3172 // need more data to finish parsing
3177 catch (const std::exception
&ex
) {
3178 debugs(83, 2, "error on FD " << clientConnection
->fd
<< ": " << ex
.what());
3179 unsupportedProtocol
= true;
3182 parsingTlsHandshake
= false;
3184 // Even if the parser failed, each TLS detail should either be set
3185 // correctly or still be "unknown"; copying unknown detail is a no-op.
3186 clientConnection
->tlsNegotiations()->retrieveParsedInfo(tlsParser
.details
);
3188 // We should disable read/write handlers
3189 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3190 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
3192 if (!sslServerBump
) { // BumpClientFirst mode does not use this member
3193 getSslContextStart();
3195 } else if (sslServerBump
->act
.step1
== Ssl::bumpServerFirst
) {
3196 // will call httpsPeeked() with certificate and connection, eventually
3197 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3199 Must(sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
);
3200 startPeekAndSplice(unsupportedProtocol
);
3205 ConnStateData::spliceOnError(const err_type err
)
3207 if (Config
.accessList
.on_unsupported_protocol
) {
3208 assert(serverBump());
3209 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
3210 checklist
.requestErrorType
= err
;
3211 checklist
.conn(this);
3212 allow_t answer
= checklist
.fastCheck();
3213 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
3221 ConnStateData::startPeekAndSplice(const bool unsupportedProtocol
)
3223 if (unsupportedProtocol
) {
3224 if (!spliceOnError(ERR_PROTOCOL_UNKNOWN
))
3225 clientConnection
->close();
3230 Security::TlsDetails::Pointer
const &details
= tlsParser
.details
;
3231 if (details
&& !details
->serverName
.isEmpty()) {
3232 serverBump()->clientSni
= details
->serverName
;
3233 resetSslCommonName(details
->serverName
.c_str());
3237 startPeekAndSpliceDone();
3240 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
3242 ConnStateData
*connState
= (ConnStateData
*) data
;
3244 // if the connection is closed or closing, just return.
3245 if (!connState
->isOpen())
3248 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
3249 assert(connState
->serverBump());
3250 Ssl::BumpMode bumpAction
;
3251 if (answer
== ACCESS_ALLOWED
) {
3252 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
3254 bumpAction
= Ssl::bumpSplice
;
3256 connState
->serverBump()->act
.step2
= bumpAction
;
3257 connState
->sslBumpMode
= bumpAction
;
3259 if (bumpAction
== Ssl::bumpTerminate
) {
3260 connState
->clientConnection
->close();
3261 } else if (bumpAction
!= Ssl::bumpSplice
) {
3262 connState
->startPeekAndSpliceDone();
3263 } else if (!connState
->splice())
3264 connState
->clientConnection
->close();
3268 ConnStateData::splice()
3270 // normally we can splice here, because we just got client hello message
3272 if (fd_table
[clientConnection
->fd
].ssl
.get()) {
3273 // Restore default read methods
3274 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
3275 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
3278 if (transparent()) {
3279 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
3280 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
3281 transferProtocol
= Http::ProtocolVersion();
3282 return fakeAConnectRequest("intercepted TLS spliced", inBuf
);
3284 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
3286 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
3287 transferProtocol
= Http::ProtocolVersion();
3288 Http::StreamPointer context
= pipeline
.front();
3289 ClientHttpRequest
*http
= context
->http
;
3296 ConnStateData::startPeekAndSpliceDone()
3298 // This is the Step2 of the SSL bumping
3299 assert(sslServerBump
);
3300 Http::StreamPointer context
= pipeline
.front();
3301 ClientHttpRequest
*http
= context
? context
->http
: NULL
;
3303 if (sslServerBump
->step
== Ssl::bumpStep1
) {
3304 sslServerBump
->step
= Ssl::bumpStep2
;
3305 // Run a accessList check to check if want to splice or continue bumping
3307 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
3308 acl_checklist
->al
= http
? http
->al
: NULL
;
3309 //acl_checklist->src_addr = params.conn->remote;
3310 //acl_checklist->my_addr = s->s;
3311 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpNone
));
3312 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpClientFirst
));
3313 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpServerFirst
));
3314 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
3318 // will call httpsPeeked() with certificate and connection, eventually
3319 auto unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
3320 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
3322 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
3325 switchedToHttps_
= true;
3327 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3328 BIO
*b
= SSL_get_rbio(ssl
);
3329 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3330 bio
->setReadBufData(inBuf
);
3333 // Here squid should have all of the client hello message so the
3334 // Squid_SSL_accept should return 0;
3335 // This block exist only to force openSSL parse client hello and detect
3336 // ERR_SECURE_ACCEPT_FAIL error, which should be checked and splice if required.
3338 if ((ret
= Squid_SSL_accept(this, NULL
)) < 0) {
3339 debugs(83, 2, "SSL_accept failed.");
3340 const err_type err
= ERR_SECURE_ACCEPT_FAIL
;
3341 if (!spliceOnError(err
))
3342 clientConnection
->close();
3346 // We need to reset inBuf here, to be used by incoming requests in the case
3350 debugs(83, 5, "Peek and splice at step2 done. Start forwarding the request!!! ");
3351 FwdState::Start(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw(), http
? http
->al
: NULL
);
3355 ConnStateData::doPeekAndSpliceStep()
3357 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3358 BIO
*b
= SSL_get_rbio(ssl
);
3360 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3362 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
3365 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
3366 switchedToHttps_
= true;
3370 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3372 Must(sslServerBump
!= NULL
);
3374 if (Comm::IsConnOpen(serverConnection
)) {
3375 pinConnection(serverConnection
, NULL
, NULL
, false);
3377 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3379 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3381 // copy error detail from bump-server-first request to CONNECT request
3382 if (!pipeline
.empty() && pipeline
.front()->http
!= nullptr && pipeline
.front()->http
->request
)
3383 pipeline
.front()->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3386 getSslContextStart();
3389 #endif /* USE_OPENSSL */
3392 ConnStateData::fakeAConnectRequest(const char *reason
, const SBuf
&payload
)
3394 // fake a CONNECT request to force connState to tunnel
3397 if (serverBump() && !serverBump()->clientSni
.isEmpty()) {
3398 connectHost
.assign(serverBump()->clientSni
);
3399 if (clientConnection
->local
.port() > 0)
3400 connectHost
.appendf(":%d",clientConnection
->local
.port());
3404 static char ip
[MAX_IPSTRLEN
];
3405 connectHost
.assign(clientConnection
->local
.toUrl(ip
, sizeof(ip
)));
3407 // Pre-pend this fake request to the TLS bits already in the buffer
3409 retStr
.append("CONNECT ");
3410 retStr
.append(connectHost
);
3411 retStr
.append(" HTTP/1.1\r\nHost: ");
3412 retStr
.append(connectHost
);
3413 retStr
.append("\r\n\r\n");
3414 retStr
.append(payload
);
3416 bool ret
= handleReadData();
3418 ret
= clientParseRequests();
3421 debugs(33, 2, "Failed to start fake CONNECT request for " << reason
<< " connection: " << clientConnection
);
3427 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3429 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3431 if (!Comm::IsConnOpen(c
)) {
3432 Must(NHttpSockets
> 0); // we tried to open some
3433 --NHttpSockets
; // there will be fewer sockets than planned
3434 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3436 if (!NHttpSockets
) // we could not open any listen sockets at all
3437 fatalf("Unable to open %s",FdNote(portType
));
3444 /// find any unused HttpSockets[] slot and store fd there or return false
3446 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
3449 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
3450 if ((found
= HttpSockets
[i
] < 0))
3451 HttpSockets
[i
] = conn
->fd
;
3457 clientHttpConnectionsOpen(void)
3459 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3460 const SBuf
&scheme
= AnyP::UriScheme(s
->transport
.protocol
).image();
3462 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
3463 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many '" << scheme
<< "_port' lines.");
3464 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
3469 if (s
->flags
.tunnelSslBumping
) {
3470 if (!Config
.accessList
.ssl_bump
) {
3471 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme
<< "_port " << s
->s
);
3472 s
->flags
.tunnelSslBumping
= false;
3474 if (!s
->secure
.staticContext
&& !s
->generateHostCertificates
) {
3475 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at " << scheme
<< "_port " << s
->s
<< " due to TLS initialization failure.");
3476 s
->flags
.tunnelSslBumping
= false;
3477 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
)
3478 s
->secure
.encryptTransport
= false;
3480 if (s
->flags
.tunnelSslBumping
) {
3481 // Create ssl_ctx cache for this port.
3482 auto sz
= s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
;
3483 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, sz
);
3487 if (s
->secure
.encryptTransport
&& !s
->secure
.staticContext
) {
3488 debugs(1, DBG_CRITICAL
, "ERROR: Ignoring " << scheme
<< "_port " << s
->s
<< " due to TLS context initialization failure.");
3493 // Fill out a Comm::Connection which IPC will open as a listener for us
3494 // then pass back when active so we can start a TcpAcceptor subscription.
3495 s
->listenConn
= new Comm::Connection
;
3496 s
->listenConn
->local
= s
->s
;
3498 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3499 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3501 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3502 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
) {
3503 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
3504 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
3505 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3507 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
3508 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
3509 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
3512 } else if (s
->transport
.protocol
== AnyP::PROTO_HTTPS
) {
3513 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
3514 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
3515 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3517 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
3518 ListeningStartedDialer(&clientListenerConnectionOpened
,
3519 s
, Ipc::fdnHttpsSocket
, sub
));
3520 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
3524 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
3530 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
3532 // Fill out a Comm::Connection which IPC will open as a listener for us
3533 port
->listenConn
= new Comm::Connection
;
3534 port
->listenConn
->local
= port
->s
;
3535 port
->listenConn
->flags
=
3537 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3538 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3540 // route new connections to subCall
3541 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3542 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3543 AsyncCall::Pointer listenCall
=
3544 asyncCall(33, 2, "clientListenerConnectionOpened",
3545 ListeningStartedDialer(&clientListenerConnectionOpened
,
3546 port
, fdNote
, sub
));
3547 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
3549 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
3550 HttpSockets
[NHttpSockets
] = -1;
3554 /// process clientHttpConnectionsOpen result
3556 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
3560 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
3563 Must(Comm::IsConnOpen(s
->listenConn
));
3565 // TCP: setup a job to handle accept() with subscribed handler
3566 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
3568 debugs(1, DBG_IMPORTANT
, "Accepting " <<
3569 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
3570 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
3571 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
3572 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
3573 << FdNote(portTypeNote
) << " connections at "
3576 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
3580 clientOpenListenSockets(void)
3582 clientHttpConnectionsOpen();
3583 Ftp::StartListening();
3585 if (NHttpSockets
< 1)
3586 fatal("No HTTP, HTTPS, or FTP ports configured");
3590 clientConnectionsClose()
3592 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3593 if (s
->listenConn
!= NULL
) {
3594 debugs(1, DBG_IMPORTANT
, "Closing HTTP(S) port " << s
->listenConn
->local
);
3595 s
->listenConn
->close();
3596 s
->listenConn
= NULL
;
3600 Ftp::StopListening();
3602 // TODO see if we can drop HttpSockets array entirely */
3603 for (int i
= 0; i
< NHttpSockets
; ++i
) {
3604 HttpSockets
[i
] = -1;
3611 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
3613 SBuf
vary(request
->vary_headers
);
3614 int has_vary
= entry
->getReply()->header
.has(Http::HdrType::VARY
);
3615 #if X_ACCELERATOR_VARY
3618 entry
->getReply()->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
3621 if (!has_vary
|| entry
->mem_obj
->vary_headers
.isEmpty()) {
3622 if (!vary
.isEmpty()) {
3623 /* Oops... something odd is going on here.. */
3624 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
3625 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3626 request
->vary_headers
.clear();
3631 /* This is not a varying object */
3635 /* virtual "vary" object found. Calculate the vary key and
3636 * continue the search
3638 vary
= httpMakeVaryMark(request
, entry
->getReply());
3640 if (!vary
.isEmpty()) {
3641 request
->vary_headers
= vary
;
3644 /* Ouch.. we cannot handle this kind of variance */
3645 /* XXX This cannot really happen, but just to be complete */
3649 if (vary
.isEmpty()) {
3650 vary
= httpMakeVaryMark(request
, entry
->getReply());
3652 if (!vary
.isEmpty())
3653 request
->vary_headers
= vary
;
3656 if (vary
.isEmpty()) {
3657 /* Ouch.. we cannot handle this kind of variance */
3658 /* XXX This cannot really happen, but just to be complete */
3660 } else if (vary
.cmp(entry
->mem_obj
->vary_headers
) == 0) {
3663 /* Oops.. we have already been here and still haven't
3664 * found the requested variant. Bail out
3666 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
3667 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3673 ACLFilledChecklist
*
3674 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
3676 ConnStateData
* conn
= http
->getConn();
3677 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
3678 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
3681 * hack for ident ACL. It needs to get full addresses, and a place to store
3682 * the ident result on persistent connections...
3684 /* connection oriented auth also needs these two lines for it's operation. */
3689 ConnStateData::transparent() const
3691 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
3695 ConnStateData::expectRequestBody(int64_t size
)
3697 bodyPipe
= new BodyPipe(this);
3699 bodyPipe
->setBodySize(size
);
3701 startDechunkingRequest();
3706 ConnStateData::mayNeedToReadMoreBody() const
3709 return 0; // request without a body or read/produced all body bytes
3711 if (!bodyPipe
->bodySizeKnown())
3712 return -1; // probably need to read more, but we cannot be sure
3714 const int64_t needToProduce
= bodyPipe
->unproducedSize();
3715 const int64_t haveAvailable
= static_cast<int64_t>(inBuf
.length());
3717 if (needToProduce
<= haveAvailable
)
3718 return 0; // we have read what we need (but are waiting for pipe space)
3720 return needToProduce
- haveAvailable
;
3724 ConnStateData::stopReceiving(const char *error
)
3726 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
3727 "; old sending error: " <<
3728 (stoppedSending() ? stoppedSending_
: "none"));
3730 if (const char *oldError
= stoppedReceiving()) {
3731 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
3732 return; // nothing has changed as far as this connection is concerned
3735 stoppedReceiving_
= error
;
3737 if (const char *sendError
= stoppedSending()) {
3738 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
3739 clientConnection
->close();
3744 ConnStateData::expectNoForwarding()
3746 if (bodyPipe
!= NULL
) {
3747 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
3748 bodyPipe
->expectNoConsumption();
3752 /// initialize dechunking state
3754 ConnStateData::startDechunkingRequest()
3756 Must(bodyPipe
!= NULL
);
3757 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
3758 assert(!bodyParser
);
3759 bodyParser
= new Http1::TeChunkedParser
;
3762 /// put parsed content into input buffer and clean up
3764 ConnStateData::finishDechunkingRequest(bool withSuccess
)
3766 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
3768 if (bodyPipe
!= NULL
) {
3769 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
3770 BodyPipe::Pointer myPipe
= bodyPipe
;
3771 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
3772 Must(!bodyPipe
); // we rely on it being nil after we are done with body
3774 Must(myPipe
->bodySizeKnown());
3775 Http::StreamPointer context
= pipeline
.front();
3776 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
3777 context
->http
->request
->setContentLength(myPipe
->bodySize());
3785 // XXX: this is an HTTP/1-only operation
3787 ConnStateData::sendControlMsg(HttpControlMsg msg
)
3790 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
3794 // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them
3795 if (!pipeline
.empty()) {
3796 HttpReply::Pointer
rep(msg
.reply
);
3798 // remember the callback
3799 cbControlMsgSent
= msg
.cbSuccess
;
3801 typedef CommCbMemFunT
<HttpControlMsgSink
, CommIoCbParams
> Dialer
;
3802 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, HttpControlMsgSink::wroteControlMsg
);
3804 writeControlMsgAndCall(rep
.getRaw(), call
);
3808 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
3809 clientConnection
->close();
3812 /// Our close handler called by Comm when the pinned connection is closed
3814 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
3816 // FwdState might repin a failed connection sooner than this close
3817 // callback is called for the failed connection.
3818 assert(pinning
.serverConnection
== io
.conn
);
3819 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
3820 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
3821 pinning
.serverConnection
->noteClosure();
3822 unpinConnection(false);
3824 if (sawZeroReply
&& clientConnection
!= NULL
) {
3825 debugs(33, 3, "Closing client connection on pinned zero reply.");
3826 clientConnection
->close();
3832 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
3834 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
3835 pinning
.serverConnection
->fd
!= pinServer
->fd
)
3836 pinNewConnection(pinServer
, request
, aPeer
, auth
);
3839 startPinnedConnectionMonitoring();
3843 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
3845 unpinConnection(true); // closes pinned connection, if any, and resets fields
3847 pinning
.serverConnection
= pinServer
;
3849 debugs(33, 3, HERE
<< pinning
.serverConnection
);
3851 Must(pinning
.serverConnection
!= NULL
);
3853 // when pinning an SSL bumped connection, the request may be NULL
3854 const char *pinnedHost
= "[unknown]";
3856 pinning
.host
= xstrdup(request
->url
.host());
3857 pinning
.port
= request
->url
.port();
3858 pinnedHost
= pinning
.host
;
3860 pinning
.port
= pinServer
->remote
.port();
3862 pinning
.pinned
= true;
3864 pinning
.peer
= cbdataReference(aPeer
);
3865 pinning
.auth
= auth
;
3866 char stmp
[MAX_IPSTRLEN
];
3867 char desc
[FD_DESC_SZ
];
3868 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
3869 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
3870 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
3871 clientConnection
->fd
);
3872 fd_note(pinning
.serverConnection
->fd
, desc
);
3874 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3875 pinning
.closeHandler
= JobCallback(33, 5,
3876 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
3877 // remember the pinned connection so that cb does not unpin a fresher one
3878 typedef CommCloseCbParams Params
;
3879 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
3880 params
.conn
= pinning
.serverConnection
;
3881 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
3884 /// [re]start monitoring pinned connection for peer closures so that we can
3885 /// propagate them to an _idle_ client pinned to that peer
3887 ConnStateData::startPinnedConnectionMonitoring()
3889 if (pinning
.readHandler
!= NULL
)
3890 return; // already monitoring
3892 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
3893 pinning
.readHandler
= JobCallback(33, 3,
3894 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
3895 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
3899 ConnStateData::stopPinnedConnectionMonitoring()
3901 if (pinning
.readHandler
!= NULL
) {
3902 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
3903 pinning
.readHandler
= NULL
;
3909 ConnStateData::handleIdleClientPinnedTlsRead()
3911 // A ready-for-reading connection means that the TLS server either closed
3912 // the connection, sent us some unexpected HTTP data, or started TLS
3913 // renegotiations. We should close the connection except for the last case.
3915 Must(pinning
.serverConnection
!= nullptr);
3916 auto ssl
= fd_table
[pinning
.serverConnection
->fd
].ssl
.get();
3921 const int readResult
= SSL_read(ssl
, buf
, sizeof(buf
));
3923 if (readResult
> 0 || SSL_pending(ssl
) > 0) {
3924 debugs(83, 2, pinning
.serverConnection
<< " TLS application data read");
3928 switch(const int error
= SSL_get_error(ssl
, readResult
)) {
3929 case SSL_ERROR_WANT_WRITE
:
3930 debugs(83, DBG_IMPORTANT
, pinning
.serverConnection
<< " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection");
3931 // fall through to restart monitoring, for now
3932 case SSL_ERROR_NONE
:
3933 case SSL_ERROR_WANT_READ
:
3934 startPinnedConnectionMonitoring();
3938 debugs(83, 2, pinning
.serverConnection
<< " TLS error: " << error
);
3947 /// Our read handler called by Comm when the server either closes an idle pinned connection or
3948 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
3950 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
3952 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
3954 if (io
.flag
== Comm::ERR_CLOSING
)
3955 return; // close handler will clean up
3957 Must(pinning
.serverConnection
== io
.conn
);
3960 if (handleIdleClientPinnedTlsRead())
3964 const bool clientIsIdle
= pipeline
.empty();
3966 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
3967 io
.size
<< (clientIsIdle
? " with idle client" : ""));
3969 pinning
.serverConnection
->close();
3971 // If we are still sending data to the client, do not close now. When we are done sending,
3972 // ConnStateData::kick() checks pinning.serverConnection and will close.
3973 // However, if we are idle, then we must close to inform the idle client and minimize races.
3974 if (clientIsIdle
&& clientConnection
!= NULL
)
3975 clientConnection
->close();
3978 const Comm::ConnectionPointer
3979 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
3981 debugs(33, 7, HERE
<< pinning
.serverConnection
);
3984 if (!Comm::IsConnOpen(pinning
.serverConnection
))
3986 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->url
.host()) != 0)
3988 else if (request
&& pinning
.port
!= request
->url
.port())
3990 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
3992 else if (aPeer
!= pinning
.peer
)
3996 /* The pinning info is not safe, remove any pinning info */
3997 unpinConnection(true);
4000 return pinning
.serverConnection
;
4003 Comm::ConnectionPointer
4004 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4006 debugs(33, 7, pinning
.serverConnection
);
4007 if (validatePinnedConnection(request
, aPeer
) != NULL
)
4008 stopPinnedConnectionMonitoring();
4010 return pinning
.serverConnection
; // closed if validation failed
4014 ConnStateData::unpinConnection(const bool andClose
)
4016 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4019 cbdataReferenceDone(pinning
.peer
);
4021 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4022 if (pinning
.closeHandler
!= NULL
) {
4023 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4024 pinning
.closeHandler
= NULL
;
4027 stopPinnedConnectionMonitoring();
4029 // close the server side socket if requested
4031 pinning
.serverConnection
->close();
4032 pinning
.serverConnection
= NULL
;
4035 safe_free(pinning
.host
);
4037 pinning
.zeroReply
= false;
4039 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4040 * connection has gone away */
4044 ConnStateData::checkLogging()
4046 // if we are parsing request body, its request is responsible for logging
4050 // a request currently using this connection is responsible for logging
4051 if (!pipeline
.empty() && pipeline
.back()->mayUseConnection())
4054 /* Either we are waiting for the very first transaction, or
4055 * we are done with the Nth transaction and are waiting for N+1st.
4056 * XXX: We assume that if anything was added to inBuf, then it could
4057 * only be consumed by actions already covered by the above checks.
4060 // do not log connections that closed after a transaction (it is normal)
4061 // TODO: access_log needs ACLs to match received-no-bytes connections
4062 // XXX: TLS may return here even though we got no transactions yet
4063 // XXX: PROXY protocol may return here even though we got no
4065 if (receivedFirstByte_
&& inBuf
.isEmpty())
4068 /* Create a temporary ClientHttpRequest object. Its destructor will log. */
4069 ClientHttpRequest
http(this);
4070 http
.req_sz
= inBuf
.length();
4071 char const *uri
= "error:transaction-end-before-headers";
4072 http
.uri
= xstrdup(uri
);
4073 setLogUri(&http
, uri
);