2 * Copyright (C) 1996-2015 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 "HttpHdrContRange.h"
91 #include "HttpHeaderTools.h"
92 #include "HttpReply.h"
93 #include "HttpRequest.h"
94 #include "ident/Config.h"
95 #include "ident/Ident.h"
97 #include "ipc/FdNotes.h"
98 #include "ipc/StartListening.h"
99 #include "log/access_log.h"
101 #include "MemObject.h"
102 #include "mime_header.h"
103 #include "parser/Tokenizer.h"
104 #include "profiler/Profiler.h"
106 #include "servers/forward.h"
107 #include "SquidConfig.h"
108 #include "SquidTime.h"
109 #include "StatCounters.h"
110 #include "StatHist.h"
112 #include "TimeOrTag.h"
117 #include "auth/UserRequest.h"
120 #include "ClientInfo.h"
124 #include "ssl/context_storage.h"
125 #include "ssl/gadgets.h"
126 #include "ssl/helper.h"
127 #include "ssl/ProxyCerts.h"
128 #include "ssl/ServerBump.h"
129 #include "ssl/support.h"
132 #include "ssl/certificate_db.h"
133 #include "ssl/crtd_message.h"
136 // for tvSubUsec() which should be in SquidTime.h
144 #define comm_close comm_lingering_close
147 /// dials clientListenerConnectionOpened call
148 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
151 typedef void (*Handler
)(AnyP::PortCfgPointer
&portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
152 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfgPointer
&aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
153 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
155 virtual void print(std::ostream
&os
) const {
157 ", " << FdNote(portTypeNote
) << " port=" << (void*)&portCfg
<< ')';
160 virtual bool canDial(AsyncCall
&) const { return true; }
161 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
167 AnyP::PortCfgPointer portCfg
; ///< from HttpPortList
168 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
169 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
172 static void clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
174 /* our socket-related context */
176 CBDATA_CLASS_INIT(ClientSocketContext
);
178 /* Local functions */
179 static IOACB httpAccept
;
181 static IOACB httpsAccept
;
183 static CTCB clientLifetimeTimeout
;
185 static IDCB clientIdentDone
;
187 static int clientIsContentLengthValid(HttpRequest
* r
);
188 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
190 static void clientUpdateStatHistCounters(const LogTags
&logType
, int svc_time
);
191 static void clientUpdateStatCounters(const LogTags
&logType
);
192 static void clientUpdateHierCounters(HierarchyLogEntry
*);
193 static bool clientPingHasFinished(ping_data
const *aPing
);
194 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
195 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
196 static void clientUpdateSocketStats(const LogTags
&logType
, size_t size
);
198 char *skipLeadingSpace(char *aString
);
201 ClientSocketContext::getTail() const
203 if (http
->client_stream
.tail
)
204 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
210 ClientSocketContext::getClientReplyContext() const
212 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
216 ClientSocketContext::getConn() const
218 return http
->getConn();
221 ClientSocketContext::~ClientSocketContext()
223 clientStreamNode
*node
= getTail();
226 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
229 /* We are *always* the tail - prevent recursive free */
230 assert(this == streamContext
);
235 httpRequestFree(http
);
239 ClientSocketContext::registerWithConn()
241 assert (!connRegistered_
);
243 assert (http
->getConn() != NULL
);
244 connRegistered_
= true;
245 http
->getConn()->pipeline
.add(ClientSocketContext::Pointer(this));
249 ClientSocketContext::finished()
252 assert (http
->getConn() != NULL
);
253 ConnStateData
*conn
= http
->getConn();
255 /* we can't handle any more stream data - detach */
256 clientStreamDetach(getTail(), http
);
258 assert(connRegistered_
);
259 connRegistered_
= false;
260 assert(conn
->pipeline
.front() == this); // XXX: still assumes HTTP/1 semantics
261 conn
->pipeline
.popMe(ClientSocketContext::Pointer(this));
264 ClientSocketContext::ClientSocketContext(const Comm::ConnectionPointer
&aConn
, ClientHttpRequest
*aReq
) :
265 clientConnection(aConn
),
269 mayUseConnection_ (false),
270 connRegistered_ (false)
272 assert(http
!= NULL
);
273 memset (reqbuf
, '\0', sizeof (reqbuf
));
276 deferredparams
.node
= NULL
;
277 deferredparams
.rep
= NULL
;
282 clientIdentDone(const char *ident
, void *data
)
284 ConnStateData
*conn
= (ConnStateData
*)data
;
285 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
290 clientUpdateStatCounters(const LogTags
&logType
)
292 ++statCounter
.client_http
.requests
;
294 if (logType
.isTcpHit())
295 ++statCounter
.client_http
.hits
;
297 if (logType
.oldType
== LOG_TCP_HIT
)
298 ++statCounter
.client_http
.disk_hits
;
299 else if (logType
.oldType
== LOG_TCP_MEM_HIT
)
300 ++statCounter
.client_http
.mem_hits
;
304 clientUpdateStatHistCounters(const LogTags
&logType
, int svc_time
)
306 statCounter
.client_http
.allSvcTime
.count(svc_time
);
308 * The idea here is not to be complete, but to get service times
309 * for only well-defined types. For example, we don't include
310 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
311 * (we *tried* to validate it, but failed).
314 switch (logType
.oldType
) {
316 case LOG_TCP_REFRESH_UNMODIFIED
:
317 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
320 case LOG_TCP_IMS_HIT
:
321 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
326 case LOG_TCP_MEM_HIT
:
328 case LOG_TCP_OFFLINE_HIT
:
329 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
334 case LOG_TCP_CLIENT_REFRESH_MISS
:
335 statCounter
.client_http
.missSvcTime
.count(svc_time
);
339 /* make compiler warnings go away */
345 clientPingHasFinished(ping_data
const *aPing
)
347 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
354 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
358 switch (someEntry
->code
) {
359 #if USE_CACHE_DIGESTS
364 ++ statCounter
.cd
.times_used
;
372 case FIRST_PARENT_MISS
:
374 case CLOSEST_PARENT_MISS
:
375 ++ statCounter
.icp
.times_used
;
376 i
= &someEntry
->ping
;
378 if (clientPingHasFinished(i
))
379 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
382 ++ statCounter
.icp
.query_timeouts
;
389 ++ statCounter
.netdb
.times_used
;
399 ClientHttpRequest::updateCounters()
401 clientUpdateStatCounters(logType
);
403 if (request
->errType
!= ERR_NONE
)
404 ++ statCounter
.client_http
.errors
;
406 clientUpdateStatHistCounters(logType
,
407 tvSubMsec(al
->cache
.start_time
, current_time
));
409 clientUpdateHierCounters(&request
->hier
);
413 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
416 assert(aLogEntry
!= NULL
);
418 if (Config
.onoff
.log_mime_hdrs
) {
421 request
->header
.packInto(&mb
);
422 //This is the request after adaptation or redirection
423 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
425 // the virgin request is saved to aLogEntry->request
426 if (aLogEntry
->request
) {
428 aLogEntry
->request
->header
.packInto(&mb
);
429 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
433 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
436 ah
->lastMeta
.packInto(&mb
);
437 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
445 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
447 ih
->processingTime(aLogEntry
->icap
.processingTime
);
450 aLogEntry
->http
.method
= request
->method
;
451 aLogEntry
->http
.version
= request
->http_ver
;
452 aLogEntry
->hier
= request
->hier
;
453 if (request
->content_length
> 0) // negative when no body or unknown length
454 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
455 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
457 // Adapted request, if any, inherits and then collects all the stats, but
458 // the virgin request gets logged instead; copy the stats to log them.
459 // TODO: avoid losses by keeping these stats in a shared history object?
460 if (aLogEntry
->request
) {
461 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
462 aLogEntry
->request
->errType
= request
->errType
;
463 aLogEntry
->request
->errDetail
= request
->errDetail
;
468 ClientHttpRequest::logRequest()
470 if (!out
.size
&& logType
.oldType
== LOG_TAG_NONE
)
471 debugs(33, 5, "logging half-baked transaction: " << log_uri
);
473 al
->icp
.opcode
= ICP_INVALID
;
475 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
478 al
->http
.code
= al
->reply
->sline
.status();
479 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
480 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
481 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
482 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
485 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
487 if (loggingEntry() && loggingEntry()->mem_obj
&& loggingEntry()->objectLen() >= 0)
488 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
490 al
->http
.clientRequestSz
.header
= req_sz
;
491 al
->http
.clientReplySz
.header
= out
.headers_sz
;
492 // XXX: calculate without payload encoding or headers !!
493 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
495 al
->cache
.highOffset
= out
.offset
;
497 al
->cache
.code
= logType
;
499 tvSub(al
->cache
.trTime
, al
->cache
.start_time
, current_time
);
502 prepareLogWithRequestDetails(request
, al
);
504 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
505 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
509 /* This is broken. Fails if the connection has been closed. Needs
510 * to snarf the ssl details some place earlier..
512 if (getConn() != NULL
)
513 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
517 /* Add notes (if we have a request to annotate) */
519 // The al->notes and request->notes must point to the same object.
520 (void)SyncNotes(*al
, *request
);
521 for (auto i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
522 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
523 NotePairs
¬es
= SyncNotes(*al
, *request
);
524 notes
.add((*i
)->key
.termedBuf(), value
);
525 debugs(33, 3, (*i
)->key
.termedBuf() << " " << value
);
530 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
532 checklist
.reply
= al
->reply
;
533 HTTPMSGLOCK(checklist
.reply
);
537 al
->adapted_request
= request
;
538 HTTPMSGLOCK(al
->adapted_request
);
540 accessLogLog(al
, &checklist
);
542 bool updatePerformanceCounters
= true;
543 if (Config
.accessList
.stats_collection
) {
544 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
546 statsCheck
.reply
= al
->reply
;
547 HTTPMSGLOCK(statsCheck
.reply
);
549 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
552 if (updatePerformanceCounters
) {
556 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
557 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
562 ClientHttpRequest::freeResources()
566 safe_free(redirect
.location
);
567 range_iter
.boundary
.clean();
568 HTTPMSGUNLOCK(request
);
570 if (client_stream
.tail
)
571 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
575 httpRequestFree(void *data
)
577 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
578 assert(http
!= NULL
);
582 /* This is a handler normally called by comm_close() */
583 void ConnStateData::connStateClosed(const CommCloseCbParams
&)
585 deleteThis("ConnStateData::connStateClosed");
590 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
594 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
600 // clobered with self-pointer
601 // NP: something nasty is going on in Squid, but harmless.
603 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
608 * Connection-auth relies on a single set of credentials being preserved
609 * for all requests on a connection once they have been setup.
610 * There are several things which need to happen to preserve security
611 * when connection-auth credentials change unexpectedly or are unset.
613 * 1) auth helper released from any active state
615 * They can only be reserved by a handshake process which this
616 * connection can now never complete.
617 * This prevents helpers hanging when their connections close.
619 * 2) pinning is expected to be removed and server conn closed
621 * The upstream link is authenticated with the same credentials.
622 * Expecting the same level of consistency we should have received.
623 * This prevents upstream being faced with multiple or missing
624 * credentials after authentication.
625 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
626 * we just trigger that cleanup here via comm_reset_close() or
627 * ConnStateData::stopReceiving()
629 * 3) the connection needs to close.
631 * This prevents attackers injecting requests into a connection,
632 * or gateways wrongly multiplexing users into a single connection.
634 * When credentials are missing closure needs to follow an auth
635 * challenge for best recovery by the client.
637 * When credentials change there is nothing we can do but abort as
638 * fast as possible. Sending TCP RST instead of an HTTP response
639 * is the best-case action.
642 // clobbered with nul-pointer
644 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
645 auth_
->releaseAuthServer();
647 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
648 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
649 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
650 stopReceiving("connection-auth removed");
654 // clobbered with alternative credentials
656 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
657 auth_
->releaseAuthServer();
659 // this is a fatal type of problem.
660 // Close the connection immediately with TCP RST to abort all traffic flow
661 comm_reset_close(clientConnection
);
669 // cleans up before destructor is called
671 ConnStateData::swanSong()
673 debugs(33, 2, HERE
<< clientConnection
);
674 flags
.readMore
= false;
675 DeregisterRunner(this);
676 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
677 pipeline
.terminateAll(0);
679 unpinConnection(true);
681 Server::swanSong(); // closes the client connection
684 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
685 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
688 flags
.swanSang
= true;
692 ConnStateData::isOpen() const
694 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
695 Comm::IsConnOpen(clientConnection
) &&
696 !fd_table
[clientConnection
->fd
].closing();
699 ConnStateData::~ConnStateData()
701 debugs(33, 3, HERE
<< clientConnection
);
704 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
707 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
709 if (bodyPipe
!= NULL
)
710 stopProducingFor(bodyPipe
, false);
712 delete bodyParser
; // TODO: pool
715 delete sslServerBump
;
720 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
721 * This is the client-side persistent connection flag. We need
722 * to set this relatively early in the request processing
723 * to handle hacks for broken servers and clients.
726 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
728 HttpRequest
*request
= http
->request
;
730 debugs(33, 3, "http_ver = " << request
->http_ver
);
731 debugs(33, 3, "method = " << request
->method
);
733 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
734 request
->flags
.proxyKeepalive
= request
->persistent();
737 /// checks body length of non-chunked requests
739 clientIsContentLengthValid(HttpRequest
* r
)
741 // No Content-Length means this request just has no body, but conflicting
742 // Content-Lengths mean a message framing error (RFC 7230 Section 3.3.3 #4).
743 if (r
->header
.conflictingContentLength())
746 switch (r
->method
.id()) {
748 case Http::METHOD_GET
:
750 case Http::METHOD_HEAD
:
751 /* We do not want to see a request entity on GET/HEAD requests */
752 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
755 /* For other types of requests we don't care */
763 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
765 if (Config
.maxRequestBodySize
&&
766 bodyLength
> Config
.maxRequestBodySize
)
767 return 1; /* too large */
773 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
775 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
776 assert(flags
.deferred
== 0);
778 deferredparams
.node
= node
;
779 deferredparams
.rep
= rep
;
780 deferredparams
.queuedBuffer
= receivedData
;
785 ClientSocketContext::startOfOutput() const
787 return http
->out
.size
== 0;
791 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
793 /*the size of available range can always fit in a size_t type*/
794 size_t maximum
= (size_t)available
.size();
796 if (!http
->request
->range
)
799 assert (canPackMoreRanges());
801 if (http
->range_iter
.debt() == -1)
804 assert (http
->range_iter
.debt() > 0);
806 /* TODO this + the last line could be a range intersection calculation */
807 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
810 return min(http
->range_iter
.debt(), (int64_t)maximum
);
814 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
816 debugs(33, 7, bytes
<< " body bytes");
818 http
->out
.offset
+= bytes
;
820 if (!http
->request
->range
)
823 if (http
->range_iter
.debt() != -1) {
824 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
825 assert (http
->range_iter
.debt() >= 0);
828 /* debt() always stops at -1, below that is a bug */
829 assert (http
->range_iter
.debt() >= -1);
833 ClientHttpRequest::multipartRangeRequest() const
835 return request
->multipartRangeRequest();
839 ClientSocketContext::multipartRangeRequest() const
841 return http
->multipartRangeRequest();
845 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
849 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
850 size_t length
= lengthToSend(bodyData
.range());
851 noteSentBodyBytes (length
);
852 getConn()->write(bodyData
.data
, length
);
858 if (multipartRangeRequest())
859 packRange(bodyData
, &mb
);
861 packChunk(bodyData
, mb
);
863 if (mb
.contentSize())
864 getConn()->write(&mb
);
870 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
871 * if bodyData is empty.
874 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
876 const uint64_t length
=
877 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
878 noteSentBodyBytes(length
);
880 mb
.appendf("%" PRIX64
"\r\n", length
);
881 mb
.append(bodyData
.data
, length
);
882 mb
.append("\r\n", 2);
885 /** put terminating boundary for multiparts */
887 clientPackTermBound(String boundary
, MemBuf
* mb
)
889 mb
->appendf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
890 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
893 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
895 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
897 HttpHeader
hdr(hoReply
);
902 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
903 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
904 mb
->appendf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
906 /* stuff the header with required entries and pack it */
908 if (rep
->header
.has(Http::HdrType::CONTENT_TYPE
))
909 hdr
.putStr(Http::HdrType::CONTENT_TYPE
, rep
->header
.getStr(Http::HdrType::CONTENT_TYPE
));
911 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
916 /* append <crlf> (we packed a header, not a reply) */
917 mb
->append("\r\n", 2);
921 * extracts a "range" from *buf and appends them to mb, updating
922 * all offsets and such.
925 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
927 HttpHdrRangeIter
* i
= &http
->range_iter
;
928 Range
<int64_t> available (source
.range());
929 char const *buf
= source
.data
;
931 while (i
->currentSpec() && available
.size()) {
932 const size_t copy_sz
= lengthToSend(available
);
936 * intersection of "have" and "need" ranges must not be empty
938 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
939 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
942 * put boundary and headers at the beginning of a range in a
946 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
947 assert(http
->memObject());
949 http
->memObject()->getReply(), /* original reply */
950 i
->currentSpec(), /* current range */
951 i
->boundary
, /* boundary, the same for all */
958 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
960 noteSentBodyBytes (copy_sz
);
962 mb
->append(buf
, copy_sz
);
967 available
.start
+= copy_sz
;
973 if (!canPackMoreRanges()) {
974 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
977 /* put terminating boundary for multiparts */
978 clientPackTermBound(i
->boundary
, mb
);
983 int64_t nextOffset
= getNextRangeOffset();
985 assert (nextOffset
>= http
->out
.offset
);
987 int64_t skip
= nextOffset
- http
->out
.offset
;
989 /* adjust for not to be transmitted bytes */
990 http
->out
.offset
= nextOffset
;
992 if (available
.size() <= (uint64_t)skip
)
995 available
.start
+= skip
;
1004 /** returns expected content length for multi-range replies
1005 * note: assumes that httpHdrRangeCanonize has already been called
1006 * warning: assumes that HTTP headers for individual ranges at the
1007 * time of the actuall assembly will be exactly the same as
1008 * the headers when clientMRangeCLen() is called */
1010 ClientHttpRequest::mRangeCLen()
1015 assert(memObject());
1018 HttpHdrRange::iterator pos
= request
->range
->begin();
1020 while (pos
!= request
->range
->end()) {
1021 /* account for headers for this range */
1023 clientPackRangeHdr(memObject()->getReply(),
1024 *pos
, range_iter
.boundary
, &mb
);
1027 /* account for range content */
1028 clen
+= (*pos
)->length
;
1030 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1034 /* account for the terminating boundary */
1037 clientPackTermBound(range_iter
.boundary
, &mb
);
1047 * returns true if If-Range specs match reply, false otherwise
1050 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1052 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(Http::HdrType::IF_RANGE
);
1053 /* check for parsing falure */
1060 ETag rep_tag
= rep
->header
.getETag(Http::HdrType::ETAG
);
1061 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1062 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1065 return 0; /* entity has no etag to compare with! */
1067 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1068 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1069 return 0; /* must use strong validator for sub-range requests */
1072 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1075 /* got modification time? */
1076 if (spec
.time
>= 0) {
1077 return http
->storeEntry()->lastmod
<= spec
.time
;
1080 assert(0); /* should not happen */
1085 * generates a "unique" boundary string for multipart responses
1086 * the caller is responsible for cleaning the string */
1088 ClientHttpRequest::rangeBoundaryStr() const
1091 String
b(APP_FULLNAME
);
1093 key
= storeEntry()->getMD5Text();
1094 b
.append(key
, strlen(key
));
1098 /** adds appropriate Range headers if needed */
1100 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1102 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1103 const char *range_err
= NULL
;
1104 HttpRequest
*request
= http
->request
;
1105 assert(request
->range
);
1106 /* check if we still want to do ranges */
1108 int64_t roffLimit
= request
->getRangeOffsetLimit();
1111 range_err
= "no [parse-able] reply";
1112 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1113 range_err
= "wrong status code";
1114 else if (hdr
->has(Http::HdrType::CONTENT_RANGE
))
1115 range_err
= "origin server does ranges";
1116 else if (rep
->content_length
< 0)
1117 range_err
= "unknown length";
1118 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1119 range_err
= "INCONSISTENT length"; /* a bug? */
1121 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1124 else if (http
->logType
.isTcpHit() && http
->request
->header
.has(Http::HdrType::IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1125 range_err
= "If-Range match failed";
1126 else if (!http
->request
->range
->canonize(rep
))
1127 range_err
= "canonization failed";
1128 else if (http
->request
->range
->isComplex())
1129 range_err
= "too complex range header";
1130 else if (!http
->logType
.isTcpHit() && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1131 range_err
= "range outside range_offset_limit";
1133 /* get rid of our range specs on error */
1135 /* XXX We do this here because we need canonisation etc. However, this current
1136 * code will lead to incorrect store offset requests - the store will have the
1137 * offset data, but we won't be requesting it.
1138 * So, we can either re-request, or generate an error
1140 http
->request
->ignoreRange(range_err
);
1142 /* XXX: TODO: Review, this unconditional set may be wrong. */
1143 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1144 // web server responded with a valid, but unexpected range.
1145 // will (try-to) forward as-is.
1146 //TODO: we should cope with multirange request/responses
1147 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1148 request
->range
->contains(rep
->content_range
->spec
) :
1150 const int spec_count
= http
->request
->range
->specs
.size();
1151 int64_t actual_clen
= -1;
1153 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1154 spec_count
<< " virgin clen: " << rep
->content_length
);
1155 assert(spec_count
> 0);
1156 /* append appropriate header(s) */
1158 if (spec_count
== 1) {
1159 if (!replyMatchRequest
) {
1160 hdr
->delById(Http::HdrType::CONTENT_RANGE
);
1161 hdr
->putContRange(rep
->content_range
);
1162 actual_clen
= rep
->content_length
;
1163 //http->range_iter.pos = rep->content_range->spec.begin();
1164 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1165 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1168 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1170 /* append Content-Range */
1172 if (!hdr
->has(Http::HdrType::CONTENT_RANGE
)) {
1173 /* No content range, so this was a full object we are
1176 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1179 /* set new Content-Length to the actual number of bytes
1180 * transmitted in the message-body */
1181 actual_clen
= (*pos
)->length
;
1185 /* generate boundary string */
1186 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1187 /* delete old Content-Type, add ours */
1188 hdr
->delById(Http::HdrType::CONTENT_TYPE
);
1189 httpHeaderPutStrf(hdr
, Http::HdrType::CONTENT_TYPE
,
1190 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1191 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1192 /* Content-Length is not required in multipart responses
1193 * but it is always nice to have one */
1194 actual_clen
= http
->mRangeCLen();
1195 /* http->out needs to start where we want data at */
1196 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1199 /* replace Content-Length header */
1200 assert(actual_clen
>= 0);
1202 hdr
->delById(Http::HdrType::CONTENT_LENGTH
);
1204 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, actual_clen
);
1206 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1208 /* And start the range iter off */
1209 http
->range_iter
.updateSpec();
1214 ClientSocketContext::prepareReply(HttpReply
* rep
)
1218 if (http
->request
->range
)
1219 buildRangeHeader(rep
);
1223 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1227 MemBuf
*mb
= rep
->pack();
1229 // dump now, so we dont output any body.
1230 debugs(11, 2, "HTTP Client " << clientConnection
);
1231 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1233 /* Save length of headers for persistent conn checks */
1234 http
->out
.headers_sz
= mb
->contentSize();
1237 headersLog(0, 0, http
->request
->method
, rep
);
1240 if (bodyData
.data
&& bodyData
.length
) {
1241 if (multipartRangeRequest())
1242 packRange(bodyData
, mb
);
1243 else if (http
->request
->flags
.chunkedReply
) {
1244 packChunk(bodyData
, *mb
);
1246 size_t length
= lengthToSend(bodyData
.range());
1247 noteSentBodyBytes (length
);
1249 mb
->append(bodyData
.data
, length
);
1253 getConn()->write(mb
);
1258 * Write a chunk of data to a client socket. If the reply is present,
1259 * send the reply headers down the wire too, and clean them up when
1262 * The request is one backed by a connection, not an internal request.
1263 * data context is not NULL
1264 * There are no more entries in the stream chain.
1267 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1268 HttpReply
* rep
, StoreIOBuffer receivedData
)
1270 // dont tryt to deliver if client already ABORTED
1271 if (!http
->getConn() || !cbdataReferenceValid(http
->getConn()) || !Comm::IsConnOpen(http
->getConn()->clientConnection
))
1274 /* Test preconditions */
1275 assert(node
!= NULL
);
1276 PROF_start(clientSocketRecipient
);
1277 /* TODO: handle this rather than asserting
1278 * - it should only ever happen if we cause an abort and
1279 * the callback chain loops back to here, so we can simply return.
1280 * However, that itself shouldn't happen, so it stays as an assert for now.
1282 assert(cbdataReferenceValid(node
));
1283 assert(node
->node
.next
== NULL
);
1284 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1285 assert(context
!= NULL
);
1287 /* TODO: check offset is what we asked for */
1289 // TODO: enforces HTTP/1 MUST on pipeline order, but is irrelevant to HTTP/2
1290 if (context
!= http
->getConn()->pipeline
.front())
1291 context
->deferRecipientForLater(node
, rep
, receivedData
);
1293 http
->getConn()->handleReply(rep
, receivedData
);
1295 PROF_stop(clientSocketRecipient
);
1299 * Called when a downstream node is no longer interested in
1300 * our data. As we are a terminal node, this means on aborts
1304 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1306 /* Test preconditions */
1307 assert(node
!= NULL
);
1308 /* TODO: handle this rather than asserting
1309 * - it should only ever happen if we cause an abort and
1310 * the callback chain loops back to here, so we can simply return.
1311 * However, that itself shouldn't happen, so it stays as an assert for now.
1313 assert(cbdataReferenceValid(node
));
1314 /* Set null by ContextFree */
1315 assert(node
->node
.next
== NULL
);
1316 /* this is the assert discussed above */
1317 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1318 /* We are only called when the client socket shutsdown.
1319 * Tell the prev pipeline member we're finished
1321 clientStreamDetach(node
, http
);
1325 ConnStateData::readNextRequest()
1327 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1329 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1331 * Set the timeout BEFORE calling readSomeData().
1333 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1334 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1335 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1336 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
1339 /** Please don't do anything with the FD past here! */
1343 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1345 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1347 /** If the client stream is waiting on a socket write to occur, then */
1349 if (deferredRequest
->flags
.deferred
) {
1350 /** NO data is allowed to have been sent. */
1351 assert(deferredRequest
->http
->out
.size
== 0);
1353 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1354 deferredRequest
->http
,
1355 deferredRequest
->deferredparams
.rep
,
1356 deferredRequest
->deferredparams
.queuedBuffer
);
1359 /** otherwise, the request is still active in a callbacksomewhere,
1365 ConnStateData::kick()
1367 if (!Comm::IsConnOpen(clientConnection
)) {
1368 debugs(33, 2, clientConnection
<< " Connection was closed");
1372 if (pinning
.pinned
&& !Comm::IsConnOpen(pinning
.serverConnection
)) {
1373 debugs(33, 2, clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1374 clientConnection
->close();
1379 * We are done with the response, and we are either still receiving request
1380 * body (early response!) or have already stopped receiving anything.
1382 * If we are still receiving, then clientParseRequest() below will fail.
1383 * (XXX: but then we will call readNextRequest() which may succeed and
1384 * execute a smuggled request as we are not done with the current request).
1386 * If we stopped because we got everything, then try the next request.
1388 * If we stopped receiving because of an error, then close now to avoid
1389 * getting stuck and to prevent accidental request smuggling.
1392 if (const char *reason
= stoppedReceiving()) {
1393 debugs(33, 3, "closing for earlier request error: " << reason
);
1394 clientConnection
->close();
1399 * Attempt to parse a request from the request buffer.
1400 * If we've been fed a pipelined request it may already
1401 * be in our read buffer.
1404 * This needs to fall through - if we're unlucky and parse the _last_ request
1405 * from our read buffer we may never re-register for another client read.
1408 if (clientParseRequests()) {
1409 debugs(33, 3, clientConnection
<< ": parsed next request from buffer");
1413 * Either we need to kick-start another read or, if we have
1414 * a half-closed connection, kill it after the last request.
1415 * This saves waiting for half-closed connections to finished being
1416 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1417 * the keepalive "Waiting for next request" state.
1419 if (commIsHalfClosed(clientConnection
->fd
) && pipeline
.empty()) {
1420 debugs(33, 3, "half-closed client with no pending requests, closing");
1421 clientConnection
->close();
1426 * At this point we either have a parsed request (which we've
1427 * kicked off the processing for) or not. If we have a deferred
1428 * request (parsed but deferred for pipeling processing reasons)
1429 * then look at processing it. If not, simply kickstart
1432 ClientSocketContext::Pointer deferredRequest
= pipeline
.front();
1433 if (deferredRequest
!= nullptr) {
1434 debugs(33, 3, clientConnection
<< ": calling PushDeferredIfNeeded");
1435 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, this);
1436 } else if (flags
.readMore
) {
1437 debugs(33, 3, clientConnection
<< ": calling readNextRequest()");
1440 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1441 debugs(33, DBG_IMPORTANT
, MYNAME
<< "abandoning " << clientConnection
);
1446 clientUpdateSocketStats(const LogTags
&logType
, size_t size
)
1451 statCounter
.client_http
.kbytes_out
+= size
;
1453 if (logType
.isTcpHit())
1454 statCounter
.client_http
.hit_kbytes_out
+= size
;
1458 * increments iterator "i"
1459 * used by clientPackMoreRanges
1461 \retval true there is still data available to pack more ranges
1465 ClientSocketContext::canPackMoreRanges() const
1467 /** first update iterator "i" if needed */
1469 if (!http
->range_iter
.debt()) {
1470 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1472 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1473 ++http
->range_iter
.pos
;
1475 http
->range_iter
.updateSpec();
1478 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1480 /* paranoid sync condition */
1481 /* continue condition: need_more_data */
1482 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1483 return http
->range_iter
.currentSpec() ? true : false;
1487 ClientSocketContext::getNextRangeOffset() const
1489 debugs (33, 5, "range: " << http
->request
->range
<<
1490 "; http offset " << http
->out
.offset
<<
1491 "; reply " << reply
);
1493 // XXX: This method is called from many places, including pullData() which
1494 // may be called before prepareReply() [on some Squid-generated errors].
1495 // Hence, we may not even know yet whether we should honor/do ranges.
1497 if (http
->request
->range
) {
1498 /* offset in range specs does not count the prefix of an http msg */
1499 /* check: reply was parsed and range iterator was initialized */
1500 assert(http
->range_iter
.valid
);
1501 /* filter out data according to range specs */
1502 assert (canPackMoreRanges());
1504 int64_t start
; /* offset of still missing data */
1505 assert(http
->range_iter
.currentSpec());
1506 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1507 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1508 debugs(33, 3, "clientPackMoreRanges: out:"
1509 " start: " << start
<<
1510 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1511 " [" << http
->range_iter
.currentSpec()->offset
<<
1512 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1513 " len: " << http
->range_iter
.currentSpec()->length
<<
1514 " debt: " << http
->range_iter
.debt());
1515 if (http
->range_iter
.currentSpec()->length
!= -1)
1516 assert(http
->out
.offset
<= start
); /* we did not miss it */
1521 } else if (reply
&& reply
->content_range
) {
1522 /* request does not have ranges, but reply does */
1523 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1524 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1526 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1529 return http
->out
.offset
;
1533 ClientSocketContext::pullData()
1535 debugs(33, 5, reply
<< " written " << http
->out
.size
<< " into " << clientConnection
);
1537 /* More data will be coming from the stream. */
1538 StoreIOBuffer readBuffer
;
1539 /* XXX: Next requested byte in the range sequence */
1540 /* XXX: length = getmaximumrangelenfgth */
1541 readBuffer
.offset
= getNextRangeOffset();
1542 readBuffer
.length
= HTTP_REQBUF_SZ
;
1543 readBuffer
.data
= reqbuf
;
1544 /* we may note we have reached the end of the wanted ranges */
1545 clientStreamRead(getTail(), http
, readBuffer
);
1548 /** Adapt stream status to account for Range cases
1551 clientStream_status_t
1552 ClientSocketContext::socketState()
1554 switch (clientStreamStatus(getTail(), http
)) {
1557 /* check for range support ending */
1559 if (http
->request
->range
) {
1560 /* check: reply was parsed and range iterator was initialized */
1561 assert(http
->range_iter
.valid
);
1562 /* filter out data according to range specs */
1564 if (!canPackMoreRanges()) {
1565 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1566 "range sequence on " << clientConnection
);
1567 // we got everything we wanted from the store
1568 return STREAM_COMPLETE
;
1570 } else if (reply
&& reply
->content_range
) {
1571 /* reply has content-range, but Squid is not managing ranges */
1572 const int64_t &bytesSent
= http
->out
.offset
;
1573 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1575 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1576 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1577 reply
->content_range
->spec
.offset
<< ")");
1579 // did we get at least what we expected, based on range specs?
1581 if (bytesSent
== bytesExpected
) // got everything
1582 return STREAM_COMPLETE
;
1584 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1585 return STREAM_UNPLANNED_COMPLETE
;
1590 case STREAM_COMPLETE
:
1591 return STREAM_COMPLETE
;
1593 case STREAM_UNPLANNED_COMPLETE
:
1594 return STREAM_UNPLANNED_COMPLETE
;
1597 return STREAM_FAILED
;
1600 fatal ("unreachable code\n");
1604 /// remembers the abnormal connection termination for logging purposes
1606 ClientSocketContext::noteIoError(const int xerrno
)
1609 http
->logType
.err
.timedout
= (xerrno
== ETIMEDOUT
);
1610 // aborted even if xerrno is zero (which means read abort/eof)
1611 http
->logType
.err
.aborted
= (xerrno
!= ETIMEDOUT
);
1616 ClientSocketContext::doClose()
1618 clientConnection
->close();
1621 /// called when we encounter a response-related error
1623 ClientSocketContext::initiateClose(const char *reason
)
1625 debugs(33, 4, clientConnection
<< " because " << reason
);
1626 http
->getConn()->stopSending(reason
); // closes ASAP
1630 ConnStateData::stopSending(const char *error
)
1632 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1633 "; old receiving error: " <<
1634 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1636 if (const char *oldError
= stoppedSending()) {
1637 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1638 return; // nothing has changed as far as this connection is concerned
1640 stoppedSending_
= error
;
1642 if (!stoppedReceiving()) {
1643 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1644 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1645 " request body bytes with " << inBuf
.length() << " unused");
1646 return; // wait for the request receiver to finish reading
1650 clientConnection
->close();
1654 ConnStateData::afterClientWrite(size_t size
)
1656 if (pipeline
.empty())
1659 pipeline
.front()->writeComplete(size
);
1662 // TODO: make this only need size parameter, ConnStateData handles the rest
1664 ClientSocketContext::writeComplete(size_t size
)
1666 const StoreEntry
*entry
= http
->storeEntry();
1667 debugs(33, 5, clientConnection
<< ", sz " << size
<<
1668 ", off " << (http
->out
.size
+ size
) << ", len " <<
1669 (entry
? entry
->objectLen() : 0));
1671 http
->out
.size
+= size
;
1672 clientUpdateSocketStats(http
->logType
, size
);
1674 if (clientHttpRequestStatus(clientConnection
->fd
, http
)) {
1675 initiateClose("failure or true request status");
1676 /* Do we leak here ? */
1680 switch (socketState()) {
1686 case STREAM_COMPLETE
: {
1687 debugs(33, 5, clientConnection
<< " Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1688 ConnStateData
*c
= http
->getConn();
1689 if (!http
->request
->flags
.proxyKeepalive
)
1690 clientConnection
->close();
1696 case STREAM_UNPLANNED_COMPLETE
:
1697 initiateClose("STREAM_UNPLANNED_COMPLETE");
1701 initiateClose("STREAM_FAILED");
1705 fatal("Hit unreachable code in ClientSocketContext::writeComplete\n");
1709 ClientSocketContext
*
1710 ConnStateData::abortRequestParsing(const char *const uri
)
1712 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1713 http
->req_sz
= inBuf
.length();
1714 http
->uri
= xstrdup(uri
);
1715 setLogUri (http
, uri
);
1716 ClientSocketContext
*context
= new ClientSocketContext(clientConnection
, http
);
1717 StoreIOBuffer tempBuffer
;
1718 tempBuffer
.data
= context
->reqbuf
;
1719 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1720 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1721 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1722 clientSocketDetach
, context
, tempBuffer
);
1727 ConnStateData::startShutdown()
1729 // RegisteredRunner API callback - Squid has been shut down
1731 // if connection is idle terminate it now,
1732 // otherwise wait for grace period to end
1733 if (pipeline
.empty())
1738 ConnStateData::endingShutdown()
1740 // RegisteredRunner API callback - Squid shutdown grace period is over
1742 // force the client connection to close immediately
1743 // swanSong() in the close handler will cleanup.
1744 if (Comm::IsConnOpen(clientConnection
))
1745 clientConnection
->close();
1747 // deregister now to ensure finalShutdown() does not kill us prematurely.
1748 // fd_table purge will cleanup if close handler was not fast enough.
1749 DeregisterRunner(this);
1753 skipLeadingSpace(char *aString
)
1755 char *result
= aString
;
1757 while (xisspace(*aString
))
1764 * 'end' defaults to NULL for backwards compatibility
1765 * remove default value if we ever get rid of NULL-terminated
1769 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1772 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1776 for (; end
> uriAndHTTPVersion
; --end
) {
1777 if (*end
== '\n' || *end
== '\r')
1780 if (xisspace(*end
)) {
1781 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1792 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1794 safe_free(http
->log_uri
);
1797 // The uri is already clean just dump it.
1798 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1801 switch (Config
.uri_whitespace
) {
1802 case URI_WHITESPACE_ALLOW
:
1803 flags
|= RFC1738_ESCAPE_NOSPACE
;
1805 case URI_WHITESPACE_ENCODE
:
1806 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1807 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1810 case URI_WHITESPACE_CHOP
: {
1811 flags
|= RFC1738_ESCAPE_NOSPACE
;
1812 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1813 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1814 int pos
= strcspn(http
->log_uri
, w_space
);
1815 http
->log_uri
[pos
] = '\0';
1819 case URI_WHITESPACE_DENY
:
1820 case URI_WHITESPACE_STRIP
:
1823 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1827 if (!xisspace(*t
)) {
1834 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
1843 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1845 int vhost
= conn
->port
->vhost
;
1846 int vport
= conn
->port
->vport
;
1847 static char ipbuf
[MAX_IPSTRLEN
];
1849 http
->flags
.accel
= true;
1851 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1853 static const SBuf
cache_object("cache_object://");
1854 if (hp
->requestUri().startsWith(cache_object
))
1855 return; /* already in good shape */
1857 // XXX: re-use proper URL parser for this
1858 SBuf url
= hp
->requestUri(); // use full provided URI if we abort
1859 do { // use a loop so we can break out of it
1860 ::Parser::Tokenizer
tok(url
);
1861 if (tok
.skip('/')) // origin-form URL already.
1864 if (conn
->port
->vhost
)
1865 return; /* already in good shape */
1867 // skip the URI scheme
1868 static const CharacterSet uriScheme
= CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1869 static const SBuf
uriSchemeEnd("://");
1870 if (!tok
.skipAll(uriScheme
) || !tok
.skip(uriSchemeEnd
))
1873 // skip the authority segment
1874 // RFC 3986 complex nested ABNF for "authority" boils down to this:
1875 static const CharacterSet authority
= CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
1876 CharacterSet::HEXDIG
+ CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1877 if (!tok
.skipAll(authority
))
1880 static const SBuf
slashUri("/");
1881 const SBuf t
= tok
.remaining();
1884 else if (t
[0]=='/') // looks like path
1886 else if (t
[0]=='?' || t
[0]=='#') { // looks like query or fragment. fix '/'
1889 } // else do nothing. invalid path
1893 #if SHOULD_REJECT_UNKNOWN_URLS
1894 // reject URI which are not well-formed even after the processing above
1895 if (url
.isEmpty() || url
[0] != '/') {
1896 hp
->parseStatusCode
= Http::scBadRequest
;
1897 return conn
->abortRequestParsing("error:invalid-request");
1902 vport
= http
->getConn()->clientConnection
->local
.port();
1904 const bool switchedToHttps
= conn
->switchedToHttps();
1905 const bool tryHostHeader
= vhost
|| switchedToHttps
;
1907 if (tryHostHeader
&& (host
= hp
->getHeaderField("Host"))) {
1908 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
1913 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
1914 strncpy(thost
, host
, (t
-host
));
1915 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
1918 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
1921 } // else nothing to alter port-wise.
1922 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+ strlen(host
);
1923 http
->uri
= (char *)xcalloc(url_sz
, 1);
1924 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
, AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(url
));
1925 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
1926 } else if (conn
->port
->defaultsite
/* && !vhost */) {
1927 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
1928 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1929 strlen(conn
->port
->defaultsite
);
1930 http
->uri
= (char *)xcalloc(url_sz
, 1);
1934 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
1936 snprintf(http
->uri
, url_sz
, "%s://%s%s" SQUIDSBUFPH
,
1937 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
1938 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
1939 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
1940 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
1941 /* Put the local socket IP address as the hostname, with whatever vport we found */
1942 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1943 http
->uri
= (char *)xcalloc(url_sz
, 1);
1944 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1945 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
1946 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(),
1947 ipbuf
, vport
, SQUIDSBUFPRINT(url
));
1948 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
1953 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1955 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
1956 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
1957 return; /* already in good shape */
1959 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1961 if (const char *host
= hp
->getHeaderField("Host")) {
1962 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1964 http
->uri
= (char *)xcalloc(url_sz
, 1);
1965 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
,
1966 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(hp
->requestUri()));
1967 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
1969 /* Put the local socket IP address as the hostname. */
1970 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1971 http
->uri
= (char *)xcalloc(url_sz
, 1);
1972 static char ipbuf
[MAX_IPSTRLEN
];
1973 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1974 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
1975 AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).c_str(),
1976 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SQUIDSBUFPRINT(hp
->requestUri()));
1977 debugs(33, 5, "TRANSPARENT REWRITE: " << http
->uri
);
1981 /** Parse an HTTP request
1983 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
1984 * to 1 if the request was correctly parsed.
1985 * \param[in] csd a ConnStateData. The caller must make sure it is not null
1986 * \param[in] hp an Http1::RequestParser
1987 * \param[out] mehtod_p will be set as a side-effect of the parsing.
1988 * Pointed-to value will be set to Http::METHOD_NONE in case of
1990 * \param[out] http_ver will be set as a side-effect of the parsing
1991 * \return NULL on incomplete requests,
1992 * a ClientSocketContext structure on success or failure.
1994 ClientSocketContext
*
1995 parseHttpRequest(ConnStateData
*csd
, const Http1::RequestParserPointer
&hp
)
1997 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
1999 const bool parsedOk
= hp
->parse(csd
->inBuf
);
2001 if (csd
->port
->flags
.isIntercepted() && Config
.accessList
.on_unsupported_protocol
)
2002 csd
->preservedClientData
= csd
->inBuf
;
2003 // sync the buffers after parsing.
2004 csd
->inBuf
= hp
->remaining();
2006 if (hp
->needsMoreData()) {
2007 debugs(33, 5, "Incomplete request, waiting for end of request line");
2012 if (hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
|| hp
->parseStatusCode
== Http::scUriTooLong
)
2013 return csd
->abortRequestParsing("error:request-too-large");
2015 return csd
->abortRequestParsing("error:invalid-request");
2019 /* We know the whole request is in parser now */
2020 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2021 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
2022 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
2026 /* deny CONNECT via accelerated ports */
2027 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
2028 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
2029 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2030 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2031 return csd
->abortRequestParsing("error:method-not-allowed");
2034 /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific
2035 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
2036 * If seen it signals a broken client or proxy has corrupted the traffic.
2038 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
2039 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
2040 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2041 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2042 return csd
->abortRequestParsing("error:method-not-allowed");
2045 if (hp
->method() == Http::METHOD_NONE
) {
2046 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2047 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2048 return csd
->abortRequestParsing("error:unsupported-request-method");
2051 // Process headers after request line
2052 debugs(33, 3, "complete request received. " <<
2053 "prefix_sz = " << hp
->messageHeaderSize() <<
2054 ", request-line-size=" << hp
->firstLineSize() <<
2055 ", mime-header-size=" << hp
->headerBlockSize() <<
2056 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
2058 /* Ok, all headers are received */
2059 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
2061 http
->req_sz
= hp
->messageHeaderSize();
2062 ClientSocketContext
*result
= new ClientSocketContext(csd
->clientConnection
, http
);
2064 StoreIOBuffer tempBuffer
;
2065 tempBuffer
.data
= result
->reqbuf
;
2066 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2068 ClientStreamData newServer
= new clientReplyContext(http
);
2069 ClientStreamData newClient
= result
;
2070 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2071 clientReplyStatus
, newServer
, clientSocketRecipient
,
2072 clientSocketDetach
, newClient
, tempBuffer
);
2075 debugs(33,5, "Prepare absolute URL from " <<
2076 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2077 /* Rewrite the URL in transparent or accelerator mode */
2078 /* NP: there are several cases to traverse here:
2079 * - standard mode (forward proxy)
2080 * - transparent mode (TPROXY)
2081 * - transparent mode with failures
2082 * - intercept mode (NAT)
2083 * - intercept mode with failures
2084 * - accelerator mode (reverse proxy)
2085 * - internal relative-URL
2086 * - mixed combos of the above with internal URL
2087 * - remote interception with PROXY protocol
2088 * - remote reverse-proxy with PROXY protocol
2090 if (csd
->transparent()) {
2091 /* intercept or transparent mode, properly working with no failures */
2092 prepareTransparentURL(csd
, http
, hp
);
2094 } else if (internalCheck(hp
->requestUri())) { // NP: only matches relative-URI
2095 /* internal URL mode */
2096 /* prepend our name & port */
2097 http
->uri
= xstrdup(internalLocalUri(NULL
, hp
->requestUri()));
2098 // We just re-wrote the URL. Must replace the Host: header.
2099 // But have not parsed there yet!! flag for local-only handling.
2100 http
->flags
.internal
= true;
2102 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2103 /* accelerator mode */
2104 prepareAcceleratedURL(csd
, http
, hp
);
2108 /* No special rewrites have been applied above, use the
2109 * requested url. may be rewritten later, so make extra room */
2110 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
2111 http
->uri
= (char *)xcalloc(url_sz
, 1);
2112 SBufToCstring(http
->uri
, hp
->requestUri());
2115 result
->flags
.parsed_ok
= 1;
2120 ConnStateData::connFinishedWithConn(int size
)
2123 if (pipeline
.empty() && inBuf
.isEmpty()) {
2124 /* no current or pending requests */
2125 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2127 } else if (!Config
.onoff
.half_closed_clients
) {
2128 /* admin doesn't want to support half-closed client sockets */
2129 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2130 pipeline
.terminateAll(0);
2139 ConnStateData::consumeInput(const size_t byteCount
)
2141 assert(byteCount
> 0 && byteCount
<= inBuf
.length());
2142 inBuf
.consume(byteCount
);
2143 debugs(33, 5, "inBuf has " << inBuf
.length() << " unused bytes");
2147 ConnStateData::clientAfterReadingRequests()
2149 // Were we expecting to read more request body from half-closed connection?
2150 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2151 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2152 clientConnection
->close();
2161 ConnStateData::quitAfterError(HttpRequest
*request
)
2163 // From HTTP p.o.v., we do not have to close after every error detected
2164 // at the client-side, but many such errors do require closure and the
2165 // client-side code is bad at handling errors so we play it safe.
2167 request
->flags
.proxyKeepalive
= false;
2168 flags
.readMore
= false;
2169 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2173 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2175 ClientHttpRequest
*http
= context
->http
;
2180 assert(sslServerBump
->entry
);
2181 // Did we create an error entry while processing CONNECT?
2182 if (!sslServerBump
->entry
->isEmpty()) {
2183 quitAfterError(http
->request
);
2185 // Get the saved error entry and send it to the client by replacing the
2186 // ClientHttpRequest store entry with it.
2187 clientStreamNode
*node
= context
->getClientReplyContext();
2188 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2190 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2191 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
2193 // save the original request for logging purposes
2194 if (!context
->http
->al
->request
) {
2195 context
->http
->al
->request
= http
->request
;
2196 HTTPMSGLOCK(context
->http
->al
->request
);
2199 // Get error details from the fake certificate-peeking request.
2200 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2201 context
->pullData();
2205 // In bump-server-first mode, we have not necessarily seen the intended
2206 // server name at certificate-peeking time. Check for domain mismatch now,
2207 // when we can extract the intended name from the bumped HTTP request.
2208 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2209 HttpRequest
*request
= http
->request
;
2210 if (!Ssl::checkX509ServerValidity(srvCert
, request
->url
.host())) {
2211 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2212 "does not match domainname " << request
->url
.host());
2214 bool allowDomainMismatch
= false;
2215 if (Config
.ssl_client
.cert_error
) {
2216 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2217 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2218 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2219 delete check
.sslErrors
;
2220 check
.sslErrors
= NULL
;
2223 if (!allowDomainMismatch
) {
2224 quitAfterError(request
);
2226 clientStreamNode
*node
= context
->getClientReplyContext();
2227 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2228 assert (repContext
);
2230 // Fill the server IP and hostname for error page generation.
2231 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2232 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->url
.host());
2234 // Create an error object and fill it
2235 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2236 err
->src_addr
= clientConnection
->remote
;
2237 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2238 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2240 err
->detail
= errDetail
;
2241 // Save the original request for logging purposes.
2242 if (!context
->http
->al
->request
) {
2243 context
->http
->al
->request
= request
;
2244 HTTPMSGLOCK(context
->http
->al
->request
);
2246 repContext
->setReplyToError(request
->method
, err
);
2247 assert(context
->http
->out
.offset
== 0);
2248 context
->pullData();
2256 #endif // USE_OPENSSL
2259 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
2260 * or false otherwise
2263 clientTunnelOnError(ConnStateData
*conn
, ClientSocketContext
*context
, HttpRequest
*request
, const HttpRequestMethod
& method
, err_type requestError
, Http::StatusCode errStatusCode
, const char *requestErrorBytes
)
2265 if (conn
->port
->flags
.isIntercepted() &&
2266 Config
.accessList
.on_unsupported_protocol
&& conn
->pipeline
.nrequests
<= 1) {
2267 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
, NULL
);
2268 checklist
.requestErrorType
= requestError
;
2269 checklist
.src_addr
= conn
->clientConnection
->remote
;
2270 checklist
.my_addr
= conn
->clientConnection
->local
;
2271 checklist
.conn(conn
);
2272 allow_t answer
= checklist
.fastCheck();
2273 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
2274 debugs(33, 3, "Request will be tunneled to server");
2276 // XXX: Either the context is finished() or it should stay queued.
2277 // The below may leak client streams BodyPipe objects. BUT, we need
2278 // to check if client-streams detatch is safe to do here (finished() will detatch).
2279 assert(conn
->pipeline
.front() == context
); // XXX: still assumes HTTP/1 semantics
2280 conn
->pipeline
.popMe(ClientSocketContextPointer(context
));
2282 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2283 conn
->fakeAConnectRequest("unknown-protocol", conn
->preservedClientData
);
2286 debugs(33, 3, "Continue with returning the error: " << requestError
);
2291 conn
->quitAfterError(request
);
2292 clientStreamNode
*node
= context
->getClientReplyContext();
2293 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2294 assert (repContext
);
2296 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
2298 assert(context
->http
->out
.offset
== 0);
2299 context
->pullData();
2300 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
2305 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
2309 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2310 * to here because calling comm_reset_close() causes http to
2311 * be freed before accessing.
2313 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2314 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2315 conn
->flags
.readMore
= false;
2316 comm_reset_close(conn
->clientConnection
);
2321 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, ClientSocketContext
*context
)
2323 ClientHttpRequest
*http
= context
->http
;
2324 bool chunked
= false;
2325 bool mustReplyToOptions
= false;
2326 bool unsupportedTe
= false;
2327 bool expectBody
= false;
2329 // We already have the request parsed and checked, so we
2330 // only need to go through the final body/conn setup to doCallouts().
2331 assert(http
->request
);
2332 HttpRequest::Pointer request
= http
->request
;
2334 // temporary hack to avoid splitting this huge function with sensitive code
2335 const bool isFtp
= !hp
;
2337 // Some blobs below are still HTTP-specific, but we would have to rewrite
2338 // this entire function to remove them from the FTP code path. Connection
2339 // setup and body_pipe preparation blobs are needed for FTP.
2341 request
->clientConnectionManager
= conn
;
2343 request
->flags
.accelerated
= http
->flags
.accel
;
2344 request
->flags
.sslBumped
=conn
->switchedToHttps();
2345 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2346 // TODO: decouple http->flags.accel from request->flags.sslBumped
2347 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2348 !conn
->port
->allow_direct
: 0;
2350 if (request
->flags
.sslBumped
) {
2351 if (conn
->getAuth() != NULL
)
2352 request
->auth_user_request
= conn
->getAuth();
2357 * If transparent or interception mode is working clone the transparent and interception flags
2358 * from the port settings to the request.
2360 if (http
->clientConnection
!= NULL
) {
2361 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2362 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2363 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
2364 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
2365 if (Config
.accessList
.spoof_client_ip
) {
2366 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2367 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2370 request
->flags
.spoofClientIp
= true;
2372 request
->flags
.spoofClientIp
= false;
2375 if (internalCheck(request
->url
.path())) {
2376 if (internalHostnameIs(request
->url
.host()) && request
->url
.port() == getMyPort()) {
2377 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true));
2378 http
->flags
.internal
= true;
2379 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->url
.path())) {
2380 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (global_internal_static on)");
2381 request
->url
.setScheme(AnyP::PROTO_HTTP
);
2382 request
->url
.host(internalHostname());
2383 request
->url
.port(getMyPort());
2384 http
->flags
.internal
= true;
2386 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (not this proxy)");
2389 request
->flags
.internal
= http
->flags
.internal
;
2390 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2391 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2392 #if FOLLOW_X_FORWARDED_FOR
2393 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2394 // not a details about teh TCP connection itself
2395 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2396 #endif /* FOLLOW_X_FORWARDED_FOR */
2397 request
->my_addr
= conn
->clientConnection
->local
;
2398 request
->myportname
= conn
->port
->name
;
2401 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
2402 // for now Squid only supports HTTP requests
2403 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
2404 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
2405 request
->http_ver
.major
= http_ver
.major
;
2406 request
->http_ver
.minor
= http_ver
.minor
;
2409 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2410 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2411 request
->clientConnectionManager
= conn
;
2413 if (request
->header
.chunked()) {
2415 } else if (request
->header
.has(Http::HdrType::TRANSFER_ENCODING
)) {
2416 const String te
= request
->header
.getList(Http::HdrType::TRANSFER_ENCODING
);
2417 // HTTP/1.1 requires chunking to be the last encoding if there is one
2418 unsupportedTe
= te
.size() && te
!= "identity";
2419 } // else implied identity coding
2421 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
2422 (request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0);
2423 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2424 clientStreamNode
*node
= context
->getClientReplyContext();
2425 conn
->quitAfterError(request
.getRaw());
2426 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2427 assert (repContext
);
2428 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2429 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2430 assert(context
->http
->out
.offset
== 0);
2431 context
->pullData();
2432 clientProcessRequestFinished(conn
, request
);
2436 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2437 clientStreamNode
*node
= context
->getClientReplyContext();
2438 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2439 assert (repContext
);
2440 conn
->quitAfterError(request
.getRaw());
2441 repContext
->setReplyToError(ERR_INVALID_REQ
,
2442 Http::scLengthRequired
, request
->method
, NULL
,
2443 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2444 assert(context
->http
->out
.offset
== 0);
2445 context
->pullData();
2446 clientProcessRequestFinished(conn
, request
);
2450 clientSetKeepaliveFlag(http
);
2451 // Let tunneling code be fully responsible for CONNECT requests
2452 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2453 context
->mayUseConnection(true);
2454 conn
->flags
.readMore
= false;
2458 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
2459 clientProcessRequestFinished(conn
, request
);
2464 /* Do we expect a request-body? */
2465 expectBody
= chunked
|| request
->content_length
> 0;
2466 if (!context
->mayUseConnection() && expectBody
) {
2467 request
->body_pipe
= conn
->expectRequestBody(
2468 chunked
? -1 : request
->content_length
);
2470 /* Is it too large? */
2471 if (!chunked
&& // if chunked, we will check as we accumulate
2472 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2473 clientStreamNode
*node
= context
->getClientReplyContext();
2474 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2475 assert (repContext
);
2476 conn
->quitAfterError(request
.getRaw());
2477 repContext
->setReplyToError(ERR_TOO_BIG
,
2478 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
2479 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2480 assert(context
->http
->out
.offset
== 0);
2481 context
->pullData();
2482 clientProcessRequestFinished(conn
, request
);
2487 // We may stop producing, comm_close, and/or call setReplyToError()
2488 // below, so quit on errors to avoid http->doCallouts()
2489 if (!conn
->handleRequestBodyData()) {
2490 clientProcessRequestFinished(conn
, request
);
2494 if (!request
->body_pipe
->productionEnded()) {
2495 debugs(33, 5, "need more request body");
2496 context
->mayUseConnection(true);
2497 assert(conn
->flags
.readMore
);
2502 http
->calloutContext
= new ClientRequestContext(http
);
2506 clientProcessRequestFinished(conn
, request
);
2510 ConnStateData::pipelinePrefetchMax() const
2512 // TODO: Support pipelined requests through pinned connections.
2515 return Config
.pipeline_max_prefetch
;
2519 * Limit the number of concurrent requests.
2520 * \return true when there are available position(s) in the pipeline queue for another request.
2521 * \return false when the pipeline queue is full or disabled.
2524 ConnStateData::concurrentRequestQueueFilled() const
2526 const int existingRequestCount
= pipeline
.count();
2528 // default to the configured pipeline size.
2529 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2531 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
2533 const int internalRequest
= 0;
2535 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
2537 // when queue filled already we cant add more.
2538 if (existingRequestCount
>= concurrentRequestLimit
) {
2539 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2540 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2548 * Perform proxy_protocol_access ACL tests on the client which
2549 * connected to PROXY protocol port to see if we trust the
2550 * sender enough to accept their PROXY header claim.
2553 ConnStateData::proxyProtocolValidateClient()
2555 if (!Config
.accessList
.proxyProtocol
)
2556 return proxyProtocolError("PROXY client not permitted by default ACL");
2558 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
2559 ch
.src_addr
= clientConnection
->remote
;
2560 ch
.my_addr
= clientConnection
->local
;
2563 if (ch
.fastCheck() != ACCESS_ALLOWED
)
2564 return proxyProtocolError("PROXY client not permitted by ACLs");
2570 * Perform cleanup on PROXY protocol errors.
2571 * If header parsing hits a fatal error terminate the connection,
2572 * otherwise wait for more data.
2575 ConnStateData::proxyProtocolError(const char *msg
)
2578 // This is important to know, but maybe not so much that flooding the log is okay.
2579 #if QUIET_PROXY_PROTOCOL
2580 // display the first of every 32 occurances at level 1, the others at level 2.
2581 static uint8_t hide
= 0;
2582 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
2584 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
2591 /// magic octet prefix for PROXY protocol version 1
2592 static const SBuf
Proxy1p0magic("PROXY ", 6);
2594 /// magic octet prefix for PROXY protocol version 2
2595 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
2598 * Test the connection read buffer for PROXY protocol header.
2599 * Version 1 and 2 header currently supported.
2602 ConnStateData::parseProxyProtocolHeader()
2604 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
2606 // detect and parse PROXY/2.0 protocol header
2607 if (inBuf
.startsWith(Proxy2p0magic
))
2608 return parseProxy2p0();
2610 // detect and parse PROXY/1.0 protocol header
2611 if (inBuf
.startsWith(Proxy1p0magic
))
2612 return parseProxy1p0();
2614 // detect and terminate other protocols
2615 if (inBuf
.length() >= Proxy2p0magic
.length()) {
2616 // PROXY/1.0 magic is shorter, so we know that
2617 // the input does not start with any PROXY magic
2618 return proxyProtocolError("PROXY protocol error: invalid header");
2621 // TODO: detect short non-magic prefixes earlier to avoid
2622 // waiting for more data which may never come
2624 // not enough bytes to parse yet.
2628 /// parse the PROXY/1.0 protocol header from the connection read buffer
2630 ConnStateData::parseProxy1p0()
2632 ::Parser::Tokenizer
tok(inBuf
);
2633 tok
.skip(Proxy1p0magic
);
2635 // skip to first LF (assumes it is part of CRLF)
2636 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
2638 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
2639 if (tok
.skip('\n')) {
2640 // found valid header
2641 inBuf
= tok
.remaining();
2642 needProxyProtocolHeader_
= false;
2643 // reset the tokenizer to work on found line only.
2646 return false; // no LF yet
2648 } else // protocol error only if there are more than 107 bytes prefix header
2649 return proxyProtocolError(inBuf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
2651 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
2652 if (tok
.skip(tcpName
)) {
2654 // skip TCP/IP version number
2655 static const CharacterSet
tcpVersions("TCP-version","46");
2656 if (!tok
.skipOne(tcpVersions
))
2657 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
2659 // skip SP after protocol version
2661 return proxyProtocolError("PROXY/1.0 error: missing SP");
2664 int64_t porta
, portb
;
2665 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
2667 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
2668 // leave the LF until later.
2669 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
2670 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
2671 tok
.int64(porta
) && tok
.skip(' ') &&
2675 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
2677 // parse IP and port strings
2678 Ip::Address originalClient
, originalDest
;
2680 if (!originalClient
.GetHostByName(ipa
.c_str()))
2681 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
2683 if (!originalDest
.GetHostByName(ipb
.c_str()))
2684 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
2686 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
2687 originalClient
.port(static_cast<uint16_t>(porta
));
2689 return proxyProtocolError("PROXY/1.0 error: invalid src port");
2691 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
2692 originalDest
.port(static_cast<uint16_t>(portb
));
2694 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
2696 // we have original client and destination details now
2697 // replace the client connection values
2698 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
2699 clientConnection
->local
= originalDest
;
2700 clientConnection
->remote
= originalClient
;
2701 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2702 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2703 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2705 // repeat fetch ensuring the new client FQDN can be logged
2706 if (Config
.onoff
.log_fqdn
)
2707 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2711 } else if (tok
.skip(unknown
)) {
2712 // found valid but unusable header
2716 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2721 /// parse the PROXY/2.0 protocol header from the connection read buffer
2723 ConnStateData::parseProxy2p0()
2725 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2726 if (inBuf
.length() < prefixLen
+ 4)
2727 return false; // need more bytes
2729 if ((inBuf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2730 return proxyProtocolError("PROXY/2.0 error: invalid version");
2732 const char command
= (inBuf
[prefixLen
] & 0x0F);
2733 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2734 return proxyProtocolError("PROXY/2.0 error: invalid command");
2736 const char family
= (inBuf
[prefixLen
+1] & 0xF0) >>4;
2737 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2738 return proxyProtocolError("PROXY/2.0 error: invalid family");
2740 const char proto
= (inBuf
[prefixLen
+1] & 0x0F);
2741 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2742 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2744 const char *clen
= inBuf
.rawContent() + prefixLen
+ 2;
2746 memcpy(&len
, clen
, sizeof(len
));
2749 if (inBuf
.length() < prefixLen
+ 4 + len
)
2750 return false; // need more bytes
2752 inBuf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2753 const SBuf extra
= inBuf
.consume(len
);
2754 needProxyProtocolHeader_
= false; // found successfully
2756 // LOCAL connections do nothing with the extras
2757 if (command
== 0x00/* LOCAL*/)
2761 struct { /* for TCP/UDP over IPv4, len = 12 */
2762 struct in_addr src_addr
;
2763 struct in_addr dst_addr
;
2767 struct { /* for TCP/UDP over IPv6, len = 36 */
2768 struct in6_addr src_addr
;
2769 struct in6_addr dst_addr
;
2774 struct { /* for AF_UNIX sockets, len = 216 */
2775 uint8_t src_addr
[108];
2776 uint8_t dst_addr
[108];
2782 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2784 // replace the client connection values
2785 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2788 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2789 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2790 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2791 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2792 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2793 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2796 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2797 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2798 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2799 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2800 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2801 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2803 default: // do nothing
2806 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2808 // repeat fetch ensuring the new client FQDN can be logged
2809 if (Config
.onoff
.log_fqdn
)
2810 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2816 ConnStateData::receivedFirstByte()
2818 if (receivedFirstByte_
)
2821 receivedFirstByte_
= true;
2822 // Set timeout to Config.Timeout.request
2823 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2824 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
2825 TimeoutDialer
, this, ConnStateData::requestTimeout
);
2826 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
2830 * Attempt to parse one or more requests from the input buffer.
2831 * Returns true after completing parsing of at least one request [header]. That
2832 * includes cases where parsing ended with an error (e.g., a huge request).
2835 ConnStateData::clientParseRequests()
2837 bool parsed_req
= false;
2839 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2841 // Loop while we have read bytes that are not needed for producing the body
2842 // On errors, bodyPipe may become nil, but readMore will be cleared
2843 while (!inBuf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2845 /* Don't try to parse if the buffer is empty */
2846 if (inBuf
.isEmpty())
2849 /* Limit the number of concurrent requests */
2850 if (concurrentRequestQueueFilled())
2853 // try to parse the PROXY protocol header magic bytes
2854 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
2857 if (ClientSocketContext
*context
= parseOneRequest()) {
2858 debugs(33, 5, clientConnection
<< ": done parsing a request");
2860 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2861 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2862 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2864 context
->registerWithConn();
2866 processParsedRequest(context
);
2868 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2870 if (context
->mayUseConnection()) {
2871 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2875 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
2876 inBuf
.length() << " < " << Config
.maxRequestHeaderSize
);
2877 Must(inBuf
.length() < Config
.maxRequestHeaderSize
);
2882 /* XXX where to 'finish' the parsing pass? */
2887 ConnStateData::afterClientRead()
2889 /* Process next request */
2890 if (pipeline
.empty())
2891 fd_note(clientConnection
->fd
, "Reading next request");
2893 if (!clientParseRequests()) {
2897 * If the client here is half closed and we failed
2898 * to parse a request, close the connection.
2899 * The above check with connFinishedWithConn() only
2900 * succeeds _if_ the buffer is empty which it won't
2901 * be if we have an incomplete request.
2902 * XXX: This duplicates ConnStateData::kick
2904 if (pipeline
.empty() && commIsHalfClosed(clientConnection
->fd
)) {
2905 debugs(33, 5, clientConnection
<< ": half-closed connection, no completed request parsed, connection closing.");
2906 clientConnection
->close();
2914 clientAfterReadingRequests();
2918 * called when new request data has been read from the socket
2920 * \retval false called comm_close or setReplyToError (the caller should bail)
2921 * \retval true we did not call comm_close or setReplyToError
2924 ConnStateData::handleReadData()
2926 // if we are reading a body, stuff data into the body pipe
2927 if (bodyPipe
!= NULL
)
2928 return handleRequestBodyData();
2933 * called when new request body data has been buffered in inBuf
2934 * may close the connection if we were closing and piped everything out
2936 * \retval false called comm_close or setReplyToError (the caller should bail)
2937 * \retval true we did not call comm_close or setReplyToError
2940 ConnStateData::handleRequestBodyData()
2942 assert(bodyPipe
!= NULL
);
2944 if (bodyParser
) { // chunked encoding
2945 if (const err_type error
= handleChunkedRequestBody()) {
2946 abortChunkedRequestBody(error
);
2949 } else { // identity encoding
2950 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
2951 const size_t putSize
= bodyPipe
->putMoreData(inBuf
.c_str(), inBuf
.length());
2953 consumeInput(putSize
);
2955 if (!bodyPipe
->mayNeedMoreData()) {
2956 // BodyPipe will clear us automagically when we produced everything
2962 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
2964 if (const char *reason
= stoppedSending()) {
2965 /* we've finished reading like good clients,
2966 * now do the close that initiateClose initiated.
2968 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
2969 clientConnection
->close();
2977 /// parses available chunked encoded body bytes, checks size, returns errors
2979 ConnStateData::handleChunkedRequestBody()
2981 debugs(33, 7, "chunked from " << clientConnection
<< ": " << inBuf
.length());
2983 try { // the parser will throw on errors
2985 if (inBuf
.isEmpty()) // nothing to do
2988 BodyPipeCheckout
bpc(*bodyPipe
);
2989 bodyParser
->setPayloadBuffer(&bpc
.buf
);
2990 const bool parsed
= bodyParser
->parse(inBuf
);
2991 inBuf
= bodyParser
->remaining(); // sync buffers
2994 // dechunk then check: the size limit applies to _dechunked_ content
2995 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
2999 finishDechunkingRequest(true);
3001 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3004 // if chunk parser needs data, then the body pipe must need it too
3005 Must(!bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3007 // if parser needs more space and we can consume nothing, we will stall
3008 Must(!bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3009 } catch (...) { // TODO: be more specific
3010 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3011 return ERR_INVALID_REQ
;
3014 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3018 /// quit on errors related to chunked request body handling
3020 ConnStateData::abortChunkedRequestBody(const err_type error
)
3022 finishDechunkingRequest(false);
3024 // XXX: The code below works if we fail during initial request parsing,
3025 // but if we fail when the server connection is used already, the server may send
3026 // us its response too, causing various assertions. How to prevent that?
3027 #if WE_KNOW_HOW_TO_SEND_ERRORS
3028 ClientSocketContext::Pointer context
= pipeline
.front();
3029 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3030 clientStreamNode
*node
= context
->getClientReplyContext();
3031 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3033 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3034 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
3035 repContext
->setReplyToError(error
, scode
,
3036 repContext
->http
->request
->method
,
3037 repContext
->http
->uri
,
3039 repContext
->http
->request
,
3041 context
->pullData();
3043 // close or otherwise we may get stuck as nobody will notice the error?
3044 comm_reset_close(clientConnection
);
3047 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3048 comm_reset_close(clientConnection
);
3050 flags
.readMore
= false;
3054 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3056 // request reader may get stuck waiting for space if nobody consumes body
3057 if (bodyPipe
!= NULL
)
3058 bodyPipe
->enableAutoConsumption();
3063 /** general lifetime handler for HTTP requests */
3065 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3067 if (!Comm::IsConnOpen(io
.conn
))
3070 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
3072 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
3073 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
3074 receivedFirstByte();
3077 } else if (fd_table
[io
.conn
->fd
].ssl
== NULL
)
3080 const HttpRequestMethod method
;
3081 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
3082 // Tunnel established. Set receivedFirstByte to avoid loop.
3083 receivedFirstByte();
3089 * Just close the connection to not confuse browsers
3090 * using persistent connections. Some browsers open
3091 * a connection and then do not use it until much
3092 * later (presumeably because the request triggering
3093 * the open has already been completed on another
3096 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3101 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3103 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3104 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3105 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3106 http
->logType
.err
.timedout
= true;
3107 if (Comm::IsConnOpen(io
.conn
))
3111 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3112 AsyncJob("ConnStateData"), // kids overwrite
3114 bodyParser(nullptr),
3116 sslBumpMode(Ssl::bumpEnd
),
3118 needProxyProtocolHeader_(false),
3120 switchedToHttps_(false),
3121 sslServerBump(NULL
),
3122 signAlgorithm(Ssl::algSignTrusted
),
3124 stoppedSending_(NULL
),
3125 stoppedReceiving_(NULL
)
3127 flags
.readMore
= true; // kids may overwrite
3128 flags
.swanSang
= false;
3130 pinning
.host
= NULL
;
3132 pinning
.pinned
= false;
3133 pinning
.auth
= false;
3134 pinning
.zeroReply
= false;
3135 pinning
.peer
= NULL
;
3137 // store the details required for creating more MasterXaction objects as new requests come in
3138 log_addr
= xact
->tcpClient
->remote
;
3139 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3141 // register to receive notice of Squid signal events
3142 // which may affect long persisting client connections
3143 RegisterRunner(this);
3147 ConnStateData::start()
3149 BodyProducer::start();
3150 HttpControlMsgSink::start();
3152 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3153 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3154 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3155 int i
= IP_PMTUDISC_DONT
;
3156 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3157 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3159 static bool reported
= false;
3162 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3168 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3169 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3170 comm_add_close_handler(clientConnection
->fd
, call
);
3172 if (Config
.onoff
.log_fqdn
)
3173 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3176 if (Ident::TheConfig
.identLookup
) {
3177 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3178 identChecklist
.src_addr
= clientConnection
->remote
;
3179 identChecklist
.my_addr
= clientConnection
->local
;
3180 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3181 Ident::Start(clientConnection
, clientIdentDone
, this);
3185 clientdbEstablished(clientConnection
->remote
, 1);
3187 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
3188 if (needProxyProtocolHeader_
) {
3189 if (!proxyProtocolValidateClient()) // will close the connection on failure
3194 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
3196 if (Config
.onoff
.client_db
) {
3197 /* it was said several times that client write limiter does not work if client_db is disabled */
3199 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3200 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3202 // TODO: we check early to limit error response bandwith but we
3203 // should recheck when we can honor delay_pool_uses_indirect
3204 // TODO: we should also pass the port details for myportname here.
3205 ch
.src_addr
= clientConnection
->remote
;
3206 ch
.my_addr
= clientConnection
->local
;
3208 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3210 /* pools require explicit 'allow' to assign a client into them */
3211 if (pools
[pool
].access
) {
3212 ch
.changeAcl(pools
[pool
].access
);
3213 allow_t answer
= ch
.fastCheck();
3214 if (answer
== ACCESS_ALLOWED
) {
3216 /* request client information from db after we did all checks
3217 this will save hash lookup if client failed checks */
3218 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
3221 /* put client info in FDE */
3222 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
3224 /* setup write limiter for this request */
3225 const double burst
= floor(0.5 +
3226 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3227 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3230 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3237 // kids must extend to actually start doing something (e.g., reading)
3240 /** Handle a new connection on an HTTP socket. */
3242 httpAccept(const CommAcceptCbParams
¶ms
)
3244 MasterXaction::Pointer xact
= params
.xaction
;
3245 AnyP::PortCfgPointer s
= xact
->squidPort
;
3247 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3249 if (params
.flag
!= Comm::OK
) {
3250 // Its possible the call was still queued when the client disconnected
3251 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3255 debugs(33, 4, params
.conn
<< ": accepted");
3256 fd_note(params
.conn
->fd
, "client http connect");
3258 if (s
->tcp_keepalive
.enabled
)
3259 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3261 ++incoming_sockets_accepted
;
3263 // Socket is ready, setup the connection manager to start using it
3264 ConnStateData
*connState
= Http::NewServer(xact
);
3265 AsyncJob::Start(connState
); // usually async-calls readSomeData()
3270 /** Create SSL connection structure and update fd_table */
3271 static Security::SessionPointer
3272 httpsCreate(const Comm::ConnectionPointer
&conn
, Security::ContextPtr sslContext
)
3274 if (auto ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
3275 debugs(33, 5, "will negotate SSL on " << conn
);
3285 * \retval 1 on success
3286 * \retval 0 when needs more data
3287 * \retval -1 on error
3290 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
3292 int fd
= conn
->clientConnection
->fd
;
3293 auto ssl
= fd_table
[fd
].ssl
;
3297 if ((ret
= SSL_accept(ssl
)) <= 0) {
3298 const int xerrno
= errno
;
3299 const int ssl_error
= SSL_get_error(ssl
, ret
);
3301 switch (ssl_error
) {
3303 case SSL_ERROR_WANT_READ
:
3304 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, conn
, 0);
3307 case SSL_ERROR_WANT_WRITE
:
3308 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, conn
, 0);
3311 case SSL_ERROR_SYSCALL
:
3313 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
3315 debugs(83, (xerrno
== ECONNRESET
) ? 1 : 2, "Error negotiating SSL connection on FD " << fd
<< ": " <<
3316 (xerrno
== 0 ? ERR_error_string(ssl_error
, NULL
) : xstrerr(xerrno
)));
3320 case SSL_ERROR_ZERO_RETURN
:
3321 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3325 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
3326 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3327 " (" << ssl_error
<< "/" << ret
<< ")");
3336 /** negotiate an SSL connection */
3338 clientNegotiateSSL(int fd
, void *data
)
3340 ConnStateData
*conn
= (ConnStateData
*)data
;
3342 auto ssl
= fd_table
[fd
].ssl
;
3345 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
3346 if (ret
< 0) // An error
3347 conn
->clientConnection
->close();
3351 if (SSL_session_reused(ssl
)) {
3352 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3353 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3355 if (do_debug(83, 4)) {
3356 /* Write out the SSL session details.. actually the call below, but
3357 * OpenSSL headers do strange typecasts confusing GCC.. */
3358 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3359 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3360 PEM_ASN1_write((i2d_of_void
*)i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3362 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3364 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3365 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3366 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3367 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3368 * Because there are two possible usable cast, if you get an error here, try the other
3369 * commented line. */
3371 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3372 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3376 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3379 /* Note: This does not automatically fflush the log file.. */
3382 debugs(83, 2, "clientNegotiateSSL: New session " <<
3383 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3384 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3388 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3389 SSL_get_cipher(ssl
));
3391 client_cert
= SSL_get_peer_certificate(ssl
);
3393 if (client_cert
!= NULL
) {
3394 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3395 " client certificate: subject: " <<
3396 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3398 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3399 " client certificate: issuer: " <<
3400 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3402 X509_free(client_cert
);
3404 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3405 " has no certificate.");
3408 #if defined(TLSEXT_NAMETYPE_host_name)
3409 if (!conn
->serverBump()) {
3410 // when in bumpClientFirst mode, get the server name from SNI
3411 if (const char *server
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))
3412 conn
->resetSslCommonName(server
);
3416 conn
->readSomeData();
3420 * If Security::ContextPtr is given, starts reading the TLS handshake.
3421 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPtr.
3424 httpsEstablish(ConnStateData
*connState
, Security::ContextPtr sslContext
)
3426 Security::SessionPointer ssl
= nullptr;
3428 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3430 if (!sslContext
|| !(ssl
= httpsCreate(details
, sslContext
)))
3433 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3434 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3435 connState
, ConnStateData::requestTimeout
);
3436 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3438 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3442 * A callback function to use with the ACLFilledChecklist callback.
3443 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3444 * else reverts the connection to tunnel mode.
3447 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3449 ConnStateData
*connState
= (ConnStateData
*) data
;
3451 // if the connection is closed or closing, just return.
3452 if (!connState
->isOpen())
3455 // Require both a match and a positive bump mode to work around exceptional
3456 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3457 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
3458 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
3459 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3461 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3462 connState
->sslBumpMode
= Ssl::bumpNone
;
3464 connState
->fakeAConnectRequest("ssl-bump", connState
->inBuf
);
3467 /** handle a new HTTPS connection */
3469 httpsAccept(const CommAcceptCbParams
¶ms
)
3471 MasterXaction::Pointer xact
= params
.xaction
;
3472 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3474 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3476 if (params
.flag
!= Comm::OK
) {
3477 // Its possible the call was still queued when the client disconnected
3478 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3482 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3483 fd_note(params
.conn
->fd
, "client https connect");
3485 if (s
->tcp_keepalive
.enabled
) {
3486 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3489 ++incoming_sockets_accepted
;
3491 // Socket is ready, setup the connection manager to start using it
3492 ConnStateData
*connState
= Https::NewServer(xact
);
3493 AsyncJob::Start(connState
); // usually async-calls postHttpsAccept()
3497 ConnStateData::postHttpsAccept()
3499 if (port
->flags
.tunnelSslBumping
) {
3500 debugs(33, 5, "accept transparent connection: " << clientConnection
);
3502 if (!Config
.accessList
.ssl_bump
) {
3503 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
3507 // Create a fake HTTP request for ssl_bump ACL check,
3508 // using tproxy/intercept provided destination IP and port.
3509 HttpRequest
*request
= new HttpRequest();
3510 static char ip
[MAX_IPSTRLEN
];
3511 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3512 request
->url
.host(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
3513 request
->url
.port(clientConnection
->local
.port());
3514 request
->myportname
= port
->name
;
3516 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3517 acl_checklist
->src_addr
= clientConnection
->remote
;
3518 acl_checklist
->my_addr
= port
->s
;
3519 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
3522 httpsEstablish(this, port
->secure
.staticContext
.get());
3527 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
3529 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3530 state_data
->sslCrtdHandleReply(reply
);
3534 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
3537 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply
);
3541 if (reply
.result
== Helper::BrokenHelper
) {
3542 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3543 } else if (!reply
.other().hasContent()) {
3544 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3546 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3547 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3548 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3550 if (reply
.result
!= Helper::Okay
) {
3551 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3553 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3554 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3555 doPeekAndSpliceStep();
3556 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3557 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
3559 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3561 auto ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3562 getSslContextDone(ctx
, true);
3568 getSslContextDone(NULL
);
3571 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3573 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
3575 // fake certificate adaptation requires bump-server-first mode
3576 if (!sslServerBump
) {
3577 assert(port
->signingCert
.get());
3578 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3579 if (port
->signPkey
.get())
3580 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3581 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3585 // In case of an error while connecting to the secure server, use a fake
3586 // trusted certificate, with no mimicked fields and no adaptation
3587 // algorithms. There is nothing we can mimic so we want to minimize the
3588 // number of warnings the user will have to see to get to the error page.
3589 assert(sslServerBump
->entry
);
3590 if (sslServerBump
->entry
->isEmpty()) {
3591 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3592 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3594 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3595 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3596 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3598 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3599 // If the algorithm already set, then ignore it.
3600 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3601 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3602 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3605 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3606 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3607 const char *param
= ca
->param
;
3609 // For parameterless CN adaptation, use hostname from the
3611 if (ca
->alg
== Ssl::algSetCommonName
) {
3613 param
= sslConnectHostOrIp
.termedBuf();
3614 certProperties
.commonName
= param
;
3615 certProperties
.setCommonName
= true;
3616 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3617 certProperties
.setValidAfter
= true;
3618 else if (ca
->alg
== Ssl::algSetValidBefore
)
3619 certProperties
.setValidBefore
= true;
3621 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3622 alg
<< " param: " << (param
? param
: "-"));
3626 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3627 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3628 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3629 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3633 } else {// if (!sslServerBump->entry->isEmpty())
3634 // Use trusted certificate for a Squid-generated error
3635 // or the user would have to add a security exception
3636 // just to see the error page. We will close the connection
3637 // so that the trust is not extended to non-Squid content.
3638 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3641 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3643 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3644 assert(port
->untrustedSigningCert
.get());
3645 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3646 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3648 assert(port
->signingCert
.get());
3649 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3651 if (port
->signPkey
.get())
3652 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3654 signAlgorithm
= certProperties
.signAlgorithm
;
3656 certProperties
.signHash
= Ssl::DefaultSignHash
;
3660 ConnStateData::getSslContextStart()
3662 // XXX starting SSL with a pipeline of requests still waiting for non-SSL replies?
3663 assert(pipeline
.count() < 2); // the CONNECT is okay for now. Anything else is a bug.
3664 pipeline
.terminateAll(0);
3665 /* careful: terminateAll(0) above frees request, host, etc. */
3667 if (port
->generateHostCertificates
) {
3668 Ssl::CertificateProperties certProperties
;
3669 buildSslCertGenerationParams(certProperties
);
3670 sslBumpCertKey
= certProperties
.dbKey().c_str();
3671 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3673 // Disable caching for bumpPeekAndSplice mode
3674 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
3675 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3676 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3677 Security::ContextPtr dynCtx
= nullptr;
3678 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3679 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3680 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3681 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3682 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3683 getSslContextDone(dynCtx
);
3686 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3688 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3691 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3697 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3698 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3699 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3700 request_message
.composeRequest(certProperties
);
3701 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3702 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3704 } catch (const std::exception
&e
) {
3705 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3706 "request for " << certProperties
.commonName
<<
3707 " certificate: " << e
.what() << "; will now block to " <<
3708 "generate that certificate.");
3709 // fall through to do blocking in-process generation.
3711 #endif // USE_SSL_CRTD
3713 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3714 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3715 doPeekAndSpliceStep();
3716 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3717 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3718 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3720 auto dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3721 getSslContextDone(dynCtx
, true);
3725 getSslContextDone(NULL
);
3729 ConnStateData::getSslContextDone(Security::ContextPtr sslContext
, bool isNew
)
3731 // Try to add generated ssl context to storage.
3732 if (port
->generateHostCertificates
&& isNew
) {
3734 if (signAlgorithm
== Ssl::algSignTrusted
) {
3735 // Add signing certificate to the certificates chain
3736 X509
*cert
= port
->signingCert
.get();
3737 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3738 // increase the certificate lock
3739 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3741 const int ssl_error
= ERR_get_error();
3742 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3744 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3746 //else it is self-signed or untrusted do not attrach any certificate
3748 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3749 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3751 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3752 // If it is not in storage delete after using. Else storage deleted it.
3753 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3756 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3760 // If generated ssl context = NULL, try to use static ssl context.
3762 if (!port
->secure
.staticContext
) {
3763 debugs(83, DBG_IMPORTANT
, "Closing " << clientConnection
->remote
<< " as lacking TLS context");
3764 clientConnection
->close();
3767 debugs(33, 5, "Using static TLS context.");
3768 sslContext
= port
->secure
.staticContext
.get();
3772 if (!httpsCreate(clientConnection
, sslContext
))
3775 // bumped intercepted conns should already have Config.Timeout.request set
3776 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3777 // to make sure the connection does not get stuck on non-SSL clients.
3778 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3779 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3780 this, ConnStateData::requestTimeout
);
3781 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3783 // Disable the client read handler until CachePeer selection is complete
3784 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3785 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3786 switchedToHttps_
= true;
3790 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3792 assert(!switchedToHttps_
);
3794 sslConnectHostOrIp
= request
->url
.host();
3795 resetSslCommonName(request
->url
.host());
3797 // We are going to read new request
3798 flags
.readMore
= true;
3799 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3801 // keep version major.minor details the same.
3802 // but we are now performing the HTTPS handshake traffic
3803 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
3805 // If sslServerBump is set, then we have decided to deny CONNECT
3806 // and now want to switch to SSL to send the error to the client
3807 // without even peeking at the origin server certificate.
3808 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3809 request
->flags
.sslPeek
= true;
3810 sslServerBump
= new Ssl::ServerBump(request
);
3812 // will call httpsPeeked() with certificate and connection, eventually
3813 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3815 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
3816 request
->flags
.sslPeek
= true;
3817 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
3818 startPeekAndSplice();
3822 // otherwise, use sslConnectHostOrIp
3823 getSslContextStart();
3827 ConnStateData::spliceOnError(const err_type err
)
3829 if (Config
.accessList
.on_unsupported_protocol
) {
3830 assert(serverBump());
3831 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
3832 checklist
.requestErrorType
= err
;
3833 checklist
.conn(this);
3834 allow_t answer
= checklist
.fastCheck();
3835 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
3843 /** negotiate an SSL connection */
3845 clientPeekAndSpliceSSL(int fd
, void *data
)
3847 ConnStateData
*conn
= (ConnStateData
*)data
;
3848 auto ssl
= fd_table
[fd
].ssl
;
3850 debugs(83, 5, "Start peek and splice on FD " << fd
);
3853 if ((ret
= Squid_SSL_accept(conn
, clientPeekAndSpliceSSL
)) < 0)
3854 debugs(83, 2, "SSL_accept failed.");
3856 BIO
*b
= SSL_get_rbio(ssl
);
3858 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3860 const err_type err
= bio
->noSslClient() ? ERR_PROTOCOL_UNKNOWN
: ERR_SECURE_ACCEPT_FAIL
;
3861 if (!conn
->spliceOnError(err
))
3862 conn
->clientConnection
->close();
3866 if (bio
->rBufData().contentSize() > 0)
3867 conn
->receivedFirstByte();
3869 if (bio
->gotHello()) {
3870 if (conn
->serverBump()) {
3871 Ssl::Bio::sslFeatures
const &features
= bio
->getFeatures();
3872 if (!features
.serverName
.isEmpty()) {
3873 conn
->serverBump()->clientSni
= features
.serverName
;
3874 conn
->resetSslCommonName(features
.serverName
.c_str());
3878 debugs(83, 5, "I got hello. Start forwarding the request!!! ");
3879 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3880 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
3881 conn
->startPeekAndSpliceDone();
3886 void ConnStateData::startPeekAndSplice()
3888 // will call httpsPeeked() with certificate and connection, eventually
3889 auto unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
3890 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
3892 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
3895 // commSetConnTimeout() was called for this request before we switched.
3896 // Fix timeout to request_start_timeout
3897 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3898 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3899 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3900 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
3901 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
3902 // a bumbed "connect" request on non transparent port.
3903 receivedFirstByte_
= false;
3905 // Disable the client read handler until CachePeer selection is complete
3906 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3907 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientPeekAndSpliceSSL
, this, 0);
3908 switchedToHttps_
= true;
3910 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3911 BIO
*b
= SSL_get_rbio(ssl
);
3912 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3916 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
3918 ConnStateData
*connState
= (ConnStateData
*) data
;
3920 // if the connection is closed or closing, just return.
3921 if (!connState
->isOpen())
3924 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
3925 assert(connState
->serverBump());
3926 Ssl::BumpMode bumpAction
;
3927 if (answer
== ACCESS_ALLOWED
) {
3928 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
3930 bumpAction
= Ssl::bumpSplice
;
3932 connState
->serverBump()->act
.step2
= bumpAction
;
3933 connState
->sslBumpMode
= bumpAction
;
3935 if (bumpAction
== Ssl::bumpTerminate
) {
3936 connState
->clientConnection
->close();
3937 } else if (bumpAction
!= Ssl::bumpSplice
) {
3938 connState
->startPeekAndSpliceDone();
3940 connState
->splice();
3944 ConnStateData::splice()
3946 //Normally we can splice here, because we just got client hello message
3947 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3948 BIO
*b
= SSL_get_rbio(ssl
);
3949 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3950 MemBuf
const &rbuf
= bio
->rBufData();
3951 debugs(83,5, "Bio for " << clientConnection
<< " read " << rbuf
.contentSize() << " helo bytes");
3953 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
3954 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
3956 if (transparent()) {
3957 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
3958 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
3959 transferProtocol
= Http::ProtocolVersion();
3960 // XXX: copy from MemBuf reallocates, not a regression since old code did too
3962 temp
.append(rbuf
.content(), rbuf
.contentSize());
3963 fakeAConnectRequest("intercepted TLS spliced", temp
);
3965 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
3967 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
3968 transferProtocol
= Http::ProtocolVersion();
3969 // inBuf still has the "CONNECT ..." request data, reset it to SSL hello message
3970 inBuf
.append(rbuf
.content(), rbuf
.contentSize());
3971 ClientSocketContext::Pointer context
= pipeline
.front();
3972 ClientHttpRequest
*http
= context
->http
;
3978 ConnStateData::startPeekAndSpliceDone()
3980 // This is the Step2 of the SSL bumping
3981 assert(sslServerBump
);
3982 if (sslServerBump
->step
== Ssl::bumpStep1
) {
3983 sslServerBump
->step
= Ssl::bumpStep2
;
3984 // Run a accessList check to check if want to splice or continue bumping
3986 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
3987 //acl_checklist->src_addr = params.conn->remote;
3988 //acl_checklist->my_addr = s->s;
3989 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpNone
));
3990 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpClientFirst
));
3991 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpServerFirst
));
3992 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
3996 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4000 ConnStateData::doPeekAndSpliceStep()
4002 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
4003 BIO
*b
= SSL_get_rbio(ssl
);
4005 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4007 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
4010 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
4011 switchedToHttps_
= true;
4015 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4017 Must(sslServerBump
!= NULL
);
4019 if (Comm::IsConnOpen(serverConnection
)) {
4020 pinConnection(serverConnection
, NULL
, NULL
, false);
4022 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4024 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4026 // copy error detail from bump-server-first request to CONNECT request
4027 if (!pipeline
.empty() && pipeline
.front()->http
!= nullptr && pipeline
.front()->http
->request
)
4028 pipeline
.front()->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4031 getSslContextStart();
4034 #endif /* USE_OPENSSL */
4037 ConnStateData::fakeAConnectRequest(const char *reason
, const SBuf
&payload
)
4039 // fake a CONNECT request to force connState to tunnel
4042 if (serverBump() && !serverBump()->clientSni
.isEmpty()) {
4043 connectHost
.assign(serverBump()->clientSni
);
4044 if (clientConnection
->local
.port() > 0)
4045 connectHost
.appendf(":%d",clientConnection
->local
.port());
4049 static char ip
[MAX_IPSTRLEN
];
4050 connectHost
.assign(clientConnection
->local
.toUrl(ip
, sizeof(ip
)));
4052 // Pre-pend this fake request to the TLS bits already in the buffer
4054 retStr
.append("CONNECT ");
4055 retStr
.append(connectHost
);
4056 retStr
.append(" HTTP/1.1\r\nHost: ");
4057 retStr
.append(connectHost
);
4058 retStr
.append("\r\n\r\n");
4059 retStr
.append(payload
);
4061 bool ret
= handleReadData();
4063 ret
= clientParseRequests();
4066 debugs(33, 2, "Failed to start fake CONNECT request for " << reason
<< " connection: " << clientConnection
);
4067 clientConnection
->close();
4071 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4073 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4075 if (!Comm::IsConnOpen(c
)) {
4076 Must(NHttpSockets
> 0); // we tried to open some
4077 --NHttpSockets
; // there will be fewer sockets than planned
4078 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4080 if (!NHttpSockets
) // we could not open any listen sockets at all
4081 fatalf("Unable to open %s",FdNote(portType
));
4088 /// find any unused HttpSockets[] slot and store fd there or return false
4090 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4093 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4094 if ((found
= HttpSockets
[i
] < 0))
4095 HttpSockets
[i
] = conn
->fd
;
4101 clientHttpConnectionsOpen(void)
4103 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4104 const char *scheme
= AnyP::UriScheme(s
->transport
.protocol
).c_str();
4106 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4107 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many '" << scheme
<< "_port' lines.");
4108 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4113 if (s
->flags
.tunnelSslBumping
) {
4114 if (!Config
.accessList
.ssl_bump
) {
4115 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme
<< "_port " << s
->s
);
4116 s
->flags
.tunnelSslBumping
= false;
4118 if (!s
->secure
.staticContext
&& !s
->generateHostCertificates
) {
4119 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at " << scheme
<< "_port " << s
->s
<< " due to TLS initialization failure.");
4120 s
->flags
.tunnelSslBumping
= false;
4121 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
)
4122 s
->secure
.encryptTransport
= false;
4124 if (s
->flags
.tunnelSslBumping
) {
4125 // Create ssl_ctx cache for this port.
4126 auto sz
= s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
;
4127 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, sz
);
4131 if (s
->secure
.encryptTransport
&& !s
->secure
.staticContext
) {
4132 debugs(1, DBG_CRITICAL
, "ERROR: Ignoring " << scheme
<< "_port " << s
->s
<< " due to TLS context initialization failure.");
4137 // Fill out a Comm::Connection which IPC will open as a listener for us
4138 // then pass back when active so we can start a TcpAcceptor subscription.
4139 s
->listenConn
= new Comm::Connection
;
4140 s
->listenConn
->local
= s
->s
;
4142 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4143 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4145 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4146 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
) {
4147 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4148 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
4149 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4151 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4152 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4153 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4156 } else if (s
->transport
.protocol
== AnyP::PROTO_HTTPS
) {
4157 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4158 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
4159 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4161 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4162 ListeningStartedDialer(&clientListenerConnectionOpened
,
4163 s
, Ipc::fdnHttpsSocket
, sub
));
4164 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4168 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4174 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
4176 // Fill out a Comm::Connection which IPC will open as a listener for us
4177 port
->listenConn
= new Comm::Connection
;
4178 port
->listenConn
->local
= port
->s
;
4179 port
->listenConn
->flags
=
4181 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4182 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4184 // route new connections to subCall
4185 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4186 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4187 AsyncCall::Pointer listenCall
=
4188 asyncCall(33, 2, "clientListenerConnectionOpened",
4189 ListeningStartedDialer(&clientListenerConnectionOpened
,
4190 port
, fdNote
, sub
));
4191 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
4193 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
4194 HttpSockets
[NHttpSockets
] = -1;
4198 /// process clientHttpConnectionsOpen result
4200 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4204 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4207 Must(Comm::IsConnOpen(s
->listenConn
));
4209 // TCP: setup a job to handle accept() with subscribed handler
4210 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
4212 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4213 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4214 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4215 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4216 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4217 << FdNote(portTypeNote
) << " connections at "
4220 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4224 clientOpenListenSockets(void)
4226 clientHttpConnectionsOpen();
4227 Ftp::StartListening();
4229 if (NHttpSockets
< 1)
4230 fatal("No HTTP, HTTPS, or FTP ports configured");
4234 clientConnectionsClose()
4236 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4237 if (s
->listenConn
!= NULL
) {
4238 debugs(1, DBG_IMPORTANT
, "Closing HTTP(S) port " << s
->listenConn
->local
);
4239 s
->listenConn
->close();
4240 s
->listenConn
= NULL
;
4244 Ftp::StopListening();
4246 // TODO see if we can drop HttpSockets array entirely */
4247 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4248 HttpSockets
[i
] = -1;
4255 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4257 const char *vary
= request
->vary_headers
;
4258 int has_vary
= entry
->getReply()->header
.has(Http::HdrType::VARY
);
4259 #if X_ACCELERATOR_VARY
4262 entry
->getReply()->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
4265 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4267 /* Oops... something odd is going on here.. */
4268 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4269 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4270 safe_free(request
->vary_headers
);
4275 /* This is not a varying object */
4279 /* virtual "vary" object found. Calculate the vary key and
4280 * continue the search
4282 vary
= httpMakeVaryMark(request
, entry
->getReply());
4285 request
->vary_headers
= xstrdup(vary
);
4288 /* Ouch.. we cannot handle this kind of variance */
4289 /* XXX This cannot really happen, but just to be complete */
4294 vary
= httpMakeVaryMark(request
, entry
->getReply());
4297 request
->vary_headers
= xstrdup(vary
);
4301 /* Ouch.. we cannot handle this kind of variance */
4302 /* XXX This cannot really happen, but just to be complete */
4304 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4307 /* Oops.. we have already been here and still haven't
4308 * found the requested variant. Bail out
4310 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4311 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4317 ACLFilledChecklist
*
4318 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4320 ConnStateData
* conn
= http
->getConn();
4321 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4322 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4325 * hack for ident ACL. It needs to get full addresses, and a place to store
4326 * the ident result on persistent connections...
4328 /* connection oriented auth also needs these two lines for it's operation. */
4333 ConnStateData::transparent() const
4335 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4339 ConnStateData::expectRequestBody(int64_t size
)
4341 bodyPipe
= new BodyPipe(this);
4343 bodyPipe
->setBodySize(size
);
4345 startDechunkingRequest();
4350 ConnStateData::mayNeedToReadMoreBody() const
4353 return 0; // request without a body or read/produced all body bytes
4355 if (!bodyPipe
->bodySizeKnown())
4356 return -1; // probably need to read more, but we cannot be sure
4358 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4359 const int64_t haveAvailable
= static_cast<int64_t>(inBuf
.length());
4361 if (needToProduce
<= haveAvailable
)
4362 return 0; // we have read what we need (but are waiting for pipe space)
4364 return needToProduce
- haveAvailable
;
4368 ConnStateData::stopReceiving(const char *error
)
4370 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4371 "; old sending error: " <<
4372 (stoppedSending() ? stoppedSending_
: "none"));
4374 if (const char *oldError
= stoppedReceiving()) {
4375 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4376 return; // nothing has changed as far as this connection is concerned
4379 stoppedReceiving_
= error
;
4381 if (const char *sendError
= stoppedSending()) {
4382 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4383 clientConnection
->close();
4388 ConnStateData::expectNoForwarding()
4390 if (bodyPipe
!= NULL
) {
4391 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4392 bodyPipe
->expectNoConsumption();
4396 /// initialize dechunking state
4398 ConnStateData::startDechunkingRequest()
4400 Must(bodyPipe
!= NULL
);
4401 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4402 assert(!bodyParser
);
4403 bodyParser
= new Http1::TeChunkedParser
;
4406 /// put parsed content into input buffer and clean up
4408 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4410 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4412 if (bodyPipe
!= NULL
) {
4413 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4414 BodyPipe::Pointer myPipe
= bodyPipe
;
4415 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4416 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4418 Must(myPipe
->bodySizeKnown());
4419 ClientSocketContext::Pointer context
= pipeline
.front();
4420 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4421 context
->http
->request
->setContentLength(myPipe
->bodySize());
4429 // XXX: this is an HTTP/1-only operation
4431 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4434 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4438 // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them
4439 if (!pipeline
.empty()) {
4440 HttpReply::Pointer
rep(msg
.reply
);
4442 // remember the callback
4443 cbControlMsgSent
= msg
.cbSuccess
;
4445 typedef CommCbMemFunT
<HttpControlMsgSink
, CommIoCbParams
> Dialer
;
4446 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, HttpControlMsgSink::wroteControlMsg
);
4448 writeControlMsgAndCall(rep
.getRaw(), call
);
4452 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4453 clientConnection
->close();
4456 /// Our close handler called by Comm when the pinned connection is closed
4458 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4460 // FwdState might repin a failed connection sooner than this close
4461 // callback is called for the failed connection.
4462 assert(pinning
.serverConnection
== io
.conn
);
4463 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4464 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4465 pinning
.serverConnection
->noteClosure();
4466 unpinConnection(false);
4468 if (sawZeroReply
&& clientConnection
!= NULL
) {
4469 debugs(33, 3, "Closing client connection on pinned zero reply.");
4470 clientConnection
->close();
4476 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
4478 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
4479 pinning
.serverConnection
->fd
!= pinServer
->fd
)
4480 pinNewConnection(pinServer
, request
, aPeer
, auth
);
4483 startPinnedConnectionMonitoring();
4487 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4489 unpinConnection(true); // closes pinned connection, if any, and resets fields
4491 pinning
.serverConnection
= pinServer
;
4493 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4495 Must(pinning
.serverConnection
!= NULL
);
4497 // when pinning an SSL bumped connection, the request may be NULL
4498 const char *pinnedHost
= "[unknown]";
4500 pinning
.host
= xstrdup(request
->url
.host());
4501 pinning
.port
= request
->url
.port();
4502 pinnedHost
= pinning
.host
;
4504 pinning
.port
= pinServer
->remote
.port();
4506 pinning
.pinned
= true;
4508 pinning
.peer
= cbdataReference(aPeer
);
4509 pinning
.auth
= auth
;
4510 char stmp
[MAX_IPSTRLEN
];
4511 char desc
[FD_DESC_SZ
];
4512 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4513 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4514 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4515 clientConnection
->fd
);
4516 fd_note(pinning
.serverConnection
->fd
, desc
);
4518 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4519 pinning
.closeHandler
= JobCallback(33, 5,
4520 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4521 // remember the pinned connection so that cb does not unpin a fresher one
4522 typedef CommCloseCbParams Params
;
4523 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4524 params
.conn
= pinning
.serverConnection
;
4525 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4528 /// [re]start monitoring pinned connection for peer closures so that we can
4529 /// propagate them to an _idle_ client pinned to that peer
4531 ConnStateData::startPinnedConnectionMonitoring()
4533 if (pinning
.readHandler
!= NULL
)
4534 return; // already monitoring
4536 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4537 pinning
.readHandler
= JobCallback(33, 3,
4538 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4539 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
4543 ConnStateData::stopPinnedConnectionMonitoring()
4545 if (pinning
.readHandler
!= NULL
) {
4546 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4547 pinning
.readHandler
= NULL
;
4553 ConnStateData::handleIdleClientPinnedTlsRead()
4555 // A ready-for-reading connection means that the TLS server either closed
4556 // the connection, sent us some unexpected HTTP data, or started TLS
4557 // renegotiations. We should close the connection except for the last case.
4559 Must(pinning
.serverConnection
!= nullptr);
4560 SSL
*ssl
= fd_table
[pinning
.serverConnection
->fd
].ssl
;
4565 const int readResult
= SSL_read(ssl
, buf
, sizeof(buf
));
4567 if (readResult
> 0 || SSL_pending(ssl
) > 0) {
4568 debugs(83, 2, pinning
.serverConnection
<< " TLS application data read");
4572 switch(const int error
= SSL_get_error(ssl
, readResult
)) {
4573 case SSL_ERROR_WANT_WRITE
:
4574 debugs(83, DBG_IMPORTANT
, pinning
.serverConnection
<< " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection");
4575 // fall through to restart monitoring, for now
4576 case SSL_ERROR_NONE
:
4577 case SSL_ERROR_WANT_READ
:
4578 startPinnedConnectionMonitoring();
4582 debugs(83, 2, pinning
.serverConnection
<< " TLS error: " << error
);
4591 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4592 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4594 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4596 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4598 if (io
.flag
== Comm::ERR_CLOSING
)
4599 return; // close handler will clean up
4601 Must(pinning
.serverConnection
== io
.conn
);
4604 if (handleIdleClientPinnedTlsRead())
4608 const bool clientIsIdle
= pipeline
.empty();
4610 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4611 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4613 pinning
.serverConnection
->close();
4615 // If we are still sending data to the client, do not close now. When we are done sending,
4616 // ConnStateData::kick() checks pinning.serverConnection and will close.
4617 // However, if we are idle, then we must close to inform the idle client and minimize races.
4618 if (clientIsIdle
&& clientConnection
!= NULL
)
4619 clientConnection
->close();
4622 const Comm::ConnectionPointer
4623 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4625 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4628 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4630 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->url
.host()) != 0)
4632 else if (request
&& pinning
.port
!= request
->url
.port())
4634 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4636 else if (aPeer
!= pinning
.peer
)
4640 /* The pinning info is not safe, remove any pinning info */
4641 unpinConnection(true);
4644 return pinning
.serverConnection
;
4647 Comm::ConnectionPointer
4648 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4650 debugs(33, 7, pinning
.serverConnection
);
4651 if (validatePinnedConnection(request
, aPeer
) != NULL
)
4652 stopPinnedConnectionMonitoring();
4654 return pinning
.serverConnection
; // closed if validation failed
4658 ConnStateData::unpinConnection(const bool andClose
)
4660 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4663 cbdataReferenceDone(pinning
.peer
);
4665 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4666 if (pinning
.closeHandler
!= NULL
) {
4667 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4668 pinning
.closeHandler
= NULL
;
4671 stopPinnedConnectionMonitoring();
4673 // close the server side socket if requested
4675 pinning
.serverConnection
->close();
4676 pinning
.serverConnection
= NULL
;
4679 safe_free(pinning
.host
);
4681 pinning
.zeroReply
= false;
4683 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4684 * connection has gone away */