2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 33 Client-side Routines */
12 \defgroup ClientSide Client-Side Logics
14 \section cserrors Errors and client side
16 \par Problem the first:
17 * the store entry is no longer authoritative on the
18 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
19 * of client_side_reply.c.
20 * Problem the second: resources are wasted if we delay in cleaning up.
21 * Problem the third we can't depend on a connection close to clean up.
23 \par Nice thing the first:
24 * Any step in the stream can callback with data
25 * representing an error.
26 * Nice thing the second: once you stop requesting reads from upstream,
27 * upstream can be stopped too.
30 * Error has a callback mechanism to hand over a membuf
31 * with the error content. The failing node pushes that back as the
32 * reply. Can this be generalised to reduce duplicate efforts?
33 * A: Possibly. For now, only one location uses this.
34 * How to deal with pre-stream errors?
35 * Tell client_side_reply that we *want* an error page before any
36 * stream calls occur. Then we simply read as normal.
39 \section pconn_logic Persistent connection logic:
42 * requests (httpClientRequest structs) get added to the connection
43 * list, with the current one being chr
46 * The request is *immediately* kicked off, and data flows through
47 * to clientSocketRecipient.
50 * If the data that arrives at clientSocketRecipient is not for the current
51 * request, clientSocketRecipient simply returns, without requesting more
52 * data, or sending it.
55 * ConnStateData::kick() will then detect the presence of data in
56 * the next ClientHttpRequest, and will send it, restablishing the
61 #include "acl/FilledChecklist.h"
62 #include "anyp/PortCfg.h"
63 #include "base/Subscription.h"
64 #include "base/TextException.h"
65 #include "CachePeer.h"
66 #include "client_db.h"
67 #include "client_side.h"
68 #include "client_side_reply.h"
69 #include "client_side_request.h"
70 #include "ClientRequestContext.h"
71 #include "clientStream.h"
73 #include "comm/Connection.h"
74 #include "comm/Loops.h"
75 #include "comm/Read.h"
76 #include "comm/TcpAcceptor.h"
77 #include "comm/Write.h"
78 #include "CommCalls.h"
79 #include "errorpage.h"
82 #include "fqdncache.h"
86 #include "helper/Reply.h"
88 #include "http/one/RequestParser.h"
89 #include "http/one/TeChunkedParser.h"
90 #include "http/Stream.h"
91 #include "HttpHdrContRange.h"
92 #include "HttpHeaderTools.h"
93 #include "HttpReply.h"
94 #include "HttpRequest.h"
95 #include "ident/Config.h"
96 #include "ident/Ident.h"
98 #include "ipc/FdNotes.h"
99 #include "ipc/StartListening.h"
100 #include "log/access_log.h"
102 #include "MemObject.h"
103 #include "mime_header.h"
104 #include "parser/Tokenizer.h"
105 #include "profiler/Profiler.h"
107 #include "security/NegotiationHistory.h"
108 #include "servers/forward.h"
109 #include "SquidConfig.h"
110 #include "SquidTime.h"
111 #include "StatCounters.h"
112 #include "StatHist.h"
114 #include "TimeOrTag.h"
119 #include "auth/UserRequest.h"
122 #include "ClientInfo.h"
126 #include "ssl/context_storage.h"
127 #include "ssl/gadgets.h"
128 #include "ssl/helper.h"
129 #include "ssl/ProxyCerts.h"
130 #include "ssl/ServerBump.h"
131 #include "ssl/support.h"
134 // for tvSubUsec() which should be in SquidTime.h
142 #define comm_close comm_lingering_close
145 /// dials clientListenerConnectionOpened call
146 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
149 typedef void (*Handler
)(AnyP::PortCfgPointer
&portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
150 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfgPointer
&aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
151 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
153 virtual void print(std::ostream
&os
) const {
155 ", " << FdNote(portTypeNote
) << " port=" << (void*)&portCfg
<< ')';
158 virtual bool canDial(AsyncCall
&) const { return true; }
159 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
165 AnyP::PortCfgPointer portCfg
; ///< from HttpPortList
166 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
167 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
170 static void clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
172 static IOACB httpAccept
;
174 static IOACB httpsAccept
;
176 static CTCB clientLifetimeTimeout
;
178 static IDCB clientIdentDone
;
180 static int clientIsContentLengthValid(HttpRequest
* r
);
181 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
183 static void clientUpdateStatHistCounters(const LogTags
&logType
, int svc_time
);
184 static void clientUpdateStatCounters(const LogTags
&logType
);
185 static void clientUpdateHierCounters(HierarchyLogEntry
*);
186 static bool clientPingHasFinished(ping_data
const *aPing
);
187 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
188 static void ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest
, ConnStateData
* conn
);
190 char *skipLeadingSpace(char *aString
);
194 clientIdentDone(const char *ident
, void *data
)
196 ConnStateData
*conn
= (ConnStateData
*)data
;
197 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
202 clientUpdateStatCounters(const LogTags
&logType
)
204 ++statCounter
.client_http
.requests
;
206 if (logType
.isTcpHit())
207 ++statCounter
.client_http
.hits
;
209 if (logType
.oldType
== LOG_TCP_HIT
)
210 ++statCounter
.client_http
.disk_hits
;
211 else if (logType
.oldType
== LOG_TCP_MEM_HIT
)
212 ++statCounter
.client_http
.mem_hits
;
216 clientUpdateStatHistCounters(const LogTags
&logType
, int svc_time
)
218 statCounter
.client_http
.allSvcTime
.count(svc_time
);
220 * The idea here is not to be complete, but to get service times
221 * for only well-defined types. For example, we don't include
222 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
223 * (we *tried* to validate it, but failed).
226 switch (logType
.oldType
) {
228 case LOG_TCP_REFRESH_UNMODIFIED
:
229 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
232 case LOG_TCP_IMS_HIT
:
233 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
238 case LOG_TCP_MEM_HIT
:
240 case LOG_TCP_OFFLINE_HIT
:
241 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
246 case LOG_TCP_CLIENT_REFRESH_MISS
:
247 statCounter
.client_http
.missSvcTime
.count(svc_time
);
251 /* make compiler warnings go away */
257 clientPingHasFinished(ping_data
const *aPing
)
259 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
266 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
270 switch (someEntry
->code
) {
271 #if USE_CACHE_DIGESTS
276 ++ statCounter
.cd
.times_used
;
284 case FIRST_PARENT_MISS
:
286 case CLOSEST_PARENT_MISS
:
287 ++ statCounter
.icp
.times_used
;
288 i
= &someEntry
->ping
;
290 if (clientPingHasFinished(i
))
291 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
294 ++ statCounter
.icp
.query_timeouts
;
301 ++ statCounter
.netdb
.times_used
;
311 ClientHttpRequest::updateCounters()
313 clientUpdateStatCounters(logType
);
315 if (request
->errType
!= ERR_NONE
)
316 ++ statCounter
.client_http
.errors
;
318 clientUpdateStatHistCounters(logType
,
319 tvSubMsec(al
->cache
.start_time
, current_time
));
321 clientUpdateHierCounters(&request
->hier
);
325 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
328 assert(aLogEntry
!= NULL
);
330 if (Config
.onoff
.log_mime_hdrs
) {
333 request
->header
.packInto(&mb
);
334 //This is the request after adaptation or redirection
335 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
337 // the virgin request is saved to aLogEntry->request
338 if (aLogEntry
->request
) {
340 aLogEntry
->request
->header
.packInto(&mb
);
341 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
345 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
348 ah
->lastMeta
.packInto(&mb
);
349 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
357 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
359 ih
->processingTime(aLogEntry
->icap
.processingTime
);
362 aLogEntry
->http
.method
= request
->method
;
363 aLogEntry
->http
.version
= request
->http_ver
;
364 aLogEntry
->hier
= request
->hier
;
365 if (request
->content_length
> 0) // negative when no body or unknown length
366 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
367 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
369 // Adapted request, if any, inherits and then collects all the stats, but
370 // the virgin request gets logged instead; copy the stats to log them.
371 // TODO: avoid losses by keeping these stats in a shared history object?
372 if (aLogEntry
->request
) {
373 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
374 aLogEntry
->request
->errType
= request
->errType
;
375 aLogEntry
->request
->errDetail
= request
->errDetail
;
380 ClientHttpRequest::logRequest()
382 if (!out
.size
&& logType
.oldType
== LOG_TAG_NONE
)
383 debugs(33, 5, "logging half-baked transaction: " << log_uri
);
385 al
->icp
.opcode
= ICP_INVALID
;
387 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
390 al
->http
.code
= al
->reply
->sline
.status();
391 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
392 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
393 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
394 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
397 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
399 if (loggingEntry() && loggingEntry()->mem_obj
&& loggingEntry()->objectLen() >= 0)
400 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
402 al
->http
.clientRequestSz
.header
= req_sz
;
403 al
->http
.clientReplySz
.header
= out
.headers_sz
;
404 // XXX: calculate without payload encoding or headers !!
405 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
407 al
->cache
.highOffset
= out
.offset
;
409 al
->cache
.code
= logType
;
411 tvSub(al
->cache
.trTime
, al
->cache
.start_time
, current_time
);
414 prepareLogWithRequestDetails(request
, al
);
416 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
417 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
421 /* This is broken. Fails if the connection has been closed. Needs
422 * to snarf the ssl details some place earlier..
424 if (getConn() != NULL
)
425 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
429 /* Add notes (if we have a request to annotate) */
431 // The al->notes and request->notes must point to the same object.
432 (void)SyncNotes(*al
, *request
);
433 for (auto i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
434 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
435 NotePairs
¬es
= SyncNotes(*al
, *request
);
436 notes
.add((*i
)->key
.termedBuf(), value
);
437 debugs(33, 3, (*i
)->key
.termedBuf() << " " << value
);
442 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
444 checklist
.reply
= al
->reply
;
445 HTTPMSGLOCK(checklist
.reply
);
449 HTTPMSGUNLOCK(al
->adapted_request
);
450 al
->adapted_request
= request
;
451 HTTPMSGLOCK(al
->adapted_request
);
453 accessLogLog(al
, &checklist
);
455 bool updatePerformanceCounters
= true;
456 if (Config
.accessList
.stats_collection
) {
457 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
459 statsCheck
.reply
= al
->reply
;
460 HTTPMSGLOCK(statsCheck
.reply
);
462 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
465 if (updatePerformanceCounters
) {
469 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
470 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
475 ClientHttpRequest::freeResources()
479 safe_free(redirect
.location
);
480 range_iter
.boundary
.clean();
481 HTTPMSGUNLOCK(request
);
483 if (client_stream
.tail
)
484 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
488 httpRequestFree(void *data
)
490 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
491 assert(http
!= NULL
);
495 /* This is a handler normally called by comm_close() */
496 void ConnStateData::connStateClosed(const CommCloseCbParams
&)
498 deleteThis("ConnStateData::connStateClosed");
503 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
507 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
513 // clobered with self-pointer
514 // NP: something nasty is going on in Squid, but harmless.
516 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
521 * Connection-auth relies on a single set of credentials being preserved
522 * for all requests on a connection once they have been setup.
523 * There are several things which need to happen to preserve security
524 * when connection-auth credentials change unexpectedly or are unset.
526 * 1) auth helper released from any active state
528 * They can only be reserved by a handshake process which this
529 * connection can now never complete.
530 * This prevents helpers hanging when their connections close.
532 * 2) pinning is expected to be removed and server conn closed
534 * The upstream link is authenticated with the same credentials.
535 * Expecting the same level of consistency we should have received.
536 * This prevents upstream being faced with multiple or missing
537 * credentials after authentication.
538 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
539 * we just trigger that cleanup here via comm_reset_close() or
540 * ConnStateData::stopReceiving()
542 * 3) the connection needs to close.
544 * This prevents attackers injecting requests into a connection,
545 * or gateways wrongly multiplexing users into a single connection.
547 * When credentials are missing closure needs to follow an auth
548 * challenge for best recovery by the client.
550 * When credentials change there is nothing we can do but abort as
551 * fast as possible. Sending TCP RST instead of an HTTP response
552 * is the best-case action.
555 // clobbered with nul-pointer
557 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
558 auth_
->releaseAuthServer();
560 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
561 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
562 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
563 stopReceiving("connection-auth removed");
567 // clobbered with alternative credentials
569 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
570 auth_
->releaseAuthServer();
572 // this is a fatal type of problem.
573 // Close the connection immediately with TCP RST to abort all traffic flow
574 comm_reset_close(clientConnection
);
582 // cleans up before destructor is called
584 ConnStateData::swanSong()
586 debugs(33, 2, HERE
<< clientConnection
);
587 flags
.readMore
= false;
588 DeregisterRunner(this);
589 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
590 pipeline
.terminateAll(0);
592 unpinConnection(true);
594 Server::swanSong(); // closes the client connection
597 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
598 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
601 flags
.swanSang
= true;
605 ConnStateData::isOpen() const
607 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
608 Comm::IsConnOpen(clientConnection
) &&
609 !fd_table
[clientConnection
->fd
].closing();
612 ConnStateData::~ConnStateData()
614 debugs(33, 3, HERE
<< clientConnection
);
617 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
620 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
622 if (bodyPipe
!= NULL
)
623 stopProducingFor(bodyPipe
, false);
625 delete bodyParser
; // TODO: pool
628 delete sslServerBump
;
633 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
634 * This is the client-side persistent connection flag. We need
635 * to set this relatively early in the request processing
636 * to handle hacks for broken servers and clients.
639 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
641 HttpRequest
*request
= http
->request
;
643 debugs(33, 3, "http_ver = " << request
->http_ver
);
644 debugs(33, 3, "method = " << request
->method
);
646 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
647 request
->flags
.proxyKeepalive
= request
->persistent();
650 /// checks body length of non-chunked requests
652 clientIsContentLengthValid(HttpRequest
* r
)
654 // No Content-Length means this request just has no body, but conflicting
655 // Content-Lengths mean a message framing error (RFC 7230 Section 3.3.3 #4).
656 if (r
->header
.conflictingContentLength())
659 switch (r
->method
.id()) {
661 case Http::METHOD_GET
:
663 case Http::METHOD_HEAD
:
664 /* We do not want to see a request entity on GET/HEAD requests */
665 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
668 /* For other types of requests we don't care */
676 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
678 if (Config
.maxRequestBodySize
&&
679 bodyLength
> Config
.maxRequestBodySize
)
680 return 1; /* too large */
686 ClientHttpRequest::multipartRangeRequest() const
688 return request
->multipartRangeRequest();
692 clientPackTermBound(String boundary
, MemBuf
*mb
)
694 mb
->appendf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
695 debugs(33, 6, "buf offset: " << mb
->size
);
699 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
701 HttpHeader
hdr(hoReply
);
706 debugs(33, 5, "appending boundary: " << boundary
);
707 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
708 mb
->appendf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
710 /* stuff the header with required entries and pack it */
712 if (rep
->header
.has(Http::HdrType::CONTENT_TYPE
))
713 hdr
.putStr(Http::HdrType::CONTENT_TYPE
, rep
->header
.getStr(Http::HdrType::CONTENT_TYPE
));
715 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
720 /* append <crlf> (we packed a header, not a reply) */
721 mb
->append("\r\n", 2);
724 /** returns expected content length for multi-range replies
725 * note: assumes that httpHdrRangeCanonize has already been called
726 * warning: assumes that HTTP headers for individual ranges at the
727 * time of the actuall assembly will be exactly the same as
728 * the headers when clientMRangeCLen() is called */
730 ClientHttpRequest::mRangeCLen()
738 HttpHdrRange::iterator pos
= request
->range
->begin();
740 while (pos
!= request
->range
->end()) {
741 /* account for headers for this range */
743 clientPackRangeHdr(memObject()->getReply(),
744 *pos
, range_iter
.boundary
, &mb
);
747 /* account for range content */
748 clen
+= (*pos
)->length
;
750 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
754 /* account for the terminating boundary */
757 clientPackTermBound(range_iter
.boundary
, &mb
);
767 * generates a "unique" boundary string for multipart responses
768 * the caller is responsible for cleaning the string */
770 ClientHttpRequest::rangeBoundaryStr() const
773 String
b(APP_FULLNAME
);
775 key
= storeEntry()->getMD5Text();
776 b
.append(key
, strlen(key
));
781 * Write a chunk of data to a client socket. If the reply is present,
782 * send the reply headers down the wire too, and clean them up when
785 * The request is one backed by a connection, not an internal request.
786 * data context is not NULL
787 * There are no more entries in the stream chain.
790 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
791 HttpReply
* rep
, StoreIOBuffer receivedData
)
793 // dont tryt to deliver if client already ABORTED
794 if (!http
->getConn() || !cbdataReferenceValid(http
->getConn()) || !Comm::IsConnOpen(http
->getConn()->clientConnection
))
797 /* Test preconditions */
798 assert(node
!= NULL
);
799 PROF_start(clientSocketRecipient
);
800 /* TODO: handle this rather than asserting
801 * - it should only ever happen if we cause an abort and
802 * the callback chain loops back to here, so we can simply return.
803 * However, that itself shouldn't happen, so it stays as an assert for now.
805 assert(cbdataReferenceValid(node
));
806 assert(node
->node
.next
== NULL
);
807 Http::StreamPointer context
= dynamic_cast<Http::Stream
*>(node
->data
.getRaw());
808 assert(context
!= NULL
);
810 /* TODO: check offset is what we asked for */
812 // TODO: enforces HTTP/1 MUST on pipeline order, but is irrelevant to HTTP/2
813 if (context
!= http
->getConn()->pipeline
.front())
814 context
->deferRecipientForLater(node
, rep
, receivedData
);
816 http
->getConn()->handleReply(rep
, receivedData
);
818 PROF_stop(clientSocketRecipient
);
822 * Called when a downstream node is no longer interested in
823 * our data. As we are a terminal node, this means on aborts
827 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
829 /* Test preconditions */
830 assert(node
!= NULL
);
831 /* TODO: handle this rather than asserting
832 * - it should only ever happen if we cause an abort and
833 * the callback chain loops back to here, so we can simply return.
834 * However, that itself shouldn't happen, so it stays as an assert for now.
836 assert(cbdataReferenceValid(node
));
837 /* Set null by ContextFree */
838 assert(node
->node
.next
== NULL
);
839 /* this is the assert discussed above */
840 assert(NULL
== dynamic_cast<Http::Stream
*>(node
->data
.getRaw()));
841 /* We are only called when the client socket shutsdown.
842 * Tell the prev pipeline member we're finished
844 clientStreamDetach(node
, http
);
848 ConnStateData::readNextRequest()
850 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
852 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
854 * Set the timeout BEFORE calling readSomeData().
856 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
857 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
858 TimeoutDialer
, this, ConnStateData::requestTimeout
);
859 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
862 /** Please don't do anything with the FD past here! */
866 ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest
, ConnStateData
* conn
)
868 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
870 /** If the client stream is waiting on a socket write to occur, then */
872 if (deferredRequest
->flags
.deferred
) {
873 /** NO data is allowed to have been sent. */
874 assert(deferredRequest
->http
->out
.size
== 0);
876 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
877 deferredRequest
->http
,
878 deferredRequest
->deferredparams
.rep
,
879 deferredRequest
->deferredparams
.queuedBuffer
);
882 /** otherwise, the request is still active in a callbacksomewhere,
888 ConnStateData::kick()
890 if (!Comm::IsConnOpen(clientConnection
)) {
891 debugs(33, 2, clientConnection
<< " Connection was closed");
895 if (pinning
.pinned
&& !Comm::IsConnOpen(pinning
.serverConnection
)) {
896 debugs(33, 2, clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
897 clientConnection
->close();
902 * We are done with the response, and we are either still receiving request
903 * body (early response!) or have already stopped receiving anything.
905 * If we are still receiving, then clientParseRequest() below will fail.
906 * (XXX: but then we will call readNextRequest() which may succeed and
907 * execute a smuggled request as we are not done with the current request).
909 * If we stopped because we got everything, then try the next request.
911 * If we stopped receiving because of an error, then close now to avoid
912 * getting stuck and to prevent accidental request smuggling.
915 if (const char *reason
= stoppedReceiving()) {
916 debugs(33, 3, "closing for earlier request error: " << reason
);
917 clientConnection
->close();
922 * Attempt to parse a request from the request buffer.
923 * If we've been fed a pipelined request it may already
924 * be in our read buffer.
927 * This needs to fall through - if we're unlucky and parse the _last_ request
928 * from our read buffer we may never re-register for another client read.
931 if (clientParseRequests()) {
932 debugs(33, 3, clientConnection
<< ": parsed next request from buffer");
936 * Either we need to kick-start another read or, if we have
937 * a half-closed connection, kill it after the last request.
938 * This saves waiting for half-closed connections to finished being
939 * half-closed _AND_ then, sometimes, spending "Timeout" time in
940 * the keepalive "Waiting for next request" state.
942 if (commIsHalfClosed(clientConnection
->fd
) && pipeline
.empty()) {
943 debugs(33, 3, "half-closed client with no pending requests, closing");
944 clientConnection
->close();
949 * At this point we either have a parsed request (which we've
950 * kicked off the processing for) or not. If we have a deferred
951 * request (parsed but deferred for pipeling processing reasons)
952 * then look at processing it. If not, simply kickstart
955 Http::StreamPointer deferredRequest
= pipeline
.front();
956 if (deferredRequest
!= nullptr) {
957 debugs(33, 3, clientConnection
<< ": calling PushDeferredIfNeeded");
958 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, this);
959 } else if (flags
.readMore
) {
960 debugs(33, 3, clientConnection
<< ": calling readNextRequest()");
963 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
964 debugs(33, DBG_IMPORTANT
, MYNAME
<< "abandoning " << clientConnection
);
969 ConnStateData::stopSending(const char *error
)
971 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
972 "; old receiving error: " <<
973 (stoppedReceiving() ? stoppedReceiving_
: "none"));
975 if (const char *oldError
= stoppedSending()) {
976 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
977 return; // nothing has changed as far as this connection is concerned
979 stoppedSending_
= error
;
981 if (!stoppedReceiving()) {
982 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
983 debugs(33, 5, HERE
<< "must still read " << expecting
<<
984 " request body bytes with " << inBuf
.length() << " unused");
985 return; // wait for the request receiver to finish reading
989 clientConnection
->close();
993 ConnStateData::afterClientWrite(size_t size
)
995 if (pipeline
.empty())
998 auto ctx
= pipeline
.front();
1000 statCounter
.client_http
.kbytes_out
+= size
;
1001 if (ctx
->http
->logType
.isTcpHit())
1002 statCounter
.client_http
.hit_kbytes_out
+= size
;
1004 ctx
->writeComplete(size
);
1008 ConnStateData::abortRequestParsing(const char *const uri
)
1010 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1011 http
->req_sz
= inBuf
.length();
1012 http
->uri
= xstrdup(uri
);
1013 setLogUri (http
, uri
);
1014 auto *context
= new Http::Stream(clientConnection
, http
);
1015 StoreIOBuffer tempBuffer
;
1016 tempBuffer
.data
= context
->reqbuf
;
1017 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1018 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1019 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1020 clientSocketDetach
, context
, tempBuffer
);
1025 ConnStateData::startShutdown()
1027 // RegisteredRunner API callback - Squid has been shut down
1029 // if connection is idle terminate it now,
1030 // otherwise wait for grace period to end
1031 if (pipeline
.empty())
1036 ConnStateData::endingShutdown()
1038 // RegisteredRunner API callback - Squid shutdown grace period is over
1040 // force the client connection to close immediately
1041 // swanSong() in the close handler will cleanup.
1042 if (Comm::IsConnOpen(clientConnection
))
1043 clientConnection
->close();
1045 // deregister now to ensure finalShutdown() does not kill us prematurely.
1046 // fd_table purge will cleanup if close handler was not fast enough.
1047 DeregisterRunner(this);
1051 skipLeadingSpace(char *aString
)
1053 char *result
= aString
;
1055 while (xisspace(*aString
))
1062 * 'end' defaults to NULL for backwards compatibility
1063 * remove default value if we ever get rid of NULL-terminated
1067 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1070 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1074 for (; end
> uriAndHTTPVersion
; --end
) {
1075 if (*end
== '\n' || *end
== '\r')
1078 if (xisspace(*end
)) {
1079 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1090 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1092 safe_free(http
->log_uri
);
1095 // The uri is already clean just dump it.
1096 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1099 switch (Config
.uri_whitespace
) {
1100 case URI_WHITESPACE_ALLOW
:
1101 flags
|= RFC1738_ESCAPE_NOSPACE
;
1103 case URI_WHITESPACE_ENCODE
:
1104 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1105 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1108 case URI_WHITESPACE_CHOP
: {
1109 flags
|= RFC1738_ESCAPE_NOSPACE
;
1110 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1111 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1112 int pos
= strcspn(http
->log_uri
, w_space
);
1113 http
->log_uri
[pos
] = '\0';
1117 case URI_WHITESPACE_DENY
:
1118 case URI_WHITESPACE_STRIP
:
1121 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1125 if (!xisspace(*t
)) {
1132 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
1141 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1143 int vhost
= conn
->port
->vhost
;
1144 int vport
= conn
->port
->vport
;
1145 static char ipbuf
[MAX_IPSTRLEN
];
1147 http
->flags
.accel
= true;
1149 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1151 static const SBuf
cache_object("cache_object://");
1152 if (hp
->requestUri().startsWith(cache_object
))
1153 return; /* already in good shape */
1155 // XXX: re-use proper URL parser for this
1156 SBuf url
= hp
->requestUri(); // use full provided URI if we abort
1157 do { // use a loop so we can break out of it
1158 ::Parser::Tokenizer
tok(url
);
1159 if (tok
.skip('/')) // origin-form URL already.
1162 if (conn
->port
->vhost
)
1163 return; /* already in good shape */
1165 // skip the URI scheme
1166 static const CharacterSet uriScheme
= CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1167 static const SBuf
uriSchemeEnd("://");
1168 if (!tok
.skipAll(uriScheme
) || !tok
.skip(uriSchemeEnd
))
1171 // skip the authority segment
1172 // RFC 3986 complex nested ABNF for "authority" boils down to this:
1173 static const CharacterSet authority
= CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
1174 CharacterSet::HEXDIG
+ CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1175 if (!tok
.skipAll(authority
))
1178 static const SBuf
slashUri("/");
1179 const SBuf t
= tok
.remaining();
1182 else if (t
[0]=='/') // looks like path
1184 else if (t
[0]=='?' || t
[0]=='#') { // looks like query or fragment. fix '/'
1187 } // else do nothing. invalid path
1191 #if SHOULD_REJECT_UNKNOWN_URLS
1192 // reject URI which are not well-formed even after the processing above
1193 if (url
.isEmpty() || url
[0] != '/') {
1194 hp
->parseStatusCode
= Http::scBadRequest
;
1195 return conn
->abortRequestParsing("error:invalid-request");
1200 vport
= http
->getConn()->clientConnection
->local
.port();
1202 const bool switchedToHttps
= conn
->switchedToHttps();
1203 const bool tryHostHeader
= vhost
|| switchedToHttps
;
1205 if (tryHostHeader
&& (host
= hp
->getHeaderField("Host"))) {
1206 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
1211 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
1212 strncpy(thost
, host
, (t
-host
));
1213 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
1216 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
1219 } // else nothing to alter port-wise.
1220 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+ strlen(host
);
1221 http
->uri
= (char *)xcalloc(url_sz
, 1);
1222 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
, AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(url
));
1223 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
1224 } else if (conn
->port
->defaultsite
/* && !vhost */) {
1225 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
1226 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1227 strlen(conn
->port
->defaultsite
);
1228 http
->uri
= (char *)xcalloc(url_sz
, 1);
1232 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
1234 snprintf(http
->uri
, url_sz
, "%s://%s%s" SQUIDSBUFPH
,
1235 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
1236 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
1237 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
1238 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
1239 /* Put the local socket IP address as the hostname, with whatever vport we found */
1240 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1241 http
->uri
= (char *)xcalloc(url_sz
, 1);
1242 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1243 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
1244 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(),
1245 ipbuf
, vport
, SQUIDSBUFPRINT(url
));
1246 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
1251 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1253 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
1254 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
1255 return; /* already in good shape */
1257 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1259 if (const char *host
= hp
->getHeaderField("Host")) {
1260 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1262 http
->uri
= (char *)xcalloc(url_sz
, 1);
1263 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
,
1264 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(hp
->requestUri()));
1265 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
1267 /* Put the local socket IP address as the hostname. */
1268 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1269 http
->uri
= (char *)xcalloc(url_sz
, 1);
1270 static char ipbuf
[MAX_IPSTRLEN
];
1271 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1272 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
1273 AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).c_str(),
1274 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SQUIDSBUFPRINT(hp
->requestUri()));
1275 debugs(33, 5, "TRANSPARENT REWRITE: " << http
->uri
);
1279 /** Parse an HTTP request
1281 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
1282 * to 1 if the request was correctly parsed.
1283 * \param[in] csd a ConnStateData. The caller must make sure it is not null
1284 * \param[in] hp an Http1::RequestParser
1285 * \param[out] mehtod_p will be set as a side-effect of the parsing.
1286 * Pointed-to value will be set to Http::METHOD_NONE in case of
1288 * \param[out] http_ver will be set as a side-effect of the parsing
1289 * \return NULL on incomplete requests,
1290 * a Http::Stream on success or failure.
1293 parseHttpRequest(ConnStateData
*csd
, const Http1::RequestParserPointer
&hp
)
1295 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
1297 const bool parsedOk
= hp
->parse(csd
->inBuf
);
1299 if (csd
->port
->flags
.isIntercepted() && Config
.accessList
.on_unsupported_protocol
)
1300 csd
->preservedClientData
= csd
->inBuf
;
1301 // sync the buffers after parsing.
1302 csd
->inBuf
= hp
->remaining();
1304 if (hp
->needsMoreData()) {
1305 debugs(33, 5, "Incomplete request, waiting for end of request line");
1310 if (hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
|| hp
->parseStatusCode
== Http::scUriTooLong
)
1311 return csd
->abortRequestParsing("error:request-too-large");
1313 return csd
->abortRequestParsing("error:invalid-request");
1317 /* We know the whole request is in parser now */
1318 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
1319 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
1320 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
1324 /* deny CONNECT via accelerated ports */
1325 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
1326 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
1327 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1328 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1329 return csd
->abortRequestParsing("error:method-not-allowed");
1332 /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific
1333 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
1334 * If seen it signals a broken client or proxy has corrupted the traffic.
1336 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
1337 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
1338 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1339 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1340 return csd
->abortRequestParsing("error:method-not-allowed");
1343 if (hp
->method() == Http::METHOD_NONE
) {
1344 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1345 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1346 return csd
->abortRequestParsing("error:unsupported-request-method");
1349 // Process headers after request line
1350 debugs(33, 3, "complete request received. " <<
1351 "prefix_sz = " << hp
->messageHeaderSize() <<
1352 ", request-line-size=" << hp
->firstLineSize() <<
1353 ", mime-header-size=" << hp
->headerBlockSize() <<
1354 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
1356 /* Ok, all headers are received */
1357 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
1359 http
->req_sz
= hp
->messageHeaderSize();
1360 Http::Stream
*result
= new Http::Stream(csd
->clientConnection
, http
);
1362 StoreIOBuffer tempBuffer
;
1363 tempBuffer
.data
= result
->reqbuf
;
1364 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1366 ClientStreamData newServer
= new clientReplyContext(http
);
1367 ClientStreamData newClient
= result
;
1368 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1369 clientReplyStatus
, newServer
, clientSocketRecipient
,
1370 clientSocketDetach
, newClient
, tempBuffer
);
1373 debugs(33,5, "Prepare absolute URL from " <<
1374 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
1375 /* Rewrite the URL in transparent or accelerator mode */
1376 /* NP: there are several cases to traverse here:
1377 * - standard mode (forward proxy)
1378 * - transparent mode (TPROXY)
1379 * - transparent mode with failures
1380 * - intercept mode (NAT)
1381 * - intercept mode with failures
1382 * - accelerator mode (reverse proxy)
1383 * - internal relative-URL
1384 * - mixed combos of the above with internal URL
1385 * - remote interception with PROXY protocol
1386 * - remote reverse-proxy with PROXY protocol
1388 if (csd
->transparent()) {
1389 /* intercept or transparent mode, properly working with no failures */
1390 prepareTransparentURL(csd
, http
, hp
);
1392 } else if (internalCheck(hp
->requestUri())) { // NP: only matches relative-URI
1393 /* internal URL mode */
1394 /* prepend our name & port */
1395 http
->uri
= xstrdup(internalLocalUri(NULL
, hp
->requestUri()));
1396 // We just re-wrote the URL. Must replace the Host: header.
1397 // But have not parsed there yet!! flag for local-only handling.
1398 http
->flags
.internal
= true;
1400 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
1401 /* accelerator mode */
1402 prepareAcceleratedURL(csd
, http
, hp
);
1406 /* No special rewrites have been applied above, use the
1407 * requested url. may be rewritten later, so make extra room */
1408 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
1409 http
->uri
= (char *)xcalloc(url_sz
, 1);
1410 SBufToCstring(http
->uri
, hp
->requestUri());
1413 result
->flags
.parsed_ok
= 1;
1418 ConnStateData::connFinishedWithConn(int size
)
1421 if (pipeline
.empty() && inBuf
.isEmpty()) {
1422 /* no current or pending requests */
1423 debugs(33, 4, HERE
<< clientConnection
<< " closed");
1425 } else if (!Config
.onoff
.half_closed_clients
) {
1426 /* admin doesn't want to support half-closed client sockets */
1427 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
1428 pipeline
.terminateAll(0);
1437 ConnStateData::consumeInput(const size_t byteCount
)
1439 assert(byteCount
> 0 && byteCount
<= inBuf
.length());
1440 inBuf
.consume(byteCount
);
1441 debugs(33, 5, "inBuf has " << inBuf
.length() << " unused bytes");
1445 ConnStateData::clientAfterReadingRequests()
1447 // Were we expecting to read more request body from half-closed connection?
1448 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
1449 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
1450 clientConnection
->close();
1459 ConnStateData::quitAfterError(HttpRequest
*request
)
1461 // From HTTP p.o.v., we do not have to close after every error detected
1462 // at the client-side, but many such errors do require closure and the
1463 // client-side code is bad at handling errors so we play it safe.
1465 request
->flags
.proxyKeepalive
= false;
1466 flags
.readMore
= false;
1467 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
1471 bool ConnStateData::serveDelayedError(Http::Stream
*context
)
1473 ClientHttpRequest
*http
= context
->http
;
1478 assert(sslServerBump
->entry
);
1479 // Did we create an error entry while processing CONNECT?
1480 if (!sslServerBump
->entry
->isEmpty()) {
1481 quitAfterError(http
->request
);
1483 // Get the saved error entry and send it to the client by replacing the
1484 // ClientHttpRequest store entry with it.
1485 clientStreamNode
*node
= context
->getClientReplyContext();
1486 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1488 debugs(33, 5, "Responding with delated error for " << http
->uri
);
1489 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
1491 // save the original request for logging purposes
1492 if (!context
->http
->al
->request
) {
1493 context
->http
->al
->request
= http
->request
;
1494 HTTPMSGLOCK(context
->http
->al
->request
);
1497 // Get error details from the fake certificate-peeking request.
1498 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
1499 context
->pullData();
1503 // In bump-server-first mode, we have not necessarily seen the intended
1504 // server name at certificate-peeking time. Check for domain mismatch now,
1505 // when we can extract the intended name from the bumped HTTP request.
1506 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
1507 HttpRequest
*request
= http
->request
;
1508 if (!Ssl::checkX509ServerValidity(srvCert
, request
->url
.host())) {
1509 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
1510 "does not match domainname " << request
->url
.host());
1512 bool allowDomainMismatch
= false;
1513 if (Config
.ssl_client
.cert_error
) {
1514 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
1515 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
1516 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
1517 delete check
.sslErrors
;
1518 check
.sslErrors
= NULL
;
1521 if (!allowDomainMismatch
) {
1522 quitAfterError(request
);
1524 clientStreamNode
*node
= context
->getClientReplyContext();
1525 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1526 assert (repContext
);
1528 // Fill the server IP and hostname for error page generation.
1529 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
1530 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->url
.host());
1532 // Create an error object and fill it
1533 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
1534 err
->src_addr
= clientConnection
->remote
;
1535 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
1536 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
1538 err
->detail
= errDetail
;
1539 // Save the original request for logging purposes.
1540 if (!context
->http
->al
->request
) {
1541 context
->http
->al
->request
= request
;
1542 HTTPMSGLOCK(context
->http
->al
->request
);
1544 repContext
->setReplyToError(request
->method
, err
);
1545 assert(context
->http
->out
.offset
== 0);
1546 context
->pullData();
1554 #endif // USE_OPENSSL
1557 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
1558 * or false otherwise
1561 clientTunnelOnError(ConnStateData
*conn
, Http::Stream
*context
, HttpRequest
*request
, const HttpRequestMethod
& method
, err_type requestError
, Http::StatusCode errStatusCode
, const char *requestErrorBytes
)
1563 if (conn
->port
->flags
.isIntercepted() &&
1564 Config
.accessList
.on_unsupported_protocol
&& conn
->pipeline
.nrequests
<= 1) {
1565 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
, NULL
);
1566 checklist
.requestErrorType
= requestError
;
1567 checklist
.src_addr
= conn
->clientConnection
->remote
;
1568 checklist
.my_addr
= conn
->clientConnection
->local
;
1569 checklist
.conn(conn
);
1570 allow_t answer
= checklist
.fastCheck();
1571 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
1572 debugs(33, 3, "Request will be tunneled to server");
1574 // XXX: Either the context is finished() or it should stay queued.
1575 // The below may leak client streams BodyPipe objects. BUT, we need
1576 // to check if client-streams detatch is safe to do here (finished() will detatch).
1577 assert(conn
->pipeline
.front() == context
); // XXX: still assumes HTTP/1 semantics
1578 conn
->pipeline
.popMe(Http::StreamPointer(context
));
1580 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
1581 return conn
->fakeAConnectRequest("unknown-protocol", conn
->preservedClientData
);
1583 debugs(33, 3, "Continue with returning the error: " << requestError
);
1588 conn
->quitAfterError(request
);
1589 clientStreamNode
*node
= context
->getClientReplyContext();
1590 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1591 assert (repContext
);
1593 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
1595 assert(context
->http
->out
.offset
== 0);
1596 context
->pullData();
1597 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
1602 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
1606 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
1607 * to here because calling comm_reset_close() causes http to
1608 * be freed before accessing.
1610 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
1611 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
1612 conn
->flags
.readMore
= false;
1613 comm_reset_close(conn
->clientConnection
);
1618 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, Http::Stream
*context
)
1620 ClientHttpRequest
*http
= context
->http
;
1621 bool chunked
= false;
1622 bool mustReplyToOptions
= false;
1623 bool unsupportedTe
= false;
1624 bool expectBody
= false;
1626 // We already have the request parsed and checked, so we
1627 // only need to go through the final body/conn setup to doCallouts().
1628 assert(http
->request
);
1629 HttpRequest::Pointer request
= http
->request
;
1631 // temporary hack to avoid splitting this huge function with sensitive code
1632 const bool isFtp
= !hp
;
1634 // Some blobs below are still HTTP-specific, but we would have to rewrite
1635 // this entire function to remove them from the FTP code path. Connection
1636 // setup and body_pipe preparation blobs are needed for FTP.
1638 request
->clientConnectionManager
= conn
;
1640 request
->flags
.accelerated
= http
->flags
.accel
;
1641 request
->flags
.sslBumped
=conn
->switchedToHttps();
1642 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
1643 // TODO: decouple http->flags.accel from request->flags.sslBumped
1644 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
1645 !conn
->port
->allow_direct
: 0;
1646 request
->sources
|= isFtp
? HttpMsg::srcFtp
:
1647 ((request
->flags
.sslBumped
|| conn
->port
->transport
.protocol
== AnyP::PROTO_HTTPS
) ? HttpMsg::srcHttps
: HttpMsg::srcHttp
);
1649 if (request
->flags
.sslBumped
) {
1650 if (conn
->getAuth() != NULL
)
1651 request
->auth_user_request
= conn
->getAuth();
1656 * If transparent or interception mode is working clone the transparent and interception flags
1657 * from the port settings to the request.
1659 if (http
->clientConnection
!= NULL
) {
1660 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
1661 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
1662 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
1663 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
1664 if (Config
.accessList
.spoof_client_ip
) {
1665 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
1666 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
1669 request
->flags
.spoofClientIp
= true;
1671 request
->flags
.spoofClientIp
= false;
1674 if (internalCheck(request
->url
.path())) {
1675 if (internalHostnameIs(request
->url
.host()) && request
->url
.port() == getMyPort()) {
1676 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true));
1677 http
->flags
.internal
= true;
1678 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->url
.path())) {
1679 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (global_internal_static on)");
1680 request
->url
.setScheme(AnyP::PROTO_HTTP
);
1681 request
->url
.host(internalHostname());
1682 request
->url
.port(getMyPort());
1683 http
->flags
.internal
= true;
1685 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (not this proxy)");
1688 request
->flags
.internal
= http
->flags
.internal
;
1689 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
1690 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
1691 #if FOLLOW_X_FORWARDED_FOR
1692 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
1693 // not a details about teh TCP connection itself
1694 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
1695 #endif /* FOLLOW_X_FORWARDED_FOR */
1696 request
->my_addr
= conn
->clientConnection
->local
;
1697 request
->myportname
= conn
->port
->name
;
1700 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
1701 // for now Squid only supports HTTP requests
1702 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
1703 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
1704 request
->http_ver
.major
= http_ver
.major
;
1705 request
->http_ver
.minor
= http_ver
.minor
;
1708 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
1709 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
1710 request
->clientConnectionManager
= conn
;
1712 if (request
->header
.chunked()) {
1714 } else if (request
->header
.has(Http::HdrType::TRANSFER_ENCODING
)) {
1715 const String te
= request
->header
.getList(Http::HdrType::TRANSFER_ENCODING
);
1716 // HTTP/1.1 requires chunking to be the last encoding if there is one
1717 unsupportedTe
= te
.size() && te
!= "identity";
1718 } // else implied identity coding
1720 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
1721 (request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0);
1722 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
1723 clientStreamNode
*node
= context
->getClientReplyContext();
1724 conn
->quitAfterError(request
.getRaw());
1725 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1726 assert (repContext
);
1727 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
1728 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1729 assert(context
->http
->out
.offset
== 0);
1730 context
->pullData();
1731 clientProcessRequestFinished(conn
, request
);
1735 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
1736 clientStreamNode
*node
= context
->getClientReplyContext();
1737 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1738 assert (repContext
);
1739 conn
->quitAfterError(request
.getRaw());
1740 repContext
->setReplyToError(ERR_INVALID_REQ
,
1741 Http::scLengthRequired
, request
->method
, NULL
,
1742 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1743 assert(context
->http
->out
.offset
== 0);
1744 context
->pullData();
1745 clientProcessRequestFinished(conn
, request
);
1749 clientSetKeepaliveFlag(http
);
1750 // Let tunneling code be fully responsible for CONNECT requests
1751 if (http
->request
->method
== Http::METHOD_CONNECT
) {
1752 context
->mayUseConnection(true);
1753 conn
->flags
.readMore
= false;
1757 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
1758 clientProcessRequestFinished(conn
, request
);
1763 /* Do we expect a request-body? */
1764 expectBody
= chunked
|| request
->content_length
> 0;
1765 if (!context
->mayUseConnection() && expectBody
) {
1766 request
->body_pipe
= conn
->expectRequestBody(
1767 chunked
? -1 : request
->content_length
);
1769 /* Is it too large? */
1770 if (!chunked
&& // if chunked, we will check as we accumulate
1771 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
1772 clientStreamNode
*node
= context
->getClientReplyContext();
1773 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1774 assert (repContext
);
1775 conn
->quitAfterError(request
.getRaw());
1776 repContext
->setReplyToError(ERR_TOO_BIG
,
1777 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
1778 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
1779 assert(context
->http
->out
.offset
== 0);
1780 context
->pullData();
1781 clientProcessRequestFinished(conn
, request
);
1786 // We may stop producing, comm_close, and/or call setReplyToError()
1787 // below, so quit on errors to avoid http->doCallouts()
1788 if (!conn
->handleRequestBodyData()) {
1789 clientProcessRequestFinished(conn
, request
);
1793 if (!request
->body_pipe
->productionEnded()) {
1794 debugs(33, 5, "need more request body");
1795 context
->mayUseConnection(true);
1796 assert(conn
->flags
.readMore
);
1801 http
->calloutContext
= new ClientRequestContext(http
);
1805 clientProcessRequestFinished(conn
, request
);
1809 ConnStateData::pipelinePrefetchMax() const
1811 // TODO: Support pipelined requests through pinned connections.
1814 return Config
.pipeline_max_prefetch
;
1818 * Limit the number of concurrent requests.
1819 * \return true when there are available position(s) in the pipeline queue for another request.
1820 * \return false when the pipeline queue is full or disabled.
1823 ConnStateData::concurrentRequestQueueFilled() const
1825 const int existingRequestCount
= pipeline
.count();
1827 // default to the configured pipeline size.
1828 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
1830 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
1832 const int internalRequest
= 0;
1834 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
1836 // when queue filled already we cant add more.
1837 if (existingRequestCount
>= concurrentRequestLimit
) {
1838 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
1839 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
1847 * Perform proxy_protocol_access ACL tests on the client which
1848 * connected to PROXY protocol port to see if we trust the
1849 * sender enough to accept their PROXY header claim.
1852 ConnStateData::proxyProtocolValidateClient()
1854 if (!Config
.accessList
.proxyProtocol
)
1855 return proxyProtocolError("PROXY client not permitted by default ACL");
1857 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
1858 ch
.src_addr
= clientConnection
->remote
;
1859 ch
.my_addr
= clientConnection
->local
;
1862 if (ch
.fastCheck() != ACCESS_ALLOWED
)
1863 return proxyProtocolError("PROXY client not permitted by ACLs");
1869 * Perform cleanup on PROXY protocol errors.
1870 * If header parsing hits a fatal error terminate the connection,
1871 * otherwise wait for more data.
1874 ConnStateData::proxyProtocolError(const char *msg
)
1877 // This is important to know, but maybe not so much that flooding the log is okay.
1878 #if QUIET_PROXY_PROTOCOL
1879 // display the first of every 32 occurances at level 1, the others at level 2.
1880 static uint8_t hide
= 0;
1881 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
1883 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
1890 /// magic octet prefix for PROXY protocol version 1
1891 static const SBuf
Proxy1p0magic("PROXY ", 6);
1893 /// magic octet prefix for PROXY protocol version 2
1894 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
1897 * Test the connection read buffer for PROXY protocol header.
1898 * Version 1 and 2 header currently supported.
1901 ConnStateData::parseProxyProtocolHeader()
1903 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
1905 // detect and parse PROXY/2.0 protocol header
1906 if (inBuf
.startsWith(Proxy2p0magic
))
1907 return parseProxy2p0();
1909 // detect and parse PROXY/1.0 protocol header
1910 if (inBuf
.startsWith(Proxy1p0magic
))
1911 return parseProxy1p0();
1913 // detect and terminate other protocols
1914 if (inBuf
.length() >= Proxy2p0magic
.length()) {
1915 // PROXY/1.0 magic is shorter, so we know that
1916 // the input does not start with any PROXY magic
1917 return proxyProtocolError("PROXY protocol error: invalid header");
1920 // TODO: detect short non-magic prefixes earlier to avoid
1921 // waiting for more data which may never come
1923 // not enough bytes to parse yet.
1927 /// parse the PROXY/1.0 protocol header from the connection read buffer
1929 ConnStateData::parseProxy1p0()
1931 ::Parser::Tokenizer
tok(inBuf
);
1932 tok
.skip(Proxy1p0magic
);
1934 // skip to first LF (assumes it is part of CRLF)
1935 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
1937 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
1938 if (tok
.skip('\n')) {
1939 // found valid header
1940 inBuf
= tok
.remaining();
1941 needProxyProtocolHeader_
= false;
1942 // reset the tokenizer to work on found line only.
1945 return false; // no LF yet
1947 } else // protocol error only if there are more than 107 bytes prefix header
1948 return proxyProtocolError(inBuf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
1950 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
1951 if (tok
.skip(tcpName
)) {
1953 // skip TCP/IP version number
1954 static const CharacterSet
tcpVersions("TCP-version","46");
1955 if (!tok
.skipOne(tcpVersions
))
1956 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
1958 // skip SP after protocol version
1960 return proxyProtocolError("PROXY/1.0 error: missing SP");
1963 int64_t porta
, portb
;
1964 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
1966 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
1967 // leave the LF until later.
1968 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
1969 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
1970 tok
.int64(porta
) && tok
.skip(' ') &&
1974 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
1976 // parse IP and port strings
1977 Ip::Address originalClient
, originalDest
;
1979 if (!originalClient
.GetHostByName(ipa
.c_str()))
1980 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
1982 if (!originalDest
.GetHostByName(ipb
.c_str()))
1983 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
1985 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
1986 originalClient
.port(static_cast<uint16_t>(porta
));
1988 return proxyProtocolError("PROXY/1.0 error: invalid src port");
1990 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
1991 originalDest
.port(static_cast<uint16_t>(portb
));
1993 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
1995 // we have original client and destination details now
1996 // replace the client connection values
1997 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
1998 clientConnection
->local
= originalDest
;
1999 clientConnection
->remote
= originalClient
;
2000 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2001 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2002 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2004 // repeat fetch ensuring the new client FQDN can be logged
2005 if (Config
.onoff
.log_fqdn
)
2006 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2010 } else if (tok
.skip(unknown
)) {
2011 // found valid but unusable header
2015 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2020 /// parse the PROXY/2.0 protocol header from the connection read buffer
2022 ConnStateData::parseProxy2p0()
2024 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2025 if (inBuf
.length() < prefixLen
+ 4)
2026 return false; // need more bytes
2028 if ((inBuf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2029 return proxyProtocolError("PROXY/2.0 error: invalid version");
2031 const char command
= (inBuf
[prefixLen
] & 0x0F);
2032 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2033 return proxyProtocolError("PROXY/2.0 error: invalid command");
2035 const char family
= (inBuf
[prefixLen
+1] & 0xF0) >>4;
2036 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2037 return proxyProtocolError("PROXY/2.0 error: invalid family");
2039 const char proto
= (inBuf
[prefixLen
+1] & 0x0F);
2040 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2041 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2043 const char *clen
= inBuf
.rawContent() + prefixLen
+ 2;
2045 memcpy(&len
, clen
, sizeof(len
));
2048 if (inBuf
.length() < prefixLen
+ 4 + len
)
2049 return false; // need more bytes
2051 inBuf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2052 const SBuf extra
= inBuf
.consume(len
);
2053 needProxyProtocolHeader_
= false; // found successfully
2055 // LOCAL connections do nothing with the extras
2056 if (command
== 0x00/* LOCAL*/)
2060 struct { /* for TCP/UDP over IPv4, len = 12 */
2061 struct in_addr src_addr
;
2062 struct in_addr dst_addr
;
2066 struct { /* for TCP/UDP over IPv6, len = 36 */
2067 struct in6_addr src_addr
;
2068 struct in6_addr dst_addr
;
2073 struct { /* for AF_UNIX sockets, len = 216 */
2074 uint8_t src_addr
[108];
2075 uint8_t dst_addr
[108];
2081 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2083 // replace the client connection values
2084 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2087 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2088 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2089 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2090 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2091 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2092 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2095 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2096 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2097 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2098 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2099 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2100 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2102 default: // do nothing
2105 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2107 // repeat fetch ensuring the new client FQDN can be logged
2108 if (Config
.onoff
.log_fqdn
)
2109 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2115 ConnStateData::receivedFirstByte()
2117 if (receivedFirstByte_
)
2120 receivedFirstByte_
= true;
2121 // Set timeout to Config.Timeout.request
2122 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2123 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
2124 TimeoutDialer
, this, ConnStateData::requestTimeout
);
2125 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
2129 * Attempt to parse one or more requests from the input buffer.
2130 * Returns true after completing parsing of at least one request [header]. That
2131 * includes cases where parsing ended with an error (e.g., a huge request).
2134 ConnStateData::clientParseRequests()
2136 bool parsed_req
= false;
2138 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2140 // Loop while we have read bytes that are not needed for producing the body
2141 // On errors, bodyPipe may become nil, but readMore will be cleared
2142 while (!inBuf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2144 /* Don't try to parse if the buffer is empty */
2145 if (inBuf
.isEmpty())
2148 /* Limit the number of concurrent requests */
2149 if (concurrentRequestQueueFilled())
2152 // try to parse the PROXY protocol header magic bytes
2153 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
2156 if (Http::Stream
*context
= parseOneRequest()) {
2157 debugs(33, 5, clientConnection
<< ": done parsing a request");
2159 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2160 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2161 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2163 context
->registerWithConn();
2165 processParsedRequest(context
);
2167 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2169 if (context
->mayUseConnection()) {
2170 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2174 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
2175 inBuf
.length() << " < " << Config
.maxRequestHeaderSize
);
2176 Must(inBuf
.length() < Config
.maxRequestHeaderSize
);
2181 /* XXX where to 'finish' the parsing pass? */
2186 ConnStateData::afterClientRead()
2189 if (parsingTlsHandshake
) {
2190 parseTlsHandshake();
2195 /* Process next request */
2196 if (pipeline
.empty())
2197 fd_note(clientConnection
->fd
, "Reading next request");
2199 if (!clientParseRequests()) {
2203 * If the client here is half closed and we failed
2204 * to parse a request, close the connection.
2205 * The above check with connFinishedWithConn() only
2206 * succeeds _if_ the buffer is empty which it won't
2207 * be if we have an incomplete request.
2208 * XXX: This duplicates ConnStateData::kick
2210 if (pipeline
.empty() && commIsHalfClosed(clientConnection
->fd
)) {
2211 debugs(33, 5, clientConnection
<< ": half-closed connection, no completed request parsed, connection closing.");
2212 clientConnection
->close();
2220 clientAfterReadingRequests();
2224 * called when new request data has been read from the socket
2226 * \retval false called comm_close or setReplyToError (the caller should bail)
2227 * \retval true we did not call comm_close or setReplyToError
2230 ConnStateData::handleReadData()
2232 // if we are reading a body, stuff data into the body pipe
2233 if (bodyPipe
!= NULL
)
2234 return handleRequestBodyData();
2239 * called when new request body data has been buffered in inBuf
2240 * may close the connection if we were closing and piped everything out
2242 * \retval false called comm_close or setReplyToError (the caller should bail)
2243 * \retval true we did not call comm_close or setReplyToError
2246 ConnStateData::handleRequestBodyData()
2248 assert(bodyPipe
!= NULL
);
2250 if (bodyParser
) { // chunked encoding
2251 if (const err_type error
= handleChunkedRequestBody()) {
2252 abortChunkedRequestBody(error
);
2255 } else { // identity encoding
2256 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
2257 const size_t putSize
= bodyPipe
->putMoreData(inBuf
.c_str(), inBuf
.length());
2259 consumeInput(putSize
);
2261 if (!bodyPipe
->mayNeedMoreData()) {
2262 // BodyPipe will clear us automagically when we produced everything
2268 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
2270 if (const char *reason
= stoppedSending()) {
2271 /* we've finished reading like good clients,
2272 * now do the close that initiateClose initiated.
2274 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
2275 clientConnection
->close();
2283 /// parses available chunked encoded body bytes, checks size, returns errors
2285 ConnStateData::handleChunkedRequestBody()
2287 debugs(33, 7, "chunked from " << clientConnection
<< ": " << inBuf
.length());
2289 try { // the parser will throw on errors
2291 if (inBuf
.isEmpty()) // nothing to do
2294 BodyPipeCheckout
bpc(*bodyPipe
);
2295 bodyParser
->setPayloadBuffer(&bpc
.buf
);
2296 const bool parsed
= bodyParser
->parse(inBuf
);
2297 inBuf
= bodyParser
->remaining(); // sync buffers
2300 // dechunk then check: the size limit applies to _dechunked_ content
2301 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
2305 finishDechunkingRequest(true);
2307 return ERR_NONE
; // nil bodyPipe implies body end for the caller
2310 // if chunk parser needs data, then the body pipe must need it too
2311 Must(!bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
2313 // if parser needs more space and we can consume nothing, we will stall
2314 Must(!bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
2315 } catch (...) { // TODO: be more specific
2316 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
2317 return ERR_INVALID_REQ
;
2320 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
2324 /// quit on errors related to chunked request body handling
2326 ConnStateData::abortChunkedRequestBody(const err_type error
)
2328 finishDechunkingRequest(false);
2330 // XXX: The code below works if we fail during initial request parsing,
2331 // but if we fail when the server connection is used already, the server may send
2332 // us its response too, causing various assertions. How to prevent that?
2333 #if WE_KNOW_HOW_TO_SEND_ERRORS
2334 Http::StreamPointer context
= pipeline
.front();
2335 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
2336 clientStreamNode
*node
= context
->getClientReplyContext();
2337 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2339 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
2340 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
2341 repContext
->setReplyToError(error
, scode
,
2342 repContext
->http
->request
->method
,
2343 repContext
->http
->uri
,
2345 repContext
->http
->request
,
2347 context
->pullData();
2349 // close or otherwise we may get stuck as nobody will notice the error?
2350 comm_reset_close(clientConnection
);
2353 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
2354 comm_reset_close(clientConnection
);
2356 flags
.readMore
= false;
2360 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
2362 // request reader may get stuck waiting for space if nobody consumes body
2363 if (bodyPipe
!= NULL
)
2364 bodyPipe
->enableAutoConsumption();
2369 /** general lifetime handler for HTTP requests */
2371 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
2373 if (!Comm::IsConnOpen(io
.conn
))
2376 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
2378 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
2379 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
2380 receivedFirstByte();
2383 } else if (!fd_table
[io
.conn
->fd
].ssl
)
2386 const HttpRequestMethod method
;
2387 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
2388 // Tunnel established. Set receivedFirstByte to avoid loop.
2389 receivedFirstByte();
2395 * Just close the connection to not confuse browsers
2396 * using persistent connections. Some browsers open
2397 * a connection and then do not use it until much
2398 * later (presumeably because the request triggering
2399 * the open has already been completed on another
2402 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
2407 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
2409 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
2410 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
2411 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
2412 http
->logType
.err
.timedout
= true;
2413 if (Comm::IsConnOpen(io
.conn
))
2417 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
2418 AsyncJob("ConnStateData"), // kids overwrite
2420 bodyParser(nullptr),
2422 sslBumpMode(Ssl::bumpEnd
),
2424 needProxyProtocolHeader_(false),
2426 switchedToHttps_(false),
2427 parsingTlsHandshake(false),
2428 sslServerBump(NULL
),
2429 signAlgorithm(Ssl::algSignTrusted
),
2431 stoppedSending_(NULL
),
2432 stoppedReceiving_(NULL
)
2434 flags
.readMore
= true; // kids may overwrite
2435 flags
.swanSang
= false;
2437 pinning
.host
= NULL
;
2439 pinning
.pinned
= false;
2440 pinning
.auth
= false;
2441 pinning
.zeroReply
= false;
2442 pinning
.peer
= NULL
;
2444 // store the details required for creating more MasterXaction objects as new requests come in
2445 log_addr
= xact
->tcpClient
->remote
;
2446 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
2448 // register to receive notice of Squid signal events
2449 // which may affect long persisting client connections
2450 RegisterRunner(this);
2454 ConnStateData::start()
2456 BodyProducer::start();
2457 HttpControlMsgSink::start();
2459 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
2460 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
2461 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2462 int i
= IP_PMTUDISC_DONT
;
2463 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0) {
2465 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerr(xerrno
));
2468 static bool reported
= false;
2471 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
2477 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
2478 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
2479 comm_add_close_handler(clientConnection
->fd
, call
);
2481 if (Config
.onoff
.log_fqdn
)
2482 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2485 if (Ident::TheConfig
.identLookup
) {
2486 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
2487 identChecklist
.src_addr
= clientConnection
->remote
;
2488 identChecklist
.my_addr
= clientConnection
->local
;
2489 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
2490 Ident::Start(clientConnection
, clientIdentDone
, this);
2494 clientdbEstablished(clientConnection
->remote
, 1);
2496 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
2497 if (needProxyProtocolHeader_
) {
2498 if (!proxyProtocolValidateClient()) // will close the connection on failure
2503 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
2505 if (Config
.onoff
.client_db
) {
2506 /* it was said several times that client write limiter does not work if client_db is disabled */
2508 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
2509 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
2511 // TODO: we check early to limit error response bandwith but we
2512 // should recheck when we can honor delay_pool_uses_indirect
2513 // TODO: we should also pass the port details for myportname here.
2514 ch
.src_addr
= clientConnection
->remote
;
2515 ch
.my_addr
= clientConnection
->local
;
2517 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
2519 /* pools require explicit 'allow' to assign a client into them */
2520 if (pools
[pool
].access
) {
2521 ch
.changeAcl(pools
[pool
].access
);
2522 allow_t answer
= ch
.fastCheck();
2523 if (answer
== ACCESS_ALLOWED
) {
2525 /* request client information from db after we did all checks
2526 this will save hash lookup if client failed checks */
2527 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
2530 /* put client info in FDE */
2531 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
2533 /* setup write limiter for this request */
2534 const double burst
= floor(0.5 +
2535 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
2536 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
2539 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
2546 // kids must extend to actually start doing something (e.g., reading)
2549 /** Handle a new connection on an HTTP socket. */
2551 httpAccept(const CommAcceptCbParams
¶ms
)
2553 MasterXaction::Pointer xact
= params
.xaction
;
2554 AnyP::PortCfgPointer s
= xact
->squidPort
;
2556 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2558 if (params
.flag
!= Comm::OK
) {
2559 // Its possible the call was still queued when the client disconnected
2560 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2564 debugs(33, 4, params
.conn
<< ": accepted");
2565 fd_note(params
.conn
->fd
, "client http connect");
2567 if (s
->tcp_keepalive
.enabled
)
2568 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2570 ++incoming_sockets_accepted
;
2572 // Socket is ready, setup the connection manager to start using it
2573 ConnStateData
*connState
= Http::NewServer(xact
);
2574 AsyncJob::Start(connState
); // usually async-calls readSomeData()
2579 /** Create SSL connection structure and update fd_table */
2580 static Security::SessionPtr
2581 httpsCreate(const Comm::ConnectionPointer
&conn
, Security::ContextPtr sslContext
)
2583 if (auto ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
2584 debugs(33, 5, "will negotate SSL on " << conn
);
2594 * \retval 1 on success
2595 * \retval 0 when needs more data
2596 * \retval -1 on error
2599 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
2601 int fd
= conn
->clientConnection
->fd
;
2602 auto ssl
= fd_table
[fd
].ssl
.get();
2606 if ((ret
= SSL_accept(ssl
)) <= 0) {
2607 const int xerrno
= errno
;
2608 const int ssl_error
= SSL_get_error(ssl
, ret
);
2610 switch (ssl_error
) {
2612 case SSL_ERROR_WANT_READ
:
2613 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, (callback
!= NULL
? conn
: NULL
), 0);
2616 case SSL_ERROR_WANT_WRITE
:
2617 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, (callback
!= NULL
? conn
: NULL
), 0);
2620 case SSL_ERROR_SYSCALL
:
2622 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
2624 debugs(83, (xerrno
== ECONNRESET
) ? 1 : 2, "Error negotiating SSL connection on FD " << fd
<< ": " <<
2625 (xerrno
== 0 ? ERR_error_string(ssl_error
, NULL
) : xstrerr(xerrno
)));
2629 case SSL_ERROR_ZERO_RETURN
:
2630 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
2634 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
2635 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
2636 " (" << ssl_error
<< "/" << ret
<< ")");
2645 /** negotiate an SSL connection */
2647 clientNegotiateSSL(int fd
, void *data
)
2649 ConnStateData
*conn
= (ConnStateData
*)data
;
2651 auto ssl
= fd_table
[fd
].ssl
.get();
2654 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
2655 if (ret
< 0) // An error
2656 conn
->clientConnection
->close();
2660 if (SSL_session_reused(ssl
)) {
2661 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
2662 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
2664 if (do_debug(83, 4)) {
2665 /* Write out the SSL session details.. actually the call below, but
2666 * OpenSSL headers do strange typecasts confusing GCC.. */
2667 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
2668 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
2669 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
);
2671 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
2673 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
2674 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
2675 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
2676 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
2677 * Because there are two possible usable cast, if you get an error here, try the other
2678 * commented line. */
2680 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
2681 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
2685 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
2688 /* Note: This does not automatically fflush the log file.. */
2691 debugs(83, 2, "clientNegotiateSSL: New session " <<
2692 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
2693 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
2697 // Connection established. Retrieve TLS connection parameters for logging.
2698 conn
->clientConnection
->tlsNegotiations()->retrieveNegotiatedInfo(ssl
);
2700 client_cert
= SSL_get_peer_certificate(ssl
);
2702 if (client_cert
!= NULL
) {
2703 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2704 " client certificate: subject: " <<
2705 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
2707 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2708 " client certificate: issuer: " <<
2709 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
2711 X509_free(client_cert
);
2713 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
2714 " has no certificate.");
2717 #if defined(TLSEXT_NAMETYPE_host_name)
2718 if (!conn
->serverBump()) {
2719 // when in bumpClientFirst mode, get the server name from SNI
2720 if (const char *server
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))
2721 conn
->resetSslCommonName(server
);
2725 conn
->readSomeData();
2729 * If Security::ContextPtr is given, starts reading the TLS handshake.
2730 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPtr.
2733 httpsEstablish(ConnStateData
*connState
, Security::ContextPtr sslContext
)
2735 Security::SessionPtr ssl
= nullptr;
2737 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
2739 if (!sslContext
|| !(ssl
= httpsCreate(details
, sslContext
)))
2742 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2743 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
2744 connState
, ConnStateData::requestTimeout
);
2745 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
2747 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
2751 * A callback function to use with the ACLFilledChecklist callback.
2752 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
2753 * else reverts the connection to tunnel mode.
2756 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
2758 ConnStateData
*connState
= (ConnStateData
*) data
;
2760 // if the connection is closed or closing, just return.
2761 if (!connState
->isOpen())
2764 // Require both a match and a positive bump mode to work around exceptional
2765 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
2766 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
2767 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
2768 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
2770 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
2771 connState
->sslBumpMode
= Ssl::bumpNone
;
2773 if (!connState
->fakeAConnectRequest("ssl-bump", connState
->inBuf
))
2774 connState
->clientConnection
->close();
2777 /** handle a new HTTPS connection */
2779 httpsAccept(const CommAcceptCbParams
¶ms
)
2781 MasterXaction::Pointer xact
= params
.xaction
;
2782 const AnyP::PortCfgPointer s
= xact
->squidPort
;
2784 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2786 if (params
.flag
!= Comm::OK
) {
2787 // Its possible the call was still queued when the client disconnected
2788 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2792 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
2793 fd_note(params
.conn
->fd
, "client https connect");
2795 if (s
->tcp_keepalive
.enabled
) {
2796 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2798 ++incoming_sockets_accepted
;
2800 // Socket is ready, setup the connection manager to start using it
2801 ConnStateData
*connState
= Https::NewServer(xact
);
2802 AsyncJob::Start(connState
); // usually async-calls postHttpsAccept()
2806 ConnStateData::postHttpsAccept()
2808 if (port
->flags
.tunnelSslBumping
) {
2809 debugs(33, 5, "accept transparent connection: " << clientConnection
);
2811 if (!Config
.accessList
.ssl_bump
) {
2812 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
2816 // Create a fake HTTP request for ssl_bump ACL check,
2817 // using tproxy/intercept provided destination IP and port.
2818 HttpRequest
*request
= new HttpRequest();
2819 static char ip
[MAX_IPSTRLEN
];
2820 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
2821 request
->url
.host(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
2822 request
->url
.port(clientConnection
->local
.port());
2823 request
->myportname
= port
->name
;
2825 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
2826 acl_checklist
->src_addr
= clientConnection
->remote
;
2827 acl_checklist
->my_addr
= port
->s
;
2828 // Build a local AccessLogEntry to allow requiresAle() acls work
2829 acl_checklist
->al
= new AccessLogEntry
;
2830 acl_checklist
->al
->cache
.start_time
= current_time
;
2831 acl_checklist
->al
->tcpClient
= clientConnection
;
2832 acl_checklist
->al
->cache
.port
= port
;
2833 acl_checklist
->al
->cache
.caddr
= log_addr
;
2834 HTTPMSGUNLOCK(acl_checklist
->al
->request
);
2835 acl_checklist
->al
->request
= request
;
2836 HTTPMSGLOCK(acl_checklist
->al
->request
);
2837 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
2840 httpsEstablish(this, port
->secure
.staticContext
.get());
2845 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
2847 ConnStateData
* state_data
= (ConnStateData
*)(data
);
2848 state_data
->sslCrtdHandleReply(reply
);
2852 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
2855 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply
);
2859 if (reply
.result
== Helper::BrokenHelper
) {
2860 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
2861 } else if (!reply
.other().hasContent()) {
2862 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
2864 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
2865 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
2866 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
2868 if (reply
.result
!= Helper::Okay
) {
2869 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
2871 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
2872 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
2873 doPeekAndSpliceStep();
2874 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
2875 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
2877 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
2879 SSL_CTX
*sslContext
= SSL_get_SSL_CTX(ssl
);
2880 Ssl::configureUnconfiguredSslContext(sslContext
, signAlgorithm
, *port
);
2882 auto ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
2883 getSslContextDone(ctx
, true);
2889 getSslContextDone(NULL
);
2892 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
2894 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
2896 // fake certificate adaptation requires bump-server-first mode
2897 if (!sslServerBump
) {
2898 assert(port
->signingCert
.get());
2899 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2900 if (port
->signPkey
.get())
2901 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2902 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2906 // In case of an error while connecting to the secure server, use a fake
2907 // trusted certificate, with no mimicked fields and no adaptation
2908 // algorithms. There is nothing we can mimic so we want to minimize the
2909 // number of warnings the user will have to see to get to the error page.
2910 assert(sslServerBump
->entry
);
2911 if (sslServerBump
->entry
->isEmpty()) {
2912 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
2913 certProperties
.mimicCert
.resetAndLock(mimicCert
);
2915 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
2916 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
2917 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors());
2919 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
2920 // If the algorithm already set, then ignore it.
2921 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
2922 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
2923 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
2926 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
2927 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
2928 const char *param
= ca
->param
;
2930 // For parameterless CN adaptation, use hostname from the
2932 if (ca
->alg
== Ssl::algSetCommonName
) {
2934 param
= sslConnectHostOrIp
.termedBuf();
2935 certProperties
.commonName
= param
;
2936 certProperties
.setCommonName
= true;
2937 } else if (ca
->alg
== Ssl::algSetValidAfter
)
2938 certProperties
.setValidAfter
= true;
2939 else if (ca
->alg
== Ssl::algSetValidBefore
)
2940 certProperties
.setValidBefore
= true;
2942 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
2943 alg
<< " param: " << (param
? param
: "-"));
2947 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
2948 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
2949 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
2950 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
2954 } else {// if (!sslServerBump->entry->isEmpty())
2955 // Use trusted certificate for a Squid-generated error
2956 // or the user would have to add a security exception
2957 // just to see the error page. We will close the connection
2958 // so that the trust is not extended to non-Squid content.
2959 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2962 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
2964 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
2965 assert(port
->untrustedSigningCert
.get());
2966 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
2967 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
2969 assert(port
->signingCert
.get());
2970 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2972 if (port
->signPkey
.get())
2973 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2975 signAlgorithm
= certProperties
.signAlgorithm
;
2977 certProperties
.signHash
= Ssl::DefaultSignHash
;
2981 ConnStateData::getSslContextStart()
2983 // XXX starting SSL with a pipeline of requests still waiting for non-SSL replies?
2984 assert(pipeline
.count() < 2); // the CONNECT is okay for now. Anything else is a bug.
2985 pipeline
.terminateAll(0);
2986 /* careful: terminateAll(0) above frees request, host, etc. */
2988 if (port
->generateHostCertificates
) {
2989 Ssl::CertificateProperties certProperties
;
2990 buildSslCertGenerationParams(certProperties
);
2991 sslBumpCertKey
= certProperties
.dbKey().c_str();
2992 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
2994 // Disable caching for bumpPeekAndSplice mode
2995 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
2996 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
2997 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
2998 Security::ContextPtr dynCtx
= nullptr;
2999 Security::ContextPointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : nullptr;
3000 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3001 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3002 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3003 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3004 getSslContextDone(dynCtx
);
3007 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3009 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3012 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3018 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3019 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3020 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3021 request_message
.composeRequest(certProperties
);
3022 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3023 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3025 } catch (const std::exception
&e
) {
3026 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3027 "request for " << certProperties
.commonName
<<
3028 " certificate: " << e
.what() << "; will now block to " <<
3029 "generate that certificate.");
3030 // fall through to do blocking in-process generation.
3032 #endif // USE_SSL_CRTD
3034 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3035 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3036 doPeekAndSpliceStep();
3037 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3038 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3039 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3041 SSL_CTX
*sslContext
= SSL_get_SSL_CTX(ssl
);
3042 Ssl::configureUnconfiguredSslContext(sslContext
, certProperties
.signAlgorithm
, *port
);
3044 auto dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3045 getSslContextDone(dynCtx
, true);
3049 getSslContextDone(NULL
);
3053 ConnStateData::getSslContextDone(Security::ContextPtr sslContext
, bool isNew
)
3055 // Try to add generated ssl context to storage.
3056 if (port
->generateHostCertificates
&& isNew
) {
3058 if (sslContext
&& (signAlgorithm
== Ssl::algSignTrusted
)) {
3059 Ssl::chainCertificatesToSSLContext(sslContext
, *port
);
3060 } else if (signAlgorithm
== Ssl::algSignTrusted
) {
3061 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain because SSL context chain is invalid!");
3063 //else it is self-signed or untrusted do not attrach any certificate
3065 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3066 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3068 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Security::ContextPointer(sslContext
))) {
3069 // If it is not in storage delete after using. Else storage deleted it.
3070 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3073 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3077 // If generated ssl context = NULL, try to use static ssl context.
3079 if (!port
->secure
.staticContext
) {
3080 debugs(83, DBG_IMPORTANT
, "Closing " << clientConnection
->remote
<< " as lacking TLS context");
3081 clientConnection
->close();
3084 debugs(33, 5, "Using static TLS context.");
3085 sslContext
= port
->secure
.staticContext
.get();
3089 if (!httpsCreate(clientConnection
, sslContext
))
3092 // bumped intercepted conns should already have Config.Timeout.request set
3093 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3094 // to make sure the connection does not get stuck on non-SSL clients.
3095 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3096 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3097 this, ConnStateData::requestTimeout
);
3098 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3100 switchedToHttps_
= true;
3102 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3103 BIO
*b
= SSL_get_rbio(ssl
);
3104 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3105 bio
->setReadBufData(inBuf
);
3107 clientNegotiateSSL(clientConnection
->fd
, this);
3111 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3113 assert(!switchedToHttps_
);
3115 sslConnectHostOrIp
= request
->url
.host();
3116 resetSslCommonName(request
->url
.host());
3118 // We are going to read new request
3119 flags
.readMore
= true;
3120 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3122 // keep version major.minor details the same.
3123 // but we are now performing the HTTPS handshake traffic
3124 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
3126 // If sslServerBump is set, then we have decided to deny CONNECT
3127 // and now want to switch to SSL to send the error to the client
3128 // without even peeking at the origin server certificate.
3129 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3130 request
->flags
.sslPeek
= true;
3131 sslServerBump
= new Ssl::ServerBump(request
);
3132 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
3133 request
->flags
.sslPeek
= true;
3134 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
3137 // commSetConnTimeout() was called for this request before we switched.
3138 // Fix timeout to request_start_timeout
3139 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3140 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3141 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3142 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
3143 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
3144 // a bumbed "connect" request on non transparent port.
3145 receivedFirstByte_
= false;
3146 // Get more data to peek at Tls
3147 parsingTlsHandshake
= true;
3152 ConnStateData::parseTlsHandshake()
3154 Must(parsingTlsHandshake
);
3156 assert(!inBuf
.isEmpty());
3157 receivedFirstByte();
3158 fd_note(clientConnection
->fd
, "Parsing TLS handshake");
3160 bool unsupportedProtocol
= false;
3162 if (!tlsParser
.parseHello(inBuf
)) {
3163 // need more data to finish parsing
3168 catch (const std::exception
&ex
) {
3169 debugs(83, 2, "error on FD " << clientConnection
->fd
<< ": " << ex
.what());
3170 unsupportedProtocol
= true;
3173 parsingTlsHandshake
= false;
3175 // Even if the parser failed, each TLS detail should either be set
3176 // correctly or still be "unknown"; copying unknown detail is a no-op.
3177 clientConnection
->tlsNegotiations()->retrieveParsedInfo(tlsParser
.details
);
3179 // We should disable read/write handlers
3180 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3181 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
3183 if (!sslServerBump
) { // BumpClientFirst mode does not use this member
3184 getSslContextStart();
3186 } else if (sslServerBump
->act
.step1
== Ssl::bumpServerFirst
) {
3187 // will call httpsPeeked() with certificate and connection, eventually
3188 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3190 Must(sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
);
3191 startPeekAndSplice(unsupportedProtocol
);
3196 ConnStateData::spliceOnError(const err_type err
)
3198 if (Config
.accessList
.on_unsupported_protocol
) {
3199 assert(serverBump());
3200 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
3201 checklist
.requestErrorType
= err
;
3202 checklist
.conn(this);
3203 allow_t answer
= checklist
.fastCheck();
3204 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
3212 ConnStateData::startPeekAndSplice(const bool unsupportedProtocol
)
3214 if (unsupportedProtocol
) {
3215 if (!spliceOnError(ERR_PROTOCOL_UNKNOWN
))
3216 clientConnection
->close();
3221 Security::TlsDetails::Pointer
const &details
= tlsParser
.details
;
3222 if (details
&& !details
->serverName
.isEmpty()) {
3223 serverBump()->clientSni
= details
->serverName
;
3224 resetSslCommonName(details
->serverName
.c_str());
3228 startPeekAndSpliceDone();
3231 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
3233 ConnStateData
*connState
= (ConnStateData
*) data
;
3235 // if the connection is closed or closing, just return.
3236 if (!connState
->isOpen())
3239 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
3240 assert(connState
->serverBump());
3241 Ssl::BumpMode bumpAction
;
3242 if (answer
== ACCESS_ALLOWED
) {
3243 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
3245 bumpAction
= Ssl::bumpSplice
;
3247 connState
->serverBump()->act
.step2
= bumpAction
;
3248 connState
->sslBumpMode
= bumpAction
;
3250 if (bumpAction
== Ssl::bumpTerminate
) {
3251 connState
->clientConnection
->close();
3252 } else if (bumpAction
!= Ssl::bumpSplice
) {
3253 connState
->startPeekAndSpliceDone();
3254 } else if (!connState
->splice())
3255 connState
->clientConnection
->close();
3259 ConnStateData::splice()
3261 // normally we can splice here, because we just got client hello message
3263 if (fd_table
[clientConnection
->fd
].ssl
.get()) {
3264 // Restore default read methods
3265 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
3266 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
3269 if (transparent()) {
3270 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
3271 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
3272 transferProtocol
= Http::ProtocolVersion();
3273 return fakeAConnectRequest("intercepted TLS spliced", inBuf
);
3275 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
3277 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
3278 transferProtocol
= Http::ProtocolVersion();
3279 Http::StreamPointer context
= pipeline
.front();
3280 ClientHttpRequest
*http
= context
->http
;
3287 ConnStateData::startPeekAndSpliceDone()
3289 // This is the Step2 of the SSL bumping
3290 assert(sslServerBump
);
3291 Http::StreamPointer context
= pipeline
.front();
3292 ClientHttpRequest
*http
= context
? context
->http
: NULL
;
3294 if (sslServerBump
->step
== Ssl::bumpStep1
) {
3295 sslServerBump
->step
= Ssl::bumpStep2
;
3296 // Run a accessList check to check if want to splice or continue bumping
3298 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
3299 acl_checklist
->al
= http
? http
->al
: NULL
;
3300 //acl_checklist->src_addr = params.conn->remote;
3301 //acl_checklist->my_addr = s->s;
3302 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpNone
));
3303 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpClientFirst
));
3304 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpServerFirst
));
3305 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
3309 // will call httpsPeeked() with certificate and connection, eventually
3310 auto unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
3311 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
3313 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
3316 switchedToHttps_
= true;
3318 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3319 BIO
*b
= SSL_get_rbio(ssl
);
3320 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3321 bio
->setReadBufData(inBuf
);
3324 // Here squid should have all of the client hello message so the
3325 // Squid_SSL_accept should return 0;
3326 // This block exist only to force openSSL parse client hello and detect
3327 // ERR_SECURE_ACCEPT_FAIL error, which should be checked and splice if required.
3329 if ((ret
= Squid_SSL_accept(this, NULL
)) < 0) {
3330 debugs(83, 2, "SSL_accept failed.");
3331 const err_type err
= ERR_SECURE_ACCEPT_FAIL
;
3332 if (!spliceOnError(err
))
3333 clientConnection
->close();
3337 // We need to reset inBuf here, to be used by incoming requests in the case
3341 debugs(83, 5, "Peek and splice at step2 done. Start forwarding the request!!! ");
3342 FwdState::Start(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw(), http
? http
->al
: NULL
);
3346 ConnStateData::doPeekAndSpliceStep()
3348 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3349 BIO
*b
= SSL_get_rbio(ssl
);
3351 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3353 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
3356 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
3357 switchedToHttps_
= true;
3361 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3363 Must(sslServerBump
!= NULL
);
3365 if (Comm::IsConnOpen(serverConnection
)) {
3366 pinConnection(serverConnection
, NULL
, NULL
, false);
3368 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3370 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3372 // copy error detail from bump-server-first request to CONNECT request
3373 if (!pipeline
.empty() && pipeline
.front()->http
!= nullptr && pipeline
.front()->http
->request
)
3374 pipeline
.front()->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3377 getSslContextStart();
3380 #endif /* USE_OPENSSL */
3383 ConnStateData::fakeAConnectRequest(const char *reason
, const SBuf
&payload
)
3385 // fake a CONNECT request to force connState to tunnel
3388 if (serverBump() && !serverBump()->clientSni
.isEmpty()) {
3389 connectHost
.assign(serverBump()->clientSni
);
3390 if (clientConnection
->local
.port() > 0)
3391 connectHost
.appendf(":%d",clientConnection
->local
.port());
3395 static char ip
[MAX_IPSTRLEN
];
3396 connectHost
.assign(clientConnection
->local
.toUrl(ip
, sizeof(ip
)));
3398 // Pre-pend this fake request to the TLS bits already in the buffer
3400 retStr
.append("CONNECT ");
3401 retStr
.append(connectHost
);
3402 retStr
.append(" HTTP/1.1\r\nHost: ");
3403 retStr
.append(connectHost
);
3404 retStr
.append("\r\n\r\n");
3405 retStr
.append(payload
);
3407 bool ret
= handleReadData();
3409 ret
= clientParseRequests();
3412 debugs(33, 2, "Failed to start fake CONNECT request for " << reason
<< " connection: " << clientConnection
);
3418 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3420 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3422 if (!Comm::IsConnOpen(c
)) {
3423 Must(NHttpSockets
> 0); // we tried to open some
3424 --NHttpSockets
; // there will be fewer sockets than planned
3425 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3427 if (!NHttpSockets
) // we could not open any listen sockets at all
3428 fatalf("Unable to open %s",FdNote(portType
));
3435 /// find any unused HttpSockets[] slot and store fd there or return false
3437 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
3440 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
3441 if ((found
= HttpSockets
[i
] < 0))
3442 HttpSockets
[i
] = conn
->fd
;
3448 clientHttpConnectionsOpen(void)
3450 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3451 const char *scheme
= AnyP::UriScheme(s
->transport
.protocol
).c_str();
3453 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
3454 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many '" << scheme
<< "_port' lines.");
3455 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
3460 if (s
->flags
.tunnelSslBumping
) {
3461 if (!Config
.accessList
.ssl_bump
) {
3462 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme
<< "_port " << s
->s
);
3463 s
->flags
.tunnelSslBumping
= false;
3465 if (!s
->secure
.staticContext
&& !s
->generateHostCertificates
) {
3466 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at " << scheme
<< "_port " << s
->s
<< " due to TLS initialization failure.");
3467 s
->flags
.tunnelSslBumping
= false;
3468 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
)
3469 s
->secure
.encryptTransport
= false;
3471 if (s
->flags
.tunnelSslBumping
) {
3472 // Create ssl_ctx cache for this port.
3473 auto sz
= s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
;
3474 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, sz
);
3478 if (s
->secure
.encryptTransport
&& !s
->secure
.staticContext
) {
3479 debugs(1, DBG_CRITICAL
, "ERROR: Ignoring " << scheme
<< "_port " << s
->s
<< " due to TLS context initialization failure.");
3484 // Fill out a Comm::Connection which IPC will open as a listener for us
3485 // then pass back when active so we can start a TcpAcceptor subscription.
3486 s
->listenConn
= new Comm::Connection
;
3487 s
->listenConn
->local
= s
->s
;
3489 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3490 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3492 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3493 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
) {
3494 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
3495 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
3496 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3498 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
3499 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
3500 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
3503 } else if (s
->transport
.protocol
== AnyP::PROTO_HTTPS
) {
3504 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
3505 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
3506 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3508 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
3509 ListeningStartedDialer(&clientListenerConnectionOpened
,
3510 s
, Ipc::fdnHttpsSocket
, sub
));
3511 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
3515 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
3521 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
3523 // Fill out a Comm::Connection which IPC will open as a listener for us
3524 port
->listenConn
= new Comm::Connection
;
3525 port
->listenConn
->local
= port
->s
;
3526 port
->listenConn
->flags
=
3528 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3529 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3531 // route new connections to subCall
3532 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3533 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3534 AsyncCall::Pointer listenCall
=
3535 asyncCall(33, 2, "clientListenerConnectionOpened",
3536 ListeningStartedDialer(&clientListenerConnectionOpened
,
3537 port
, fdNote
, sub
));
3538 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
3540 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
3541 HttpSockets
[NHttpSockets
] = -1;
3545 /// process clientHttpConnectionsOpen result
3547 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
3551 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
3554 Must(Comm::IsConnOpen(s
->listenConn
));
3556 // TCP: setup a job to handle accept() with subscribed handler
3557 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
3559 debugs(1, DBG_IMPORTANT
, "Accepting " <<
3560 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
3561 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
3562 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
3563 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
3564 << FdNote(portTypeNote
) << " connections at "
3567 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
3571 clientOpenListenSockets(void)
3573 clientHttpConnectionsOpen();
3574 Ftp::StartListening();
3576 if (NHttpSockets
< 1)
3577 fatal("No HTTP, HTTPS, or FTP ports configured");
3581 clientConnectionsClose()
3583 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3584 if (s
->listenConn
!= NULL
) {
3585 debugs(1, DBG_IMPORTANT
, "Closing HTTP(S) port " << s
->listenConn
->local
);
3586 s
->listenConn
->close();
3587 s
->listenConn
= NULL
;
3591 Ftp::StopListening();
3593 // TODO see if we can drop HttpSockets array entirely */
3594 for (int i
= 0; i
< NHttpSockets
; ++i
) {
3595 HttpSockets
[i
] = -1;
3602 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
3604 SBuf
vary(request
->vary_headers
);
3605 int has_vary
= entry
->getReply()->header
.has(Http::HdrType::VARY
);
3606 #if X_ACCELERATOR_VARY
3609 entry
->getReply()->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
3612 if (!has_vary
|| entry
->mem_obj
->vary_headers
.isEmpty()) {
3613 if (!vary
.isEmpty()) {
3614 /* Oops... something odd is going on here.. */
3615 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
3616 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3617 request
->vary_headers
.clear();
3622 /* This is not a varying object */
3626 /* virtual "vary" object found. Calculate the vary key and
3627 * continue the search
3629 vary
= httpMakeVaryMark(request
, entry
->getReply());
3631 if (!vary
.isEmpty()) {
3632 request
->vary_headers
= vary
;
3635 /* Ouch.. we cannot handle this kind of variance */
3636 /* XXX This cannot really happen, but just to be complete */
3640 if (vary
.isEmpty()) {
3641 vary
= httpMakeVaryMark(request
, entry
->getReply());
3643 if (!vary
.isEmpty())
3644 request
->vary_headers
= vary
;
3647 if (vary
.isEmpty()) {
3648 /* Ouch.. we cannot handle this kind of variance */
3649 /* XXX This cannot really happen, but just to be complete */
3651 } else if (vary
.cmp(entry
->mem_obj
->vary_headers
) == 0) {
3654 /* Oops.. we have already been here and still haven't
3655 * found the requested variant. Bail out
3657 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
3658 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3664 ACLFilledChecklist
*
3665 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
3667 ConnStateData
* conn
= http
->getConn();
3668 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
3669 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
3672 * hack for ident ACL. It needs to get full addresses, and a place to store
3673 * the ident result on persistent connections...
3675 /* connection oriented auth also needs these two lines for it's operation. */
3680 ConnStateData::transparent() const
3682 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
3686 ConnStateData::expectRequestBody(int64_t size
)
3688 bodyPipe
= new BodyPipe(this);
3690 bodyPipe
->setBodySize(size
);
3692 startDechunkingRequest();
3697 ConnStateData::mayNeedToReadMoreBody() const
3700 return 0; // request without a body or read/produced all body bytes
3702 if (!bodyPipe
->bodySizeKnown())
3703 return -1; // probably need to read more, but we cannot be sure
3705 const int64_t needToProduce
= bodyPipe
->unproducedSize();
3706 const int64_t haveAvailable
= static_cast<int64_t>(inBuf
.length());
3708 if (needToProduce
<= haveAvailable
)
3709 return 0; // we have read what we need (but are waiting for pipe space)
3711 return needToProduce
- haveAvailable
;
3715 ConnStateData::stopReceiving(const char *error
)
3717 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
3718 "; old sending error: " <<
3719 (stoppedSending() ? stoppedSending_
: "none"));
3721 if (const char *oldError
= stoppedReceiving()) {
3722 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
3723 return; // nothing has changed as far as this connection is concerned
3726 stoppedReceiving_
= error
;
3728 if (const char *sendError
= stoppedSending()) {
3729 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
3730 clientConnection
->close();
3735 ConnStateData::expectNoForwarding()
3737 if (bodyPipe
!= NULL
) {
3738 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
3739 bodyPipe
->expectNoConsumption();
3743 /// initialize dechunking state
3745 ConnStateData::startDechunkingRequest()
3747 Must(bodyPipe
!= NULL
);
3748 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
3749 assert(!bodyParser
);
3750 bodyParser
= new Http1::TeChunkedParser
;
3753 /// put parsed content into input buffer and clean up
3755 ConnStateData::finishDechunkingRequest(bool withSuccess
)
3757 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
3759 if (bodyPipe
!= NULL
) {
3760 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
3761 BodyPipe::Pointer myPipe
= bodyPipe
;
3762 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
3763 Must(!bodyPipe
); // we rely on it being nil after we are done with body
3765 Must(myPipe
->bodySizeKnown());
3766 Http::StreamPointer context
= pipeline
.front();
3767 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
3768 context
->http
->request
->setContentLength(myPipe
->bodySize());
3776 // XXX: this is an HTTP/1-only operation
3778 ConnStateData::sendControlMsg(HttpControlMsg msg
)
3781 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
3785 // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them
3786 if (!pipeline
.empty()) {
3787 HttpReply::Pointer
rep(msg
.reply
);
3789 // remember the callback
3790 cbControlMsgSent
= msg
.cbSuccess
;
3792 typedef CommCbMemFunT
<HttpControlMsgSink
, CommIoCbParams
> Dialer
;
3793 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, HttpControlMsgSink::wroteControlMsg
);
3795 writeControlMsgAndCall(rep
.getRaw(), call
);
3799 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
3800 clientConnection
->close();
3803 /// Our close handler called by Comm when the pinned connection is closed
3805 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
3807 // FwdState might repin a failed connection sooner than this close
3808 // callback is called for the failed connection.
3809 assert(pinning
.serverConnection
== io
.conn
);
3810 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
3811 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
3812 pinning
.serverConnection
->noteClosure();
3813 unpinConnection(false);
3815 if (sawZeroReply
&& clientConnection
!= NULL
) {
3816 debugs(33, 3, "Closing client connection on pinned zero reply.");
3817 clientConnection
->close();
3823 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
3825 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
3826 pinning
.serverConnection
->fd
!= pinServer
->fd
)
3827 pinNewConnection(pinServer
, request
, aPeer
, auth
);
3830 startPinnedConnectionMonitoring();
3834 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
3836 unpinConnection(true); // closes pinned connection, if any, and resets fields
3838 pinning
.serverConnection
= pinServer
;
3840 debugs(33, 3, HERE
<< pinning
.serverConnection
);
3842 Must(pinning
.serverConnection
!= NULL
);
3844 // when pinning an SSL bumped connection, the request may be NULL
3845 const char *pinnedHost
= "[unknown]";
3847 pinning
.host
= xstrdup(request
->url
.host());
3848 pinning
.port
= request
->url
.port();
3849 pinnedHost
= pinning
.host
;
3851 pinning
.port
= pinServer
->remote
.port();
3853 pinning
.pinned
= true;
3855 pinning
.peer
= cbdataReference(aPeer
);
3856 pinning
.auth
= auth
;
3857 char stmp
[MAX_IPSTRLEN
];
3858 char desc
[FD_DESC_SZ
];
3859 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
3860 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
3861 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
3862 clientConnection
->fd
);
3863 fd_note(pinning
.serverConnection
->fd
, desc
);
3865 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3866 pinning
.closeHandler
= JobCallback(33, 5,
3867 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
3868 // remember the pinned connection so that cb does not unpin a fresher one
3869 typedef CommCloseCbParams Params
;
3870 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
3871 params
.conn
= pinning
.serverConnection
;
3872 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
3875 /// [re]start monitoring pinned connection for peer closures so that we can
3876 /// propagate them to an _idle_ client pinned to that peer
3878 ConnStateData::startPinnedConnectionMonitoring()
3880 if (pinning
.readHandler
!= NULL
)
3881 return; // already monitoring
3883 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
3884 pinning
.readHandler
= JobCallback(33, 3,
3885 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
3886 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
3890 ConnStateData::stopPinnedConnectionMonitoring()
3892 if (pinning
.readHandler
!= NULL
) {
3893 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
3894 pinning
.readHandler
= NULL
;
3900 ConnStateData::handleIdleClientPinnedTlsRead()
3902 // A ready-for-reading connection means that the TLS server either closed
3903 // the connection, sent us some unexpected HTTP data, or started TLS
3904 // renegotiations. We should close the connection except for the last case.
3906 Must(pinning
.serverConnection
!= nullptr);
3907 auto ssl
= fd_table
[pinning
.serverConnection
->fd
].ssl
.get();
3912 const int readResult
= SSL_read(ssl
, buf
, sizeof(buf
));
3914 if (readResult
> 0 || SSL_pending(ssl
) > 0) {
3915 debugs(83, 2, pinning
.serverConnection
<< " TLS application data read");
3919 switch(const int error
= SSL_get_error(ssl
, readResult
)) {
3920 case SSL_ERROR_WANT_WRITE
:
3921 debugs(83, DBG_IMPORTANT
, pinning
.serverConnection
<< " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection");
3922 // fall through to restart monitoring, for now
3923 case SSL_ERROR_NONE
:
3924 case SSL_ERROR_WANT_READ
:
3925 startPinnedConnectionMonitoring();
3929 debugs(83, 2, pinning
.serverConnection
<< " TLS error: " << error
);
3938 /// Our read handler called by Comm when the server either closes an idle pinned connection or
3939 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
3941 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
3943 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
3945 if (io
.flag
== Comm::ERR_CLOSING
)
3946 return; // close handler will clean up
3948 Must(pinning
.serverConnection
== io
.conn
);
3951 if (handleIdleClientPinnedTlsRead())
3955 const bool clientIsIdle
= pipeline
.empty();
3957 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
3958 io
.size
<< (clientIsIdle
? " with idle client" : ""));
3960 pinning
.serverConnection
->close();
3962 // If we are still sending data to the client, do not close now. When we are done sending,
3963 // ConnStateData::kick() checks pinning.serverConnection and will close.
3964 // However, if we are idle, then we must close to inform the idle client and minimize races.
3965 if (clientIsIdle
&& clientConnection
!= NULL
)
3966 clientConnection
->close();
3969 const Comm::ConnectionPointer
3970 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
3972 debugs(33, 7, HERE
<< pinning
.serverConnection
);
3975 if (!Comm::IsConnOpen(pinning
.serverConnection
))
3977 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->url
.host()) != 0)
3979 else if (request
&& pinning
.port
!= request
->url
.port())
3981 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
3983 else if (aPeer
!= pinning
.peer
)
3987 /* The pinning info is not safe, remove any pinning info */
3988 unpinConnection(true);
3991 return pinning
.serverConnection
;
3994 Comm::ConnectionPointer
3995 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
3997 debugs(33, 7, pinning
.serverConnection
);
3998 if (validatePinnedConnection(request
, aPeer
) != NULL
)
3999 stopPinnedConnectionMonitoring();
4001 return pinning
.serverConnection
; // closed if validation failed
4005 ConnStateData::unpinConnection(const bool andClose
)
4007 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4010 cbdataReferenceDone(pinning
.peer
);
4012 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4013 if (pinning
.closeHandler
!= NULL
) {
4014 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4015 pinning
.closeHandler
= NULL
;
4018 stopPinnedConnectionMonitoring();
4020 // close the server side socket if requested
4022 pinning
.serverConnection
->close();
4023 pinning
.serverConnection
= NULL
;
4026 safe_free(pinning
.host
);
4028 pinning
.zeroReply
= false;
4030 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4031 * connection has gone away */