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");
1316 if (hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
|| hp
->parseStatusCode
== Http::scUriTooLong
)
1317 return csd
->abortRequestParsing("error:request-too-large");
1319 return csd
->abortRequestParsing("error:invalid-request");
1323 /* We know the whole request is in parser now */
1324 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
1325 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
1326 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
1330 /* deny CONNECT via accelerated ports */
1331 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
1332 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
1333 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1334 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1335 return csd
->abortRequestParsing("error:method-not-allowed");
1338 /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific
1339 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
1340 * If seen it signals a broken client or proxy has corrupted the traffic.
1342 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
1343 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
1344 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1345 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1346 return csd
->abortRequestParsing("error:method-not-allowed");
1349 if (hp
->method() == Http::METHOD_NONE
) {
1350 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1351 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1352 return csd
->abortRequestParsing("error:unsupported-request-method");
1355 // Process headers after request line
1356 debugs(33, 3, "complete request received. " <<
1357 "prefix_sz = " << hp
->messageHeaderSize() <<
1358 ", request-line-size=" << hp
->firstLineSize() <<
1359 ", mime-header-size=" << hp
->headerBlockSize() <<
1360 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
1362 /* Ok, all headers are received */
1363 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
1365 http
->req_sz
= hp
->messageHeaderSize();
1366 Http::Stream
*result
= new Http::Stream(csd
->clientConnection
, http
);
1368 StoreIOBuffer tempBuffer
;
1369 tempBuffer
.data
= result
->reqbuf
;
1370 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1372 ClientStreamData newServer
= new clientReplyContext(http
);
1373 ClientStreamData newClient
= result
;
1374 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1375 clientReplyStatus
, newServer
, clientSocketRecipient
,
1376 clientSocketDetach
, newClient
, tempBuffer
);
1379 debugs(33,5, "Prepare absolute URL from " <<
1380 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
1381 /* Rewrite the URL in transparent or accelerator mode */
1382 /* NP: there are several cases to traverse here:
1383 * - standard mode (forward proxy)
1384 * - transparent mode (TPROXY)
1385 * - transparent mode with failures
1386 * - intercept mode (NAT)
1387 * - intercept mode with failures
1388 * - accelerator mode (reverse proxy)
1389 * - internal relative-URL
1390 * - mixed combos of the above with internal URL
1391 * - remote interception with PROXY protocol
1392 * - remote reverse-proxy with PROXY protocol
1394 if (csd
->transparent()) {
1395 /* intercept or transparent mode, properly working with no failures */
1396 prepareTransparentURL(csd
, http
, hp
);
1398 } else if (internalCheck(hp
->requestUri())) { // NP: only matches relative-URI
1399 /* internal URL mode */
1400 /* prepend our name & port */
1401 http
->uri
= xstrdup(internalLocalUri(NULL
, hp
->requestUri()));
1402 // We just re-wrote the URL. Must replace the Host: header.
1403 // But have not parsed there yet!! flag for local-only handling.
1404 http
->flags
.internal
= true;
1406 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
1407 /* accelerator mode */
1408 prepareAcceleratedURL(csd
, http
, hp
);
1412 /* No special rewrites have been applied above, use the
1413 * requested url. may be rewritten later, so make extra room */
1414 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
1415 http
->uri
= (char *)xcalloc(url_sz
, 1);
1416 SBufToCstring(http
->uri
, hp
->requestUri());
1419 result
->flags
.parsed_ok
= 1;
1424 ConnStateData::connFinishedWithConn(int size
)
1427 if (pipeline
.empty() && inBuf
.isEmpty()) {
1428 /* no current or pending requests */
1429 debugs(33, 4, HERE
<< clientConnection
<< " closed");
1431 } else if (!Config
.onoff
.half_closed_clients
) {
1432 /* admin doesn't want to support half-closed client sockets */
1433 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
1434 pipeline
.terminateAll(0);
1443 ConnStateData::consumeInput(const size_t byteCount
)
1445 assert(byteCount
> 0 && byteCount
<= inBuf
.length());
1446 inBuf
.consume(byteCount
);
1447 debugs(33, 5, "inBuf has " << inBuf
.length() << " unused bytes");
1451 ConnStateData::clientAfterReadingRequests()
1453 // Were we expecting to read more request body from half-closed connection?
1454 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
1455 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
1456 clientConnection
->close();
1465 ConnStateData::quitAfterError(HttpRequest
*request
)
1467 // From HTTP p.o.v., we do not have to close after every error detected
1468 // at the client-side, but many such errors do require closure and the
1469 // client-side code is bad at handling errors so we play it safe.
1471 request
->flags
.proxyKeepalive
= false;
1472 flags
.readMore
= false;
1473 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
1477 bool ConnStateData::serveDelayedError(Http::Stream
*context
)
1479 ClientHttpRequest
*http
= context
->http
;
1484 assert(sslServerBump
->entry
);
1485 // Did we create an error entry while processing CONNECT?
1486 if (!sslServerBump
->entry
->isEmpty()) {
1487 quitAfterError(http
->request
);
1489 // Get the saved error entry and send it to the client by replacing the
1490 // ClientHttpRequest store entry with it.
1491 clientStreamNode
*node
= context
->getClientReplyContext();
1492 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1494 debugs(33, 5, "Responding with delated error for " << http
->uri
);
1495 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
1497 // save the original request for logging purposes
1498 if (!context
->http
->al
->request
) {
1499 context
->http
->al
->request
= http
->request
;
1500 HTTPMSGLOCK(context
->http
->al
->request
);
1503 // Get error details from the fake certificate-peeking request.
1504 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
1505 context
->pullData();
1509 // In bump-server-first mode, we have not necessarily seen the intended
1510 // server name at certificate-peeking time. Check for domain mismatch now,
1511 // when we can extract the intended name from the bumped HTTP request.
1512 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
1513 HttpRequest
*request
= http
->request
;
1514 if (!Ssl::checkX509ServerValidity(srvCert
, request
->url
.host())) {
1515 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
1516 "does not match domainname " << request
->url
.host());
1518 bool allowDomainMismatch
= false;
1519 if (Config
.ssl_client
.cert_error
) {
1520 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
1521 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
1522 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
1523 delete check
.sslErrors
;
1524 check
.sslErrors
= NULL
;
1527 if (!allowDomainMismatch
) {
1528 quitAfterError(request
);
1530 clientStreamNode
*node
= context
->getClientReplyContext();
1531 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1532 assert (repContext
);
1534 // Fill the server IP and hostname for error page generation.
1535 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
1536 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->url
.host());
1538 // Create an error object and fill it
1539 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
1540 err
->src_addr
= clientConnection
->remote
;
1541 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
1542 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
1544 err
->detail
= errDetail
;
1545 // Save the original request for logging purposes.
1546 if (!context
->http
->al
->request
) {
1547 context
->http
->al
->request
= request
;
1548 HTTPMSGLOCK(context
->http
->al
->request
);
1550 repContext
->setReplyToError(request
->method
, err
);
1551 assert(context
->http
->out
.offset
== 0);
1552 context
->pullData();
1560 #endif // USE_OPENSSL
1563 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
1564 * or false otherwise
1567 clientTunnelOnError(ConnStateData
*conn
, Http::Stream
*context
, HttpRequest
*request
, const HttpRequestMethod
& method
, err_type requestError
, Http::StatusCode errStatusCode
, const char *requestErrorBytes
)
1569 if (conn
->port
->flags
.isIntercepted() &&
1570 Config
.accessList
.on_unsupported_protocol
&& conn
->pipeline
.nrequests
<= 1) {
1571 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
, NULL
);
1572 checklist
.requestErrorType
= requestError
;
1573 checklist
.src_addr
= conn
->clientConnection
->remote
;
1574 checklist
.my_addr
= conn
->clientConnection
->local
;
1575 checklist
.conn(conn
);
1576 allow_t answer
= checklist
.fastCheck();
1577 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
1578 debugs(33, 3, "Request will be tunneled to server");
1580 // XXX: Either the context is finished() or it should stay queued.
1581 // The below may leak client streams BodyPipe objects. BUT, we need
1582 // to check if client-streams detatch is safe to do here (finished() will detatch).
1583 assert(conn
->pipeline
.front() == context
); // XXX: still assumes HTTP/1 semantics
1584 conn
->pipeline
.popMe(Http::StreamPointer(context
));
1586 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
1587 return conn
->fakeAConnectRequest("unknown-protocol", conn
->preservedClientData
);
1589 debugs(33, 3, "Continue with returning the error: " << requestError
);
1594 conn
->quitAfterError(request
);
1595 clientStreamNode
*node
= context
->getClientReplyContext();
1596 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1597 assert (repContext
);
1599 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
1601 assert(context
->http
->out
.offset
== 0);
1602 context
->pullData();
1603 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
1608 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
1612 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
1613 * to here because calling comm_reset_close() causes http to
1614 * be freed before accessing.
1616 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
1617 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
1618 conn
->flags
.readMore
= false;
1619 comm_reset_close(conn
->clientConnection
);
1624 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, Http::Stream
*context
)
1626 ClientHttpRequest
*http
= context
->http
;
1627 bool chunked
= false;
1628 bool mustReplyToOptions
= false;
1629 bool unsupportedTe
= false;
1630 bool expectBody
= false;
1632 // We already have the request parsed and checked, so we
1633 // only need to go through the final body/conn setup to doCallouts().
1634 assert(http
->request
);
1635 HttpRequest::Pointer request
= http
->request
;
1637 // temporary hack to avoid splitting this huge function with sensitive code
1638 const bool isFtp
= !hp
;
1640 // Some blobs below are still HTTP-specific, but we would have to rewrite
1641 // this entire function to remove them from the FTP code path. Connection
1642 // setup and body_pipe preparation blobs are needed for FTP.
1644 request
->clientConnectionManager
= conn
;
1646 request
->flags
.accelerated
= http
->flags
.accel
;
1647 request
->flags
.sslBumped
=conn
->switchedToHttps();
1648 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
1649 // TODO: decouple http->flags.accel from request->flags.sslBumped
1650 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
1651 !conn
->port
->allow_direct
: 0;
1652 request
->sources
|= isFtp
? HttpMsg::srcFtp
:
1653 ((request
->flags
.sslBumped
|| conn
->port
->transport
.protocol
== AnyP::PROTO_HTTPS
) ? HttpMsg::srcHttps
: HttpMsg::srcHttp
);
1655 if (request
->flags
.sslBumped
) {
1656 if (conn
->getAuth() != NULL
)
1657 request
->auth_user_request
= conn
->getAuth();
1662 * If transparent or interception mode is working clone the transparent and interception flags
1663 * from the port settings to the request.
1665 if (http
->clientConnection
!= NULL
) {
1666 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
1667 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
1668 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
1669 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
1670 if (Config
.accessList
.spoof_client_ip
) {
1671 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
1672 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
1675 request
->flags
.spoofClientIp
= true;
1677 request
->flags
.spoofClientIp
= false;
1680 if (internalCheck(request
->url
.path())) {
1681 if (internalHostnameIs(request
->url
.host()) && request
->url
.port() == getMyPort()) {
1682 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true));
1683 http
->flags
.internal
= true;
1684 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->url
.path())) {
1685 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (global_internal_static on)");
1686 request
->url
.setScheme(AnyP::PROTO_HTTP
, "http");
1687 request
->url
.host(internalHostname());
1688 request
->url
.port(getMyPort());
1689 http
->flags
.internal
= true;
1691 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (not this proxy)");
1694 request
->flags
.internal
= http
->flags
.internal
;
1695 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
1696 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
1697 #if FOLLOW_X_FORWARDED_FOR
1698 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
1699 // not a details about teh TCP connection itself
1700 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
1701 #endif /* FOLLOW_X_FORWARDED_FOR */
1702 request
->my_addr
= conn
->clientConnection
->local
;
1703 request
->myportname
= conn
->port
->name
;
1706 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
1707 // for now Squid only supports HTTP requests
1708 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
1709 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
1710 request
->http_ver
.major
= http_ver
.major
;
1711 request
->http_ver
.minor
= http_ver
.minor
;
1714 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
1715 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
1716 request
->clientConnectionManager
= conn
;
1718 if (request
->header
.chunked()) {
1720 } else if (request
->header
.has(Http::HdrType::TRANSFER_ENCODING
)) {
1721 const String te
= request
->header
.getList(Http::HdrType::TRANSFER_ENCODING
);
1722 // HTTP/1.1 requires chunking to be the last encoding if there is one
1723 unsupportedTe
= te
.size() && te
!= "identity";
1724 } // else implied identity coding
1726 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
1727 (request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0);
1728 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
1729 clientStreamNode
*node
= context
->getClientReplyContext();
1730 conn
->quitAfterError(request
.getRaw());
1731 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1732 assert (repContext
);
1733 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
1734 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1735 assert(context
->http
->out
.offset
== 0);
1736 context
->pullData();
1737 clientProcessRequestFinished(conn
, request
);
1741 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
1742 clientStreamNode
*node
= context
->getClientReplyContext();
1743 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1744 assert (repContext
);
1745 conn
->quitAfterError(request
.getRaw());
1746 repContext
->setReplyToError(ERR_INVALID_REQ
,
1747 Http::scLengthRequired
, request
->method
, NULL
,
1748 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1749 assert(context
->http
->out
.offset
== 0);
1750 context
->pullData();
1751 clientProcessRequestFinished(conn
, request
);
1755 clientSetKeepaliveFlag(http
);
1756 // Let tunneling code be fully responsible for CONNECT requests
1757 if (http
->request
->method
== Http::METHOD_CONNECT
) {
1758 context
->mayUseConnection(true);
1759 conn
->flags
.readMore
= false;
1763 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
1764 clientProcessRequestFinished(conn
, request
);
1769 /* Do we expect a request-body? */
1770 expectBody
= chunked
|| request
->content_length
> 0;
1771 if (!context
->mayUseConnection() && expectBody
) {
1772 request
->body_pipe
= conn
->expectRequestBody(
1773 chunked
? -1 : request
->content_length
);
1775 /* Is it too large? */
1776 if (!chunked
&& // if chunked, we will check as we accumulate
1777 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
1778 clientStreamNode
*node
= context
->getClientReplyContext();
1779 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1780 assert (repContext
);
1781 conn
->quitAfterError(request
.getRaw());
1782 repContext
->setReplyToError(ERR_TOO_BIG
,
1783 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
1784 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
1785 assert(context
->http
->out
.offset
== 0);
1786 context
->pullData();
1787 clientProcessRequestFinished(conn
, request
);
1792 // We may stop producing, comm_close, and/or call setReplyToError()
1793 // below, so quit on errors to avoid http->doCallouts()
1794 if (!conn
->handleRequestBodyData()) {
1795 clientProcessRequestFinished(conn
, request
);
1799 if (!request
->body_pipe
->productionEnded()) {
1800 debugs(33, 5, "need more request body");
1801 context
->mayUseConnection(true);
1802 assert(conn
->flags
.readMore
);
1807 http
->calloutContext
= new ClientRequestContext(http
);
1811 clientProcessRequestFinished(conn
, request
);
1815 ConnStateData::pipelinePrefetchMax() const
1817 // TODO: Support pipelined requests through pinned connections.
1820 return Config
.pipeline_max_prefetch
;
1824 * Limit the number of concurrent requests.
1825 * \return true when there are available position(s) in the pipeline queue for another request.
1826 * \return false when the pipeline queue is full or disabled.
1829 ConnStateData::concurrentRequestQueueFilled() const
1831 const int existingRequestCount
= pipeline
.count();
1833 // default to the configured pipeline size.
1834 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
1836 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
1838 const int internalRequest
= 0;
1840 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
1842 // when queue filled already we cant add more.
1843 if (existingRequestCount
>= concurrentRequestLimit
) {
1844 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
1845 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
1853 * Perform proxy_protocol_access ACL tests on the client which
1854 * connected to PROXY protocol port to see if we trust the
1855 * sender enough to accept their PROXY header claim.
1858 ConnStateData::proxyProtocolValidateClient()
1860 if (!Config
.accessList
.proxyProtocol
)
1861 return proxyProtocolError("PROXY client not permitted by default ACL");
1863 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
1864 ch
.src_addr
= clientConnection
->remote
;
1865 ch
.my_addr
= clientConnection
->local
;
1868 if (ch
.fastCheck() != ACCESS_ALLOWED
)
1869 return proxyProtocolError("PROXY client not permitted by ACLs");
1875 * Perform cleanup on PROXY protocol errors.
1876 * If header parsing hits a fatal error terminate the connection,
1877 * otherwise wait for more data.
1880 ConnStateData::proxyProtocolError(const char *msg
)
1883 // This is important to know, but maybe not so much that flooding the log is okay.
1884 #if QUIET_PROXY_PROTOCOL
1885 // display the first of every 32 occurances at level 1, the others at level 2.
1886 static uint8_t hide
= 0;
1887 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
1889 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
1896 /// magic octet prefix for PROXY protocol version 1
1897 static const SBuf
Proxy1p0magic("PROXY ", 6);
1899 /// magic octet prefix for PROXY protocol version 2
1900 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
1903 * Test the connection read buffer for PROXY protocol header.
1904 * Version 1 and 2 header currently supported.
1907 ConnStateData::parseProxyProtocolHeader()
1909 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
1911 // detect and parse PROXY/2.0 protocol header
1912 if (inBuf
.startsWith(Proxy2p0magic
))
1913 return parseProxy2p0();
1915 // detect and parse PROXY/1.0 protocol header
1916 if (inBuf
.startsWith(Proxy1p0magic
))
1917 return parseProxy1p0();
1919 // detect and terminate other protocols
1920 if (inBuf
.length() >= Proxy2p0magic
.length()) {
1921 // PROXY/1.0 magic is shorter, so we know that
1922 // the input does not start with any PROXY magic
1923 return proxyProtocolError("PROXY protocol error: invalid header");
1926 // TODO: detect short non-magic prefixes earlier to avoid
1927 // waiting for more data which may never come
1929 // not enough bytes to parse yet.
1933 /// parse the PROXY/1.0 protocol header from the connection read buffer
1935 ConnStateData::parseProxy1p0()
1937 ::Parser::Tokenizer
tok(inBuf
);
1938 tok
.skip(Proxy1p0magic
);
1940 // skip to first LF (assumes it is part of CRLF)
1941 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
1943 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
1944 if (tok
.skip('\n')) {
1945 // found valid header
1946 inBuf
= tok
.remaining();
1947 needProxyProtocolHeader_
= false;
1948 // reset the tokenizer to work on found line only.
1951 return false; // no LF yet
1953 } else // protocol error only if there are more than 107 bytes prefix header
1954 return proxyProtocolError(inBuf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
1956 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
1957 if (tok
.skip(tcpName
)) {
1959 // skip TCP/IP version number
1960 static const CharacterSet
tcpVersions("TCP-version","46");
1961 if (!tok
.skipOne(tcpVersions
))
1962 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
1964 // skip SP after protocol version
1966 return proxyProtocolError("PROXY/1.0 error: missing SP");
1969 int64_t porta
, portb
;
1970 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
1972 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
1973 // leave the LF until later.
1974 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
1975 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
1976 tok
.int64(porta
) && tok
.skip(' ') &&
1980 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
1982 // parse IP and port strings
1983 Ip::Address originalClient
, originalDest
;
1985 if (!originalClient
.GetHostByName(ipa
.c_str()))
1986 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
1988 if (!originalDest
.GetHostByName(ipb
.c_str()))
1989 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
1991 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
1992 originalClient
.port(static_cast<uint16_t>(porta
));
1994 return proxyProtocolError("PROXY/1.0 error: invalid src port");
1996 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
1997 originalDest
.port(static_cast<uint16_t>(portb
));
1999 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
2001 // we have original client and destination details now
2002 // replace the client connection values
2003 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
2004 clientConnection
->local
= originalDest
;
2005 clientConnection
->remote
= originalClient
;
2006 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2007 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2008 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2010 // repeat fetch ensuring the new client FQDN can be logged
2011 if (Config
.onoff
.log_fqdn
)
2012 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2016 } else if (tok
.skip(unknown
)) {
2017 // found valid but unusable header
2021 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2026 /// parse the PROXY/2.0 protocol header from the connection read buffer
2028 ConnStateData::parseProxy2p0()
2030 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2031 if (inBuf
.length() < prefixLen
+ 4)
2032 return false; // need more bytes
2034 if ((inBuf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2035 return proxyProtocolError("PROXY/2.0 error: invalid version");
2037 const char command
= (inBuf
[prefixLen
] & 0x0F);
2038 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2039 return proxyProtocolError("PROXY/2.0 error: invalid command");
2041 const char family
= (inBuf
[prefixLen
+1] & 0xF0) >>4;
2042 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2043 return proxyProtocolError("PROXY/2.0 error: invalid family");
2045 const char proto
= (inBuf
[prefixLen
+1] & 0x0F);
2046 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2047 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2049 const char *clen
= inBuf
.rawContent() + prefixLen
+ 2;
2051 memcpy(&len
, clen
, sizeof(len
));
2054 if (inBuf
.length() < prefixLen
+ 4 + len
)
2055 return false; // need more bytes
2057 inBuf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2058 const SBuf extra
= inBuf
.consume(len
);
2059 needProxyProtocolHeader_
= false; // found successfully
2061 // LOCAL connections do nothing with the extras
2062 if (command
== 0x00/* LOCAL*/)
2066 struct { /* for TCP/UDP over IPv4, len = 12 */
2067 struct in_addr src_addr
;
2068 struct in_addr dst_addr
;
2072 struct { /* for TCP/UDP over IPv6, len = 36 */
2073 struct in6_addr src_addr
;
2074 struct in6_addr dst_addr
;
2079 struct { /* for AF_UNIX sockets, len = 216 */
2080 uint8_t src_addr
[108];
2081 uint8_t dst_addr
[108];
2087 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2089 // replace the client connection values
2090 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2093 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2094 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2095 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2096 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2097 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2098 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2101 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2102 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2103 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2104 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2105 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2106 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2108 default: // do nothing
2111 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2113 // repeat fetch ensuring the new client FQDN can be logged
2114 if (Config
.onoff
.log_fqdn
)
2115 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2121 ConnStateData::receivedFirstByte()
2123 if (receivedFirstByte_
)
2126 receivedFirstByte_
= true;
2127 // Set timeout to Config.Timeout.request
2128 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2129 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
2130 TimeoutDialer
, this, ConnStateData::requestTimeout
);
2131 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
2135 * Attempt to parse one or more requests from the input buffer.
2136 * Returns true after completing parsing of at least one request [header]. That
2137 * includes cases where parsing ended with an error (e.g., a huge request).
2140 ConnStateData::clientParseRequests()
2142 bool parsed_req
= false;
2144 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2146 // Loop while we have read bytes that are not needed for producing the body
2147 // On errors, bodyPipe may become nil, but readMore will be cleared
2148 while (!inBuf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2150 /* Limit the number of concurrent requests */
2151 if (concurrentRequestQueueFilled())
2154 // try to parse the PROXY protocol header magic bytes
2155 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
2158 if (Http::Stream
*context
= parseOneRequest()) {
2159 debugs(33, 5, clientConnection
<< ": done parsing a request");
2161 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2162 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2163 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2165 context
->registerWithConn();
2167 processParsedRequest(context
);
2169 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2171 if (context
->mayUseConnection()) {
2172 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2176 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
2177 inBuf
.length() << " < " << Config
.maxRequestHeaderSize
);
2178 Must(inBuf
.length() < Config
.maxRequestHeaderSize
);
2183 /* XXX where to 'finish' the parsing pass? */
2188 ConnStateData::afterClientRead()
2191 if (parsingTlsHandshake
) {
2192 parseTlsHandshake();
2197 /* Process next request */
2198 if (pipeline
.empty())
2199 fd_note(clientConnection
->fd
, "Reading next request");
2201 if (!clientParseRequests()) {
2205 * If the client here is half closed and we failed
2206 * to parse a request, close the connection.
2207 * The above check with connFinishedWithConn() only
2208 * succeeds _if_ the buffer is empty which it won't
2209 * be if we have an incomplete request.
2210 * XXX: This duplicates ConnStateData::kick
2212 if (pipeline
.empty() && commIsHalfClosed(clientConnection
->fd
)) {
2213 debugs(33, 5, clientConnection
<< ": half-closed connection, no completed request parsed, connection closing.");
2214 clientConnection
->close();
2222 clientAfterReadingRequests();
2226 * called when new request data has been read from the socket
2228 * \retval false called comm_close or setReplyToError (the caller should bail)
2229 * \retval true we did not call comm_close or setReplyToError
2232 ConnStateData::handleReadData()
2234 // if we are reading a body, stuff data into the body pipe
2235 if (bodyPipe
!= NULL
)
2236 return handleRequestBodyData();
2241 * called when new request body data has been buffered in inBuf
2242 * may close the connection if we were closing and piped everything out
2244 * \retval false called comm_close or setReplyToError (the caller should bail)
2245 * \retval true we did not call comm_close or setReplyToError
2248 ConnStateData::handleRequestBodyData()
2250 assert(bodyPipe
!= NULL
);
2252 if (bodyParser
) { // chunked encoding
2253 if (const err_type error
= handleChunkedRequestBody()) {
2254 abortChunkedRequestBody(error
);
2257 } else { // identity encoding
2258 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
2259 const size_t putSize
= bodyPipe
->putMoreData(inBuf
.c_str(), inBuf
.length());
2261 consumeInput(putSize
);
2263 if (!bodyPipe
->mayNeedMoreData()) {
2264 // BodyPipe will clear us automagically when we produced everything
2270 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
2272 if (const char *reason
= stoppedSending()) {
2273 /* we've finished reading like good clients,
2274 * now do the close that initiateClose initiated.
2276 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
2277 clientConnection
->close();
2285 /// parses available chunked encoded body bytes, checks size, returns errors
2287 ConnStateData::handleChunkedRequestBody()
2289 debugs(33, 7, "chunked from " << clientConnection
<< ": " << inBuf
.length());
2291 try { // the parser will throw on errors
2293 if (inBuf
.isEmpty()) // nothing to do
2296 BodyPipeCheckout
bpc(*bodyPipe
);
2297 bodyParser
->setPayloadBuffer(&bpc
.buf
);
2298 const bool parsed
= bodyParser
->parse(inBuf
);
2299 inBuf
= bodyParser
->remaining(); // sync buffers
2302 // dechunk then check: the size limit applies to _dechunked_ content
2303 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
2307 finishDechunkingRequest(true);
2309 return ERR_NONE
; // nil bodyPipe implies body end for the caller
2312 // if chunk parser needs data, then the body pipe must need it too
2313 Must(!bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
2315 // if parser needs more space and we can consume nothing, we will stall
2316 Must(!bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
2317 } catch (...) { // TODO: be more specific
2318 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
2319 return ERR_INVALID_REQ
;
2322 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
2326 /// quit on errors related to chunked request body handling
2328 ConnStateData::abortChunkedRequestBody(const err_type error
)
2330 finishDechunkingRequest(false);
2332 // XXX: The code below works if we fail during initial request parsing,
2333 // but if we fail when the server connection is used already, the server may send
2334 // us its response too, causing various assertions. How to prevent that?
2335 #if WE_KNOW_HOW_TO_SEND_ERRORS
2336 Http::StreamPointer context
= pipeline
.front();
2337 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
2338 clientStreamNode
*node
= context
->getClientReplyContext();
2339 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2341 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
2342 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
2343 repContext
->setReplyToError(error
, scode
,
2344 repContext
->http
->request
->method
,
2345 repContext
->http
->uri
,
2347 repContext
->http
->request
,
2349 context
->pullData();
2351 // close or otherwise we may get stuck as nobody will notice the error?
2352 comm_reset_close(clientConnection
);
2355 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
2356 comm_reset_close(clientConnection
);
2358 flags
.readMore
= false;
2362 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
2364 // request reader may get stuck waiting for space if nobody consumes body
2365 if (bodyPipe
!= NULL
)
2366 bodyPipe
->enableAutoConsumption();
2371 /** general lifetime handler for HTTP requests */
2373 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
2375 if (!Comm::IsConnOpen(io
.conn
))
2378 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
2380 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
2381 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
2382 receivedFirstByte();
2385 } else if (!fd_table
[io
.conn
->fd
].ssl
)
2388 const HttpRequestMethod method
;
2389 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
2390 // Tunnel established. Set receivedFirstByte to avoid loop.
2391 receivedFirstByte();
2397 * Just close the connection to not confuse browsers
2398 * using persistent connections. Some browsers open
2399 * a connection and then do not use it until much
2400 * later (presumeably because the request triggering
2401 * the open has already been completed on another
2404 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
2409 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
2411 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
2412 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
2413 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
2414 http
->logType
.err
.timedout
= true;
2415 if (Comm::IsConnOpen(io
.conn
))
2419 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
2420 AsyncJob("ConnStateData"), // kids overwrite
2422 bodyParser(nullptr),
2424 sslBumpMode(Ssl::bumpEnd
),
2426 needProxyProtocolHeader_(false),
2428 switchedToHttps_(false),
2429 parsingTlsHandshake(false),
2430 sslServerBump(NULL
),
2431 signAlgorithm(Ssl::algSignTrusted
),
2433 stoppedSending_(NULL
),
2434 stoppedReceiving_(NULL
)
2436 flags
.readMore
= true; // kids may overwrite
2437 flags
.swanSang
= false;
2439 pinning
.host
= NULL
;
2441 pinning
.pinned
= false;
2442 pinning
.auth
= false;
2443 pinning
.zeroReply
= false;
2444 pinning
.peer
= NULL
;
2446 // store the details required for creating more MasterXaction objects as new requests come in
2447 log_addr
= xact
->tcpClient
->remote
;
2448 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
2450 // register to receive notice of Squid signal events
2451 // which may affect long persisting client connections
2452 RegisterRunner(this);
2456 ConnStateData::start()
2458 BodyProducer::start();
2459 HttpControlMsgSink::start();
2461 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
2462 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
2463 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2464 int i
= IP_PMTUDISC_DONT
;
2465 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0) {
2467 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerr(xerrno
));
2470 static bool reported
= false;
2473 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
2479 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
2480 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
2481 comm_add_close_handler(clientConnection
->fd
, call
);
2483 if (Config
.onoff
.log_fqdn
)
2484 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2487 if (Ident::TheConfig
.identLookup
) {
2488 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
2489 identChecklist
.src_addr
= clientConnection
->remote
;
2490 identChecklist
.my_addr
= clientConnection
->local
;
2491 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
2492 Ident::Start(clientConnection
, clientIdentDone
, this);
2496 clientdbEstablished(clientConnection
->remote
, 1);
2498 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
2499 if (needProxyProtocolHeader_
) {
2500 if (!proxyProtocolValidateClient()) // will close the connection on failure
2505 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
2507 if (Config
.onoff
.client_db
) {
2508 /* it was said several times that client write limiter does not work if client_db is disabled */
2510 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
2511 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
2513 // TODO: we check early to limit error response bandwith but we
2514 // should recheck when we can honor delay_pool_uses_indirect
2515 // TODO: we should also pass the port details for myportname here.
2516 ch
.src_addr
= clientConnection
->remote
;
2517 ch
.my_addr
= clientConnection
->local
;
2519 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
2521 /* pools require explicit 'allow' to assign a client into them */
2522 if (pools
[pool
].access
) {
2523 ch
.changeAcl(pools
[pool
].access
);
2524 allow_t answer
= ch
.fastCheck();
2525 if (answer
== ACCESS_ALLOWED
) {
2527 /* request client information from db after we did all checks
2528 this will save hash lookup if client failed checks */
2529 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
2532 /* put client info in FDE */
2533 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
2535 /* setup write limiter for this request */
2536 const double burst
= floor(0.5 +
2537 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
2538 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
2541 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
2548 // kids must extend to actually start doing something (e.g., reading)
2551 /** Handle a new connection on an HTTP socket. */
2553 httpAccept(const CommAcceptCbParams
¶ms
)
2555 MasterXaction::Pointer xact
= params
.xaction
;
2556 AnyP::PortCfgPointer s
= xact
->squidPort
;
2558 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2560 if (params
.flag
!= Comm::OK
) {
2561 // Its possible the call was still queued when the client disconnected
2562 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2566 debugs(33, 4, params
.conn
<< ": accepted");
2567 fd_note(params
.conn
->fd
, "client http connect");
2569 if (s
->tcp_keepalive
.enabled
)
2570 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2572 ++incoming_sockets_accepted
;
2574 // Socket is ready, setup the connection manager to start using it
2575 auto *srv
= Http::NewServer(xact
);
2576 AsyncJob::Start(srv
); // usually async-calls readSomeData()
2581 /** Create SSL connection structure and update fd_table */
2583 httpsCreate(const Comm::ConnectionPointer
&conn
, Security::ContextPtr sslContext
)
2585 if (Ssl::CreateServer(sslContext
, conn
, "client https start")) {
2586 debugs(33, 5, "will negotate SSL on " << conn
);
2596 * \retval 1 on success
2597 * \retval 0 when needs more data
2598 * \retval -1 on error
2601 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
2603 int fd
= conn
->clientConnection
->fd
;
2604 auto ssl
= fd_table
[fd
].ssl
.get();
2608 if ((ret
= SSL_accept(ssl
)) <= 0) {
2609 const int xerrno
= errno
;
2610 const int ssl_error
= SSL_get_error(ssl
, ret
);
2612 switch (ssl_error
) {
2614 case SSL_ERROR_WANT_READ
:
2615 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, (callback
!= NULL
? conn
: NULL
), 0);
2618 case SSL_ERROR_WANT_WRITE
:
2619 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, (callback
!= NULL
? conn
: NULL
), 0);
2622 case SSL_ERROR_SYSCALL
:
2624 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
2626 debugs(83, (xerrno
== ECONNRESET
) ? 1 : 2, "Error negotiating SSL connection on FD " << fd
<< ": " <<
2627 (xerrno
== 0 ? ERR_error_string(ssl_error
, NULL
) : xstrerr(xerrno
)));
2631 case SSL_ERROR_ZERO_RETURN
:
2632 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
2636 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
2637 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
2638 " (" << ssl_error
<< "/" << ret
<< ")");
2647 /** negotiate an SSL connection */
2649 clientNegotiateSSL(int fd
, void *data
)
2651 ConnStateData
*conn
= (ConnStateData
*)data
;
2653 auto ssl
= fd_table
[fd
].ssl
.get();
2656 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
2657 if (ret
< 0) // An error
2658 conn
->clientConnection
->close();
2662 if (SSL_session_reused(ssl
)) {
2663 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
2664 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
2666 if (Debug::Enabled(83, 4)) {
2667 /* Write out the SSL session details.. actually the call below, but
2668 * OpenSSL headers do strange typecasts confusing GCC.. */
2669 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
2670 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
2671 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
);
2673 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
2675 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
2676 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
2677 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
2678 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
2679 * Because there are two possible usable cast, if you get an error here, try the other
2680 * commented line. */
2682 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
2683 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
2687 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
2690 /* Note: This does not automatically fflush the log file.. */
2693 debugs(83, 2, "clientNegotiateSSL: New session " <<
2694 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
2695 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
2699 // Connection established. Retrieve TLS connection parameters for logging.
2700 conn
->clientConnection
->tlsNegotiations()->retrieveNegotiatedInfo(ssl
);
2702 client_cert
= SSL_get_peer_certificate(ssl
);
2704 if (client_cert
!= NULL
) {
2705 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2706 " client certificate: subject: " <<
2707 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
2709 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2710 " client certificate: issuer: " <<
2711 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
2713 X509_free(client_cert
);
2715 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
2716 " has no certificate.");
2719 #if defined(TLSEXT_NAMETYPE_host_name)
2720 if (!conn
->serverBump()) {
2721 // when in bumpClientFirst mode, get the server name from SNI
2722 if (const char *server
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))
2723 conn
->resetSslCommonName(server
);
2727 conn
->readSomeData();
2731 * If Security::ContextPtr is given, starts reading the TLS handshake.
2732 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPtr.
2735 httpsEstablish(ConnStateData
*connState
, Security::ContextPtr sslContext
)
2738 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
2740 if (!sslContext
|| !httpsCreate(details
, sslContext
))
2743 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2744 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
2745 connState
, ConnStateData::requestTimeout
);
2746 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
2748 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
2752 * A callback function to use with the ACLFilledChecklist callback.
2753 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
2754 * else reverts the connection to tunnel mode.
2757 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
2759 ConnStateData
*connState
= (ConnStateData
*) data
;
2761 // if the connection is closed or closing, just return.
2762 if (!connState
->isOpen())
2765 // Require both a match and a positive bump mode to work around exceptional
2766 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
2767 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
2768 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
2769 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
2771 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
2772 connState
->sslBumpMode
= Ssl::bumpNone
;
2774 if (!connState
->fakeAConnectRequest("ssl-bump", connState
->inBuf
))
2775 connState
->clientConnection
->close();
2778 /** handle a new HTTPS connection */
2780 httpsAccept(const CommAcceptCbParams
¶ms
)
2782 MasterXaction::Pointer xact
= params
.xaction
;
2783 const AnyP::PortCfgPointer s
= xact
->squidPort
;
2785 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2787 if (params
.flag
!= Comm::OK
) {
2788 // Its possible the call was still queued when the client disconnected
2789 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2793 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
2794 fd_note(params
.conn
->fd
, "client https connect");
2796 if (s
->tcp_keepalive
.enabled
) {
2797 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2799 ++incoming_sockets_accepted
;
2801 // Socket is ready, setup the connection manager to start using it
2802 auto *srv
= Https::NewServer(xact
);
2803 AsyncJob::Start(srv
); // usually async-calls postHttpsAccept()
2807 ConnStateData::postHttpsAccept()
2809 if (port
->flags
.tunnelSslBumping
) {
2810 debugs(33, 5, "accept transparent connection: " << clientConnection
);
2812 if (!Config
.accessList
.ssl_bump
) {
2813 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
2817 // Create a fake HTTP request for ssl_bump ACL check,
2818 // using tproxy/intercept provided destination IP and port.
2819 HttpRequest
*request
= new HttpRequest();
2820 static char ip
[MAX_IPSTRLEN
];
2821 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
2822 request
->url
.host(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
2823 request
->url
.port(clientConnection
->local
.port());
2824 request
->myportname
= port
->name
;
2826 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
2827 acl_checklist
->src_addr
= clientConnection
->remote
;
2828 acl_checklist
->my_addr
= port
->s
;
2829 // Build a local AccessLogEntry to allow requiresAle() acls work
2830 acl_checklist
->al
= new AccessLogEntry
;
2831 acl_checklist
->al
->cache
.start_time
= current_time
;
2832 acl_checklist
->al
->tcpClient
= clientConnection
;
2833 acl_checklist
->al
->cache
.port
= port
;
2834 acl_checklist
->al
->cache
.caddr
= log_addr
;
2835 HTTPMSGUNLOCK(acl_checklist
->al
->request
);
2836 acl_checklist
->al
->request
= request
;
2837 HTTPMSGLOCK(acl_checklist
->al
->request
);
2838 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
2841 httpsEstablish(this, port
->secure
.staticContext
.get());
2846 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
2848 ConnStateData
* state_data
= (ConnStateData
*)(data
);
2849 state_data
->sslCrtdHandleReply(reply
);
2853 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
2856 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply
);
2860 if (reply
.result
== Helper::BrokenHelper
) {
2861 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
2862 } else if (!reply
.other().hasContent()) {
2863 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
2865 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
2866 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
2867 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
2869 if (reply
.result
!= Helper::Okay
) {
2870 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
2872 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
2873 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
2874 doPeekAndSpliceStep();
2875 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
2876 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
2878 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
2880 SSL_CTX
*sslContext
= SSL_get_SSL_CTX(ssl
);
2881 Ssl::configureUnconfiguredSslContext(sslContext
, signAlgorithm
, *port
);
2883 auto ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
2884 getSslContextDone(ctx
, true);
2890 getSslContextDone(NULL
);
2893 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
2895 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
2897 // fake certificate adaptation requires bump-server-first mode
2898 if (!sslServerBump
) {
2899 assert(port
->signingCert
.get());
2900 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2901 if (port
->signPkey
.get())
2902 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2903 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2907 // In case of an error while connecting to the secure server, use a fake
2908 // trusted certificate, with no mimicked fields and no adaptation
2909 // algorithms. There is nothing we can mimic so we want to minimize the
2910 // number of warnings the user will have to see to get to the error page.
2911 assert(sslServerBump
->entry
);
2912 if (sslServerBump
->entry
->isEmpty()) {
2913 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
2914 certProperties
.mimicCert
.resetAndLock(mimicCert
);
2916 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
2917 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
2918 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors());
2920 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
2921 // If the algorithm already set, then ignore it.
2922 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
2923 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
2924 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
2927 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
2928 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
2929 const char *param
= ca
->param
;
2931 // For parameterless CN adaptation, use hostname from the
2933 if (ca
->alg
== Ssl::algSetCommonName
) {
2935 param
= sslConnectHostOrIp
.termedBuf();
2936 certProperties
.commonName
= param
;
2937 certProperties
.setCommonName
= true;
2938 } else if (ca
->alg
== Ssl::algSetValidAfter
)
2939 certProperties
.setValidAfter
= true;
2940 else if (ca
->alg
== Ssl::algSetValidBefore
)
2941 certProperties
.setValidBefore
= true;
2943 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
2944 alg
<< " param: " << (param
? param
: "-"));
2948 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
2949 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
2950 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
2951 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
2955 } else {// if (!sslServerBump->entry->isEmpty())
2956 // Use trusted certificate for a Squid-generated error
2957 // or the user would have to add a security exception
2958 // just to see the error page. We will close the connection
2959 // so that the trust is not extended to non-Squid content.
2960 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2963 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
2965 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
2966 assert(port
->untrustedSigningCert
.get());
2967 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
2968 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
2970 assert(port
->signingCert
.get());
2971 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2973 if (port
->signPkey
.get())
2974 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2976 signAlgorithm
= certProperties
.signAlgorithm
;
2978 certProperties
.signHash
= Ssl::DefaultSignHash
;
2982 ConnStateData::getSslContextStart()
2984 // XXX starting SSL with a pipeline of requests still waiting for non-SSL replies?
2985 assert(pipeline
.count() < 2); // the CONNECT is okay for now. Anything else is a bug.
2986 pipeline
.terminateAll(0);
2987 /* careful: terminateAll(0) above frees request, host, etc. */
2989 if (port
->generateHostCertificates
) {
2990 Ssl::CertificateProperties certProperties
;
2991 buildSslCertGenerationParams(certProperties
);
2992 sslBumpCertKey
= certProperties
.dbKey().c_str();
2993 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
2995 // Disable caching for bumpPeekAndSplice mode
2996 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
2997 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
2998 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
2999 Security::ContextPtr dynCtx
= nullptr;
3000 Security::ContextPointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : nullptr;
3001 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3002 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3003 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3004 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3005 getSslContextDone(dynCtx
);
3008 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3010 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3013 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3019 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3020 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3021 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3022 request_message
.composeRequest(certProperties
);
3023 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3024 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3026 } catch (const std::exception
&e
) {
3027 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3028 "request for " << certProperties
.commonName
<<
3029 " certificate: " << e
.what() << "; will now block to " <<
3030 "generate that certificate.");
3031 // fall through to do blocking in-process generation.
3033 #endif // USE_SSL_CRTD
3035 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3036 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3037 doPeekAndSpliceStep();
3038 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3039 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3040 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3042 SSL_CTX
*sslContext
= SSL_get_SSL_CTX(ssl
);
3043 Ssl::configureUnconfiguredSslContext(sslContext
, certProperties
.signAlgorithm
, *port
);
3045 auto dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3046 getSslContextDone(dynCtx
, true);
3050 getSslContextDone(NULL
);
3054 ConnStateData::getSslContextDone(Security::ContextPtr sslContext
, bool isNew
)
3056 // Try to add generated ssl context to storage.
3057 if (port
->generateHostCertificates
&& isNew
) {
3059 if (sslContext
&& (signAlgorithm
== Ssl::algSignTrusted
)) {
3060 Ssl::chainCertificatesToSSLContext(sslContext
, *port
);
3061 } else if (signAlgorithm
== Ssl::algSignTrusted
) {
3062 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain because SSL context chain is invalid!");
3064 //else it is self-signed or untrusted do not attrach any certificate
3066 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3067 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3069 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Security::ContextPointer(sslContext
))) {
3070 // If it is not in storage delete after using. Else storage deleted it.
3071 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3074 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3078 // If generated ssl context = NULL, try to use static ssl context.
3080 if (!port
->secure
.staticContext
) {
3081 debugs(83, DBG_IMPORTANT
, "Closing " << clientConnection
->remote
<< " as lacking TLS context");
3082 clientConnection
->close();
3085 debugs(33, 5, "Using static TLS context.");
3086 sslContext
= port
->secure
.staticContext
.get();
3090 if (!httpsCreate(clientConnection
, sslContext
))
3093 // bumped intercepted conns should already have Config.Timeout.request set
3094 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3095 // to make sure the connection does not get stuck on non-SSL clients.
3096 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3097 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3098 this, ConnStateData::requestTimeout
);
3099 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3101 switchedToHttps_
= true;
3103 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3104 BIO
*b
= SSL_get_rbio(ssl
);
3105 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3106 bio
->setReadBufData(inBuf
);
3108 clientNegotiateSSL(clientConnection
->fd
, this);
3112 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3114 assert(!switchedToHttps_
);
3116 sslConnectHostOrIp
= request
->url
.host();
3117 resetSslCommonName(request
->url
.host());
3119 // We are going to read new request
3120 flags
.readMore
= true;
3121 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3123 // keep version major.minor details the same.
3124 // but we are now performing the HTTPS handshake traffic
3125 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
3127 // If sslServerBump is set, then we have decided to deny CONNECT
3128 // and now want to switch to SSL to send the error to the client
3129 // without even peeking at the origin server certificate.
3130 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3131 request
->flags
.sslPeek
= true;
3132 sslServerBump
= new Ssl::ServerBump(request
);
3133 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
3134 request
->flags
.sslPeek
= true;
3135 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
3138 // commSetConnTimeout() was called for this request before we switched.
3139 // Fix timeout to request_start_timeout
3140 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3141 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3142 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3143 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
3144 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
3145 // a bumbed "connect" request on non transparent port.
3146 receivedFirstByte_
= false;
3147 // Get more data to peek at Tls
3148 parsingTlsHandshake
= true;
3153 ConnStateData::parseTlsHandshake()
3155 Must(parsingTlsHandshake
);
3157 assert(!inBuf
.isEmpty());
3158 receivedFirstByte();
3159 fd_note(clientConnection
->fd
, "Parsing TLS handshake");
3161 bool unsupportedProtocol
= false;
3163 if (!tlsParser
.parseHello(inBuf
)) {
3164 // need more data to finish parsing
3169 catch (const std::exception
&ex
) {
3170 debugs(83, 2, "error on FD " << clientConnection
->fd
<< ": " << ex
.what());
3171 unsupportedProtocol
= true;
3174 parsingTlsHandshake
= false;
3176 // Even if the parser failed, each TLS detail should either be set
3177 // correctly or still be "unknown"; copying unknown detail is a no-op.
3178 clientConnection
->tlsNegotiations()->retrieveParsedInfo(tlsParser
.details
);
3180 // We should disable read/write handlers
3181 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3182 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
3184 if (!sslServerBump
) { // BumpClientFirst mode does not use this member
3185 getSslContextStart();
3187 } else if (sslServerBump
->act
.step1
== Ssl::bumpServerFirst
) {
3188 // will call httpsPeeked() with certificate and connection, eventually
3189 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3191 Must(sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
);
3192 startPeekAndSplice(unsupportedProtocol
);
3197 ConnStateData::spliceOnError(const err_type err
)
3199 if (Config
.accessList
.on_unsupported_protocol
) {
3200 assert(serverBump());
3201 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
3202 checklist
.requestErrorType
= err
;
3203 checklist
.conn(this);
3204 allow_t answer
= checklist
.fastCheck();
3205 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
3213 ConnStateData::startPeekAndSplice(const bool unsupportedProtocol
)
3215 if (unsupportedProtocol
) {
3216 if (!spliceOnError(ERR_PROTOCOL_UNKNOWN
))
3217 clientConnection
->close();
3222 Security::TlsDetails::Pointer
const &details
= tlsParser
.details
;
3223 if (details
&& !details
->serverName
.isEmpty()) {
3224 serverBump()->clientSni
= details
->serverName
;
3225 resetSslCommonName(details
->serverName
.c_str());
3229 startPeekAndSpliceDone();
3232 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
3234 ConnStateData
*connState
= (ConnStateData
*) data
;
3236 // if the connection is closed or closing, just return.
3237 if (!connState
->isOpen())
3240 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
3241 assert(connState
->serverBump());
3242 Ssl::BumpMode bumpAction
;
3243 if (answer
== ACCESS_ALLOWED
) {
3244 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
3246 bumpAction
= Ssl::bumpSplice
;
3248 connState
->serverBump()->act
.step2
= bumpAction
;
3249 connState
->sslBumpMode
= bumpAction
;
3251 if (bumpAction
== Ssl::bumpTerminate
) {
3252 connState
->clientConnection
->close();
3253 } else if (bumpAction
!= Ssl::bumpSplice
) {
3254 connState
->startPeekAndSpliceDone();
3255 } else if (!connState
->splice())
3256 connState
->clientConnection
->close();
3260 ConnStateData::splice()
3262 // normally we can splice here, because we just got client hello message
3264 if (fd_table
[clientConnection
->fd
].ssl
.get()) {
3265 // Restore default read methods
3266 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
3267 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
3270 if (transparent()) {
3271 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
3272 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
3273 transferProtocol
= Http::ProtocolVersion();
3274 return fakeAConnectRequest("intercepted TLS spliced", inBuf
);
3276 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
3278 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
3279 transferProtocol
= Http::ProtocolVersion();
3280 Http::StreamPointer context
= pipeline
.front();
3281 ClientHttpRequest
*http
= context
->http
;
3288 ConnStateData::startPeekAndSpliceDone()
3290 // This is the Step2 of the SSL bumping
3291 assert(sslServerBump
);
3292 Http::StreamPointer context
= pipeline
.front();
3293 ClientHttpRequest
*http
= context
? context
->http
: NULL
;
3295 if (sslServerBump
->step
== Ssl::bumpStep1
) {
3296 sslServerBump
->step
= Ssl::bumpStep2
;
3297 // Run a accessList check to check if want to splice or continue bumping
3299 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
3300 acl_checklist
->al
= http
? http
->al
: NULL
;
3301 //acl_checklist->src_addr = params.conn->remote;
3302 //acl_checklist->my_addr = s->s;
3303 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpNone
));
3304 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpClientFirst
));
3305 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpServerFirst
));
3306 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
3310 // will call httpsPeeked() with certificate and connection, eventually
3311 auto unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
3312 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
3314 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
3317 switchedToHttps_
= true;
3319 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3320 BIO
*b
= SSL_get_rbio(ssl
);
3321 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3322 bio
->setReadBufData(inBuf
);
3325 // Here squid should have all of the client hello message so the
3326 // Squid_SSL_accept should return 0;
3327 // This block exist only to force openSSL parse client hello and detect
3328 // ERR_SECURE_ACCEPT_FAIL error, which should be checked and splice if required.
3330 if ((ret
= Squid_SSL_accept(this, NULL
)) < 0) {
3331 debugs(83, 2, "SSL_accept failed.");
3332 const err_type err
= ERR_SECURE_ACCEPT_FAIL
;
3333 if (!spliceOnError(err
))
3334 clientConnection
->close();
3338 // We need to reset inBuf here, to be used by incoming requests in the case
3342 debugs(83, 5, "Peek and splice at step2 done. Start forwarding the request!!! ");
3343 FwdState::Start(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw(), http
? http
->al
: NULL
);
3347 ConnStateData::doPeekAndSpliceStep()
3349 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3350 BIO
*b
= SSL_get_rbio(ssl
);
3352 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3354 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
3357 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
3358 switchedToHttps_
= true;
3362 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3364 Must(sslServerBump
!= NULL
);
3366 if (Comm::IsConnOpen(serverConnection
)) {
3367 pinConnection(serverConnection
, NULL
, NULL
, false);
3369 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3371 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3373 // copy error detail from bump-server-first request to CONNECT request
3374 if (!pipeline
.empty() && pipeline
.front()->http
!= nullptr && pipeline
.front()->http
->request
)
3375 pipeline
.front()->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3378 getSslContextStart();
3381 #endif /* USE_OPENSSL */
3384 ConnStateData::fakeAConnectRequest(const char *reason
, const SBuf
&payload
)
3386 // fake a CONNECT request to force connState to tunnel
3389 if (serverBump() && !serverBump()->clientSni
.isEmpty()) {
3390 connectHost
.assign(serverBump()->clientSni
);
3391 if (clientConnection
->local
.port() > 0)
3392 connectHost
.appendf(":%d",clientConnection
->local
.port());
3396 static char ip
[MAX_IPSTRLEN
];
3397 connectHost
.assign(clientConnection
->local
.toUrl(ip
, sizeof(ip
)));
3399 // Pre-pend this fake request to the TLS bits already in the buffer
3401 retStr
.append("CONNECT ");
3402 retStr
.append(connectHost
);
3403 retStr
.append(" HTTP/1.1\r\nHost: ");
3404 retStr
.append(connectHost
);
3405 retStr
.append("\r\n\r\n");
3406 retStr
.append(payload
);
3408 bool ret
= handleReadData();
3410 ret
= clientParseRequests();
3413 debugs(33, 2, "Failed to start fake CONNECT request for " << reason
<< " connection: " << clientConnection
);
3419 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3421 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3423 if (!Comm::IsConnOpen(c
)) {
3424 Must(NHttpSockets
> 0); // we tried to open some
3425 --NHttpSockets
; // there will be fewer sockets than planned
3426 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3428 if (!NHttpSockets
) // we could not open any listen sockets at all
3429 fatalf("Unable to open %s",FdNote(portType
));
3436 /// find any unused HttpSockets[] slot and store fd there or return false
3438 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
3441 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
3442 if ((found
= HttpSockets
[i
] < 0))
3443 HttpSockets
[i
] = conn
->fd
;
3449 clientHttpConnectionsOpen(void)
3451 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3452 const SBuf
&scheme
= AnyP::UriScheme(s
->transport
.protocol
).image();
3454 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
3455 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many '" << scheme
<< "_port' lines.");
3456 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
3461 if (s
->flags
.tunnelSslBumping
) {
3462 if (!Config
.accessList
.ssl_bump
) {
3463 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme
<< "_port " << s
->s
);
3464 s
->flags
.tunnelSslBumping
= false;
3466 if (!s
->secure
.staticContext
&& !s
->generateHostCertificates
) {
3467 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at " << scheme
<< "_port " << s
->s
<< " due to TLS initialization failure.");
3468 s
->flags
.tunnelSslBumping
= false;
3469 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
)
3470 s
->secure
.encryptTransport
= false;
3472 if (s
->flags
.tunnelSslBumping
) {
3473 // Create ssl_ctx cache for this port.
3474 auto sz
= s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
;
3475 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, sz
);
3479 if (s
->secure
.encryptTransport
&& !s
->secure
.staticContext
) {
3480 debugs(1, DBG_CRITICAL
, "ERROR: Ignoring " << scheme
<< "_port " << s
->s
<< " due to TLS context initialization failure.");
3485 // Fill out a Comm::Connection which IPC will open as a listener for us
3486 // then pass back when active so we can start a TcpAcceptor subscription.
3487 s
->listenConn
= new Comm::Connection
;
3488 s
->listenConn
->local
= s
->s
;
3490 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3491 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3493 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3494 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
) {
3495 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
3496 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
3497 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3499 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
3500 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
3501 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
3504 } else if (s
->transport
.protocol
== AnyP::PROTO_HTTPS
) {
3505 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
3506 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
3507 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3509 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
3510 ListeningStartedDialer(&clientListenerConnectionOpened
,
3511 s
, Ipc::fdnHttpsSocket
, sub
));
3512 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
3516 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
3522 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
3524 // Fill out a Comm::Connection which IPC will open as a listener for us
3525 port
->listenConn
= new Comm::Connection
;
3526 port
->listenConn
->local
= port
->s
;
3527 port
->listenConn
->flags
=
3529 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3530 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3532 // route new connections to subCall
3533 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3534 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3535 AsyncCall::Pointer listenCall
=
3536 asyncCall(33, 2, "clientListenerConnectionOpened",
3537 ListeningStartedDialer(&clientListenerConnectionOpened
,
3538 port
, fdNote
, sub
));
3539 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
3541 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
3542 HttpSockets
[NHttpSockets
] = -1;
3546 /// process clientHttpConnectionsOpen result
3548 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
3552 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
3555 Must(Comm::IsConnOpen(s
->listenConn
));
3557 // TCP: setup a job to handle accept() with subscribed handler
3558 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
3560 debugs(1, DBG_IMPORTANT
, "Accepting " <<
3561 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
3562 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
3563 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
3564 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
3565 << FdNote(portTypeNote
) << " connections at "
3568 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
3572 clientOpenListenSockets(void)
3574 clientHttpConnectionsOpen();
3575 Ftp::StartListening();
3577 if (NHttpSockets
< 1)
3578 fatal("No HTTP, HTTPS, or FTP ports configured");
3582 clientConnectionsClose()
3584 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3585 if (s
->listenConn
!= NULL
) {
3586 debugs(1, DBG_IMPORTANT
, "Closing HTTP(S) port " << s
->listenConn
->local
);
3587 s
->listenConn
->close();
3588 s
->listenConn
= NULL
;
3592 Ftp::StopListening();
3594 // TODO see if we can drop HttpSockets array entirely */
3595 for (int i
= 0; i
< NHttpSockets
; ++i
) {
3596 HttpSockets
[i
] = -1;
3603 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
3605 SBuf
vary(request
->vary_headers
);
3606 int has_vary
= entry
->getReply()->header
.has(Http::HdrType::VARY
);
3607 #if X_ACCELERATOR_VARY
3610 entry
->getReply()->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
3613 if (!has_vary
|| entry
->mem_obj
->vary_headers
.isEmpty()) {
3614 if (!vary
.isEmpty()) {
3615 /* Oops... something odd is going on here.. */
3616 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
3617 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3618 request
->vary_headers
.clear();
3623 /* This is not a varying object */
3627 /* virtual "vary" object found. Calculate the vary key and
3628 * continue the search
3630 vary
= httpMakeVaryMark(request
, entry
->getReply());
3632 if (!vary
.isEmpty()) {
3633 request
->vary_headers
= vary
;
3636 /* Ouch.. we cannot handle this kind of variance */
3637 /* XXX This cannot really happen, but just to be complete */
3641 if (vary
.isEmpty()) {
3642 vary
= httpMakeVaryMark(request
, entry
->getReply());
3644 if (!vary
.isEmpty())
3645 request
->vary_headers
= vary
;
3648 if (vary
.isEmpty()) {
3649 /* Ouch.. we cannot handle this kind of variance */
3650 /* XXX This cannot really happen, but just to be complete */
3652 } else if (vary
.cmp(entry
->mem_obj
->vary_headers
) == 0) {
3655 /* Oops.. we have already been here and still haven't
3656 * found the requested variant. Bail out
3658 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
3659 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3665 ACLFilledChecklist
*
3666 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
3668 ConnStateData
* conn
= http
->getConn();
3669 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
3670 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
3673 * hack for ident ACL. It needs to get full addresses, and a place to store
3674 * the ident result on persistent connections...
3676 /* connection oriented auth also needs these two lines for it's operation. */
3681 ConnStateData::transparent() const
3683 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
3687 ConnStateData::expectRequestBody(int64_t size
)
3689 bodyPipe
= new BodyPipe(this);
3691 bodyPipe
->setBodySize(size
);
3693 startDechunkingRequest();
3698 ConnStateData::mayNeedToReadMoreBody() const
3701 return 0; // request without a body or read/produced all body bytes
3703 if (!bodyPipe
->bodySizeKnown())
3704 return -1; // probably need to read more, but we cannot be sure
3706 const int64_t needToProduce
= bodyPipe
->unproducedSize();
3707 const int64_t haveAvailable
= static_cast<int64_t>(inBuf
.length());
3709 if (needToProduce
<= haveAvailable
)
3710 return 0; // we have read what we need (but are waiting for pipe space)
3712 return needToProduce
- haveAvailable
;
3716 ConnStateData::stopReceiving(const char *error
)
3718 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
3719 "; old sending error: " <<
3720 (stoppedSending() ? stoppedSending_
: "none"));
3722 if (const char *oldError
= stoppedReceiving()) {
3723 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
3724 return; // nothing has changed as far as this connection is concerned
3727 stoppedReceiving_
= error
;
3729 if (const char *sendError
= stoppedSending()) {
3730 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
3731 clientConnection
->close();
3736 ConnStateData::expectNoForwarding()
3738 if (bodyPipe
!= NULL
) {
3739 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
3740 bodyPipe
->expectNoConsumption();
3744 /// initialize dechunking state
3746 ConnStateData::startDechunkingRequest()
3748 Must(bodyPipe
!= NULL
);
3749 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
3750 assert(!bodyParser
);
3751 bodyParser
= new Http1::TeChunkedParser
;
3754 /// put parsed content into input buffer and clean up
3756 ConnStateData::finishDechunkingRequest(bool withSuccess
)
3758 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
3760 if (bodyPipe
!= NULL
) {
3761 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
3762 BodyPipe::Pointer myPipe
= bodyPipe
;
3763 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
3764 Must(!bodyPipe
); // we rely on it being nil after we are done with body
3766 Must(myPipe
->bodySizeKnown());
3767 Http::StreamPointer context
= pipeline
.front();
3768 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
3769 context
->http
->request
->setContentLength(myPipe
->bodySize());
3777 // XXX: this is an HTTP/1-only operation
3779 ConnStateData::sendControlMsg(HttpControlMsg msg
)
3782 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
3786 // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them
3787 if (!pipeline
.empty()) {
3788 HttpReply::Pointer
rep(msg
.reply
);
3790 // remember the callback
3791 cbControlMsgSent
= msg
.cbSuccess
;
3793 typedef CommCbMemFunT
<HttpControlMsgSink
, CommIoCbParams
> Dialer
;
3794 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, HttpControlMsgSink::wroteControlMsg
);
3796 writeControlMsgAndCall(rep
.getRaw(), call
);
3800 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
3801 clientConnection
->close();
3804 /// Our close handler called by Comm when the pinned connection is closed
3806 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
3808 // FwdState might repin a failed connection sooner than this close
3809 // callback is called for the failed connection.
3810 assert(pinning
.serverConnection
== io
.conn
);
3811 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
3812 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
3813 pinning
.serverConnection
->noteClosure();
3814 unpinConnection(false);
3816 if (sawZeroReply
&& clientConnection
!= NULL
) {
3817 debugs(33, 3, "Closing client connection on pinned zero reply.");
3818 clientConnection
->close();
3824 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
3826 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
3827 pinning
.serverConnection
->fd
!= pinServer
->fd
)
3828 pinNewConnection(pinServer
, request
, aPeer
, auth
);
3831 startPinnedConnectionMonitoring();
3835 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
3837 unpinConnection(true); // closes pinned connection, if any, and resets fields
3839 pinning
.serverConnection
= pinServer
;
3841 debugs(33, 3, HERE
<< pinning
.serverConnection
);
3843 Must(pinning
.serverConnection
!= NULL
);
3845 // when pinning an SSL bumped connection, the request may be NULL
3846 const char *pinnedHost
= "[unknown]";
3848 pinning
.host
= xstrdup(request
->url
.host());
3849 pinning
.port
= request
->url
.port();
3850 pinnedHost
= pinning
.host
;
3852 pinning
.port
= pinServer
->remote
.port();
3854 pinning
.pinned
= true;
3856 pinning
.peer
= cbdataReference(aPeer
);
3857 pinning
.auth
= auth
;
3858 char stmp
[MAX_IPSTRLEN
];
3859 char desc
[FD_DESC_SZ
];
3860 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
3861 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
3862 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
3863 clientConnection
->fd
);
3864 fd_note(pinning
.serverConnection
->fd
, desc
);
3866 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3867 pinning
.closeHandler
= JobCallback(33, 5,
3868 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
3869 // remember the pinned connection so that cb does not unpin a fresher one
3870 typedef CommCloseCbParams Params
;
3871 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
3872 params
.conn
= pinning
.serverConnection
;
3873 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
3876 /// [re]start monitoring pinned connection for peer closures so that we can
3877 /// propagate them to an _idle_ client pinned to that peer
3879 ConnStateData::startPinnedConnectionMonitoring()
3881 if (pinning
.readHandler
!= NULL
)
3882 return; // already monitoring
3884 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
3885 pinning
.readHandler
= JobCallback(33, 3,
3886 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
3887 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
3891 ConnStateData::stopPinnedConnectionMonitoring()
3893 if (pinning
.readHandler
!= NULL
) {
3894 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
3895 pinning
.readHandler
= NULL
;
3901 ConnStateData::handleIdleClientPinnedTlsRead()
3903 // A ready-for-reading connection means that the TLS server either closed
3904 // the connection, sent us some unexpected HTTP data, or started TLS
3905 // renegotiations. We should close the connection except for the last case.
3907 Must(pinning
.serverConnection
!= nullptr);
3908 auto ssl
= fd_table
[pinning
.serverConnection
->fd
].ssl
.get();
3913 const int readResult
= SSL_read(ssl
, buf
, sizeof(buf
));
3915 if (readResult
> 0 || SSL_pending(ssl
) > 0) {
3916 debugs(83, 2, pinning
.serverConnection
<< " TLS application data read");
3920 switch(const int error
= SSL_get_error(ssl
, readResult
)) {
3921 case SSL_ERROR_WANT_WRITE
:
3922 debugs(83, DBG_IMPORTANT
, pinning
.serverConnection
<< " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection");
3923 // fall through to restart monitoring, for now
3924 case SSL_ERROR_NONE
:
3925 case SSL_ERROR_WANT_READ
:
3926 startPinnedConnectionMonitoring();
3930 debugs(83, 2, pinning
.serverConnection
<< " TLS error: " << error
);
3939 /// Our read handler called by Comm when the server either closes an idle pinned connection or
3940 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
3942 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
3944 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
3946 if (io
.flag
== Comm::ERR_CLOSING
)
3947 return; // close handler will clean up
3949 Must(pinning
.serverConnection
== io
.conn
);
3952 if (handleIdleClientPinnedTlsRead())
3956 const bool clientIsIdle
= pipeline
.empty();
3958 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
3959 io
.size
<< (clientIsIdle
? " with idle client" : ""));
3961 pinning
.serverConnection
->close();
3963 // If we are still sending data to the client, do not close now. When we are done sending,
3964 // ConnStateData::kick() checks pinning.serverConnection and will close.
3965 // However, if we are idle, then we must close to inform the idle client and minimize races.
3966 if (clientIsIdle
&& clientConnection
!= NULL
)
3967 clientConnection
->close();
3970 const Comm::ConnectionPointer
3971 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
3973 debugs(33, 7, HERE
<< pinning
.serverConnection
);
3976 if (!Comm::IsConnOpen(pinning
.serverConnection
))
3978 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->url
.host()) != 0)
3980 else if (request
&& pinning
.port
!= request
->url
.port())
3982 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
3984 else if (aPeer
!= pinning
.peer
)
3988 /* The pinning info is not safe, remove any pinning info */
3989 unpinConnection(true);
3992 return pinning
.serverConnection
;
3995 Comm::ConnectionPointer
3996 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
3998 debugs(33, 7, pinning
.serverConnection
);
3999 if (validatePinnedConnection(request
, aPeer
) != NULL
)
4000 stopPinnedConnectionMonitoring();
4002 return pinning
.serverConnection
; // closed if validation failed
4006 ConnStateData::unpinConnection(const bool andClose
)
4008 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4011 cbdataReferenceDone(pinning
.peer
);
4013 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4014 if (pinning
.closeHandler
!= NULL
) {
4015 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4016 pinning
.closeHandler
= NULL
;
4019 stopPinnedConnectionMonitoring();
4021 // close the server side socket if requested
4023 pinning
.serverConnection
->close();
4024 pinning
.serverConnection
= NULL
;
4027 safe_free(pinning
.host
);
4029 pinning
.zeroReply
= false;
4031 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4032 * connection has gone away */
4036 ConnStateData::checkLogging()
4038 // if we are parsing request body, its request is responsible for logging
4042 // a request currently using this connection is responsible for logging
4043 if (!pipeline
.empty() && pipeline
.back()->mayUseConnection())
4046 /* Either we are waiting for the very first transaction, or
4047 * we are done with the Nth transaction and are waiting for N+1st.
4048 * XXX: We assume that if anything was added to inBuf, then it could
4049 * only be consumed by actions already covered by the above checks.
4052 // do not log connections that closed after a transaction (it is normal)
4053 // TODO: access_log needs ACLs to match received-no-bytes connections
4054 // XXX: TLS may return here even though we got no transactions yet
4055 // XXX: PROXY protocol may return here even though we got no
4057 if (receivedFirstByte_
&& inBuf
.isEmpty())
4060 /* Create a temporary ClientHttpRequest object. Its destructor will log. */
4061 ClientHttpRequest
http(this);
4062 http
.req_sz
= inBuf
.length();
4063 char const *uri
= "error:transaction-end-before-headers";
4064 http
.uri
= xstrdup(uri
);
4065 setLogUri(&http
, uri
);