2 * Copyright (C) 1996-2018 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"
123 #include "MessageDelayPools.h"
127 #include "ssl/context_storage.h"
128 #include "ssl/gadgets.h"
129 #include "ssl/helper.h"
130 #include "ssl/ProxyCerts.h"
131 #include "ssl/ServerBump.h"
132 #include "ssl/support.h"
135 // for tvSubUsec() which should be in SquidTime.h
143 #define comm_close comm_lingering_close
146 /// dials clientListenerConnectionOpened call
147 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
150 typedef void (*Handler
)(AnyP::PortCfgPointer
&portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
151 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfgPointer
&aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
152 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
154 virtual void print(std::ostream
&os
) const {
156 ", " << FdNote(portTypeNote
) << " port=" << (void*)&portCfg
<< ')';
159 virtual bool canDial(AsyncCall
&) const { return true; }
160 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
166 AnyP::PortCfgPointer portCfg
; ///< from HttpPortList
167 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
168 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
171 static void clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
173 static IOACB httpAccept
;
174 static CTCB clientLifetimeTimeout
;
176 static IDCB clientIdentDone
;
178 static int clientIsContentLengthValid(HttpRequest
* r
);
179 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
181 static void clientUpdateStatHistCounters(const LogTags
&logType
, int svc_time
);
182 static void clientUpdateStatCounters(const LogTags
&logType
);
183 static void clientUpdateHierCounters(HierarchyLogEntry
*);
184 static bool clientPingHasFinished(ping_data
const *aPing
);
185 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
186 static void ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest
, ConnStateData
* conn
);
188 char *skipLeadingSpace(char *aString
);
192 clientIdentDone(const char *ident
, void *data
)
194 ConnStateData
*conn
= (ConnStateData
*)data
;
195 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
200 clientUpdateStatCounters(const LogTags
&logType
)
202 ++statCounter
.client_http
.requests
;
204 if (logType
.isTcpHit())
205 ++statCounter
.client_http
.hits
;
207 if (logType
.oldType
== LOG_TCP_HIT
)
208 ++statCounter
.client_http
.disk_hits
;
209 else if (logType
.oldType
== LOG_TCP_MEM_HIT
)
210 ++statCounter
.client_http
.mem_hits
;
214 clientUpdateStatHistCounters(const LogTags
&logType
, int svc_time
)
216 statCounter
.client_http
.allSvcTime
.count(svc_time
);
218 * The idea here is not to be complete, but to get service times
219 * for only well-defined types. For example, we don't include
220 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
221 * (we *tried* to validate it, but failed).
224 switch (logType
.oldType
) {
226 case LOG_TCP_REFRESH_UNMODIFIED
:
227 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
230 case LOG_TCP_INM_HIT
:
231 case LOG_TCP_IMS_HIT
:
232 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
237 case LOG_TCP_MEM_HIT
:
239 case LOG_TCP_OFFLINE_HIT
:
240 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
245 case LOG_TCP_CLIENT_REFRESH_MISS
:
246 statCounter
.client_http
.missSvcTime
.count(svc_time
);
250 /* make compiler warnings go away */
256 clientPingHasFinished(ping_data
const *aPing
)
258 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
265 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
269 switch (someEntry
->code
) {
270 #if USE_CACHE_DIGESTS
275 ++ statCounter
.cd
.times_used
;
283 case FIRST_PARENT_MISS
:
285 case CLOSEST_PARENT_MISS
:
286 ++ statCounter
.icp
.times_used
;
287 i
= &someEntry
->ping
;
289 if (clientPingHasFinished(i
))
290 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
293 ++ statCounter
.icp
.query_timeouts
;
300 ++ statCounter
.netdb
.times_used
;
310 ClientHttpRequest::updateCounters()
312 clientUpdateStatCounters(logType
);
314 if (request
->errType
!= ERR_NONE
)
315 ++ statCounter
.client_http
.errors
;
317 clientUpdateStatHistCounters(logType
,
318 tvSubMsec(al
->cache
.start_time
, current_time
));
320 clientUpdateHierCounters(&request
->hier
);
324 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
327 assert(aLogEntry
!= NULL
);
329 if (Config
.onoff
.log_mime_hdrs
) {
332 request
->header
.packInto(&mb
);
333 //This is the request after adaptation or redirection
334 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
336 // the virgin request is saved to aLogEntry->request
337 if (aLogEntry
->request
) {
339 aLogEntry
->request
->header
.packInto(&mb
);
340 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
344 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
347 ah
->lastMeta
.packInto(&mb
);
348 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
356 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
358 ih
->processingTime(aLogEntry
->icap
.processingTime
);
361 aLogEntry
->http
.method
= request
->method
;
362 aLogEntry
->http
.version
= request
->http_ver
;
363 aLogEntry
->hier
= request
->hier
;
364 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
366 // Adapted request, if any, inherits and then collects all the stats, but
367 // the virgin request gets logged instead; copy the stats to log them.
368 // TODO: avoid losses by keeping these stats in a shared history object?
369 if (aLogEntry
->request
) {
370 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
371 aLogEntry
->request
->errType
= request
->errType
;
372 aLogEntry
->request
->errDetail
= request
->errDetail
;
377 ClientHttpRequest::logRequest()
379 if (!out
.size
&& logType
.oldType
== LOG_TAG_NONE
)
380 debugs(33, 5, "logging half-baked transaction: " << log_uri
);
382 al
->icp
.opcode
= ICP_INVALID
;
384 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
387 al
->http
.code
= al
->reply
->sline
.status();
388 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
389 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
390 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
391 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
394 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
396 if (loggingEntry() && loggingEntry()->mem_obj
&& loggingEntry()->objectLen() >= 0)
397 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
399 al
->http
.clientRequestSz
.header
= req_sz
;
400 // the virgin request is saved to al->request
401 if (al
->request
&& al
->request
->body_pipe
)
402 al
->http
.clientRequestSz
.payloadData
= al
->request
->body_pipe
->producedSize();
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
);
418 /* This is broken. Fails if the connection has been closed. Needs
419 * to snarf the ssl details some place earlier..
421 if (getConn() != NULL
)
422 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
426 /* Add notes (if we have a request to annotate) */
429 for (auto h
: Config
.notes
) {
430 if (h
->match(request
, al
->reply
, NULL
, matched
)) {
431 request
->notes()->add(h
->key(), matched
);
432 debugs(33, 3, h
->key() << " " << matched
);
435 // The al->notes and request->notes must point to the same object.
436 al
->syncNotes(request
);
439 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
441 checklist
.reply
= al
->reply
;
442 HTTPMSGLOCK(checklist
.reply
);
446 HTTPMSGUNLOCK(al
->adapted_request
);
447 al
->adapted_request
= request
;
448 HTTPMSGLOCK(al
->adapted_request
);
450 // no need checklist.syncAle(): already synced
452 accessLogLog(al
, &checklist
);
454 bool updatePerformanceCounters
= true;
455 if (Config
.accessList
.stats_collection
) {
456 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
459 statsCheck
.reply
= al
->reply
;
460 HTTPMSGLOCK(statsCheck
.reply
);
462 updatePerformanceCounters
= statsCheck
.fastCheck().allowed();
465 if (updatePerformanceCounters
) {
469 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
470 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
475 ClientHttpRequest::freeResources()
479 safe_free(redirect
.location
);
480 range_iter
.boundary
.clean();
481 HTTPMSGUNLOCK(request
);
483 if (client_stream
.tail
)
484 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
488 httpRequestFree(void *data
)
490 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
491 assert(http
!= NULL
);
495 /* This is a handler normally called by comm_close() */
496 void ConnStateData::connStateClosed(const CommCloseCbParams
&)
498 deleteThis("ConnStateData::connStateClosed");
503 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
507 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
513 // clobered with self-pointer
514 // NP: something nasty is going on in Squid, but harmless.
516 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
521 * Connection-auth relies on a single set of credentials being preserved
522 * for all requests on a connection once they have been setup.
523 * There are several things which need to happen to preserve security
524 * when connection-auth credentials change unexpectedly or are unset.
526 * 1) auth helper released from any active state
528 * They can only be reserved by a handshake process which this
529 * connection can now never complete.
530 * This prevents helpers hanging when their connections close.
532 * 2) pinning is expected to be removed and server conn closed
534 * The upstream link is authenticated with the same credentials.
535 * Expecting the same level of consistency we should have received.
536 * This prevents upstream being faced with multiple or missing
537 * credentials after authentication.
538 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
539 * we just trigger that cleanup here via comm_reset_close() or
540 * ConnStateData::stopReceiving()
542 * 3) the connection needs to close.
544 * This prevents attackers injecting requests into a connection,
545 * or gateways wrongly multiplexing users into a single connection.
547 * When credentials are missing closure needs to follow an auth
548 * challenge for best recovery by the client.
550 * When credentials change there is nothing we can do but abort as
551 * fast as possible. Sending TCP RST instead of an HTTP response
552 * is the best-case action.
555 // clobbered with nul-pointer
557 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
558 auth_
->releaseAuthServer();
560 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
561 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
562 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
563 stopReceiving("connection-auth removed");
567 // clobbered with alternative credentials
569 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
570 auth_
->releaseAuthServer();
572 // this is a fatal type of problem.
573 // Close the connection immediately with TCP RST to abort all traffic flow
574 comm_reset_close(clientConnection
);
582 // cleans up before destructor is called
584 ConnStateData::swanSong()
586 debugs(33, 2, HERE
<< clientConnection
);
589 flags
.readMore
= false;
590 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
591 pipeline
.terminateAll(0);
593 // XXX: Closing pinned conn is too harsh: The Client may want to continue!
594 unpinConnection(true);
596 Server::swanSong(); // closes the client connection
599 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
600 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
603 flags
.swanSang
= true;
607 ConnStateData::isOpen() const
609 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
610 Comm::IsConnOpen(clientConnection
) &&
611 !fd_table
[clientConnection
->fd
].closing();
614 ConnStateData::~ConnStateData()
616 debugs(33, 3, HERE
<< clientConnection
);
619 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
622 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
624 if (bodyPipe
!= NULL
)
625 stopProducingFor(bodyPipe
, false);
627 delete bodyParser
; // TODO: pool
630 delete sslServerBump
;
635 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
636 * This is the client-side persistent connection flag. We need
637 * to set this relatively early in the request processing
638 * to handle hacks for broken servers and clients.
641 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
643 HttpRequest
*request
= http
->request
;
645 debugs(33, 3, "http_ver = " << request
->http_ver
);
646 debugs(33, 3, "method = " << request
->method
);
648 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
649 request
->flags
.proxyKeepalive
= request
->persistent();
652 /// checks body length of non-chunked requests
654 clientIsContentLengthValid(HttpRequest
* r
)
656 // No Content-Length means this request just has no body, but conflicting
657 // Content-Lengths mean a message framing error (RFC 7230 Section 3.3.3 #4).
658 if (r
->header
.conflictingContentLength())
661 switch (r
->method
.id()) {
663 case Http::METHOD_GET
:
665 case Http::METHOD_HEAD
:
666 /* We do not want to see a request entity on GET/HEAD requests */
667 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
670 /* For other types of requests we don't care */
678 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
680 if (Config
.maxRequestBodySize
&&
681 bodyLength
> Config
.maxRequestBodySize
)
682 return 1; /* too large */
688 ClientHttpRequest::multipartRangeRequest() const
690 return request
->multipartRangeRequest();
694 clientPackTermBound(String boundary
, MemBuf
*mb
)
696 mb
->appendf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
697 debugs(33, 6, "buf offset: " << mb
->size
);
701 clientPackRangeHdr(const HttpReplyPointer
&rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
703 HttpHeader
hdr(hoReply
);
708 debugs(33, 5, "appending boundary: " << boundary
);
709 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
710 mb
->appendf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
712 /* stuff the header with required entries and pack it */
714 if (rep
->header
.has(Http::HdrType::CONTENT_TYPE
))
715 hdr
.putStr(Http::HdrType::CONTENT_TYPE
, rep
->header
.getStr(Http::HdrType::CONTENT_TYPE
));
717 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
722 /* append <crlf> (we packed a header, not a reply) */
723 mb
->append("\r\n", 2);
726 /** returns expected content length for multi-range replies
727 * note: assumes that httpHdrRangeCanonize has already been called
728 * warning: assumes that HTTP headers for individual ranges at the
729 * time of the actuall assembly will be exactly the same as
730 * the headers when clientMRangeCLen() is called */
732 ClientHttpRequest::mRangeCLen()
740 HttpHdrRange::iterator pos
= request
->range
->begin();
742 while (pos
!= request
->range
->end()) {
743 /* account for headers for this range */
745 clientPackRangeHdr(memObject()->getReply(),
746 *pos
, range_iter
.boundary
, &mb
);
749 /* account for range content */
750 clen
+= (*pos
)->length
;
752 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
756 /* account for the terminating boundary */
759 clientPackTermBound(range_iter
.boundary
, &mb
);
769 * generates a "unique" boundary string for multipart responses
770 * the caller is responsible for cleaning the string */
772 ClientHttpRequest::rangeBoundaryStr() const
775 String
b(APP_FULLNAME
);
777 key
= storeEntry()->getMD5Text();
778 b
.append(key
, strlen(key
));
783 * Write a chunk of data to a client socket. If the reply is present,
784 * send the reply headers down the wire too, and clean them up when
787 * The request is one backed by a connection, not an internal request.
788 * data context is not NULL
789 * There are no more entries in the stream chain.
792 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
793 HttpReply
* rep
, StoreIOBuffer receivedData
)
795 // dont tryt to deliver if client already ABORTED
796 if (!http
->getConn() || !cbdataReferenceValid(http
->getConn()) || !Comm::IsConnOpen(http
->getConn()->clientConnection
))
799 /* Test preconditions */
800 assert(node
!= NULL
);
801 PROF_start(clientSocketRecipient
);
802 /* TODO: handle this rather than asserting
803 * - it should only ever happen if we cause an abort and
804 * the callback chain loops back to here, so we can simply return.
805 * However, that itself shouldn't happen, so it stays as an assert for now.
807 assert(cbdataReferenceValid(node
));
808 assert(node
->node
.next
== NULL
);
809 Http::StreamPointer context
= dynamic_cast<Http::Stream
*>(node
->data
.getRaw());
810 assert(context
!= NULL
);
812 /* TODO: check offset is what we asked for */
814 // TODO: enforces HTTP/1 MUST on pipeline order, but is irrelevant to HTTP/2
815 if (context
!= http
->getConn()->pipeline
.front())
816 context
->deferRecipientForLater(node
, rep
, receivedData
);
817 else if (http
->getConn()->cbControlMsgSent
) // 1xx to the user is pending
818 context
->deferRecipientForLater(node
, rep
, receivedData
);
820 http
->getConn()->handleReply(rep
, receivedData
);
822 PROF_stop(clientSocketRecipient
);
826 * Called when a downstream node is no longer interested in
827 * our data. As we are a terminal node, this means on aborts
831 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
833 /* Test preconditions */
834 assert(node
!= NULL
);
835 /* TODO: handle this rather than asserting
836 * - it should only ever happen if we cause an abort and
837 * the callback chain loops back to here, so we can simply return.
838 * However, that itself shouldn't happen, so it stays as an assert for now.
840 assert(cbdataReferenceValid(node
));
841 /* Set null by ContextFree */
842 assert(node
->node
.next
== NULL
);
843 /* this is the assert discussed above */
844 assert(NULL
== dynamic_cast<Http::Stream
*>(node
->data
.getRaw()));
845 /* We are only called when the client socket shutsdown.
846 * Tell the prev pipeline member we're finished
848 clientStreamDetach(node
, http
);
852 ConnStateData::readNextRequest()
854 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
856 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
858 * Set the timeout BEFORE calling readSomeData().
860 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
861 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
862 TimeoutDialer
, this, ConnStateData::requestTimeout
);
863 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
866 /** Please don't do anything with the FD past here! */
870 ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest
, ConnStateData
* conn
)
872 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
874 /** If the client stream is waiting on a socket write to occur, then */
876 if (deferredRequest
->flags
.deferred
) {
877 /** NO data is allowed to have been sent. */
878 assert(deferredRequest
->http
->out
.size
== 0);
880 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
881 deferredRequest
->http
,
882 deferredRequest
->deferredparams
.rep
,
883 deferredRequest
->deferredparams
.queuedBuffer
);
886 /** otherwise, the request is still active in a callbacksomewhere,
892 ConnStateData::kick()
894 if (!Comm::IsConnOpen(clientConnection
)) {
895 debugs(33, 2, clientConnection
<< " Connection was closed");
899 if (pinning
.pinned
&& !Comm::IsConnOpen(pinning
.serverConnection
)) {
900 debugs(33, 2, clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
901 clientConnection
->close();
906 * We are done with the response, and we are either still receiving request
907 * body (early response!) or have already stopped receiving anything.
909 * If we are still receiving, then clientParseRequest() below will fail.
910 * (XXX: but then we will call readNextRequest() which may succeed and
911 * execute a smuggled request as we are not done with the current request).
913 * If we stopped because we got everything, then try the next request.
915 * If we stopped receiving because of an error, then close now to avoid
916 * getting stuck and to prevent accidental request smuggling.
919 if (const char *reason
= stoppedReceiving()) {
920 debugs(33, 3, "closing for earlier request error: " << reason
);
921 clientConnection
->close();
926 * Attempt to parse a request from the request buffer.
927 * If we've been fed a pipelined request it may already
928 * be in our read buffer.
931 * This needs to fall through - if we're unlucky and parse the _last_ request
932 * from our read buffer we may never re-register for another client read.
935 if (clientParseRequests()) {
936 debugs(33, 3, clientConnection
<< ": parsed next request from buffer");
940 * Either we need to kick-start another read or, if we have
941 * a half-closed connection, kill it after the last request.
942 * This saves waiting for half-closed connections to finished being
943 * half-closed _AND_ then, sometimes, spending "Timeout" time in
944 * the keepalive "Waiting for next request" state.
946 if (commIsHalfClosed(clientConnection
->fd
) && pipeline
.empty()) {
947 debugs(33, 3, "half-closed client with no pending requests, closing");
948 clientConnection
->close();
953 * At this point we either have a parsed request (which we've
954 * kicked off the processing for) or not. If we have a deferred
955 * request (parsed but deferred for pipeling processing reasons)
956 * then look at processing it. If not, simply kickstart
959 Http::StreamPointer deferredRequest
= pipeline
.front();
960 if (deferredRequest
!= nullptr) {
961 debugs(33, 3, clientConnection
<< ": calling PushDeferredIfNeeded");
962 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, this);
963 } else if (flags
.readMore
) {
964 debugs(33, 3, clientConnection
<< ": calling readNextRequest()");
967 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
968 debugs(33, DBG_IMPORTANT
, MYNAME
<< "abandoning " << clientConnection
);
973 ConnStateData::stopSending(const char *error
)
975 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
976 "; old receiving error: " <<
977 (stoppedReceiving() ? stoppedReceiving_
: "none"));
979 if (const char *oldError
= stoppedSending()) {
980 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
981 return; // nothing has changed as far as this connection is concerned
983 stoppedSending_
= error
;
985 if (!stoppedReceiving()) {
986 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
987 debugs(33, 5, HERE
<< "must still read " << expecting
<<
988 " request body bytes with " << inBuf
.length() << " unused");
989 return; // wait for the request receiver to finish reading
993 clientConnection
->close();
997 ConnStateData::afterClientWrite(size_t size
)
999 if (pipeline
.empty())
1002 auto ctx
= pipeline
.front();
1004 statCounter
.client_http
.kbytes_out
+= size
;
1005 if (ctx
->http
->logType
.isTcpHit())
1006 statCounter
.client_http
.hit_kbytes_out
+= size
;
1008 ctx
->writeComplete(size
);
1012 ConnStateData::abortRequestParsing(const char *const uri
)
1014 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1015 http
->req_sz
= inBuf
.length();
1016 http
->uri
= xstrdup(uri
);
1017 setLogUri (http
, uri
);
1018 auto *context
= new Http::Stream(clientConnection
, http
);
1019 StoreIOBuffer tempBuffer
;
1020 tempBuffer
.data
= context
->reqbuf
;
1021 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1022 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1023 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1024 clientSocketDetach
, context
, tempBuffer
);
1029 ConnStateData::startShutdown()
1031 // RegisteredRunner API callback - Squid has been shut down
1033 // if connection is idle terminate it now,
1034 // otherwise wait for grace period to end
1035 if (pipeline
.empty())
1040 ConnStateData::endingShutdown()
1042 // RegisteredRunner API callback - Squid shutdown grace period is over
1044 // force the client connection to close immediately
1045 // swanSong() in the close handler will cleanup.
1046 if (Comm::IsConnOpen(clientConnection
))
1047 clientConnection
->close();
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 const SBuf
&scheme
= AnyP::UriScheme(conn
->transferProtocol
.protocol
).image();
1223 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s" SQUIDSBUFPH
, SQUIDSBUFPRINT(scheme
), host
, SQUIDSBUFPRINT(url
));
1224 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
1225 } else if (conn
->port
->defaultsite
/* && !vhost */) {
1226 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
1227 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1228 strlen(conn
->port
->defaultsite
);
1229 http
->uri
= (char *)xcalloc(url_sz
, 1);
1233 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
1235 const SBuf
&scheme
= AnyP::UriScheme(conn
->transferProtocol
.protocol
).image();
1236 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s%s" SQUIDSBUFPH
,
1237 SQUIDSBUFPRINT(scheme
), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
1238 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
1239 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
1240 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
1241 /* Put the local socket IP address as the hostname, with whatever vport we found */
1242 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1243 http
->uri
= (char *)xcalloc(url_sz
, 1);
1244 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1245 const SBuf
&scheme
= AnyP::UriScheme(conn
->transferProtocol
.protocol
).image();
1246 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s:%d" SQUIDSBUFPH
,
1247 SQUIDSBUFPRINT(scheme
), ipbuf
, vport
, SQUIDSBUFPRINT(url
));
1248 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
1253 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1255 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
1256 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
1257 return; /* already in good shape */
1259 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1261 if (const char *host
= hp
->getHeaderField("Host")) {
1262 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1264 http
->uri
= (char *)xcalloc(url_sz
, 1);
1265 const SBuf
&scheme
= AnyP::UriScheme(conn
->transferProtocol
.protocol
).image();
1266 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s" SQUIDSBUFPH
,
1267 SQUIDSBUFPRINT(scheme
), host
, SQUIDSBUFPRINT(hp
->requestUri()));
1268 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
1270 /* Put the local socket IP address as the hostname. */
1271 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1272 http
->uri
= (char *)xcalloc(url_sz
, 1);
1273 static char ipbuf
[MAX_IPSTRLEN
];
1274 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1275 const SBuf
&scheme
= AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).image();
1276 snprintf(http
->uri
, url_sz
, SQUIDSBUFPH
"://%s:%d" SQUIDSBUFPH
,
1277 SQUIDSBUFPRINT(scheme
),
1278 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SQUIDSBUFPRINT(hp
->requestUri()));
1279 debugs(33, 5, "TRANSPARENT REWRITE: " << http
->uri
);
1283 /** Parse an HTTP request
1285 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
1286 * to 1 if the request was correctly parsed.
1287 * \param[in] csd a ConnStateData. The caller must make sure it is not null
1288 * \param[in] hp an Http1::RequestParser
1289 * \param[out] mehtod_p will be set as a side-effect of the parsing.
1290 * Pointed-to value will be set to Http::METHOD_NONE in case of
1292 * \param[out] http_ver will be set as a side-effect of the parsing
1293 * \return NULL on incomplete requests,
1294 * a Http::Stream on success or failure.
1297 parseHttpRequest(ConnStateData
*csd
, const Http1::RequestParserPointer
&hp
)
1299 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
1301 const bool parsedOk
= hp
->parse(csd
->inBuf
);
1303 // sync the buffers after parsing.
1304 csd
->inBuf
= hp
->remaining();
1306 if (hp
->needsMoreData()) {
1307 debugs(33, 5, "Incomplete request, waiting for end of request line");
1311 if (csd
->mayTunnelUnsupportedProto()) {
1312 csd
->preservedClientData
= hp
->parsed();
1313 csd
->preservedClientData
.append(csd
->inBuf
);
1318 hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
||
1319 hp
->parseStatusCode
== Http::scUriTooLong
;
1320 auto result
= csd
->abortRequestParsing(
1321 tooBig
? "error:request-too-large" : "error:invalid-request");
1322 // assume that remaining leftovers belong to this bad request
1323 if (!csd
->inBuf
.isEmpty())
1324 csd
->consumeInput(csd
->inBuf
.length());
1329 /* We know the whole request is in parser now */
1330 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
1331 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
1332 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
1336 /* deny CONNECT via accelerated ports */
1337 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
1338 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
1339 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1340 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1341 return csd
->abortRequestParsing("error:method-not-allowed");
1344 /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific
1345 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
1346 * If seen it signals a broken client or proxy has corrupted the traffic.
1348 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
1349 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
1350 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1351 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1352 return csd
->abortRequestParsing("error:method-not-allowed");
1355 if (hp
->method() == Http::METHOD_NONE
) {
1356 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
1357 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
1358 return csd
->abortRequestParsing("error:unsupported-request-method");
1361 // Process headers after request line
1362 debugs(33, 3, "complete request received. " <<
1363 "prefix_sz = " << hp
->messageHeaderSize() <<
1364 ", request-line-size=" << hp
->firstLineSize() <<
1365 ", mime-header-size=" << hp
->headerBlockSize() <<
1366 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
1368 /* Ok, all headers are received */
1369 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
1371 http
->req_sz
= hp
->messageHeaderSize();
1372 Http::Stream
*result
= new Http::Stream(csd
->clientConnection
, http
);
1374 StoreIOBuffer tempBuffer
;
1375 tempBuffer
.data
= result
->reqbuf
;
1376 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1378 ClientStreamData newServer
= new clientReplyContext(http
);
1379 ClientStreamData newClient
= result
;
1380 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1381 clientReplyStatus
, newServer
, clientSocketRecipient
,
1382 clientSocketDetach
, newClient
, tempBuffer
);
1385 debugs(33,5, "Prepare absolute URL from " <<
1386 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
1387 /* Rewrite the URL in transparent or accelerator mode */
1388 /* NP: there are several cases to traverse here:
1389 * - standard mode (forward proxy)
1390 * - transparent mode (TPROXY)
1391 * - transparent mode with failures
1392 * - intercept mode (NAT)
1393 * - intercept mode with failures
1394 * - accelerator mode (reverse proxy)
1395 * - internal relative-URL
1396 * - mixed combos of the above with internal URL
1397 * - remote interception with PROXY protocol
1398 * - remote reverse-proxy with PROXY protocol
1400 if (csd
->transparent()) {
1401 /* intercept or transparent mode, properly working with no failures */
1402 prepareTransparentURL(csd
, http
, hp
);
1404 } else if (internalCheck(hp
->requestUri())) { // NP: only matches relative-URI
1405 /* internal URL mode */
1406 /* prepend our name & port */
1407 http
->uri
= xstrdup(internalLocalUri(NULL
, hp
->requestUri()));
1408 // We just re-wrote the URL. Must replace the Host: header.
1409 // But have not parsed there yet!! flag for local-only handling.
1410 http
->flags
.internal
= true;
1412 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
1413 /* accelerator mode */
1414 prepareAcceleratedURL(csd
, http
, hp
);
1418 /* No special rewrites have been applied above, use the
1419 * requested url. may be rewritten later, so make extra room */
1420 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
1421 http
->uri
= (char *)xcalloc(url_sz
, 1);
1422 SBufToCstring(http
->uri
, hp
->requestUri());
1425 result
->flags
.parsed_ok
= 1;
1430 ConnStateData::connFinishedWithConn(int size
)
1433 if (pipeline
.empty() && inBuf
.isEmpty()) {
1434 /* no current or pending requests */
1435 debugs(33, 4, HERE
<< clientConnection
<< " closed");
1437 } else if (!Config
.onoff
.half_closed_clients
) {
1438 /* admin doesn't want to support half-closed client sockets */
1439 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
1440 pipeline
.terminateAll(0);
1449 ConnStateData::consumeInput(const size_t byteCount
)
1451 assert(byteCount
> 0 && byteCount
<= inBuf
.length());
1452 inBuf
.consume(byteCount
);
1453 debugs(33, 5, "inBuf has " << inBuf
.length() << " unused bytes");
1457 ConnStateData::clientAfterReadingRequests()
1459 // Were we expecting to read more request body from half-closed connection?
1460 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
1461 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
1462 clientConnection
->close();
1471 ConnStateData::quitAfterError(HttpRequest
*request
)
1473 // From HTTP p.o.v., we do not have to close after every error detected
1474 // at the client-side, but many such errors do require closure and the
1475 // client-side code is bad at handling errors so we play it safe.
1477 request
->flags
.proxyKeepalive
= false;
1478 flags
.readMore
= false;
1479 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
1483 bool ConnStateData::serveDelayedError(Http::Stream
*context
)
1485 ClientHttpRequest
*http
= context
->http
;
1490 assert(sslServerBump
->entry
);
1491 // Did we create an error entry while processing CONNECT?
1492 if (!sslServerBump
->entry
->isEmpty()) {
1493 quitAfterError(http
->request
);
1495 // Get the saved error entry and send it to the client by replacing the
1496 // ClientHttpRequest store entry with it.
1497 clientStreamNode
*node
= context
->getClientReplyContext();
1498 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1500 debugs(33, 5, "Responding with delated error for " << http
->uri
);
1501 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
1503 // save the original request for logging purposes
1504 if (!context
->http
->al
->request
) {
1505 context
->http
->al
->request
= http
->request
;
1506 HTTPMSGLOCK(context
->http
->al
->request
);
1509 // Get error details from the fake certificate-peeking request.
1510 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
1511 context
->pullData();
1515 // In bump-server-first mode, we have not necessarily seen the intended
1516 // server name at certificate-peeking time. Check for domain mismatch now,
1517 // when we can extract the intended name from the bumped HTTP request.
1518 if (const Security::CertPointer
&srvCert
= sslServerBump
->serverCert
) {
1519 HttpRequest
*request
= http
->request
;
1520 if (!Ssl::checkX509ServerValidity(srvCert
.get(), request
->url
.host())) {
1521 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
1522 "does not match domainname " << request
->url
.host());
1524 bool allowDomainMismatch
= false;
1525 if (Config
.ssl_client
.cert_error
) {
1526 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
1527 check
.al
= http
->al
;
1528 check
.sslErrors
= new Security::CertErrors(Security::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
1529 check
.syncAle(request
, http
->log_uri
);
1530 allowDomainMismatch
= check
.fastCheck().allowed();
1531 delete check
.sslErrors
;
1532 check
.sslErrors
= NULL
;
1535 if (!allowDomainMismatch
) {
1536 quitAfterError(request
);
1538 clientStreamNode
*node
= context
->getClientReplyContext();
1539 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1540 assert (repContext
);
1542 request
->hier
= sslServerBump
->request
->hier
;
1544 // Create an error object and fill it
1545 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
1546 err
->src_addr
= clientConnection
->remote
;
1547 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
1548 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
1549 srvCert
.get(), nullptr);
1550 err
->detail
= errDetail
;
1551 // Save the original request for logging purposes.
1552 if (!context
->http
->al
->request
) {
1553 context
->http
->al
->request
= request
;
1554 HTTPMSGLOCK(context
->http
->al
->request
);
1556 repContext
->setReplyToError(request
->method
, err
);
1557 assert(context
->http
->out
.offset
== 0);
1558 context
->pullData();
1566 #endif // USE_OPENSSL
1569 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
1570 * or false otherwise
1573 clientTunnelOnError(ConnStateData
*conn
, Http::StreamPointer
&context
, HttpRequest::Pointer
&request
, const HttpRequestMethod
& method
, err_type requestError
)
1575 if (conn
->mayTunnelUnsupportedProto()) {
1576 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
.getRaw(), nullptr);
1577 checklist
.al
= (context
&& context
->http
) ? context
->http
->al
: nullptr;
1578 checklist
.requestErrorType
= requestError
;
1579 checklist
.src_addr
= conn
->clientConnection
->remote
;
1580 checklist
.my_addr
= conn
->clientConnection
->local
;
1581 checklist
.conn(conn
);
1582 ClientHttpRequest
*http
= context
? context
->http
: nullptr;
1583 const char *log_uri
= http
? http
->log_uri
: nullptr;
1584 checklist
.syncAle(request
.getRaw(), log_uri
);
1585 allow_t answer
= checklist
.fastCheck();
1586 if (answer
.allowed() && answer
.kind
== 1) {
1587 debugs(33, 3, "Request will be tunneled to server");
1589 assert(conn
->pipeline
.front() == context
); // XXX: still assumes HTTP/1 semantics
1590 context
->finished(); // Will remove from conn->pipeline queue
1592 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
1593 return conn
->initiateTunneledRequest(request
, Http::METHOD_NONE
, "unknown-protocol", conn
->preservedClientData
);
1595 debugs(33, 3, "Continue with returning the error: " << requestError
);
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
->manager(conn
, http
->al
);
1641 request
->flags
.accelerated
= http
->flags
.accel
;
1642 request
->flags
.sslBumped
=conn
->switchedToHttps();
1643 // TODO: decouple http->flags.accel from request->flags.sslBumped
1644 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
1645 !conn
->port
->allow_direct
: 0;
1646 request
->sources
|= isFtp
? Http::Message::srcFtp
:
1647 ((request
->flags
.sslBumped
|| conn
->port
->transport
.protocol
== AnyP::PROTO_HTTPS
) ? Http::Message::srcHttps
: Http::Message::srcHttp
);
1649 if (request
->flags
.sslBumped
) {
1650 if (conn
->getAuth() != NULL
)
1651 request
->auth_user_request
= conn
->getAuth();
1655 if (internalCheck(request
->url
.path())) {
1656 if (internalHostnameIs(request
->url
.host()) && request
->url
.port() == getMyPort()) {
1657 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true));
1658 http
->flags
.internal
= true;
1659 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->url
.path())) {
1660 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (global_internal_static on)");
1661 request
->url
.setScheme(AnyP::PROTO_HTTP
, "http");
1662 request
->url
.host(internalHostname());
1663 request
->url
.port(getMyPort());
1664 http
->flags
.internal
= true;
1666 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (not this proxy)");
1669 request
->flags
.internal
= http
->flags
.internal
;
1670 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
1673 // XXX: for non-HTTP messages instantiate a different Http::Message child type
1674 // for now Squid only supports HTTP requests
1675 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
1676 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
1677 request
->http_ver
.major
= http_ver
.major
;
1678 request
->http_ver
.minor
= http_ver
.minor
;
1681 if (request
->header
.chunked()) {
1683 } else if (request
->header
.has(Http::HdrType::TRANSFER_ENCODING
)) {
1684 const String te
= request
->header
.getList(Http::HdrType::TRANSFER_ENCODING
);
1685 // HTTP/1.1 requires chunking to be the last encoding if there is one
1686 unsupportedTe
= te
.size() && te
!= "identity";
1687 } // else implied identity coding
1689 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
1690 (request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0);
1691 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
1692 clientStreamNode
*node
= context
->getClientReplyContext();
1693 conn
->quitAfterError(request
.getRaw());
1694 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1695 assert (repContext
);
1696 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
1697 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1698 assert(context
->http
->out
.offset
== 0);
1699 context
->pullData();
1700 clientProcessRequestFinished(conn
, request
);
1704 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
1705 clientStreamNode
*node
= context
->getClientReplyContext();
1706 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1707 assert (repContext
);
1708 conn
->quitAfterError(request
.getRaw());
1709 repContext
->setReplyToError(ERR_INVALID_REQ
,
1710 Http::scLengthRequired
, request
->method
, NULL
,
1711 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
1712 assert(context
->http
->out
.offset
== 0);
1713 context
->pullData();
1714 clientProcessRequestFinished(conn
, request
);
1718 clientSetKeepaliveFlag(http
);
1719 // Let tunneling code be fully responsible for CONNECT requests
1720 if (http
->request
->method
== Http::METHOD_CONNECT
) {
1721 context
->mayUseConnection(true);
1722 conn
->flags
.readMore
= false;
1726 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
1727 clientProcessRequestFinished(conn
, request
);
1732 /* Do we expect a request-body? */
1733 expectBody
= chunked
|| request
->content_length
> 0;
1734 if (!context
->mayUseConnection() && expectBody
) {
1735 request
->body_pipe
= conn
->expectRequestBody(
1736 chunked
? -1 : request
->content_length
);
1738 /* Is it too large? */
1739 if (!chunked
&& // if chunked, we will check as we accumulate
1740 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
1741 clientStreamNode
*node
= context
->getClientReplyContext();
1742 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1743 assert (repContext
);
1744 conn
->quitAfterError(request
.getRaw());
1745 repContext
->setReplyToError(ERR_TOO_BIG
,
1746 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
1747 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
1748 assert(context
->http
->out
.offset
== 0);
1749 context
->pullData();
1750 clientProcessRequestFinished(conn
, request
);
1755 // We may stop producing, comm_close, and/or call setReplyToError()
1756 // below, so quit on errors to avoid http->doCallouts()
1757 if (!conn
->handleRequestBodyData()) {
1758 clientProcessRequestFinished(conn
, request
);
1762 if (!request
->body_pipe
->productionEnded()) {
1763 debugs(33, 5, "need more request body");
1764 context
->mayUseConnection(true);
1765 assert(conn
->flags
.readMore
);
1770 http
->calloutContext
= new ClientRequestContext(http
);
1774 clientProcessRequestFinished(conn
, request
);
1778 ConnStateData::pipelinePrefetchMax() const
1780 // TODO: Support pipelined requests through pinned connections.
1783 return Config
.pipeline_max_prefetch
;
1787 * Limit the number of concurrent requests.
1788 * \return true when there are available position(s) in the pipeline queue for another request.
1789 * \return false when the pipeline queue is full or disabled.
1792 ConnStateData::concurrentRequestQueueFilled() const
1794 const int existingRequestCount
= pipeline
.count();
1796 // default to the configured pipeline size.
1797 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
1799 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
1801 const int internalRequest
= 0;
1803 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
1805 // when queue filled already we cant add more.
1806 if (existingRequestCount
>= concurrentRequestLimit
) {
1807 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
1808 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
1816 * Perform proxy_protocol_access ACL tests on the client which
1817 * connected to PROXY protocol port to see if we trust the
1818 * sender enough to accept their PROXY header claim.
1821 ConnStateData::proxyProtocolValidateClient()
1823 if (!Config
.accessList
.proxyProtocol
)
1824 return proxyProtocolError("PROXY client not permitted by default ACL");
1826 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
1827 ch
.src_addr
= clientConnection
->remote
;
1828 ch
.my_addr
= clientConnection
->local
;
1831 if (!ch
.fastCheck().allowed())
1832 return proxyProtocolError("PROXY client not permitted by ACLs");
1838 * Perform cleanup on PROXY protocol errors.
1839 * If header parsing hits a fatal error terminate the connection,
1840 * otherwise wait for more data.
1843 ConnStateData::proxyProtocolError(const char *msg
)
1846 // This is important to know, but maybe not so much that flooding the log is okay.
1847 #if QUIET_PROXY_PROTOCOL
1848 // display the first of every 32 occurances at level 1, the others at level 2.
1849 static uint8_t hide
= 0;
1850 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
1852 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
1859 /// magic octet prefix for PROXY protocol version 1
1860 static const SBuf
Proxy1p0magic("PROXY ", 6);
1862 /// magic octet prefix for PROXY protocol version 2
1863 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
1866 * Test the connection read buffer for PROXY protocol header.
1867 * Version 1 and 2 header currently supported.
1870 ConnStateData::parseProxyProtocolHeader()
1872 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
1874 // detect and parse PROXY/2.0 protocol header
1875 if (inBuf
.startsWith(Proxy2p0magic
))
1876 return parseProxy2p0();
1878 // detect and parse PROXY/1.0 protocol header
1879 if (inBuf
.startsWith(Proxy1p0magic
))
1880 return parseProxy1p0();
1882 // detect and terminate other protocols
1883 if (inBuf
.length() >= Proxy2p0magic
.length()) {
1884 // PROXY/1.0 magic is shorter, so we know that
1885 // the input does not start with any PROXY magic
1886 return proxyProtocolError("PROXY protocol error: invalid header");
1889 // TODO: detect short non-magic prefixes earlier to avoid
1890 // waiting for more data which may never come
1892 // not enough bytes to parse yet.
1896 /// parse the PROXY/1.0 protocol header from the connection read buffer
1898 ConnStateData::parseProxy1p0()
1900 ::Parser::Tokenizer
tok(inBuf
);
1901 tok
.skip(Proxy1p0magic
);
1903 // skip to first LF (assumes it is part of CRLF)
1904 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
1906 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
1907 if (tok
.skip('\n')) {
1908 // found valid header
1909 inBuf
= tok
.remaining();
1910 needProxyProtocolHeader_
= false;
1911 // reset the tokenizer to work on found line only.
1914 return false; // no LF yet
1916 } else // protocol error only if there are more than 107 bytes prefix header
1917 return proxyProtocolError(inBuf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
1919 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
1920 if (tok
.skip(tcpName
)) {
1922 // skip TCP/IP version number
1923 static const CharacterSet
tcpVersions("TCP-version","46");
1924 if (!tok
.skipOne(tcpVersions
))
1925 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
1927 // skip SP after protocol version
1929 return proxyProtocolError("PROXY/1.0 error: missing SP");
1932 int64_t porta
, portb
;
1933 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
1935 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
1936 // leave the LF until later.
1937 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
1938 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
1939 tok
.int64(porta
) && tok
.skip(' ') &&
1943 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
1945 // parse IP and port strings
1946 Ip::Address originalClient
, originalDest
;
1948 if (!originalClient
.GetHostByName(ipa
.c_str()))
1949 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
1951 if (!originalDest
.GetHostByName(ipb
.c_str()))
1952 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
1954 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
1955 originalClient
.port(static_cast<uint16_t>(porta
));
1957 return proxyProtocolError("PROXY/1.0 error: invalid src port");
1959 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
1960 originalDest
.port(static_cast<uint16_t>(portb
));
1962 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
1964 // we have original client and destination details now
1965 // replace the client connection values
1966 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
1967 clientConnection
->local
= originalDest
;
1968 clientConnection
->remote
= originalClient
;
1969 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
1970 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
1971 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
1974 } else if (tok
.skip(unknown
)) {
1975 // found valid but unusable header
1979 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
1984 /// parse the PROXY/2.0 protocol header from the connection read buffer
1986 ConnStateData::parseProxy2p0()
1988 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
1989 if (inBuf
.length() < prefixLen
+ 4)
1990 return false; // need more bytes
1992 if ((inBuf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
1993 return proxyProtocolError("PROXY/2.0 error: invalid version");
1995 const char command
= (inBuf
[prefixLen
] & 0x0F);
1996 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
1997 return proxyProtocolError("PROXY/2.0 error: invalid command");
1999 const char family
= (inBuf
[prefixLen
+1] & 0xF0) >>4;
2000 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2001 return proxyProtocolError("PROXY/2.0 error: invalid family");
2003 const char proto
= (inBuf
[prefixLen
+1] & 0x0F);
2004 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2005 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2007 const char *clen
= inBuf
.rawContent() + prefixLen
+ 2;
2009 memcpy(&len
, clen
, sizeof(len
));
2012 if (inBuf
.length() < prefixLen
+ 4 + len
)
2013 return false; // need more bytes
2015 inBuf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2016 const SBuf extra
= inBuf
.consume(len
);
2017 needProxyProtocolHeader_
= false; // found successfully
2019 // LOCAL connections do nothing with the extras
2020 if (command
== 0x00/* LOCAL*/)
2024 struct { /* for TCP/UDP over IPv4, len = 12 */
2025 struct in_addr src_addr
;
2026 struct in_addr dst_addr
;
2030 struct { /* for TCP/UDP over IPv6, len = 36 */
2031 struct in6_addr src_addr
;
2032 struct in6_addr dst_addr
;
2037 struct { /* for AF_UNIX sockets, len = 216 */
2038 uint8_t src_addr
[108];
2039 uint8_t dst_addr
[108];
2045 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2047 // replace the client connection values
2048 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2051 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2052 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2053 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2054 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2055 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2056 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2059 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2060 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2061 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2062 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2063 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2064 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2066 default: // do nothing
2069 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2074 ConnStateData::receivedFirstByte()
2076 if (receivedFirstByte_
)
2079 receivedFirstByte_
= true;
2080 // Set timeout to Config.Timeout.request
2081 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2082 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
2083 TimeoutDialer
, this, ConnStateData::requestTimeout
);
2084 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
2088 * Attempt to parse one or more requests from the input buffer.
2089 * Returns true after completing parsing of at least one request [header]. That
2090 * includes cases where parsing ended with an error (e.g., a huge request).
2093 ConnStateData::clientParseRequests()
2095 bool parsed_req
= false;
2097 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2099 // Loop while we have read bytes that are not needed for producing the body
2100 // On errors, bodyPipe may become nil, but readMore will be cleared
2101 while (!inBuf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2103 // Prohibit concurrent requests when using a pinned to-server connection
2104 // because our Client classes do not support request pipelining.
2105 if (pinning
.pinned
&& !pinning
.readHandler
) {
2106 debugs(33, 3, clientConnection
<< " waits for busy " << pinning
.serverConnection
);
2110 /* Limit the number of concurrent requests */
2111 if (concurrentRequestQueueFilled())
2114 // try to parse the PROXY protocol header magic bytes
2115 if (needProxyProtocolHeader_
) {
2116 if (!parseProxyProtocolHeader())
2119 // we have been waiting for PROXY to provide client-IP
2120 // for some lookups, ie rDNS and IDENT.
2121 whenClientIpKnown();
2124 if (Http::StreamPointer context
= parseOneRequest()) {
2125 debugs(33, 5, clientConnection
<< ": done parsing a request");
2127 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2128 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2129 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2131 context
->registerWithConn();
2133 processParsedRequest(context
);
2135 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2137 if (context
->mayUseConnection()) {
2138 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2142 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
2143 inBuf
.length() << " < " << Config
.maxRequestHeaderSize
);
2144 Must(inBuf
.length() < Config
.maxRequestHeaderSize
);
2149 /* XXX where to 'finish' the parsing pass? */
2154 ConnStateData::afterClientRead()
2157 if (parsingTlsHandshake
) {
2158 parseTlsHandshake();
2163 /* Process next request */
2164 if (pipeline
.empty())
2165 fd_note(clientConnection
->fd
, "Reading next request");
2167 if (!clientParseRequests()) {
2171 * If the client here is half closed and we failed
2172 * to parse a request, close the connection.
2173 * The above check with connFinishedWithConn() only
2174 * succeeds _if_ the buffer is empty which it won't
2175 * be if we have an incomplete request.
2176 * XXX: This duplicates ConnStateData::kick
2178 if (pipeline
.empty() && commIsHalfClosed(clientConnection
->fd
)) {
2179 debugs(33, 5, clientConnection
<< ": half-closed connection, no completed request parsed, connection closing.");
2180 clientConnection
->close();
2188 clientAfterReadingRequests();
2192 * called when new request data has been read from the socket
2194 * \retval false called comm_close or setReplyToError (the caller should bail)
2195 * \retval true we did not call comm_close or setReplyToError
2198 ConnStateData::handleReadData()
2200 // if we are reading a body, stuff data into the body pipe
2201 if (bodyPipe
!= NULL
)
2202 return handleRequestBodyData();
2207 * called when new request body data has been buffered in inBuf
2208 * may close the connection if we were closing and piped everything out
2210 * \retval false called comm_close or setReplyToError (the caller should bail)
2211 * \retval true we did not call comm_close or setReplyToError
2214 ConnStateData::handleRequestBodyData()
2216 assert(bodyPipe
!= NULL
);
2218 if (bodyParser
) { // chunked encoding
2219 if (const err_type error
= handleChunkedRequestBody()) {
2220 abortChunkedRequestBody(error
);
2223 } else { // identity encoding
2224 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
2225 const size_t putSize
= bodyPipe
->putMoreData(inBuf
.c_str(), inBuf
.length());
2227 consumeInput(putSize
);
2229 if (!bodyPipe
->mayNeedMoreData()) {
2230 // BodyPipe will clear us automagically when we produced everything
2236 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
2238 if (const char *reason
= stoppedSending()) {
2239 /* we've finished reading like good clients,
2240 * now do the close that initiateClose initiated.
2242 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
2243 clientConnection
->close();
2251 /// parses available chunked encoded body bytes, checks size, returns errors
2253 ConnStateData::handleChunkedRequestBody()
2255 debugs(33, 7, "chunked from " << clientConnection
<< ": " << inBuf
.length());
2257 try { // the parser will throw on errors
2259 if (inBuf
.isEmpty()) // nothing to do
2262 BodyPipeCheckout
bpc(*bodyPipe
);
2263 bodyParser
->setPayloadBuffer(&bpc
.buf
);
2264 const bool parsed
= bodyParser
->parse(inBuf
);
2265 inBuf
= bodyParser
->remaining(); // sync buffers
2268 // dechunk then check: the size limit applies to _dechunked_ content
2269 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
2273 finishDechunkingRequest(true);
2275 return ERR_NONE
; // nil bodyPipe implies body end for the caller
2278 // if chunk parser needs data, then the body pipe must need it too
2279 Must(!bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
2281 // if parser needs more space and we can consume nothing, we will stall
2282 Must(!bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
2283 } catch (...) { // TODO: be more specific
2284 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
2285 return ERR_INVALID_REQ
;
2288 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
2292 /// quit on errors related to chunked request body handling
2294 ConnStateData::abortChunkedRequestBody(const err_type error
)
2296 finishDechunkingRequest(false);
2298 // XXX: The code below works if we fail during initial request parsing,
2299 // but if we fail when the server connection is used already, the server may send
2300 // us its response too, causing various assertions. How to prevent that?
2301 #if WE_KNOW_HOW_TO_SEND_ERRORS
2302 Http::StreamPointer context
= pipeline
.front();
2303 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
2304 clientStreamNode
*node
= context
->getClientReplyContext();
2305 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2307 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
2308 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
2309 repContext
->setReplyToError(error
, scode
,
2310 repContext
->http
->request
->method
,
2311 repContext
->http
->uri
,
2313 repContext
->http
->request
,
2315 context
->pullData();
2317 // close or otherwise we may get stuck as nobody will notice the error?
2318 comm_reset_close(clientConnection
);
2321 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
2322 comm_reset_close(clientConnection
);
2324 flags
.readMore
= false;
2328 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
2330 // request reader may get stuck waiting for space if nobody consumes body
2331 if (bodyPipe
!= NULL
)
2332 bodyPipe
->enableAutoConsumption();
2337 /** general lifetime handler for HTTP requests */
2339 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
2341 if (!Comm::IsConnOpen(io
.conn
))
2344 if (mayTunnelUnsupportedProto() && !receivedFirstByte_
) {
2345 Http::StreamPointer context
= pipeline
.front();
2346 Must(context
&& context
->http
);
2347 HttpRequest::Pointer request
= context
->http
->request
;
2348 if (clientTunnelOnError(this, context
, request
, HttpRequestMethod(), ERR_REQUEST_START_TIMEOUT
))
2352 * Just close the connection to not confuse browsers
2353 * using persistent connections. Some browsers open
2354 * a connection and then do not use it until much
2355 * later (presumeably because the request triggering
2356 * the open has already been completed on another
2359 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
2364 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
2366 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
2367 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
2368 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
2369 http
->logType
.err
.timedout
= true;
2370 if (Comm::IsConnOpen(io
.conn
))
2374 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
2375 AsyncJob("ConnStateData"), // kids overwrite
2377 bodyParser(nullptr),
2379 sslBumpMode(Ssl::bumpEnd
),
2381 needProxyProtocolHeader_(false),
2383 switchedToHttps_(false),
2384 parsingTlsHandshake(false),
2385 sslServerBump(NULL
),
2386 signAlgorithm(Ssl::algSignTrusted
),
2388 stoppedSending_(NULL
),
2389 stoppedReceiving_(NULL
)
2391 flags
.readMore
= true; // kids may overwrite
2392 flags
.swanSang
= false;
2394 pinning
.host
= NULL
;
2396 pinning
.pinned
= false;
2397 pinning
.auth
= false;
2398 pinning
.zeroReply
= false;
2399 pinning
.peer
= NULL
;
2401 // store the details required for creating more MasterXaction objects as new requests come in
2402 log_addr
= xact
->tcpClient
->remote
;
2403 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
2405 // register to receive notice of Squid signal events
2406 // which may affect long persisting client connections
2411 ConnStateData::start()
2413 BodyProducer::start();
2414 HttpControlMsgSink::start();
2416 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
2417 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
2418 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2419 int i
= IP_PMTUDISC_DONT
;
2420 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0) {
2422 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerr(xerrno
));
2425 static bool reported
= false;
2428 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
2434 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
2435 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
2436 comm_add_close_handler(clientConnection
->fd
, call
);
2438 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
2439 if (needProxyProtocolHeader_
) {
2440 if (!proxyProtocolValidateClient()) // will close the connection on failure
2443 whenClientIpKnown();
2448 ConnStateData::whenClientIpKnown()
2450 if (Config
.onoff
.log_fqdn
)
2451 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2454 if (Ident::TheConfig
.identLookup
) {
2455 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
2456 identChecklist
.src_addr
= clientConnection
->remote
;
2457 identChecklist
.my_addr
= clientConnection
->local
;
2458 if (identChecklist
.fastCheck().allowed())
2459 Ident::Start(clientConnection
, clientIdentDone
, this);
2463 clientdbEstablished(clientConnection
->remote
, 1);
2466 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
2468 if (Config
.onoff
.client_db
) {
2469 /* it was said several times that client write limiter does not work if client_db is disabled */
2471 auto &pools
= ClientDelayPools::Instance()->pools
;
2472 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
2474 // TODO: we check early to limit error response bandwith but we
2475 // should recheck when we can honor delay_pool_uses_indirect
2476 // TODO: we should also pass the port details for myportname here.
2477 ch
.src_addr
= clientConnection
->remote
;
2478 ch
.my_addr
= clientConnection
->local
;
2480 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
2482 /* pools require explicit 'allow' to assign a client into them */
2483 if (pools
[pool
]->access
) {
2484 ch
.changeAcl(pools
[pool
]->access
);
2485 allow_t answer
= ch
.fastCheck();
2486 if (answer
.allowed()) {
2488 /* request client information from db after we did all checks
2489 this will save hash lookup if client failed checks */
2490 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
2493 /* put client info in FDE */
2494 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
2496 /* setup write limiter for this request */
2497 const double burst
= floor(0.5 +
2498 (pools
[pool
]->highwatermark
* Config
.ClientDelay
.initial
)/100.0);
2499 cli
->setWriteLimiter(pools
[pool
]->rate
, burst
, pools
[pool
]->highwatermark
);
2502 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
2509 // kids must extend to actually start doing something (e.g., reading)
2512 /** Handle a new connection on an HTTP socket. */
2514 httpAccept(const CommAcceptCbParams
¶ms
)
2516 MasterXaction::Pointer xact
= params
.xaction
;
2517 AnyP::PortCfgPointer s
= xact
->squidPort
;
2519 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2521 if (params
.flag
!= Comm::OK
) {
2522 // Its possible the call was still queued when the client disconnected
2523 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2527 debugs(33, 4, params
.conn
<< ": accepted");
2528 fd_note(params
.conn
->fd
, "client http connect");
2530 if (s
->tcp_keepalive
.enabled
)
2531 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2533 ++incoming_sockets_accepted
;
2535 // Socket is ready, setup the connection manager to start using it
2536 auto *srv
= Http::NewServer(xact
);
2537 AsyncJob::Start(srv
); // usually async-calls readSomeData()
2540 /// Create TLS connection structure and update fd_table
2542 httpsCreate(const Comm::ConnectionPointer
&conn
, const Security::ContextPointer
&ctx
)
2544 if (Security::CreateServerSession(ctx
, conn
, "client https start")) {
2545 debugs(33, 5, "will negotiate TLS on " << conn
);
2549 debugs(33, DBG_IMPORTANT
, "ERROR: could not create TLS server context for " << conn
);
2556 * \retval 1 on success
2557 * \retval 0 when needs more data
2558 * \retval -1 on error
2561 tlsAttemptHandshake(ConnStateData
*conn
, PF
*callback
)
2563 // TODO: maybe throw instead of returning -1
2564 // see https://github.com/squid-cache/squid/pull/81#discussion_r153053278
2565 int fd
= conn
->clientConnection
->fd
;
2566 auto session
= fd_table
[fd
].ssl
.get();
2571 const auto ret
= SSL_accept(session
);
2575 const int xerrno
= errno
;
2576 const auto ssl_error
= SSL_get_error(session
, ret
);
2578 switch (ssl_error
) {
2580 case SSL_ERROR_WANT_READ
:
2581 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, (callback
? conn
: nullptr), 0);
2584 case SSL_ERROR_WANT_WRITE
:
2585 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, (callback
? conn
: nullptr), 0);
2588 case SSL_ERROR_SYSCALL
:
2590 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
2592 debugs(83, (xerrno
== ECONNRESET
) ? 1 : 2, "Error negotiating SSL connection on FD " << fd
<< ": " <<
2593 (xerrno
== 0 ? Security::ErrorString(ssl_error
) : xstrerr(xerrno
)));
2597 case SSL_ERROR_ZERO_RETURN
:
2598 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
2602 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
2603 fd
<< ": " << Security::ErrorString(ssl_error
) <<
2604 " (" << ssl_error
<< "/" << ret
<< ")");
2609 const auto x
= gnutls_handshake(session
);
2610 if (x
== GNUTLS_E_SUCCESS
)
2613 if (gnutls_error_is_fatal(x
)) {
2614 debugs(83, 2, "Error negotiating TLS on " << conn
->clientConnection
<< ": Aborted by client: " << Security::ErrorString(x
));
2616 } else if (x
== GNUTLS_E_INTERRUPTED
|| x
== GNUTLS_E_AGAIN
) {
2617 const auto ioAction
= (gnutls_record_get_direction(session
)==0 ? COMM_SELECT_READ
: COMM_SELECT_WRITE
);
2618 Comm::SetSelect(fd
, ioAction
, callback
, (callback
? conn
: nullptr), 0);
2623 // Performing TLS handshake should never be reachable without a TLS/SSL library.
2624 (void)session
; // avoid compiler and static analysis complaints
2625 fatal("FATAL: HTTPS not supported by this Squid.");
2631 /** negotiate an SSL connection */
2633 clientNegotiateSSL(int fd
, void *data
)
2635 ConnStateData
*conn
= (ConnStateData
*)data
;
2637 const int ret
= tlsAttemptHandshake(conn
, clientNegotiateSSL
);
2639 if (ret
< 0) // An error
2640 conn
->clientConnection
->close();
2644 Security::SessionPointer
session(fd_table
[fd
].ssl
);
2647 if (Security::SessionIsResumed(session
)) {
2648 debugs(83, 2, "Session " << SSL_get_session(session
.get()) <<
2649 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<<
2650 ":" << (int)fd_table
[fd
].remote_port
<< ")");
2652 if (Debug::Enabled(83, 4)) {
2653 /* Write out the SSL session details.. actually the call below, but
2654 * OpenSSL headers do strange typecasts confusing GCC.. */
2655 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
2656 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
2657 PEM_ASN1_write(reinterpret_cast<i2d_of_void
*>(i2d_SSL_SESSION
),
2658 PEM_STRING_SSL_SESSION
, debug_log
,
2659 reinterpret_cast<char *>(SSL_get_session(session
.get())),
2660 nullptr, nullptr, 0, nullptr, nullptr);
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
,
2673 reinterpret_cast<char *>(SSL_get_session(session
.get())),
2674 nullptr, nullptr, 0, nullptr, nullptr);
2675 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION,
2677 reinterpret_cast<char *>(SSL_get_session(session.get())),
2678 nullptr, nullptr, 0, nullptr, nullptr);
2681 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source.");
2684 /* Note: This does not automatically fflush the log file.. */
2687 debugs(83, 2, "New session " << SSL_get_session(session
.get()) <<
2688 " on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" <<
2689 fd_table
[fd
].remote_port
<< ")");
2692 debugs(83, 2, "TLS session reuse not yet implemented.");
2695 // Connection established. Retrieve TLS connection parameters for logging.
2696 conn
->clientConnection
->tlsNegotiations()->retrieveNegotiatedInfo(session
);
2699 X509
*client_cert
= SSL_get_peer_certificate(session
.get());
2702 debugs(83, 3, "FD " << fd
<< " client certificate: subject: " <<
2703 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
2705 debugs(83, 3, "FD " << fd
<< " client certificate: issuer: " <<
2706 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
2708 X509_free(client_cert
);
2710 debugs(83, 5, "FD " << fd
<< " has no client certificate.");
2713 debugs(83, 2, "Client certificate requesting not yet implemented.");
2716 conn
->readSomeData();
2720 * If Security::ContextPointer is given, starts reading the TLS handshake.
2721 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPointer.
2724 httpsEstablish(ConnStateData
*connState
, const Security::ContextPointer
&ctx
)
2727 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
2729 if (!ctx
|| !httpsCreate(details
, ctx
))
2732 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2733 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
2734 connState
, ConnStateData::requestTimeout
);
2735 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
2737 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
2742 * A callback function to use with the ACLFilledChecklist callback.
2745 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
2747 ConnStateData
*connState
= (ConnStateData
*) data
;
2749 // if the connection is closed or closing, just return.
2750 if (!connState
->isOpen())
2753 if (answer
.allowed()) {
2754 debugs(33, 2, "sslBump action " << Ssl::bumpMode(answer
.kind
) << "needed for " << connState
->clientConnection
);
2755 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
2757 debugs(33, 3, "sslBump not needed for " << connState
->clientConnection
);
2758 connState
->sslBumpMode
= Ssl::bumpSplice
;
2761 if (connState
->sslBumpMode
== Ssl::bumpTerminate
) {
2762 connState
->clientConnection
->close();
2766 if (!connState
->fakeAConnectRequest("ssl-bump", connState
->inBuf
))
2767 connState
->clientConnection
->close();
2771 /** handle a new HTTPS connection */
2773 httpsAccept(const CommAcceptCbParams
¶ms
)
2775 MasterXaction::Pointer xact
= params
.xaction
;
2776 const AnyP::PortCfgPointer s
= xact
->squidPort
;
2778 // NP: it is possible the port was reconfigured when the call or accept() was queued.
2780 if (params
.flag
!= Comm::OK
) {
2781 // Its possible the call was still queued when the client disconnected
2782 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
2786 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
2787 fd_note(params
.conn
->fd
, "client https connect");
2789 if (s
->tcp_keepalive
.enabled
) {
2790 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
2792 ++incoming_sockets_accepted
;
2794 // Socket is ready, setup the connection manager to start using it
2795 auto *srv
= Https::NewServer(xact
);
2796 AsyncJob::Start(srv
); // usually async-calls postHttpsAccept()
2800 ConnStateData::postHttpsAccept()
2802 if (port
->flags
.tunnelSslBumping
) {
2804 debugs(33, 5, "accept transparent connection: " << clientConnection
);
2806 if (!Config
.accessList
.ssl_bump
) {
2807 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
2811 MasterXaction::Pointer mx
= new MasterXaction(XactionInitiator::initClient
);
2812 mx
->tcpClient
= clientConnection
;
2813 // Create a fake HTTP request for ssl_bump ACL check,
2814 // using tproxy/intercept provided destination IP and port.
2815 HttpRequest
*request
= new HttpRequest(mx
);
2816 static char ip
[MAX_IPSTRLEN
];
2817 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
2818 request
->url
.host(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
2819 request
->url
.port(clientConnection
->local
.port());
2820 request
->myportname
= port
->name
;
2822 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
2823 acl_checklist
->src_addr
= clientConnection
->remote
;
2824 acl_checklist
->my_addr
= port
->s
;
2825 // Build a local AccessLogEntry to allow requiresAle() acls work
2826 acl_checklist
->al
= new AccessLogEntry
;
2827 acl_checklist
->al
->cache
.start_time
= current_time
;
2828 acl_checklist
->al
->tcpClient
= clientConnection
;
2829 acl_checklist
->al
->cache
.port
= port
;
2830 acl_checklist
->al
->cache
.caddr
= log_addr
;
2831 HTTPMSGUNLOCK(acl_checklist
->al
->request
);
2832 acl_checklist
->al
->request
= request
;
2833 HTTPMSGLOCK(acl_checklist
->al
->request
);
2834 Http::StreamPointer context
= pipeline
.front();
2835 ClientHttpRequest
*http
= context
? context
->http
: nullptr;
2836 const char *log_uri
= http
? http
->log_uri
: nullptr;
2837 acl_checklist
->syncAle(request
, log_uri
);
2838 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
2840 fatal("FATAL: SSL-Bump requires --with-openssl");
2844 httpsEstablish(this, port
->secure
.staticContext
);
2850 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
2852 ConnStateData
* state_data
= (ConnStateData
*)(data
);
2853 state_data
->sslCrtdHandleReply(reply
);
2857 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
2860 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply
);
2864 if (reply
.result
== Helper::BrokenHelper
) {
2865 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
2866 } else if (!reply
.other().hasContent()) {
2867 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
2869 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
2870 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
2871 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
2873 if (reply
.result
!= Helper::Okay
) {
2874 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
2876 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
2877 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
2878 doPeekAndSpliceStep();
2879 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
2880 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
2882 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
2884 Security::ContextPointer
ctx(Security::GetFrom(fd_table
[clientConnection
->fd
].ssl
));
2885 Ssl::configureUnconfiguredSslContext(ctx
, signAlgorithm
, *port
);
2887 Security::ContextPointer
ctx(Ssl::GenerateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), port
->secure
, (signAlgorithm
== Ssl::algSignTrusted
)));
2888 if (ctx
&& !sslBumpCertKey
.isEmpty())
2889 storeTlsContextToCache(sslBumpCertKey
, ctx
);
2890 getSslContextDone(ctx
);
2896 Security::ContextPointer nil
;
2897 getSslContextDone(nil
);
2900 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
2902 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
2904 const bool connectedOk
= sslServerBump
&& sslServerBump
->connectedOk();
2906 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
2907 certProperties
.mimicCert
.resetAndLock(mimicCert
);
2909 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
2910 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
2911 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors());
2913 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
2914 // If the algorithm already set, then ignore it.
2915 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
2916 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
2917 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
2920 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
).allowed()) {
2921 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
2922 const char *param
= ca
->param
;
2924 // For parameterless CN adaptation, use hostname from the
2926 if (ca
->alg
== Ssl::algSetCommonName
) {
2928 param
= sslConnectHostOrIp
.termedBuf();
2929 certProperties
.commonName
= param
;
2930 certProperties
.setCommonName
= true;
2931 } else if (ca
->alg
== Ssl::algSetValidAfter
)
2932 certProperties
.setValidAfter
= true;
2933 else if (ca
->alg
== Ssl::algSetValidBefore
)
2934 certProperties
.setValidBefore
= true;
2936 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
2937 alg
<< " param: " << (param
? param
: "-"));
2941 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
2942 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
2943 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
).allowed()) {
2944 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
2948 } else {// did not try to connect (e.g. client-first) or failed to connect
2949 // In case of an error while connecting to the secure server, use a
2950 // trusted certificate, with no mimicked fields and no adaptation
2951 // algorithms. There is nothing we can mimic, so we want to minimize the
2952 // number of warnings the user will have to see to get to the error page.
2953 // We will close the connection, so that the trust is not extended to
2954 // non-Squid content.
2955 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
2958 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
2960 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
2961 assert(port
->secure
.untrustedSigningCa
.cert
);
2962 certProperties
.signWithX509
.resetAndLock(port
->secure
.untrustedSigningCa
.cert
.get());
2963 certProperties
.signWithPkey
.resetAndLock(port
->secure
.untrustedSigningCa
.pkey
.get());
2965 assert(port
->secure
.signingCa
.cert
.get());
2966 certProperties
.signWithX509
.resetAndLock(port
->secure
.signingCa
.cert
.get());
2968 if (port
->secure
.signingCa
.pkey
)
2969 certProperties
.signWithPkey
.resetAndLock(port
->secure
.signingCa
.pkey
.get());
2971 signAlgorithm
= certProperties
.signAlgorithm
;
2973 certProperties
.signHash
= Ssl::DefaultSignHash
;
2976 Security::ContextPointer
2977 ConnStateData::getTlsContextFromCache(const SBuf
&cacheKey
, const Ssl::CertificateProperties
&certProperties
)
2979 debugs(33, 5, "Finding SSL certificate for " << cacheKey
<< " in cache");
2980 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
2981 if (Security::ContextPointer
*ctx
= ssl_ctx_cache
? ssl_ctx_cache
->get(cacheKey
) : nullptr) {
2982 if (Ssl::verifySslCertificate(*ctx
, certProperties
)) {
2983 debugs(33, 5, "Cached SSL certificate for " << certProperties
.commonName
<< " is valid");
2986 debugs(33, 5, "Cached SSL certificate for " << certProperties
.commonName
<< " is out of date. Delete this certificate from cache");
2988 ssl_ctx_cache
->del(cacheKey
);
2991 return Security::ContextPointer(nullptr);
2995 ConnStateData::storeTlsContextToCache(const SBuf
&cacheKey
, Security::ContextPointer
&ctx
)
2997 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
2998 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(cacheKey
, new Security::ContextPointer(ctx
))) {
2999 // If it is not in storage delete after using. Else storage deleted it.
3000 fd_table
[clientConnection
->fd
].dynamicTlsContext
= ctx
;
3005 ConnStateData::getSslContextStart()
3007 // If we are called, then CONNECT has succeeded. Finalize it.
3008 if (auto xact
= pipeline
.front()) {
3009 if (xact
->http
&& xact
->http
->request
&& xact
->http
->request
->method
== Http::METHOD_CONNECT
)
3011 // cannot proceed with encryption if requests wait for plain responses
3012 Must(pipeline
.empty());
3014 /* careful: finished() above frees request, host, etc. */
3016 if (port
->secure
.generateHostCertificates
) {
3017 Ssl::CertificateProperties certProperties
;
3018 buildSslCertGenerationParams(certProperties
);
3020 // Disable caching for bumpPeekAndSplice mode
3021 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
3022 sslBumpCertKey
.clear();
3023 Ssl::InRamCertificateDbKey(certProperties
, sslBumpCertKey
);
3024 assert(!sslBumpCertKey
.isEmpty());
3026 Security::ContextPointer
ctx(getTlsContextFromCache(sslBumpCertKey
, certProperties
));
3028 getSslContextDone(ctx
);
3035 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3036 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3037 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3038 request_message
.composeRequest(certProperties
);
3039 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3040 Ssl::Helper::Submit(request_message
, sslCrtdHandleReplyWrapper
, this);
3042 } catch (const std::exception
&e
) {
3043 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3044 "request for " << certProperties
.commonName
<<
3045 " certificate: " << e
.what() << "; will now block to " <<
3046 "generate that certificate.");
3047 // fall through to do blocking in-process generation.
3049 #endif // USE_SSL_CRTD
3051 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3052 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3053 doPeekAndSpliceStep();
3054 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3055 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3056 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3058 Security::ContextPointer
ctx(Security::GetFrom(fd_table
[clientConnection
->fd
].ssl
));
3059 Ssl::configureUnconfiguredSslContext(ctx
, certProperties
.signAlgorithm
, *port
);
3061 Security::ContextPointer
dynCtx(Ssl::GenerateSslContext(certProperties
, port
->secure
, (signAlgorithm
== Ssl::algSignTrusted
)));
3062 if (dynCtx
&& !sslBumpCertKey
.isEmpty())
3063 storeTlsContextToCache(sslBumpCertKey
, dynCtx
);
3064 getSslContextDone(dynCtx
);
3069 Security::ContextPointer nil
;
3070 getSslContextDone(nil
);
3074 ConnStateData::getSslContextDone(Security::ContextPointer
&ctx
)
3076 if (port
->secure
.generateHostCertificates
&& !ctx
) {
3077 debugs(33, 2, "Failed to generate TLS context for " << sslConnectHostOrIp
);
3080 // If generated ssl context = NULL, try to use static ssl context.
3082 if (!port
->secure
.staticContext
) {
3083 debugs(83, DBG_IMPORTANT
, "Closing " << clientConnection
->remote
<< " as lacking TLS context");
3084 clientConnection
->close();
3087 debugs(33, 5, "Using static TLS context.");
3088 ctx
= port
->secure
.staticContext
;
3092 if (!httpsCreate(clientConnection
, ctx
))
3095 // bumped intercepted conns should already have Config.Timeout.request set
3096 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3097 // to make sure the connection does not get stuck on non-SSL clients.
3098 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3099 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3100 this, ConnStateData::requestTimeout
);
3101 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3103 switchedToHttps_
= true;
3105 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3106 BIO
*b
= SSL_get_rbio(ssl
);
3107 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(BIO_get_data(b
));
3108 bio
->setReadBufData(inBuf
);
3110 clientNegotiateSSL(clientConnection
->fd
, this);
3114 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3116 assert(!switchedToHttps_
);
3118 sslConnectHostOrIp
= request
->url
.host();
3119 resetSslCommonName(request
->url
.host());
3121 // We are going to read new request
3122 flags
.readMore
= true;
3123 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3125 // keep version major.minor details the same.
3126 // but we are now performing the HTTPS handshake traffic
3127 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
3129 // If sslServerBump is set, then we have decided to deny CONNECT
3130 // and now want to switch to SSL to send the error to the client
3131 // without even peeking at the origin server certificate.
3132 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3133 request
->flags
.sslPeek
= true;
3134 sslServerBump
= new Ssl::ServerBump(request
);
3135 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
3136 request
->flags
.sslPeek
= true;
3137 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
3140 // commSetConnTimeout() was called for this request before we switched.
3141 // Fix timeout to request_start_timeout
3142 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3143 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3144 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3145 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
3146 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
3147 // a bumbed "connect" request on non transparent port.
3148 receivedFirstByte_
= false;
3149 // Get more data to peek at Tls
3150 parsingTlsHandshake
= true;
3155 ConnStateData::parseTlsHandshake()
3157 Must(parsingTlsHandshake
);
3159 assert(!inBuf
.isEmpty());
3160 receivedFirstByte();
3161 fd_note(clientConnection
->fd
, "Parsing TLS handshake");
3163 bool unsupportedProtocol
= false;
3165 if (!tlsParser
.parseHello(inBuf
)) {
3166 // need more data to finish parsing
3171 catch (const std::exception
&ex
) {
3172 debugs(83, 2, "error on FD " << clientConnection
->fd
<< ": " << ex
.what());
3173 unsupportedProtocol
= true;
3176 parsingTlsHandshake
= false;
3178 // client data may be needed for splicing and for
3179 // tunneling unsupportedProtocol after an error
3180 preservedClientData
= inBuf
;
3182 // Even if the parser failed, each TLS detail should either be set
3183 // correctly or still be "unknown"; copying unknown detail is a no-op.
3184 Security::TlsDetails::Pointer
const &details
= tlsParser
.details
;
3185 clientConnection
->tlsNegotiations()->retrieveParsedInfo(details
);
3186 if (details
&& !details
->serverName
.isEmpty()) {
3187 resetSslCommonName(details
->serverName
.c_str());
3188 tlsClientSni_
= details
->serverName
;
3191 // We should disable read/write handlers
3192 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3193 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
3195 if (unsupportedProtocol
) {
3196 Http::StreamPointer context
= pipeline
.front();
3197 Must(context
&& context
->http
);
3198 HttpRequest::Pointer request
= context
->http
->request
;
3199 debugs(83, 5, "Got something other than TLS Client Hello. Cannot SslBump.");
3200 sslBumpMode
= Ssl::bumpSplice
;
3201 context
->http
->al
->ssl
.bumpMode
= Ssl::bumpSplice
;
3202 if (!clientTunnelOnError(this, context
, request
, HttpRequestMethod(), ERR_PROTOCOL_UNKNOWN
))
3203 clientConnection
->close();
3207 if (!sslServerBump
|| sslServerBump
->act
.step1
== Ssl::bumpClientFirst
) { // Either means client-first.
3208 getSslContextStart();
3210 } else if (sslServerBump
->act
.step1
== Ssl::bumpServerFirst
) {
3211 // will call httpsPeeked() with certificate and connection, eventually
3212 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3214 Must(sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
);
3215 startPeekAndSplice();
3219 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
3221 ConnStateData
*connState
= (ConnStateData
*) data
;
3223 // if the connection is closed or closing, just return.
3224 if (!connState
->isOpen())
3227 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
3228 assert(connState
->serverBump());
3229 Ssl::BumpMode bumpAction
;
3230 if (answer
.allowed()) {
3231 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
3233 bumpAction
= Ssl::bumpSplice
;
3235 connState
->serverBump()->act
.step2
= bumpAction
;
3236 connState
->sslBumpMode
= bumpAction
;
3237 Http::StreamPointer context
= connState
->pipeline
.front();
3238 if (ClientHttpRequest
*http
= (context
? context
->http
: nullptr))
3239 http
->al
->ssl
.bumpMode
= bumpAction
;
3241 if (bumpAction
== Ssl::bumpTerminate
) {
3242 connState
->clientConnection
->close();
3243 } else if (bumpAction
!= Ssl::bumpSplice
) {
3244 connState
->startPeekAndSplice();
3245 } else if (!connState
->splice())
3246 connState
->clientConnection
->close();
3250 ConnStateData::splice()
3252 // normally we can splice here, because we just got client hello message
3254 if (fd_table
[clientConnection
->fd
].ssl
.get()) {
3255 // Restore default read methods
3256 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
3257 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
3260 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
3261 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
3262 transferProtocol
= Http::ProtocolVersion();
3263 assert(!pipeline
.empty());
3264 Http::StreamPointer context
= pipeline
.front();
3266 Must(context
->http
);
3267 ClientHttpRequest
*http
= context
->http
;
3268 HttpRequest::Pointer request
= http
->request
;
3269 context
->finished();
3270 if (transparent()) {
3271 // For transparent connections, make a new fake CONNECT request, now
3272 // with SNI as target. doCallout() checks, adaptations may need that.
3273 return fakeAConnectRequest("splice", preservedClientData
);
3275 // For non transparent connections make a new tunneled CONNECT, which
3276 // also sets the HttpRequest::flags::forceTunnel flag to avoid
3277 // respond with "Connection Established" to the client.
3278 // This fake CONNECT request required to allow use of SNI in
3279 // doCallout() checks and adaptations.
3280 return initiateTunneledRequest(request
, Http::METHOD_CONNECT
, "splice", preservedClientData
);
3285 ConnStateData::startPeekAndSplice()
3287 // This is the Step2 of the SSL bumping
3288 assert(sslServerBump
);
3289 Http::StreamPointer context
= pipeline
.front();
3290 ClientHttpRequest
*http
= context
? context
->http
: nullptr;
3292 if (sslServerBump
->step
== Ssl::bumpStep1
) {
3293 sslServerBump
->step
= Ssl::bumpStep2
;
3294 // Run a accessList check to check if want to splice or continue bumping
3296 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), nullptr);
3297 acl_checklist
->al
= http
? http
->al
: nullptr;
3298 //acl_checklist->src_addr = params.conn->remote;
3299 //acl_checklist->my_addr = s->s;
3300 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpNone
));
3301 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpClientFirst
));
3302 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpServerFirst
));
3303 const char *log_uri
= http
? http
->log_uri
: nullptr;
3304 acl_checklist
->syncAle(sslServerBump
->request
.getRaw(), log_uri
);
3305 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
3309 // will call httpsPeeked() with certificate and connection, eventually
3310 Security::ContextPointer
unConfiguredCTX(Ssl::createSSLContext(port
->secure
.signingCa
.cert
, port
->secure
.signingCa
.pkey
, port
->secure
));
3311 fd_table
[clientConnection
->fd
].dynamicTlsContext
= unConfiguredCTX
;
3313 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
3316 switchedToHttps_
= true;
3318 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3319 BIO
*b
= SSL_get_rbio(ssl
);
3320 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(BIO_get_data(b
));
3321 bio
->setReadBufData(inBuf
);
3324 // Here squid should have all of the client hello message so the
3325 // tlsAttemptHandshake() should return 0.
3326 // This block exist only to force openSSL parse client hello and detect
3327 // ERR_SECURE_ACCEPT_FAIL error, which should be checked and splice if required.
3328 if (tlsAttemptHandshake(this, nullptr) < 0) {
3329 debugs(83, 2, "TLS handshake failed.");
3330 HttpRequest::Pointer
request(http
? http
->request
: nullptr);
3331 if (!clientTunnelOnError(this, context
, request
, HttpRequestMethod(), ERR_SECURE_ACCEPT_FAIL
))
3332 clientConnection
->close();
3336 // We need to reset inBuf here, to be used by incoming requests in the case
3340 debugs(83, 5, "Peek and splice at step2 done. Start forwarding the request!!! ");
3341 FwdState::Start(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw(), http
? http
->al
: NULL
);
3345 ConnStateData::doPeekAndSpliceStep()
3347 auto ssl
= fd_table
[clientConnection
->fd
].ssl
.get();
3348 BIO
*b
= SSL_get_rbio(ssl
);
3350 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(BIO_get_data(b
));
3352 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
3355 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
3356 switchedToHttps_
= true;
3360 ConnStateData::httpsPeeked(PinnedIdleContext pic
)
3362 Must(sslServerBump
!= NULL
);
3363 Must(sslServerBump
->request
== pic
.request
);
3364 Must(pipeline
.empty() || pipeline
.front()->http
== nullptr || pipeline
.front()->http
->request
== pic
.request
.getRaw());
3366 if (Comm::IsConnOpen(pic
.connection
)) {
3367 notePinnedConnectionBecameIdle(pic
);
3368 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3370 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3372 getSslContextStart();
3375 #endif /* USE_OPENSSL */
3378 ConnStateData::initiateTunneledRequest(HttpRequest::Pointer
const &cause
, Http::MethodType
const method
, const char *reason
, const SBuf
&payload
)
3380 // fake a CONNECT request to force connState to tunnel
3382 unsigned short connectPort
= 0;
3384 if (pinning
.serverConnection
!= nullptr) {
3385 static char ip
[MAX_IPSTRLEN
];
3386 pinning
.serverConnection
->remote
.toHostStr(ip
, sizeof(ip
));
3387 connectHost
.assign(ip
);
3388 connectPort
= pinning
.serverConnection
->remote
.port();
3389 } else if (cause
&& cause
->method
== Http::METHOD_CONNECT
) {
3390 // We are inside a (not fully established) CONNECT request
3391 connectHost
= cause
->url
.host();
3392 connectPort
= cause
->url
.port();
3394 debugs(33, 2, "Not able to compute URL, abort request tunneling for " << reason
);
3398 debugs(33, 2, "Request tunneling for " << reason
);
3399 ClientHttpRequest
*http
= buildFakeRequest(method
, connectHost
, connectPort
, payload
);
3400 HttpRequest::Pointer request
= http
->request
;
3401 request
->flags
.forceTunnel
= true;
3402 http
->calloutContext
= new ClientRequestContext(http
);
3404 clientProcessRequestFinished(this, request
);
3409 ConnStateData::fakeAConnectRequest(const char *reason
, const SBuf
&payload
)
3411 debugs(33, 2, "fake a CONNECT request to force connState to tunnel for " << reason
);
3414 assert(transparent());
3415 const unsigned short connectPort
= clientConnection
->local
.port();
3418 if (!tlsClientSni_
.isEmpty())
3419 connectHost
.assign(tlsClientSni_
);
3423 static char ip
[MAX_IPSTRLEN
];
3424 clientConnection
->local
.toHostStr(ip
, sizeof(ip
));
3425 connectHost
.assign(ip
);
3428 ClientHttpRequest
*http
= buildFakeRequest(Http::METHOD_CONNECT
, connectHost
, connectPort
, payload
);
3430 http
->calloutContext
= new ClientRequestContext(http
);
3431 HttpRequest::Pointer request
= http
->request
;
3433 clientProcessRequestFinished(this, request
);
3438 ConnStateData::buildFakeRequest(Http::MethodType
const method
, SBuf
&useHost
, unsigned short usePort
, const SBuf
&payload
)
3440 ClientHttpRequest
*http
= new ClientHttpRequest(this);
3441 Http::Stream
*stream
= new Http::Stream(clientConnection
, http
);
3443 StoreIOBuffer tempBuffer
;
3444 tempBuffer
.data
= stream
->reqbuf
;
3445 tempBuffer
.length
= HTTP_REQBUF_SZ
;
3447 ClientStreamData newServer
= new clientReplyContext(http
);
3448 ClientStreamData newClient
= stream
;
3449 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
3450 clientReplyStatus
, newServer
, clientSocketRecipient
,
3451 clientSocketDetach
, newClient
, tempBuffer
);
3453 http
->uri
= SBufToCstring(useHost
);
3454 stream
->flags
.parsed_ok
= 1; // Do we need it?
3455 stream
->mayUseConnection(true);
3457 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3458 CommTimeoutCbPtrFun(clientLifetimeTimeout
, stream
->http
));
3459 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3461 stream
->registerWithConn();
3463 MasterXaction::Pointer mx
= new MasterXaction(XactionInitiator::initClient
);
3464 mx
->tcpClient
= clientConnection
;
3465 // Setup Http::Request object. Maybe should be replaced by a call to (modified)
3466 // clientProcessRequest
3467 HttpRequest::Pointer request
= new HttpRequest(mx
);
3468 AnyP::ProtocolType proto
= (method
== Http::METHOD_NONE
) ? AnyP::PROTO_AUTHORITY_FORM
: AnyP::PROTO_HTTP
;
3469 request
->url
.setScheme(proto
, nullptr);
3470 request
->method
= method
;
3471 request
->url
.host(useHost
.c_str());
3472 request
->url
.port(usePort
);
3473 http
->request
= request
.getRaw();
3474 HTTPMSGLOCK(http
->request
);
3476 request
->manager(this, http
->al
);
3478 if (proto
== AnyP::PROTO_HTTP
)
3479 request
->header
.putStr(Http::HOST
, useHost
.c_str());
3481 request
->sources
|= ((switchedToHttps() || port
->transport
.protocol
== AnyP::PROTO_HTTPS
) ? Http::Message::srcHttps
: Http::Message::srcHttp
);
3484 request
->auth_user_request
= getAuth();
3488 flags
.readMore
= false;
3490 setLogUri(http
, urlCanonicalClean(request
.getRaw()));
3494 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3496 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3498 if (!Comm::IsConnOpen(c
)) {
3499 Must(NHttpSockets
> 0); // we tried to open some
3500 --NHttpSockets
; // there will be fewer sockets than planned
3501 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3503 if (!NHttpSockets
) // we could not open any listen sockets at all
3504 fatalf("Unable to open %s",FdNote(portType
));
3511 /// find any unused HttpSockets[] slot and store fd there or return false
3513 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
3516 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
3517 if ((found
= HttpSockets
[i
] < 0))
3518 HttpSockets
[i
] = conn
->fd
;
3524 clientHttpConnectionsOpen(void)
3526 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3527 const SBuf
&scheme
= AnyP::UriScheme(s
->transport
.protocol
).image();
3529 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
3530 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many '" << scheme
<< "_port' lines.");
3531 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
3536 if (s
->flags
.tunnelSslBumping
) {
3537 if (!Config
.accessList
.ssl_bump
) {
3538 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme
<< "_port " << s
->s
);
3539 s
->flags
.tunnelSslBumping
= false;
3541 if (!s
->secure
.staticContext
&& !s
->secure
.generateHostCertificates
) {
3542 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at " << scheme
<< "_port " << s
->s
<< " due to TLS initialization failure.");
3543 s
->flags
.tunnelSslBumping
= false;
3544 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
)
3545 s
->secure
.encryptTransport
= false;
3547 if (s
->flags
.tunnelSslBumping
) {
3548 // Create ssl_ctx cache for this port.
3549 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->secure
.dynamicCertMemCacheSize
);
3554 if (s
->secure
.encryptTransport
&& !s
->secure
.staticContext
) {
3555 debugs(1, DBG_CRITICAL
, "ERROR: Ignoring " << scheme
<< "_port " << s
->s
<< " due to TLS context initialization failure.");
3559 // Fill out a Comm::Connection which IPC will open as a listener for us
3560 // then pass back when active so we can start a TcpAcceptor subscription.
3561 s
->listenConn
= new Comm::Connection
;
3562 s
->listenConn
->local
= s
->s
;
3564 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3565 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3567 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3568 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
) {
3569 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
3570 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
3571 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3573 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
3574 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
3575 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
3577 } else if (s
->transport
.protocol
== AnyP::PROTO_HTTPS
) {
3578 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
3579 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
3580 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3582 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
3583 ListeningStartedDialer(&clientListenerConnectionOpened
,
3584 s
, Ipc::fdnHttpsSocket
, sub
));
3585 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
3588 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
3594 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
3596 // Fill out a Comm::Connection which IPC will open as a listener for us
3597 port
->listenConn
= new Comm::Connection
;
3598 port
->listenConn
->local
= port
->s
;
3599 port
->listenConn
->flags
=
3601 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
3602 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3604 // route new connections to subCall
3605 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3606 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
3607 AsyncCall::Pointer listenCall
=
3608 asyncCall(33, 2, "clientListenerConnectionOpened",
3609 ListeningStartedDialer(&clientListenerConnectionOpened
,
3610 port
, fdNote
, sub
));
3611 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
3613 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
3614 HttpSockets
[NHttpSockets
] = -1;
3618 /// process clientHttpConnectionsOpen result
3620 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
3624 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
3627 Must(Comm::IsConnOpen(s
->listenConn
));
3629 // TCP: setup a job to handle accept() with subscribed handler
3630 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
3632 debugs(1, DBG_IMPORTANT
, "Accepting " <<
3633 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
3634 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
3635 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
3636 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
3637 << FdNote(portTypeNote
) << " connections at "
3640 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
3644 clientOpenListenSockets(void)
3646 clientHttpConnectionsOpen();
3647 Ftp::StartListening();
3649 if (NHttpSockets
< 1)
3650 fatal("No HTTP, HTTPS, or FTP ports configured");
3654 clientConnectionsClose()
3656 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
3657 if (s
->listenConn
!= NULL
) {
3658 debugs(1, DBG_IMPORTANT
, "Closing HTTP(S) port " << s
->listenConn
->local
);
3659 s
->listenConn
->close();
3660 s
->listenConn
= NULL
;
3664 Ftp::StopListening();
3666 // TODO see if we can drop HttpSockets array entirely */
3667 for (int i
= 0; i
< NHttpSockets
; ++i
) {
3668 HttpSockets
[i
] = -1;
3675 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
3677 SBuf
vary(request
->vary_headers
);
3678 int has_vary
= entry
->getReply()->header
.has(Http::HdrType::VARY
);
3679 #if X_ACCELERATOR_VARY
3682 entry
->getReply()->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
3685 if (!has_vary
|| entry
->mem_obj
->vary_headers
.isEmpty()) {
3686 if (!vary
.isEmpty()) {
3687 /* Oops... something odd is going on here.. */
3688 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
3689 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3690 request
->vary_headers
.clear();
3695 /* This is not a varying object */
3699 /* virtual "vary" object found. Calculate the vary key and
3700 * continue the search
3702 vary
= httpMakeVaryMark(request
, entry
->getReply());
3704 if (!vary
.isEmpty()) {
3705 request
->vary_headers
= vary
;
3708 /* Ouch.. we cannot handle this kind of variance */
3709 /* XXX This cannot really happen, but just to be complete */
3713 if (vary
.isEmpty()) {
3714 vary
= httpMakeVaryMark(request
, entry
->getReply());
3716 if (!vary
.isEmpty())
3717 request
->vary_headers
= vary
;
3720 if (vary
.isEmpty()) {
3721 /* Ouch.. we cannot handle this kind of variance */
3722 /* XXX This cannot really happen, but just to be complete */
3724 } else if (vary
.cmp(entry
->mem_obj
->vary_headers
) == 0) {
3727 /* Oops.. we have already been here and still haven't
3728 * found the requested variant. Bail out
3730 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
3731 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
3737 ACLFilledChecklist
*
3738 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
3740 const auto checklist
= new ACLFilledChecklist(acl
, nullptr, nullptr);
3741 clientAclChecklistFill(*checklist
, http
);
3746 clientAclChecklistFill(ACLFilledChecklist
&checklist
, ClientHttpRequest
*http
)
3748 checklist
.setRequest(http
->request
);
3749 checklist
.al
= http
->al
;
3750 checklist
.syncAle(http
->request
, http
->log_uri
);
3752 // TODO: If http->getConn is always http->request->clientConnectionManager,
3753 // then call setIdent() inside checklist.setRequest(). Otherwise, restore
3754 // USE_IDENT lost in commit 94439e4.
3755 ConnStateData
* conn
= http
->getConn();
3756 const char *ident
= (cbdataReferenceValid(conn
) &&
3757 conn
&& conn
->clientConnection
) ?
3758 conn
->clientConnection
->rfc931
: dash_str
;
3759 checklist
.setIdent(ident
);
3763 ConnStateData::transparent() const
3765 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
3769 ConnStateData::expectRequestBody(int64_t size
)
3771 bodyPipe
= new BodyPipe(this);
3773 bodyPipe
->setBodySize(size
);
3775 startDechunkingRequest();
3780 ConnStateData::mayNeedToReadMoreBody() const
3783 return 0; // request without a body or read/produced all body bytes
3785 if (!bodyPipe
->bodySizeKnown())
3786 return -1; // probably need to read more, but we cannot be sure
3788 const int64_t needToProduce
= bodyPipe
->unproducedSize();
3789 const int64_t haveAvailable
= static_cast<int64_t>(inBuf
.length());
3791 if (needToProduce
<= haveAvailable
)
3792 return 0; // we have read what we need (but are waiting for pipe space)
3794 return needToProduce
- haveAvailable
;
3798 ConnStateData::stopReceiving(const char *error
)
3800 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
3801 "; old sending error: " <<
3802 (stoppedSending() ? stoppedSending_
: "none"));
3804 if (const char *oldError
= stoppedReceiving()) {
3805 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
3806 return; // nothing has changed as far as this connection is concerned
3809 stoppedReceiving_
= error
;
3811 if (const char *sendError
= stoppedSending()) {
3812 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
3813 clientConnection
->close();
3818 ConnStateData::expectNoForwarding()
3820 if (bodyPipe
!= NULL
) {
3821 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
3822 bodyPipe
->expectNoConsumption();
3826 /// initialize dechunking state
3828 ConnStateData::startDechunkingRequest()
3830 Must(bodyPipe
!= NULL
);
3831 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
3832 assert(!bodyParser
);
3833 bodyParser
= new Http1::TeChunkedParser
;
3836 /// put parsed content into input buffer and clean up
3838 ConnStateData::finishDechunkingRequest(bool withSuccess
)
3840 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
3842 if (bodyPipe
!= NULL
) {
3843 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
3844 BodyPipe::Pointer myPipe
= bodyPipe
;
3845 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
3846 Must(!bodyPipe
); // we rely on it being nil after we are done with body
3848 Must(myPipe
->bodySizeKnown());
3849 Http::StreamPointer context
= pipeline
.front();
3850 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
3851 context
->http
->request
->setContentLength(myPipe
->bodySize());
3859 // XXX: this is an HTTP/1-only operation
3861 ConnStateData::sendControlMsg(HttpControlMsg msg
)
3864 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
3868 // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them
3869 if (!pipeline
.empty()) {
3870 HttpReply::Pointer
rep(msg
.reply
);
3872 // remember the callback
3873 cbControlMsgSent
= msg
.cbSuccess
;
3875 typedef CommCbMemFunT
<HttpControlMsgSink
, CommIoCbParams
> Dialer
;
3876 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, HttpControlMsgSink::wroteControlMsg
);
3878 if (!writeControlMsgAndCall(rep
.getRaw(), call
)) {
3879 // but still inform the caller (so it may resume its operation)
3880 doneWithControlMsg();
3885 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
3886 clientConnection
->close();
3890 ConnStateData::doneWithControlMsg()
3892 HttpControlMsgSink::doneWithControlMsg();
3894 if (Http::StreamPointer deferredRequest
= pipeline
.front()) {
3895 debugs(33, 3, clientConnection
<< ": calling PushDeferredIfNeeded after control msg wrote");
3896 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, this);
3900 /// Our close handler called by Comm when the pinned connection is closed
3902 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
3904 // FwdState might repin a failed connection sooner than this close
3905 // callback is called for the failed connection.
3906 assert(pinning
.serverConnection
== io
.conn
);
3907 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
3908 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
3909 pinning
.serverConnection
->noteClosure();
3910 unpinConnection(false);
3912 if (sawZeroReply
&& clientConnection
!= NULL
) {
3913 debugs(33, 3, "Closing client connection on pinned zero reply.");
3914 clientConnection
->close();
3920 ConnStateData::pinBusyConnection(const Comm::ConnectionPointer
&pinServer
, const HttpRequest::Pointer
&request
)
3922 pinConnection(pinServer
, *request
);
3926 ConnStateData::notePinnedConnectionBecameIdle(PinnedIdleContext pic
)
3928 Must(pic
.connection
);
3930 pinConnection(pic
.connection
, *pic
.request
);
3932 // monitor pinned server connection for remote-end closures.
3933 startPinnedConnectionMonitoring();
3935 if (pipeline
.empty())
3936 kick(); // in case clientParseRequests() was blocked by a busy pic.connection
3939 /// Forward future client requests using the given server connection.
3941 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, const HttpRequest
&request
)
3943 if (Comm::IsConnOpen(pinning
.serverConnection
) &&
3944 pinning
.serverConnection
->fd
== pinServer
->fd
) {
3945 debugs(33, 3, "already pinned" << pinServer
);
3949 unpinConnection(true); // closes pinned connection, if any, and resets fields
3951 pinning
.serverConnection
= pinServer
;
3953 debugs(33, 3, HERE
<< pinning
.serverConnection
);
3955 Must(pinning
.serverConnection
!= NULL
);
3957 const char *pinnedHost
= "[unknown]";
3958 pinning
.host
= xstrdup(request
.url
.host());
3959 pinning
.port
= request
.url
.port();
3960 pinnedHost
= pinning
.host
;
3961 pinning
.pinned
= true;
3962 if (CachePeer
*aPeer
= pinServer
->getPeer())
3963 pinning
.peer
= cbdataReference(aPeer
);
3964 pinning
.auth
= request
.flags
.connectionAuth
;
3965 char stmp
[MAX_IPSTRLEN
];
3966 char desc
[FD_DESC_SZ
];
3967 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
3968 (pinning
.auth
|| !pinning
.peer
) ? pinnedHost
: pinning
.peer
->name
,
3969 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
3970 clientConnection
->fd
);
3971 fd_note(pinning
.serverConnection
->fd
, desc
);
3973 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3974 pinning
.closeHandler
= JobCallback(33, 5,
3975 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
3976 // remember the pinned connection so that cb does not unpin a fresher one
3977 typedef CommCloseCbParams Params
;
3978 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
3979 params
.conn
= pinning
.serverConnection
;
3980 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
3983 /// [re]start monitoring pinned connection for peer closures so that we can
3984 /// propagate them to an _idle_ client pinned to that peer
3986 ConnStateData::startPinnedConnectionMonitoring()
3988 if (pinning
.readHandler
!= NULL
)
3989 return; // already monitoring
3991 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
3992 pinning
.readHandler
= JobCallback(33, 3,
3993 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
3994 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
3998 ConnStateData::stopPinnedConnectionMonitoring()
4000 if (pinning
.readHandler
!= NULL
) {
4001 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4002 pinning
.readHandler
= NULL
;
4008 ConnStateData::handleIdleClientPinnedTlsRead()
4010 // A ready-for-reading connection means that the TLS server either closed
4011 // the connection, sent us some unexpected HTTP data, or started TLS
4012 // renegotiations. We should close the connection except for the last case.
4014 Must(pinning
.serverConnection
!= nullptr);
4015 auto ssl
= fd_table
[pinning
.serverConnection
->fd
].ssl
.get();
4020 const int readResult
= SSL_read(ssl
, buf
, sizeof(buf
));
4022 if (readResult
> 0 || SSL_pending(ssl
) > 0) {
4023 debugs(83, 2, pinning
.serverConnection
<< " TLS application data read");
4027 switch(const int error
= SSL_get_error(ssl
, readResult
)) {
4028 case SSL_ERROR_WANT_WRITE
:
4029 debugs(83, DBG_IMPORTANT
, pinning
.serverConnection
<< " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection");
4030 // fall through to restart monitoring, for now
4031 case SSL_ERROR_NONE
:
4032 case SSL_ERROR_WANT_READ
:
4033 startPinnedConnectionMonitoring();
4037 debugs(83, 2, pinning
.serverConnection
<< " TLS error: " << error
);
4046 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4047 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4049 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4051 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4053 if (io
.flag
== Comm::ERR_CLOSING
)
4054 return; // close handler will clean up
4056 Must(pinning
.serverConnection
== io
.conn
);
4059 if (handleIdleClientPinnedTlsRead())
4063 const bool clientIsIdle
= pipeline
.empty();
4065 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4066 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4068 pinning
.serverConnection
->close();
4070 // If we are still sending data to the client, do not close now. When we are done sending,
4071 // ConnStateData::kick() checks pinning.serverConnection and will close.
4072 // However, if we are idle, then we must close to inform the idle client and minimize races.
4073 if (clientIsIdle
&& clientConnection
!= NULL
)
4074 clientConnection
->close();
4077 const Comm::ConnectionPointer
4078 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4080 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4083 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4085 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->url
.host()) != 0)
4087 else if (request
&& pinning
.port
!= request
->url
.port())
4089 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4091 else if (aPeer
!= pinning
.peer
)
4095 /* The pinning info is not safe, remove any pinning info */
4096 unpinConnection(true);
4099 return pinning
.serverConnection
;
4102 Comm::ConnectionPointer
4103 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4105 debugs(33, 7, pinning
.serverConnection
);
4106 if (validatePinnedConnection(request
, aPeer
) != NULL
)
4107 stopPinnedConnectionMonitoring();
4109 return pinning
.serverConnection
; // closed if validation failed
4113 ConnStateData::unpinConnection(const bool andClose
)
4115 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4118 cbdataReferenceDone(pinning
.peer
);
4120 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4121 if (pinning
.closeHandler
!= NULL
) {
4122 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4123 pinning
.closeHandler
= NULL
;
4126 stopPinnedConnectionMonitoring();
4128 // close the server side socket if requested
4130 pinning
.serverConnection
->close();
4131 pinning
.serverConnection
= NULL
;
4134 safe_free(pinning
.host
);
4136 pinning
.zeroReply
= false;
4138 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4139 * connection has gone away */
4143 ConnStateData::checkLogging()
4145 // if we are parsing request body, its request is responsible for logging
4149 // a request currently using this connection is responsible for logging
4150 if (!pipeline
.empty() && pipeline
.back()->mayUseConnection())
4153 /* Either we are waiting for the very first transaction, or
4154 * we are done with the Nth transaction and are waiting for N+1st.
4155 * XXX: We assume that if anything was added to inBuf, then it could
4156 * only be consumed by actions already covered by the above checks.
4159 // do not log connections that closed after a transaction (it is normal)
4160 // TODO: access_log needs ACLs to match received-no-bytes connections
4161 if (pipeline
.nrequests
&& inBuf
.isEmpty())
4164 /* Create a temporary ClientHttpRequest object. Its destructor will log. */
4165 ClientHttpRequest
http(this);
4166 http
.req_sz
= inBuf
.length();
4167 // XXX: Or we died while waiting for the pinned connection to become idle.
4168 char const *uri
= "error:transaction-end-before-headers";
4169 http
.uri
= xstrdup(uri
);
4170 setLogUri(&http
, uri
);
4174 ConnStateData::mayTunnelUnsupportedProto()
4176 return Config
.accessList
.on_unsupported_protocol
4179 ((port
->flags
.isIntercepted() && port
->flags
.tunnelSslBumping
)
4180 || (serverBump() && pinning
.serverConnection
))
4186 ConnStateData::notes()
4189 theNotes
= new NotePairs
;
4194 operator <<(std::ostream
&os
, const ConnStateData::PinnedIdleContext
&pic
)
4196 return os
<< pic
.connection
<< ", request=" << pic
.request
;