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 conn
->fakeAConnectRequest("unknown-protocol", conn
->preservedClientData
);
1584 debugs(33, 3, "Continue with returning the error: " << requestError
);
1589 conn
->quitAfterError(request
);
1590 clientStreamNode
*node
= context
->getClientReplyContext();
1591 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1592 assert (repContext
);
1594 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
1596 assert(context
->http
->out
.offset
== 0);
1597 context
->pullData();
1598 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
1603 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
1607 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
1608 * to here because calling comm_reset_close() causes http to
1609 * be freed before accessing.
1611 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
1612 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
1613 conn
->flags
.readMore
= false;
1614 comm_reset_close(conn
->clientConnection
);
1619 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, Http::Stream
*context
)
1621 ClientHttpRequest
*http
= context
->http
;
1622 bool chunked
= false;
1623 bool mustReplyToOptions
= false;
1624 bool unsupportedTe
= false;
1625 bool expectBody
= false;
1627 // We already have the request parsed and checked, so we
1628 // only need to go through the final body/conn setup to doCallouts().
1629 assert(http
->request
);
1630 HttpRequest::Pointer request
= http
->request
;
1632 // temporary hack to avoid splitting this huge function with sensitive code
1633 const bool isFtp
= !hp
;
1635 // Some blobs below are still HTTP-specific, but we would have to rewrite
1636 // this entire function to remove them from the FTP code path. Connection
1637 // setup and body_pipe preparation blobs are needed for FTP.
1639 request
->clientConnectionManager
= conn
;
1641 request
->flags
.accelerated
= http
->flags
.accel
;
1642 request
->flags
.sslBumped
=conn
->switchedToHttps();
1643 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
1644 // TODO: decouple http->flags.accel from request->flags.sslBumped
1645 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
1646 !conn
->port
->allow_direct
: 0;
1647 request
->sources
|= isFtp
? HttpMsg::srcFtp
:
1648 ((request
->flags
.sslBumped
|| conn
->port
->transport
.protocol
== AnyP::PROTO_HTTPS
) ? HttpMsg::srcHttps
: HttpMsg::srcHttp
);
1650 if (request
->flags
.sslBumped
) {
1651 if (conn
->getAuth() != NULL
)
1652 request
->auth_user_request
= conn
->getAuth();
1657 * If transparent or interception mode is working clone the transparent and interception flags
1658 * from the port settings to the request.
1660 if (http
->clientConnection
!= NULL
) {
1661 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
1662 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
1663 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
1664 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
1665 if (Config
.accessList
.spoof_client_ip
) {
1666 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
1667 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
1670 request
->flags
.spoofClientIp
= true;
1672 request
->flags
.spoofClientIp
= false;
1675 if (internalCheck(request
->url
.path())) {
1676 if (internalHostnameIs(request
->url
.host()) && request
->url
.port() == getMyPort()) {
1677 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true));
1678 http
->flags
.internal
= true;
1679 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->url
.path())) {
1680 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (global_internal_static on)");
1681 request
->url
.setScheme(AnyP::PROTO_HTTP
);
1682 request
->url
.host(internalHostname());
1683 request
->url
.port(getMyPort());
1684 http
->flags
.internal
= true;
1686 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (not this proxy)");
1689 request
->flags
.internal
= http
->flags
.internal
;
1690 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
1691 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
1692 #if FOLLOW_X_FORWARDED_FOR
1693 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
1694 // not a details about teh TCP connection itself
1695 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
1696 #endif /* FOLLOW_X_FORWARDED_FOR */
1697 request
->my_addr
= conn
->clientConnection
->local
;
1698 request
->myportname
= conn
->port
->name
;
1701 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
1702 // for now Squid only supports HTTP requests
1703 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
1704 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
1705 request
->http_ver
.major
= http_ver
.major
;
1706 request
->http_ver
.minor
= http_ver
.minor
;
1709 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
1710 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
1711 request
->clientConnectionManager
= conn
;
1713 if (request
->header
.chunked()) {
1715 } else if (request
->header
.has(Http::HdrType::TRANSFER_ENCODING
)) {
1716 const String te
= request
->header
.getList(Http::HdrType::TRANSFER_ENCODING
);
1717 // HTTP/1.1 requires chunking to be the last encoding if there is one
1718 unsupportedTe
= te
.size() && te
!= "identity";
1719 } // else implied identity coding
1721 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
1722 (request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0);
1723 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
1724 clientStreamNode
*node
= context
->getClientReplyContext();
1725 conn
->quitAfterError(request
.getRaw());
1726 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1727 assert (repContext
);
1728 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
1729 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1730 assert(context
->http
->out
.offset
== 0);
1731 context
->pullData();
1732 clientProcessRequestFinished(conn
, request
);
1736 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
1737 clientStreamNode
*node
= context
->getClientReplyContext();
1738 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1739 assert (repContext
);
1740 conn
->quitAfterError(request
.getRaw());
1741 repContext
->setReplyToError(ERR_INVALID_REQ
,
1742 Http::scLengthRequired
, request
->method
, NULL
,
1743 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1744 assert(context
->http
->out
.offset
== 0);
1745 context
->pullData();
1746 clientProcessRequestFinished(conn
, request
);
1750 clientSetKeepaliveFlag(http
);
1751 // Let tunneling code be fully responsible for CONNECT requests
1752 if (http
->request
->method
== Http::METHOD_CONNECT
) {
1753 context
->mayUseConnection(true);
1754 conn
->flags
.readMore
= false;
1758 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
1759 clientProcessRequestFinished(conn
, request
);
1764 /* Do we expect a request-body? */
1765 expectBody
= chunked
|| request
->content_length
> 0;
1766 if (!context
->mayUseConnection() && expectBody
) {
1767 request
->body_pipe
= conn
->expectRequestBody(
1768 chunked
? -1 : request
->content_length
);
1770 /* Is it too large? */
1771 if (!chunked
&& // if chunked, we will check as we accumulate
1772 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
1773 clientStreamNode
*node
= context
->getClientReplyContext();
1774 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1775 assert (repContext
);
1776 conn
->quitAfterError(request
.getRaw());
1777 repContext
->setReplyToError(ERR_TOO_BIG
,
1778 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
1779 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
1780 assert(context
->http
->out
.offset
== 0);
1781 context
->pullData();
1782 clientProcessRequestFinished(conn
, request
);
1787 // We may stop producing, comm_close, and/or call setReplyToError()
1788 // below, so quit on errors to avoid http->doCallouts()
1789 if (!conn
->handleRequestBodyData()) {
1790 clientProcessRequestFinished(conn
, request
);
1794 if (!request
->body_pipe
->productionEnded()) {
1795 debugs(33, 5, "need more request body");
1796 context
->mayUseConnection(true);
1797 assert(conn
->flags
.readMore
);
1802 http
->calloutContext
= new ClientRequestContext(http
);
1806 clientProcessRequestFinished(conn
, request
);
1810 ConnStateData::pipelinePrefetchMax() const
1812 // TODO: Support pipelined requests through pinned connections.
1815 return Config
.pipeline_max_prefetch
;
1819 * Limit the number of concurrent requests.
1820 * \return true when there are available position(s) in the pipeline queue for another request.
1821 * \return false when the pipeline queue is full or disabled.
1824 ConnStateData::concurrentRequestQueueFilled() const
1826 const int existingRequestCount
= pipeline
.count();
1828 // default to the configured pipeline size.
1829 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
1831 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
1833 const int internalRequest
= 0;
1835 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
1837 // when queue filled already we cant add more.
1838 if (existingRequestCount
>= concurrentRequestLimit
) {
1839 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
1840 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
1848 * Perform proxy_protocol_access ACL tests on the client which
1849 * connected to PROXY protocol port to see if we trust the
1850 * sender enough to accept their PROXY header claim.
1853 ConnStateData::proxyProtocolValidateClient()
1855 if (!Config
.accessList
.proxyProtocol
)
1856 return proxyProtocolError("PROXY client not permitted by default ACL");
1858 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
1859 ch
.src_addr
= clientConnection
->remote
;
1860 ch
.my_addr
= clientConnection
->local
;
1863 if (ch
.fastCheck() != ACCESS_ALLOWED
)
1864 return proxyProtocolError("PROXY client not permitted by ACLs");
1870 * Perform cleanup on PROXY protocol errors.
1871 * If header parsing hits a fatal error terminate the connection,
1872 * otherwise wait for more data.
1875 ConnStateData::proxyProtocolError(const char *msg
)
1878 // This is important to know, but maybe not so much that flooding the log is okay.
1879 #if QUIET_PROXY_PROTOCOL
1880 // display the first of every 32 occurances at level 1, the others at level 2.
1881 static uint8_t hide
= 0;
1882 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
1884 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
1891 /// magic octet prefix for PROXY protocol version 1
1892 static const SBuf
Proxy1p0magic("PROXY ", 6);
1894 /// magic octet prefix for PROXY protocol version 2
1895 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
1898 * Test the connection read buffer for PROXY protocol header.
1899 * Version 1 and 2 header currently supported.
1902 ConnStateData::parseProxyProtocolHeader()
1904 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
1906 // detect and parse PROXY/2.0 protocol header
1907 if (inBuf
.startsWith(Proxy2p0magic
))
1908 return parseProxy2p0();
1910 // detect and parse PROXY/1.0 protocol header
1911 if (inBuf
.startsWith(Proxy1p0magic
))
1912 return parseProxy1p0();
1914 // detect and terminate other protocols
1915 if (inBuf
.length() >= Proxy2p0magic
.length()) {
1916 // PROXY/1.0 magic is shorter, so we know that
1917 // the input does not start with any PROXY magic
1918 return proxyProtocolError("PROXY protocol error: invalid header");
1921 // TODO: detect short non-magic prefixes earlier to avoid
1922 // waiting for more data which may never come
1924 // not enough bytes to parse yet.
1928 /// parse the PROXY/1.0 protocol header from the connection read buffer
1930 ConnStateData::parseProxy1p0()
1932 ::Parser::Tokenizer
tok(inBuf
);
1933 tok
.skip(Proxy1p0magic
);
1935 // skip to first LF (assumes it is part of CRLF)
1936 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
1938 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
1939 if (tok
.skip('\n')) {
1940 // found valid header
1941 inBuf
= tok
.remaining();
1942 needProxyProtocolHeader_
= false;
1943 // reset the tokenizer to work on found line only.
1946 return false; // no LF yet
1948 } else // protocol error only if there are more than 107 bytes prefix header
1949 return proxyProtocolError(inBuf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
1951 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
1952 if (tok
.skip(tcpName
)) {
1954 // skip TCP/IP version number
1955 static const CharacterSet
tcpVersions("TCP-version","46");
1956 if (!tok
.skipOne(tcpVersions
))
1957 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
1959 // skip SP after protocol version
1961 return proxyProtocolError("PROXY/1.0 error: missing SP");
1964 int64_t porta
, portb
;
1965 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
1967 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
1968 // leave the LF until later.
1969 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
1970 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
1971 tok
.int64(porta
) && tok
.skip(' ') &&
1975 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
1977 // parse IP and port strings
1978 Ip::Address originalClient
, originalDest
;
1980 if (!originalClient
.GetHostByName(ipa
.c_str()))
1981 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
1983 if (!originalDest
.GetHostByName(ipb
.c_str()))
1984 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
1986 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
1987 originalClient
.port(static_cast<uint16_t>(porta
));
1989 return proxyProtocolError("PROXY/1.0 error: invalid src port");
1991 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
1992 originalDest
.port(static_cast<uint16_t>(portb
));
1994 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
1996 // we have original client and destination details now
1997 // replace the client connection values
1998 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
1999 clientConnection
->local
= originalDest
;
2000 clientConnection
->remote
= originalClient
;
2001 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2002 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2003 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2005 // repeat fetch ensuring the new client FQDN can be logged
2006 if (Config
.onoff
.log_fqdn
)
2007 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2011 } else if (tok
.skip(unknown
)) {
2012 // found valid but unusable header
2016 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2021 /// parse the PROXY/2.0 protocol header from the connection read buffer
2023 ConnStateData::parseProxy2p0()
2025 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2026 if (inBuf
.length() < prefixLen
+ 4)
2027 return false; // need more bytes
2029 if ((inBuf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2030 return proxyProtocolError("PROXY/2.0 error: invalid version");
2032 const char command
= (inBuf
[prefixLen
] & 0x0F);
2033 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2034 return proxyProtocolError("PROXY/2.0 error: invalid command");
2036 const char family
= (inBuf
[prefixLen
+1] & 0xF0) >>4;
2037 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2038 return proxyProtocolError("PROXY/2.0 error: invalid family");
2040 const char proto
= (inBuf
[prefixLen
+1] & 0x0F);
2041 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2042 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2044 const char *clen
= inBuf
.rawContent() + prefixLen
+ 2;
2046 memcpy(&len
, clen
, sizeof(len
));
2049 if (inBuf
.length() < prefixLen
+ 4 + len
)
2050 return false; // need more bytes
2052 inBuf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2053 const SBuf extra
= inBuf
.consume(len
);
2054 needProxyProtocolHeader_
= false; // found successfully
2056 // LOCAL connections do nothing with the extras
2057 if (command
== 0x00/* LOCAL*/)
2061 struct { /* for TCP/UDP over IPv4, len = 12 */
2062 struct in_addr src_addr
;
2063 struct in_addr dst_addr
;
2067 struct { /* for TCP/UDP over IPv6, len = 36 */
2068 struct in6_addr src_addr
;
2069 struct in6_addr dst_addr
;
2074 struct { /* for AF_UNIX sockets, len = 216 */
2075 uint8_t src_addr
[108];
2076 uint8_t dst_addr
[108];
2082 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2084 // replace the client connection values
2085 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2088 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2089 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2090 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2091 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2092 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2093 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2096 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2097 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2098 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2099 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2100 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2101 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2103 default: // do nothing
2106 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2108 // repeat fetch ensuring the new client FQDN can be logged
2109 if (Config
.onoff
.log_fqdn
)
2110 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2116 ConnStateData::receivedFirstByte()
2118 if (receivedFirstByte_
)
2121 receivedFirstByte_
= true;
2122 // Set timeout to Config.Timeout.request
2123 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2124 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
2125 TimeoutDialer
, this, ConnStateData::requestTimeout
);
2126 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
2130 * Attempt to parse one or more requests from the input buffer.
2131 * Returns true after completing parsing of at least one request [header]. That
2132 * includes cases where parsing ended with an error (e.g., a huge request).
2135 ConnStateData::clientParseRequests()
2137 bool parsed_req
= false;
2139 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2141 // Loop while we have read bytes that are not needed for producing the body
2142 // On errors, bodyPipe may become nil, but readMore will be cleared
2143 while (!inBuf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2145 /* Don't try to parse if the buffer is empty */
2146 if (inBuf
.isEmpty())
2149 /* Limit the number of concurrent requests */
2150 if (concurrentRequestQueueFilled())
2153 // try to parse the PROXY protocol header magic bytes
2154 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
2157 if (Http::Stream
*context
= parseOneRequest()) {
2158 debugs(33, 5, clientConnection
<< ": done parsing a request");
2160 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2161 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2162 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2164 context
->registerWithConn();
2166 processParsedRequest(context
);
2168 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2170 if (context
->mayUseConnection()) {
2171 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2175 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
2176 inBuf
.length() << " < " << Config
.maxRequestHeaderSize
);
2177 Must(inBuf
.length() < Config
.maxRequestHeaderSize
);
2182 /* XXX where to 'finish' the parsing pass? */
2187 ConnStateData::afterClientRead()
2189 /* Process next request */
2190 if (pipeline
.empty())
2191 fd_note(clientConnection
->fd
, "Reading next request");
2193 if (!clientParseRequests()) {
2197 * If the client here is half closed and we failed
2198 * to parse a request, close the connection.
2199 * The above check with connFinishedWithConn() only
2200 * succeeds _if_ the buffer is empty which it won't
2201 * be if we have an incomplete request.
2202 * XXX: This duplicates ConnStateData::kick
2204 if (pipeline
.empty() && commIsHalfClosed(clientConnection
->fd
)) {
2205 debugs(33, 5, clientConnection
<< ": half-closed connection, no completed request parsed, connection closing.");
2206 clientConnection
->close();
2214 clientAfterReadingRequests();
2218 * called when new request data has been read from the socket
2220 * \retval false called comm_close or setReplyToError (the caller should bail)
2221 * \retval true we did not call comm_close or setReplyToError
2224 ConnStateData::handleReadData()
2226 // if we are reading a body, stuff data into the body pipe
2227 if (bodyPipe
!= NULL
)
2228 return handleRequestBodyData();
2233 * called when new request body data has been buffered in inBuf
2234 * may close the connection if we were closing and piped everything out
2236 * \retval false called comm_close or setReplyToError (the caller should bail)
2237 * \retval true we did not call comm_close or setReplyToError
2240 ConnStateData::handleRequestBodyData()
2242 assert(bodyPipe
!= NULL
);
2244 if (bodyParser
) { // chunked encoding
2245 if (const err_type error
= handleChunkedRequestBody()) {
2246 abortChunkedRequestBody(error
);
2249 } else { // identity encoding
2250 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
2251 const size_t putSize
= bodyPipe
->putMoreData(inBuf
.c_str(), inBuf
.length());
2253 consumeInput(putSize
);
2255 if (!bodyPipe
->mayNeedMoreData()) {
2256 // BodyPipe will clear us automagically when we produced everything
2262 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
2264 if (const char *reason
= stoppedSending()) {
2265 /* we've finished reading like good clients,
2266 * now do the close that initiateClose initiated.
2268 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
2269 clientConnection
->close();
2277 /// parses available chunked encoded body bytes, checks size, returns errors
2279 ConnStateData::handleChunkedRequestBody()
2281 debugs(33, 7, "chunked from " << clientConnection
<< ": " << inBuf
.length());
2283 try { // the parser will throw on errors
2285 if (inBuf
.isEmpty()) // nothing to do
2288 BodyPipeCheckout
bpc(*bodyPipe
);
2289 bodyParser
->setPayloadBuffer(&bpc
.buf
);
2290 const bool parsed
= bodyParser
->parse(inBuf
);
2291 inBuf
= bodyParser
->remaining(); // sync buffers
2294 // dechunk then check: the size limit applies to _dechunked_ content
2295 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
2299 finishDechunkingRequest(true);
2301 return ERR_NONE
; // nil bodyPipe implies body end for the caller
2304 // if chunk parser needs data, then the body pipe must need it too
2305 Must(!bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
2307 // if parser needs more space and we can consume nothing, we will stall
2308 Must(!bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
2309 } catch (...) { // TODO: be more specific
2310 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
2311 return ERR_INVALID_REQ
;
2314 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
2318 /// quit on errors related to chunked request body handling
2320 ConnStateData::abortChunkedRequestBody(const err_type error
)
2322 finishDechunkingRequest(false);
2324 // XXX: The code below works if we fail during initial request parsing,
2325 // but if we fail when the server connection is used already, the server may send
2326 // us its response too, causing various assertions. How to prevent that?
2327 #if WE_KNOW_HOW_TO_SEND_ERRORS
2328 Http::StreamPointer context
= pipeline
.front();
2329 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
2330 clientStreamNode
*node
= context
->getClientReplyContext();
2331 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2333 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
2334 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
2335 repContext
->setReplyToError(error
, scode
,
2336 repContext
->http
->request
->method
,
2337 repContext
->http
->uri
,
2339 repContext
->http
->request
,
2341 context
->pullData();
2343 // close or otherwise we may get stuck as nobody will notice the error?
2344 comm_reset_close(clientConnection
);
2347 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
2348 comm_reset_close(clientConnection
);
2350 flags
.readMore
= false;
2354 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
2356 // request reader may get stuck waiting for space if nobody consumes body
2357 if (bodyPipe
!= NULL
)
2358 bodyPipe
->enableAutoConsumption();
2363 /** general lifetime handler for HTTP requests */
2365 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
2367 if (!Comm::IsConnOpen(io
.conn
))
2370 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
2372 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
2373 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
2374 receivedFirstByte();
2377 } else if (!fd_table
[io
.conn
->fd
].ssl
)
2380 const HttpRequestMethod method
;
2381 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
2382 // Tunnel established. Set receivedFirstByte to avoid loop.
2383 receivedFirstByte();
2389 * Just close the connection to not confuse browsers
2390 * using persistent connections. Some browsers open
2391 * a connection and then do not use it until much
2392 * later (presumeably because the request triggering
2393 * the open has already been completed on another
2396 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
2401 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
2403 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
2404 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
2405 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
2406 http
->logType
.err
.timedout
= true;
2407 if (Comm::IsConnOpen(io
.conn
))
2411 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
2412 AsyncJob("ConnStateData"), // kids overwrite
2414 bodyParser(nullptr),
2416 sslBumpMode(Ssl::bumpEnd
),
2418 needProxyProtocolHeader_(false),
2420 switchedToHttps_(false),
2421 sslServerBump(NULL
),
2422 signAlgorithm(Ssl::algSignTrusted
),
2424 stoppedSending_(NULL
),
2425 stoppedReceiving_(NULL
)
2427 flags
.readMore
= true; // kids may overwrite
2428 flags
.swanSang
= false;
2430 pinning
.host
= NULL
;
2432 pinning
.pinned
= false;
2433 pinning
.auth
= false;
2434 pinning
.zeroReply
= false;
2435 pinning
.peer
= NULL
;
2437 // store the details required for creating more MasterXaction objects as new requests come in
2438 log_addr
= xact
->tcpClient
->remote
;
2439 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
2441 // register to receive notice of Squid signal events
2442 // which may affect long persisting client connections
2443 RegisterRunner(this);
2447 ConnStateData::start()
2449 BodyProducer::start();
2450 HttpControlMsgSink::start();
2452 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
2453 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
2454 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2455 int i
= IP_PMTUDISC_DONT
;
2456 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
2457 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
2459 static bool reported
= false;
2462 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
2468 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
2469 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
2470 comm_add_close_handler(clientConnection
->fd
, call
);
2472 if (Config
.onoff
.log_fqdn
)
2473 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2476 if (Ident::TheConfig
.identLookup
) {
2477 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
2478 identChecklist
.src_addr
= clientConnection
->remote
;
2479 identChecklist
.my_addr
= clientConnection
->local
;
2480 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
2481 Ident::Start(clientConnection
, clientIdentDone
, this);
2485 clientdbEstablished(clientConnection
->remote
, 1);
2487 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
2488 if (needProxyProtocolHeader_
) {
2489 if (!proxyProtocolValidateClient()) // will close the connection on failure
2494 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
2496 if (Config
.onoff
.client_db
) {
2497 /* it was said several times that client write limiter does not work if client_db is disabled */
2499 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
2500 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
2502 // TODO: we check early to limit error response bandwith but we
2503 // should recheck when we can honor delay_pool_uses_indirect
2504 // TODO: we should also pass the port details for myportname here.
2505 ch
.src_addr
= clientConnection
->remote
;
2506 ch
.my_addr
= clientConnection
->local
;
2508 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
2510 /* pools require explicit 'allow' to assign a client into them */
2511 if (pools
[pool
].access
) {
2512 ch
.changeAcl(pools
[pool
].access
);
2513 allow_t answer
= ch
.fastCheck();
2514 if (answer
== ACCESS_ALLOWED
) {
2516 /* request client information from db after we did all checks
2517 this will save hash lookup if client failed checks */
2518 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
2521 /* put client info in FDE */
2522 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
2524 /* setup write limiter for this request */
2525 const double burst
= floor(0.5 +
2526 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
2527 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
2530 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
2537 // kids must extend to actually start doing something (e.g., reading)
2540 /** Handle a new connection on an HTTP socket. */
2542 httpAccept(const CommAcceptCbParams
¶ms
)
2544 MasterXaction::Pointer xact
= params
.xaction
;
2545 AnyP::PortCfgPointer s
= xact
->squidPort
;
2547 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2549 if (params
.flag
!= Comm::OK
) {
2550 // Its possible the call was still queued when the client disconnected
2551 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2555 debugs(33, 4, params
.conn
<< ": accepted");
2556 fd_note(params
.conn
->fd
, "client http connect");
2558 if (s
->tcp_keepalive
.enabled
)
2559 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2561 ++incoming_sockets_accepted
;
2563 // Socket is ready, setup the connection manager to start using it
2564 ConnStateData
*connState
= Http::NewServer(xact
);
2565 AsyncJob::Start(connState
); // usually async-calls readSomeData()
2570 /** Create SSL connection structure and update fd_table */
2571 static Security::SessionPtr
2572 httpsCreate(const Comm::ConnectionPointer
&conn
, Security::ContextPtr sslContext
)
2574 if (auto ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
2575 debugs(33, 5, "will negotate SSL on " << conn
);
2585 * \retval 1 on success
2586 * \retval 0 when needs more data
2587 * \retval -1 on error
2590 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
2592 int fd
= conn
->clientConnection
->fd
;
2593 auto ssl
= fd_table
[fd
].ssl
.get();
2597 if ((ret
= SSL_accept(ssl
)) <= 0) {
2598 const int xerrno
= errno
;
2599 const int ssl_error
= SSL_get_error(ssl
, ret
);
2601 switch (ssl_error
) {
2603 case SSL_ERROR_WANT_READ
:
2604 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, conn
, 0);
2607 case SSL_ERROR_WANT_WRITE
:
2608 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, conn
, 0);
2611 case SSL_ERROR_SYSCALL
:
2613 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
2615 debugs(83, (xerrno
== ECONNRESET
) ? 1 : 2, "Error negotiating SSL connection on FD " << fd
<< ": " <<
2616 (xerrno
== 0 ? ERR_error_string(ssl_error
, NULL
) : xstrerr(xerrno
)));
2620 case SSL_ERROR_ZERO_RETURN
:
2621 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
2625 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
2626 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
2627 " (" << ssl_error
<< "/" << ret
<< ")");
2636 /** negotiate an SSL connection */
2638 clientNegotiateSSL(int fd
, void *data
)
2640 ConnStateData
*conn
= (ConnStateData
*)data
;
2642 auto ssl
= fd_table
[fd
].ssl
.get();
2645 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
2646 if (ret
< 0) // An error
2647 conn
->clientConnection
->close();
2651 if (SSL_session_reused(ssl
)) {
2652 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
2653 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
2655 if (do_debug(83, 4)) {
2656 /* Write out the SSL session details.. actually the call below, but
2657 * OpenSSL headers do strange typecasts confusing GCC.. */
2658 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
2659 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
2660 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
);
2662 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
2664 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
2665 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
2666 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
2667 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
2668 * Because there are two possible usable cast, if you get an error here, try the other
2669 * commented line. */
2671 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
2672 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
2676 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
2679 /* Note: This does not automatically fflush the log file.. */
2682 debugs(83, 2, "clientNegotiateSSL: New session " <<
2683 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
2684 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
2688 // Connection established. Retrieve TLS connection parameters for logging.
2689 conn
->clientConnection
->tlsNegotiations()->fillWith(ssl
);
2691 client_cert
= SSL_get_peer_certificate(ssl
);
2693 if (client_cert
!= NULL
) {
2694 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2695 " client certificate: subject: " <<
2696 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
2698 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
2699 " client certificate: issuer: " <<
2700 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
2702 X509_free(client_cert
);
2704 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
2705 " has no certificate.");
2708 #if defined(TLSEXT_NAMETYPE_host_name)
2709 if (!conn
->serverBump()) {
2710 // when in bumpClientFirst mode, get the server name from SNI
2711 if (const char *server
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))
2712 conn
->resetSslCommonName(server
);
2716 conn
->readSomeData();
2720 * If Security::ContextPtr is given, starts reading the TLS handshake.
2721 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPtr.
2724 httpsEstablish(ConnStateData
*connState
, Security::ContextPtr sslContext
)
2726 Security::SessionPtr ssl
= nullptr;
2728 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
2730 if (!sslContext
|| !(ssl
= httpsCreate(details
, sslContext
)))
2733 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2734 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
2735 connState
, ConnStateData::requestTimeout
);
2736 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
2738 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
2742 * A callback function to use with the ACLFilledChecklist callback.
2743 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
2744 * else reverts the connection to tunnel mode.
2747 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
2749 ConnStateData
*connState
= (ConnStateData
*) data
;
2751 // if the connection is closed or closing, just return.
2752 if (!connState
->isOpen())
2755 // Require both a match and a positive bump mode to work around exceptional
2756 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
2757 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
2758 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
2759 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
2761 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
2762 connState
->sslBumpMode
= Ssl::bumpNone
;
2764 connState
->fakeAConnectRequest("ssl-bump", connState
->inBuf
);
2767 /** handle a new HTTPS connection */
2769 httpsAccept(const CommAcceptCbParams
¶ms
)
2771 MasterXaction::Pointer xact
= params
.xaction
;
2772 const AnyP::PortCfgPointer s
= xact
->squidPort
;
2774 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2776 if (params
.flag
!= Comm::OK
) {
2777 // Its possible the call was still queued when the client disconnected
2778 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2782 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
2783 fd_note(params
.conn
->fd
, "client https connect");
2785 if (s
->tcp_keepalive
.enabled
) {
2786 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2788 ++incoming_sockets_accepted
;
2790 // Socket is ready, setup the connection manager to start using it
2791 ConnStateData
*connState
= Https::NewServer(xact
);
2792 AsyncJob::Start(connState
); // usually async-calls postHttpsAccept()
2796 ConnStateData::postHttpsAccept()
2798 if (port
->flags
.tunnelSslBumping
) {
2799 debugs(33, 5, "accept transparent connection: " << clientConnection
);
2801 if (!Config
.accessList
.ssl_bump
) {
2802 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
2806 // Create a fake HTTP request for ssl_bump ACL check,
2807 // using tproxy/intercept provided destination IP and port.
2808 HttpRequest
*request
= new HttpRequest();
2809 static char ip
[MAX_IPSTRLEN
];
2810 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
2811 request
->url
.host(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
2812 request
->url
.port(clientConnection
->local
.port());
2813 request
->myportname
= port
->name
;
2815 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
2816 acl_checklist
->src_addr
= clientConnection
->remote
;
2817 acl_checklist
->my_addr
= port
->s
;
2818 // Build a local AccessLogEntry to allow requiresAle() acls work
2819 acl_checklist
->al
= new AccessLogEntry
;
2820 acl_checklist
->al
->cache
.start_time
= current_time
;
2821 acl_checklist
->al
->tcpClient
= clientConnection
;
2822 acl_checklist
->al
->cache
.port
= port
;
2823 acl_checklist
->al
->cache
.caddr
= log_addr
;
2824 HTTPMSGUNLOCK(acl_checklist
->al
->request
);
2825 acl_checklist
->al
->request
= request
;
2826 HTTPMSGLOCK(acl_checklist
->al
->request
);
2827 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
2830 httpsEstablish(this, port
->secure
.staticContext
.get());
2835 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
2837 ConnStateData
* state_data
= (ConnStateData
*)(data
);
2838 state_data
->sslCrtdHandleReply(reply
);
2842 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
2845 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply
);
2849 if (reply
.result
== Helper::BrokenHelper
) {
2850 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
2851 } else if (!reply
.other().hasContent()) {
2852 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
2854 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
2855 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
2856 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
2858 if (reply
.result
!= Helper::Okay
) {
2859 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
2861 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
2862 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
2863 doPeekAndSpliceStep();
2864 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
2865 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
2867 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
2869 auto ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
2870 getSslContextDone(ctx
, true);
2876 getSslContextDone(NULL
);
2879 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
2881 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
2883 // fake certificate adaptation requires bump-server-first mode
2884 if (!sslServerBump
) {
2885 assert(port
->signingCert
.get());
2886 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2887 if (port
->signPkey
.get())
2888 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2889 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2893 // In case of an error while connecting to the secure server, use a fake
2894 // trusted certificate, with no mimicked fields and no adaptation
2895 // algorithms. There is nothing we can mimic so we want to minimize the
2896 // number of warnings the user will have to see to get to the error page.
2897 assert(sslServerBump
->entry
);
2898 if (sslServerBump
->entry
->isEmpty()) {
2899 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
2900 certProperties
.mimicCert
.resetAndLock(mimicCert
);
2902 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
2903 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
2904 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors());
2906 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
2907 // If the algorithm already set, then ignore it.
2908 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
2909 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
2910 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
2913 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
2914 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
2915 const char *param
= ca
->param
;
2917 // For parameterless CN adaptation, use hostname from the
2919 if (ca
->alg
== Ssl::algSetCommonName
) {
2921 param
= sslConnectHostOrIp
.termedBuf();
2922 certProperties
.commonName
= param
;
2923 certProperties
.setCommonName
= true;
2924 } else if (ca
->alg
== Ssl::algSetValidAfter
)
2925 certProperties
.setValidAfter
= true;
2926 else if (ca
->alg
== Ssl::algSetValidBefore
)
2927 certProperties
.setValidBefore
= true;
2929 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
2930 alg
<< " param: " << (param
? param
: "-"));
2934 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
2935 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
2936 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
2937 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
2941 } else {// if (!sslServerBump->entry->isEmpty())
2942 // Use trusted certificate for a Squid-generated error
2943 // or the user would have to add a security exception
2944 // just to see the error page. We will close the connection
2945 // so that the trust is not extended to non-Squid content.
2946 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2949 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
2951 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
2952 assert(port
->untrustedSigningCert
.get());
2953 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
2954 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
2956 assert(port
->signingCert
.get());
2957 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
2959 if (port
->signPkey
.get())
2960 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
2962 signAlgorithm
= certProperties
.signAlgorithm
;
2964 certProperties
.signHash
= Ssl::DefaultSignHash
;
2968 ConnStateData::getSslContextStart()
2970 // XXX starting SSL with a pipeline of requests still waiting for non-SSL replies?
2971 assert(pipeline
.count() < 2); // the CONNECT is okay for now. Anything else is a bug.
2972 pipeline
.terminateAll(0);
2973 /* careful: terminateAll(0) above frees request, host, etc. */
2975 if (port
->generateHostCertificates
) {
2976 Ssl::CertificateProperties certProperties
;
2977 buildSslCertGenerationParams(certProperties
);
2978 sslBumpCertKey
= certProperties
.dbKey().c_str();
2979 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
2981 // Disable caching for bumpPeekAndSplice mode
2982 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
2983 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
2984 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
2985 Security::ContextPtr dynCtx
= nullptr;
2986 Security::ContextPointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : nullptr;
2987 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
2988 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
2989 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
2990 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
2991 getSslContextDone(dynCtx
);
2994 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
2996 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
2999 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3005 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3006 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3007 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3008 request_message
.composeRequest(certProperties
);
3009 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3010 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3012 } catch (const std::exception
&e
) {
3013 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3014 "request for " << certProperties
.commonName
<<
3015 " certificate: " << e
.what() << "; will now block to " <<
3016 "generate that certificate.");
3017 // fall through to do blocking in-process generation.
3019 #endif // USE_SSL_CRTD
3021 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3022 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3023 doPeekAndSpliceStep();
3024 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3025 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3026 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3028 auto dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3029 getSslContextDone(dynCtx
, true);
3033 getSslContextDone(NULL
);
3037 ConnStateData::getSslContextDone(Security::ContextPtr sslContext
, bool isNew
)
3039 // Try to add generated ssl context to storage.
3040 if (port
->generateHostCertificates
&& isNew
) {
3042 if (signAlgorithm
== Ssl::algSignTrusted
) {
3043 // Add signing certificate to the certificates chain
3044 X509
*cert
= port
->signingCert
.get();
3045 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3046 // increase the certificate lock
3047 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3049 const int ssl_error
= ERR_get_error();
3050 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3052 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3054 //else it is self-signed or untrusted do not attrach any certificate
3056 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3057 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3059 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Security::ContextPointer(sslContext
))) {
3060 // If it is not in storage delete after using. Else storage deleted it.
3061 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3064 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3068 // If generated ssl context = NULL, try to use static ssl context.
3070 if (!port
->secure
.staticContext
) {
3071 debugs(83, DBG_IMPORTANT
, "Closing " << clientConnection
->remote
<< " as lacking TLS context");
3072 clientConnection
->close();
3075 debugs(33, 5, "Using static TLS context.");
3076 sslContext
= port
->secure
.staticContext
.get();
3080 if (!httpsCreate(clientConnection
, sslContext
))
3083 // bumped intercepted conns should already have Config.Timeout.request set
3084 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3085 // to make sure the connection does not get stuck on non-SSL clients.
3086 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3087 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3088 this, ConnStateData::requestTimeout
);
3089 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3091 // Disable the client read handler until CachePeer selection is complete
3092 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3093 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3094 switchedToHttps_
= true;
3098 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3100 assert(!switchedToHttps_
);
3102 sslConnectHostOrIp
= request
->url
.host();
3103 resetSslCommonName(request
->url
.host());
3105 // We are going to read new request
3106 flags
.readMore
= true;
3107 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3109 // keep version major.minor details the same.
3110 // but we are now performing the HTTPS handshake traffic
3111 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
3113 // If sslServerBump is set, then we have decided to deny CONNECT
3114 // and now want to switch to SSL to send the error to the client
3115 // without even peeking at the origin server certificate.
3116 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3117 request
->flags
.sslPeek
= true;
3118 sslServerBump
= new Ssl::ServerBump(request
);
3120 // will call httpsPeeked() with certificate and connection, eventually
3121 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3123 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
3124 request
->flags
.sslPeek
= true;
3125 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
3126 startPeekAndSplice();
3130 // otherwise, use sslConnectHostOrIp
3131 getSslContextStart();
3135 ConnStateData::spliceOnError(const err_type err
)
3137 if (Config
.accessList
.on_unsupported_protocol
) {
3138 assert(serverBump());
3139 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
3140 checklist
.requestErrorType
= err
;
3141 checklist
.conn(this);
3142 allow_t answer
= checklist
.fastCheck();
3143 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
3151 /** negotiate an SSL connection */
3153 clientPeekAndSpliceSSL(int fd
, void *data
)
3155 ConnStateData
*conn
= (ConnStateData
*)data
;
3156 auto ssl
= fd_table
[fd
].ssl
.get();
3158 debugs(83, 5, "Start peek and splice on FD " << fd
);
3161 if ((ret
= Squid_SSL_accept(conn
, clientPeekAndSpliceSSL
)) < 0)
3162 debugs(83, 2, "SSL_accept failed.");
3164 BIO
*b
= SSL_get_rbio(ssl
);
3166 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3168 const err_type err
= bio
->noSslClient() ? ERR_PROTOCOL_UNKNOWN
: ERR_SECURE_ACCEPT_FAIL
;
3169 if (!conn
->spliceOnError(err
))
3170 conn
->clientConnection
->close();
3174 if (!bio
->rBufData().isEmpty() > 0)
3175 conn
->receivedFirstByte();
3177 if (bio
->gotHello()) {
3178 if (conn
->serverBump()) {
3179 Ssl::Bio::sslFeatures
const &features
= bio
->receivedHelloFeatures();
3180 if (!features
.serverName
.isEmpty()) {
3181 conn
->serverBump()->clientSni
= features
.serverName
;
3182 conn
->resetSslCommonName(features
.serverName
.c_str());
3186 debugs(83, 5, "I got hello. Start forwarding the request!!! ");
3187 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3188 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
3189 conn
->startPeekAndSpliceDone();
3194 void ConnStateData::startPeekAndSplice()
3196 // will call httpsPeeked() with certificate and connection, eventually
3197 auto unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
3198 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
3200 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
3203 // commSetConnTimeout() was called for this request before we switched.
3204 // Fix timeout to request_start_timeout
3205 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3206 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3207 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3208 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
3209 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
3210 // a bumbed "connect" request on non transparent port.
3211 receivedFirstByte_
= false;
3213 // Disable the client read handler until CachePeer selection is complete
3214 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3215 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientPeekAndSpliceSSL
, this, 0);
3216 switchedToHttps_
= true;
3218 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3219 BIO
*b
= SSL_get_rbio(ssl
);
3220 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3224 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
3226 ConnStateData
*connState
= (ConnStateData
*) data
;
3228 // if the connection is closed or closing, just return.
3229 if (!connState
->isOpen())
3232 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
3233 assert(connState
->serverBump());
3234 Ssl::BumpMode bumpAction
;
3235 if (answer
== ACCESS_ALLOWED
) {
3236 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
3238 bumpAction
= Ssl::bumpSplice
;
3240 connState
->serverBump()->act
.step2
= bumpAction
;
3241 connState
->sslBumpMode
= bumpAction
;
3243 if (bumpAction
== Ssl::bumpTerminate
) {
3244 connState
->clientConnection
->close();
3245 } else if (bumpAction
!= Ssl::bumpSplice
) {
3246 connState
->startPeekAndSpliceDone();
3248 connState
->splice();
3252 ConnStateData::splice()
3254 // normally we can splice here, because we just got client hello message
3255 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3257 //retrieve received TLS client information
3258 clientConnection
->tlsNegotiations()->fillWith(ssl
);
3260 BIO
*b
= SSL_get_rbio(ssl
);
3261 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3262 SBuf
const &rbuf
= bio
->rBufData();
3263 debugs(83,5, "Bio for " << clientConnection
<< " read " << rbuf
.length() << " helo bytes");
3265 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
3266 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
3268 if (transparent()) {
3269 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
3270 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
3271 transferProtocol
= Http::ProtocolVersion();
3272 // XXX: copy from MemBuf reallocates, not a regression since old code did too
3273 fakeAConnectRequest("intercepted TLS spliced", rbuf
);
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 // inBuf still has the "CONNECT ..." request data, reset it to SSL hello message
3281 Http::StreamPointer context
= pipeline
.front();
3282 ClientHttpRequest
*http
= context
->http
;
3288 ConnStateData::startPeekAndSpliceDone()
3290 // This is the Step2 of the SSL bumping
3291 assert(sslServerBump
);
3292 Http::StreamPointer context
= pipeline
.front();
3293 ClientHttpRequest
*http
= context
? context
->http
: NULL
;
3295 if (sslServerBump
->step
== Ssl::bumpStep1
) {
3296 sslServerBump
->step
= Ssl::bumpStep2
;
3297 // Run a accessList check to check if want to splice or continue bumping
3299 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
3300 acl_checklist
->al
= http
? http
->al
: NULL
;
3301 //acl_checklist->src_addr = params.conn->remote;
3302 //acl_checklist->my_addr = s->s;
3303 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpNone
));
3304 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpClientFirst
));
3305 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpServerFirst
));
3306 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
3310 FwdState::Start(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw(), http
? http
->al
: NULL
);
3314 ConnStateData::doPeekAndSpliceStep()
3316 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3317 BIO
*b
= SSL_get_rbio(ssl
);
3319 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3321 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
3324 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
3325 switchedToHttps_
= true;
3329 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3331 Must(sslServerBump
!= NULL
);
3333 if (Comm::IsConnOpen(serverConnection
)) {
3334 pinConnection(serverConnection
, NULL
, NULL
, false);
3336 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3338 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3340 // copy error detail from bump-server-first request to CONNECT request
3341 if (!pipeline
.empty() && pipeline
.front()->http
!= nullptr && pipeline
.front()->http
->request
)
3342 pipeline
.front()->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3345 getSslContextStart();
3348 #endif /* USE_OPENSSL */
3351 ConnStateData::fakeAConnectRequest(const char *reason
, const SBuf
&payload
)
3353 // fake a CONNECT request to force connState to tunnel
3356 if (serverBump() && !serverBump()->clientSni
.isEmpty()) {
3357 connectHost
.assign(serverBump()->clientSni
);
3358 if (clientConnection
->local
.port() > 0)
3359 connectHost
.appendf(":%d",clientConnection
->local
.port());
3363 static char ip
[MAX_IPSTRLEN
];
3364 connectHost
.assign(clientConnection
->local
.toUrl(ip
, sizeof(ip
)));
3366 // Pre-pend this fake request to the TLS bits already in the buffer
3368 retStr
.append("CONNECT ");
3369 retStr
.append(connectHost
);
3370 retStr
.append(" HTTP/1.1\r\nHost: ");
3371 retStr
.append(connectHost
);
3372 retStr
.append("\r\n\r\n");
3373 retStr
.append(payload
);
3375 bool ret
= handleReadData();
3377 ret
= clientParseRequests();
3380 debugs(33, 2, "Failed to start fake CONNECT request for " << reason
<< " connection: " << clientConnection
);
3381 clientConnection
->close();
3385 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3387 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3389 if (!Comm::IsConnOpen(c
)) {
3390 Must(NHttpSockets
> 0); // we tried to open some
3391 --NHttpSockets
; // there will be fewer sockets than planned
3392 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3394 if (!NHttpSockets
) // we could not open any listen sockets at all
3395 fatalf("Unable to open %s",FdNote(portType
));
3402 /// find any unused HttpSockets[] slot and store fd there or return false
3404 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
3407 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
3408 if ((found
= HttpSockets
[i
] < 0))
3409 HttpSockets
[i
] = conn
->fd
;
3415 clientHttpConnectionsOpen(void)
3417 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3418 const char *scheme
= AnyP::UriScheme(s
->transport
.protocol
).c_str();
3420 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
3421 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many '" << scheme
<< "_port' lines.");
3422 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
3427 if (s
->flags
.tunnelSslBumping
) {
3428 if (!Config
.accessList
.ssl_bump
) {
3429 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme
<< "_port " << s
->s
);
3430 s
->flags
.tunnelSslBumping
= false;
3432 if (!s
->secure
.staticContext
&& !s
->generateHostCertificates
) {
3433 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at " << scheme
<< "_port " << s
->s
<< " due to TLS initialization failure.");
3434 s
->flags
.tunnelSslBumping
= false;
3435 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
)
3436 s
->secure
.encryptTransport
= false;
3438 if (s
->flags
.tunnelSslBumping
) {
3439 // Create ssl_ctx cache for this port.
3440 auto sz
= s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
;
3441 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, sz
);
3445 if (s
->secure
.encryptTransport
&& !s
->secure
.staticContext
) {
3446 debugs(1, DBG_CRITICAL
, "ERROR: Ignoring " << scheme
<< "_port " << s
->s
<< " due to TLS context initialization failure.");
3451 // Fill out a Comm::Connection which IPC will open as a listener for us
3452 // then pass back when active so we can start a TcpAcceptor subscription.
3453 s
->listenConn
= new Comm::Connection
;
3454 s
->listenConn
->local
= s
->s
;
3456 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3457 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3459 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3460 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
) {
3461 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
3462 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
3463 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3465 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
3466 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
3467 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
3470 } else if (s
->transport
.protocol
== AnyP::PROTO_HTTPS
) {
3471 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
3472 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
3473 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3475 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
3476 ListeningStartedDialer(&clientListenerConnectionOpened
,
3477 s
, Ipc::fdnHttpsSocket
, sub
));
3478 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
3482 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
3488 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
3490 // Fill out a Comm::Connection which IPC will open as a listener for us
3491 port
->listenConn
= new Comm::Connection
;
3492 port
->listenConn
->local
= port
->s
;
3493 port
->listenConn
->flags
=
3495 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3496 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3498 // route new connections to subCall
3499 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3500 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3501 AsyncCall::Pointer listenCall
=
3502 asyncCall(33, 2, "clientListenerConnectionOpened",
3503 ListeningStartedDialer(&clientListenerConnectionOpened
,
3504 port
, fdNote
, sub
));
3505 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
3507 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
3508 HttpSockets
[NHttpSockets
] = -1;
3512 /// process clientHttpConnectionsOpen result
3514 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
3518 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
3521 Must(Comm::IsConnOpen(s
->listenConn
));
3523 // TCP: setup a job to handle accept() with subscribed handler
3524 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
3526 debugs(1, DBG_IMPORTANT
, "Accepting " <<
3527 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
3528 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
3529 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
3530 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
3531 << FdNote(portTypeNote
) << " connections at "
3534 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
3538 clientOpenListenSockets(void)
3540 clientHttpConnectionsOpen();
3541 Ftp::StartListening();
3543 if (NHttpSockets
< 1)
3544 fatal("No HTTP, HTTPS, or FTP ports configured");
3548 clientConnectionsClose()
3550 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3551 if (s
->listenConn
!= NULL
) {
3552 debugs(1, DBG_IMPORTANT
, "Closing HTTP(S) port " << s
->listenConn
->local
);
3553 s
->listenConn
->close();
3554 s
->listenConn
= NULL
;
3558 Ftp::StopListening();
3560 // TODO see if we can drop HttpSockets array entirely */
3561 for (int i
= 0; i
< NHttpSockets
; ++i
) {
3562 HttpSockets
[i
] = -1;
3569 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
3571 const char *vary
= request
->vary_headers
;
3572 int has_vary
= entry
->getReply()->header
.has(Http::HdrType::VARY
);
3573 #if X_ACCELERATOR_VARY
3576 entry
->getReply()->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
3579 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
3581 /* Oops... something odd is going on here.. */
3582 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
3583 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3584 safe_free(request
->vary_headers
);
3589 /* This is not a varying object */
3593 /* virtual "vary" object found. Calculate the vary key and
3594 * continue the search
3596 vary
= httpMakeVaryMark(request
, entry
->getReply());
3599 request
->vary_headers
= xstrdup(vary
);
3602 /* Ouch.. we cannot handle this kind of variance */
3603 /* XXX This cannot really happen, but just to be complete */
3608 vary
= httpMakeVaryMark(request
, entry
->getReply());
3611 request
->vary_headers
= xstrdup(vary
);
3615 /* Ouch.. we cannot handle this kind of variance */
3616 /* XXX This cannot really happen, but just to be complete */
3618 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
3621 /* Oops.. we have already been here and still haven't
3622 * found the requested variant. Bail out
3624 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
3625 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3631 ACLFilledChecklist
*
3632 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
3634 ConnStateData
* conn
= http
->getConn();
3635 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
3636 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
3639 * hack for ident ACL. It needs to get full addresses, and a place to store
3640 * the ident result on persistent connections...
3642 /* connection oriented auth also needs these two lines for it's operation. */
3647 ConnStateData::transparent() const
3649 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
3653 ConnStateData::expectRequestBody(int64_t size
)
3655 bodyPipe
= new BodyPipe(this);
3657 bodyPipe
->setBodySize(size
);
3659 startDechunkingRequest();
3664 ConnStateData::mayNeedToReadMoreBody() const
3667 return 0; // request without a body or read/produced all body bytes
3669 if (!bodyPipe
->bodySizeKnown())
3670 return -1; // probably need to read more, but we cannot be sure
3672 const int64_t needToProduce
= bodyPipe
->unproducedSize();
3673 const int64_t haveAvailable
= static_cast<int64_t>(inBuf
.length());
3675 if (needToProduce
<= haveAvailable
)
3676 return 0; // we have read what we need (but are waiting for pipe space)
3678 return needToProduce
- haveAvailable
;
3682 ConnStateData::stopReceiving(const char *error
)
3684 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
3685 "; old sending error: " <<
3686 (stoppedSending() ? stoppedSending_
: "none"));
3688 if (const char *oldError
= stoppedReceiving()) {
3689 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
3690 return; // nothing has changed as far as this connection is concerned
3693 stoppedReceiving_
= error
;
3695 if (const char *sendError
= stoppedSending()) {
3696 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
3697 clientConnection
->close();
3702 ConnStateData::expectNoForwarding()
3704 if (bodyPipe
!= NULL
) {
3705 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
3706 bodyPipe
->expectNoConsumption();
3710 /// initialize dechunking state
3712 ConnStateData::startDechunkingRequest()
3714 Must(bodyPipe
!= NULL
);
3715 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
3716 assert(!bodyParser
);
3717 bodyParser
= new Http1::TeChunkedParser
;
3720 /// put parsed content into input buffer and clean up
3722 ConnStateData::finishDechunkingRequest(bool withSuccess
)
3724 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
3726 if (bodyPipe
!= NULL
) {
3727 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
3728 BodyPipe::Pointer myPipe
= bodyPipe
;
3729 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
3730 Must(!bodyPipe
); // we rely on it being nil after we are done with body
3732 Must(myPipe
->bodySizeKnown());
3733 Http::StreamPointer context
= pipeline
.front();
3734 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
3735 context
->http
->request
->setContentLength(myPipe
->bodySize());
3743 // XXX: this is an HTTP/1-only operation
3745 ConnStateData::sendControlMsg(HttpControlMsg msg
)
3748 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
3752 // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them
3753 if (!pipeline
.empty()) {
3754 HttpReply::Pointer
rep(msg
.reply
);
3756 // remember the callback
3757 cbControlMsgSent
= msg
.cbSuccess
;
3759 typedef CommCbMemFunT
<HttpControlMsgSink
, CommIoCbParams
> Dialer
;
3760 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, HttpControlMsgSink::wroteControlMsg
);
3762 writeControlMsgAndCall(rep
.getRaw(), call
);
3766 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
3767 clientConnection
->close();
3770 /// Our close handler called by Comm when the pinned connection is closed
3772 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
3774 // FwdState might repin a failed connection sooner than this close
3775 // callback is called for the failed connection.
3776 assert(pinning
.serverConnection
== io
.conn
);
3777 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
3778 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
3779 pinning
.serverConnection
->noteClosure();
3780 unpinConnection(false);
3782 if (sawZeroReply
&& clientConnection
!= NULL
) {
3783 debugs(33, 3, "Closing client connection on pinned zero reply.");
3784 clientConnection
->close();
3790 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
3792 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
3793 pinning
.serverConnection
->fd
!= pinServer
->fd
)
3794 pinNewConnection(pinServer
, request
, aPeer
, auth
);
3797 startPinnedConnectionMonitoring();
3801 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
3803 unpinConnection(true); // closes pinned connection, if any, and resets fields
3805 pinning
.serverConnection
= pinServer
;
3807 debugs(33, 3, HERE
<< pinning
.serverConnection
);
3809 Must(pinning
.serverConnection
!= NULL
);
3811 // when pinning an SSL bumped connection, the request may be NULL
3812 const char *pinnedHost
= "[unknown]";
3814 pinning
.host
= xstrdup(request
->url
.host());
3815 pinning
.port
= request
->url
.port();
3816 pinnedHost
= pinning
.host
;
3818 pinning
.port
= pinServer
->remote
.port();
3820 pinning
.pinned
= true;
3822 pinning
.peer
= cbdataReference(aPeer
);
3823 pinning
.auth
= auth
;
3824 char stmp
[MAX_IPSTRLEN
];
3825 char desc
[FD_DESC_SZ
];
3826 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
3827 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
3828 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
3829 clientConnection
->fd
);
3830 fd_note(pinning
.serverConnection
->fd
, desc
);
3832 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3833 pinning
.closeHandler
= JobCallback(33, 5,
3834 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
3835 // remember the pinned connection so that cb does not unpin a fresher one
3836 typedef CommCloseCbParams Params
;
3837 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
3838 params
.conn
= pinning
.serverConnection
;
3839 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
3842 /// [re]start monitoring pinned connection for peer closures so that we can
3843 /// propagate them to an _idle_ client pinned to that peer
3845 ConnStateData::startPinnedConnectionMonitoring()
3847 if (pinning
.readHandler
!= NULL
)
3848 return; // already monitoring
3850 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
3851 pinning
.readHandler
= JobCallback(33, 3,
3852 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
3853 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
3857 ConnStateData::stopPinnedConnectionMonitoring()
3859 if (pinning
.readHandler
!= NULL
) {
3860 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
3861 pinning
.readHandler
= NULL
;
3867 ConnStateData::handleIdleClientPinnedTlsRead()
3869 // A ready-for-reading connection means that the TLS server either closed
3870 // the connection, sent us some unexpected HTTP data, or started TLS
3871 // renegotiations. We should close the connection except for the last case.
3873 Must(pinning
.serverConnection
!= nullptr);
3874 auto ssl
= fd_table
[pinning
.serverConnection
->fd
].ssl
.get();
3879 const int readResult
= SSL_read(ssl
, buf
, sizeof(buf
));
3881 if (readResult
> 0 || SSL_pending(ssl
) > 0) {
3882 debugs(83, 2, pinning
.serverConnection
<< " TLS application data read");
3886 switch(const int error
= SSL_get_error(ssl
, readResult
)) {
3887 case SSL_ERROR_WANT_WRITE
:
3888 debugs(83, DBG_IMPORTANT
, pinning
.serverConnection
<< " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection");
3889 // fall through to restart monitoring, for now
3890 case SSL_ERROR_NONE
:
3891 case SSL_ERROR_WANT_READ
:
3892 startPinnedConnectionMonitoring();
3896 debugs(83, 2, pinning
.serverConnection
<< " TLS error: " << error
);
3905 /// Our read handler called by Comm when the server either closes an idle pinned connection or
3906 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
3908 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
3910 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
3912 if (io
.flag
== Comm::ERR_CLOSING
)
3913 return; // close handler will clean up
3915 Must(pinning
.serverConnection
== io
.conn
);
3918 if (handleIdleClientPinnedTlsRead())
3922 const bool clientIsIdle
= pipeline
.empty();
3924 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
3925 io
.size
<< (clientIsIdle
? " with idle client" : ""));
3927 pinning
.serverConnection
->close();
3929 // If we are still sending data to the client, do not close now. When we are done sending,
3930 // ConnStateData::kick() checks pinning.serverConnection and will close.
3931 // However, if we are idle, then we must close to inform the idle client and minimize races.
3932 if (clientIsIdle
&& clientConnection
!= NULL
)
3933 clientConnection
->close();
3936 const Comm::ConnectionPointer
3937 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
3939 debugs(33, 7, HERE
<< pinning
.serverConnection
);
3942 if (!Comm::IsConnOpen(pinning
.serverConnection
))
3944 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->url
.host()) != 0)
3946 else if (request
&& pinning
.port
!= request
->url
.port())
3948 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
3950 else if (aPeer
!= pinning
.peer
)
3954 /* The pinning info is not safe, remove any pinning info */
3955 unpinConnection(true);
3958 return pinning
.serverConnection
;
3961 Comm::ConnectionPointer
3962 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
3964 debugs(33, 7, pinning
.serverConnection
);
3965 if (validatePinnedConnection(request
, aPeer
) != NULL
)
3966 stopPinnedConnectionMonitoring();
3968 return pinning
.serverConnection
; // closed if validation failed
3972 ConnStateData::unpinConnection(const bool andClose
)
3974 debugs(33, 3, HERE
<< pinning
.serverConnection
);
3977 cbdataReferenceDone(pinning
.peer
);
3979 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
3980 if (pinning
.closeHandler
!= NULL
) {
3981 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
3982 pinning
.closeHandler
= NULL
;
3985 stopPinnedConnectionMonitoring();
3987 // close the server side socket if requested
3989 pinning
.serverConnection
->close();
3990 pinning
.serverConnection
= NULL
;
3993 safe_free(pinning
.host
);
3995 pinning
.zeroReply
= false;
3997 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
3998 * connection has gone away */