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 if (clientConnection
!= NULL
)
677 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
678 pipeline
.terminateAll(0);
680 unpinConnection(true);
682 Server::swanSong(); // closes the client connection
685 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
686 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
689 flags
.swanSang
= true;
693 ConnStateData::isOpen() const
695 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
696 Comm::IsConnOpen(clientConnection
) &&
697 !fd_table
[clientConnection
->fd
].closing();
700 ConnStateData::~ConnStateData()
702 debugs(33, 3, HERE
<< clientConnection
);
705 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
708 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
710 if (bodyPipe
!= NULL
)
711 stopProducingFor(bodyPipe
, false);
713 delete bodyParser
; // TODO: pool
716 delete sslServerBump
;
721 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
722 * This is the client-side persistent connection flag. We need
723 * to set this relatively early in the request processing
724 * to handle hacks for broken servers and clients.
727 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
729 HttpRequest
*request
= http
->request
;
731 debugs(33, 3, "http_ver = " << request
->http_ver
);
732 debugs(33, 3, "method = " << request
->method
);
734 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
735 request
->flags
.proxyKeepalive
= request
->persistent();
738 /// checks body length of non-chunked requests
740 clientIsContentLengthValid(HttpRequest
* r
)
742 // No Content-Length means this request just has no body, but conflicting
743 // Content-Lengths mean a message framing error (RFC 7230 Section 3.3.3 #4).
744 if (r
->header
.conflictingContentLength())
747 switch (r
->method
.id()) {
749 case Http::METHOD_GET
:
751 case Http::METHOD_HEAD
:
752 /* We do not want to see a request entity on GET/HEAD requests */
753 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
756 /* For other types of requests we don't care */
764 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
766 if (Config
.maxRequestBodySize
&&
767 bodyLength
> Config
.maxRequestBodySize
)
768 return 1; /* too large */
774 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
776 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
777 assert(flags
.deferred
== 0);
779 deferredparams
.node
= node
;
780 deferredparams
.rep
= rep
;
781 deferredparams
.queuedBuffer
= receivedData
;
786 ClientSocketContext::startOfOutput() const
788 return http
->out
.size
== 0;
792 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
794 /*the size of available range can always fit in a size_t type*/
795 size_t maximum
= (size_t)available
.size();
797 if (!http
->request
->range
)
800 assert (canPackMoreRanges());
802 if (http
->range_iter
.debt() == -1)
805 assert (http
->range_iter
.debt() > 0);
807 /* TODO this + the last line could be a range intersection calculation */
808 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
811 return min(http
->range_iter
.debt(), (int64_t)maximum
);
815 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
817 debugs(33, 7, bytes
<< " body bytes");
819 http
->out
.offset
+= bytes
;
821 if (!http
->request
->range
)
824 if (http
->range_iter
.debt() != -1) {
825 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
826 assert (http
->range_iter
.debt() >= 0);
829 /* debt() always stops at -1, below that is a bug */
830 assert (http
->range_iter
.debt() >= -1);
834 ClientHttpRequest::multipartRangeRequest() const
836 return request
->multipartRangeRequest();
840 ClientSocketContext::multipartRangeRequest() const
842 return http
->multipartRangeRequest();
846 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
850 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
851 size_t length
= lengthToSend(bodyData
.range());
852 noteSentBodyBytes (length
);
853 getConn()->write(bodyData
.data
, length
);
859 if (multipartRangeRequest())
860 packRange(bodyData
, &mb
);
862 packChunk(bodyData
, mb
);
864 if (mb
.contentSize())
865 getConn()->write(&mb
);
871 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
872 * if bodyData is empty.
875 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
877 const uint64_t length
=
878 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
879 noteSentBodyBytes(length
);
881 mb
.appendf("%" PRIX64
"\r\n", length
);
882 mb
.append(bodyData
.data
, length
);
883 mb
.append("\r\n", 2);
886 /** put terminating boundary for multiparts */
888 clientPackTermBound(String boundary
, MemBuf
* mb
)
890 mb
->appendf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
891 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
894 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
896 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
898 HttpHeader
hdr(hoReply
);
903 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
904 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
905 mb
->appendf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
907 /* stuff the header with required entries and pack it */
909 if (rep
->header
.has(Http::HdrType::CONTENT_TYPE
))
910 hdr
.putStr(Http::HdrType::CONTENT_TYPE
, rep
->header
.getStr(Http::HdrType::CONTENT_TYPE
));
912 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
917 /* append <crlf> (we packed a header, not a reply) */
918 mb
->append("\r\n", 2);
922 * extracts a "range" from *buf and appends them to mb, updating
923 * all offsets and such.
926 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
928 HttpHdrRangeIter
* i
= &http
->range_iter
;
929 Range
<int64_t> available (source
.range());
930 char const *buf
= source
.data
;
932 while (i
->currentSpec() && available
.size()) {
933 const size_t copy_sz
= lengthToSend(available
);
937 * intersection of "have" and "need" ranges must not be empty
939 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
940 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
943 * put boundary and headers at the beginning of a range in a
947 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
948 assert(http
->memObject());
950 http
->memObject()->getReply(), /* original reply */
951 i
->currentSpec(), /* current range */
952 i
->boundary
, /* boundary, the same for all */
959 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
961 noteSentBodyBytes (copy_sz
);
963 mb
->append(buf
, copy_sz
);
968 available
.start
+= copy_sz
;
974 if (!canPackMoreRanges()) {
975 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
978 /* put terminating boundary for multiparts */
979 clientPackTermBound(i
->boundary
, mb
);
984 int64_t nextOffset
= getNextRangeOffset();
986 assert (nextOffset
>= http
->out
.offset
);
988 int64_t skip
= nextOffset
- http
->out
.offset
;
990 /* adjust for not to be transmitted bytes */
991 http
->out
.offset
= nextOffset
;
993 if (available
.size() <= (uint64_t)skip
)
996 available
.start
+= skip
;
1005 /** returns expected content length for multi-range replies
1006 * note: assumes that httpHdrRangeCanonize has already been called
1007 * warning: assumes that HTTP headers for individual ranges at the
1008 * time of the actuall assembly will be exactly the same as
1009 * the headers when clientMRangeCLen() is called */
1011 ClientHttpRequest::mRangeCLen()
1016 assert(memObject());
1019 HttpHdrRange::iterator pos
= request
->range
->begin();
1021 while (pos
!= request
->range
->end()) {
1022 /* account for headers for this range */
1024 clientPackRangeHdr(memObject()->getReply(),
1025 *pos
, range_iter
.boundary
, &mb
);
1028 /* account for range content */
1029 clen
+= (*pos
)->length
;
1031 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1035 /* account for the terminating boundary */
1038 clientPackTermBound(range_iter
.boundary
, &mb
);
1048 * returns true if If-Range specs match reply, false otherwise
1051 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1053 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(Http::HdrType::IF_RANGE
);
1054 /* check for parsing falure */
1061 ETag rep_tag
= rep
->header
.getETag(Http::HdrType::ETAG
);
1062 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1063 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1066 return 0; /* entity has no etag to compare with! */
1068 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1069 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1070 return 0; /* must use strong validator for sub-range requests */
1073 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1076 /* got modification time? */
1077 if (spec
.time
>= 0) {
1078 return http
->storeEntry()->lastmod
<= spec
.time
;
1081 assert(0); /* should not happen */
1086 * generates a "unique" boundary string for multipart responses
1087 * the caller is responsible for cleaning the string */
1089 ClientHttpRequest::rangeBoundaryStr() const
1092 String
b(APP_FULLNAME
);
1094 key
= storeEntry()->getMD5Text();
1095 b
.append(key
, strlen(key
));
1099 /** adds appropriate Range headers if needed */
1101 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1103 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1104 const char *range_err
= NULL
;
1105 HttpRequest
*request
= http
->request
;
1106 assert(request
->range
);
1107 /* check if we still want to do ranges */
1109 int64_t roffLimit
= request
->getRangeOffsetLimit();
1112 range_err
= "no [parse-able] reply";
1113 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1114 range_err
= "wrong status code";
1115 else if (hdr
->has(Http::HdrType::CONTENT_RANGE
))
1116 range_err
= "origin server does ranges";
1117 else if (rep
->content_length
< 0)
1118 range_err
= "unknown length";
1119 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1120 range_err
= "INCONSISTENT length"; /* a bug? */
1122 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1125 else if (http
->logType
.isTcpHit() && http
->request
->header
.has(Http::HdrType::IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1126 range_err
= "If-Range match failed";
1127 else if (!http
->request
->range
->canonize(rep
))
1128 range_err
= "canonization failed";
1129 else if (http
->request
->range
->isComplex())
1130 range_err
= "too complex range header";
1131 else if (!http
->logType
.isTcpHit() && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1132 range_err
= "range outside range_offset_limit";
1134 /* get rid of our range specs on error */
1136 /* XXX We do this here because we need canonisation etc. However, this current
1137 * code will lead to incorrect store offset requests - the store will have the
1138 * offset data, but we won't be requesting it.
1139 * So, we can either re-request, or generate an error
1141 http
->request
->ignoreRange(range_err
);
1143 /* XXX: TODO: Review, this unconditional set may be wrong. */
1144 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1145 // web server responded with a valid, but unexpected range.
1146 // will (try-to) forward as-is.
1147 //TODO: we should cope with multirange request/responses
1148 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1149 request
->range
->contains(rep
->content_range
->spec
) :
1151 const int spec_count
= http
->request
->range
->specs
.size();
1152 int64_t actual_clen
= -1;
1154 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1155 spec_count
<< " virgin clen: " << rep
->content_length
);
1156 assert(spec_count
> 0);
1157 /* append appropriate header(s) */
1159 if (spec_count
== 1) {
1160 if (!replyMatchRequest
) {
1161 hdr
->delById(Http::HdrType::CONTENT_RANGE
);
1162 hdr
->putContRange(rep
->content_range
);
1163 actual_clen
= rep
->content_length
;
1164 //http->range_iter.pos = rep->content_range->spec.begin();
1165 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1166 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1169 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1171 /* append Content-Range */
1173 if (!hdr
->has(Http::HdrType::CONTENT_RANGE
)) {
1174 /* No content range, so this was a full object we are
1177 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1180 /* set new Content-Length to the actual number of bytes
1181 * transmitted in the message-body */
1182 actual_clen
= (*pos
)->length
;
1186 /* generate boundary string */
1187 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1188 /* delete old Content-Type, add ours */
1189 hdr
->delById(Http::HdrType::CONTENT_TYPE
);
1190 httpHeaderPutStrf(hdr
, Http::HdrType::CONTENT_TYPE
,
1191 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1192 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1193 /* Content-Length is not required in multipart responses
1194 * but it is always nice to have one */
1195 actual_clen
= http
->mRangeCLen();
1196 /* http->out needs to start where we want data at */
1197 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1200 /* replace Content-Length header */
1201 assert(actual_clen
>= 0);
1203 hdr
->delById(Http::HdrType::CONTENT_LENGTH
);
1205 hdr
->putInt64(Http::HdrType::CONTENT_LENGTH
, actual_clen
);
1207 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1209 /* And start the range iter off */
1210 http
->range_iter
.updateSpec();
1215 ClientSocketContext::prepareReply(HttpReply
* rep
)
1219 if (http
->request
->range
)
1220 buildRangeHeader(rep
);
1224 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1228 MemBuf
*mb
= rep
->pack();
1230 // dump now, so we dont output any body.
1231 debugs(11, 2, "HTTP Client " << clientConnection
);
1232 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1234 /* Save length of headers for persistent conn checks */
1235 http
->out
.headers_sz
= mb
->contentSize();
1238 headersLog(0, 0, http
->request
->method
, rep
);
1241 if (bodyData
.data
&& bodyData
.length
) {
1242 if (multipartRangeRequest())
1243 packRange(bodyData
, mb
);
1244 else if (http
->request
->flags
.chunkedReply
) {
1245 packChunk(bodyData
, *mb
);
1247 size_t length
= lengthToSend(bodyData
.range());
1248 noteSentBodyBytes (length
);
1250 mb
->append(bodyData
.data
, length
);
1254 getConn()->write(mb
);
1259 * Write a chunk of data to a client socket. If the reply is present,
1260 * send the reply headers down the wire too, and clean them up when
1263 * The request is one backed by a connection, not an internal request.
1264 * data context is not NULL
1265 * There are no more entries in the stream chain.
1268 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1269 HttpReply
* rep
, StoreIOBuffer receivedData
)
1271 // dont tryt to deliver if client already ABORTED
1272 if (!http
->getConn() || !cbdataReferenceValid(http
->getConn()))
1275 // If it is not connectionless and connection is closed return
1276 if (!http
->getConn()->connectionless() && !Comm::IsConnOpen(http
->getConn()->clientConnection
))
1280 /* Test preconditions */
1281 assert(node
!= NULL
);
1282 PROF_start(clientSocketRecipient
);
1283 /* TODO: handle this rather than asserting
1284 * - it should only ever happen if we cause an abort and
1285 * the callback chain loops back to here, so we can simply return.
1286 * However, that itself shouldn't happen, so it stays as an assert for now.
1288 assert(cbdataReferenceValid(node
));
1289 assert(node
->node
.next
== NULL
);
1290 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1291 assert(context
!= NULL
);
1293 /* TODO: check offset is what we asked for */
1295 // TODO: enforces HTTP/1 MUST on pipeline order, but is irrelevant to HTTP/2
1296 if (context
!= http
->getConn()->pipeline
.front())
1297 context
->deferRecipientForLater(node
, rep
, receivedData
);
1299 http
->getConn()->handleReply(rep
, receivedData
);
1301 PROF_stop(clientSocketRecipient
);
1305 * Called when a downstream node is no longer interested in
1306 * our data. As we are a terminal node, this means on aborts
1310 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1312 /* Test preconditions */
1313 assert(node
!= NULL
);
1314 /* TODO: handle this rather than asserting
1315 * - it should only ever happen if we cause an abort and
1316 * the callback chain loops back to here, so we can simply return.
1317 * However, that itself shouldn't happen, so it stays as an assert for now.
1319 assert(cbdataReferenceValid(node
));
1320 /* Set null by ContextFree */
1321 assert(node
->node
.next
== NULL
);
1322 /* this is the assert discussed above */
1323 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1324 /* We are only called when the client socket shutsdown.
1325 * Tell the prev pipeline member we're finished
1327 clientStreamDetach(node
, http
);
1331 ConnStateData::readNextRequest()
1333 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1335 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1337 * Set the timeout BEFORE calling readSomeData().
1339 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1340 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1341 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1342 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
1345 /** Please don't do anything with the FD past here! */
1349 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1351 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1353 /** If the client stream is waiting on a socket write to occur, then */
1355 if (deferredRequest
->flags
.deferred
) {
1356 /** NO data is allowed to have been sent. */
1357 assert(deferredRequest
->http
->out
.size
== 0);
1359 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1360 deferredRequest
->http
,
1361 deferredRequest
->deferredparams
.rep
,
1362 deferredRequest
->deferredparams
.queuedBuffer
);
1365 /** otherwise, the request is still active in a callbacksomewhere,
1371 ConnStateData::kick()
1373 if (!Comm::IsConnOpen(clientConnection
)) {
1374 debugs(33, 2, clientConnection
<< " Connection was closed");
1378 if (pinning
.pinned
&& !Comm::IsConnOpen(pinning
.serverConnection
)) {
1379 debugs(33, 2, clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1380 clientConnection
->close();
1385 * We are done with the response, and we are either still receiving request
1386 * body (early response!) or have already stopped receiving anything.
1388 * If we are still receiving, then clientParseRequest() below will fail.
1389 * (XXX: but then we will call readNextRequest() which may succeed and
1390 * execute a smuggled request as we are not done with the current request).
1392 * If we stopped because we got everything, then try the next request.
1394 * If we stopped receiving because of an error, then close now to avoid
1395 * getting stuck and to prevent accidental request smuggling.
1398 if (const char *reason
= stoppedReceiving()) {
1399 debugs(33, 3, "closing for earlier request error: " << reason
);
1400 clientConnection
->close();
1405 * Attempt to parse a request from the request buffer.
1406 * If we've been fed a pipelined request it may already
1407 * be in our read buffer.
1410 * This needs to fall through - if we're unlucky and parse the _last_ request
1411 * from our read buffer we may never re-register for another client read.
1414 if (clientParseRequests()) {
1415 debugs(33, 3, clientConnection
<< ": parsed next request from buffer");
1419 * Either we need to kick-start another read or, if we have
1420 * a half-closed connection, kill it after the last request.
1421 * This saves waiting for half-closed connections to finished being
1422 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1423 * the keepalive "Waiting for next request" state.
1425 if (commIsHalfClosed(clientConnection
->fd
) && pipeline
.empty()) {
1426 debugs(33, 3, "half-closed client with no pending requests, closing");
1427 clientConnection
->close();
1432 * At this point we either have a parsed request (which we've
1433 * kicked off the processing for) or not. If we have a deferred
1434 * request (parsed but deferred for pipeling processing reasons)
1435 * then look at processing it. If not, simply kickstart
1438 ClientSocketContext::Pointer deferredRequest
= pipeline
.front();
1439 if (deferredRequest
!= nullptr) {
1440 debugs(33, 3, clientConnection
<< ": calling PushDeferredIfNeeded");
1441 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, this);
1442 } else if (flags
.readMore
) {
1443 debugs(33, 3, clientConnection
<< ": calling readNextRequest()");
1446 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1447 debugs(33, DBG_IMPORTANT
, MYNAME
<< "abandoning " << clientConnection
);
1452 clientUpdateSocketStats(const LogTags
&logType
, size_t size
)
1457 statCounter
.client_http
.kbytes_out
+= size
;
1459 if (logType
.isTcpHit())
1460 statCounter
.client_http
.hit_kbytes_out
+= size
;
1464 * increments iterator "i"
1465 * used by clientPackMoreRanges
1467 \retval true there is still data available to pack more ranges
1471 ClientSocketContext::canPackMoreRanges() const
1473 /** first update iterator "i" if needed */
1475 if (!http
->range_iter
.debt()) {
1476 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1478 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1479 ++http
->range_iter
.pos
;
1481 http
->range_iter
.updateSpec();
1484 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1486 /* paranoid sync condition */
1487 /* continue condition: need_more_data */
1488 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1489 return http
->range_iter
.currentSpec() ? true : false;
1493 ClientSocketContext::getNextRangeOffset() const
1495 debugs (33, 5, "range: " << http
->request
->range
<<
1496 "; http offset " << http
->out
.offset
<<
1497 "; reply " << reply
);
1499 // XXX: This method is called from many places, including pullData() which
1500 // may be called before prepareReply() [on some Squid-generated errors].
1501 // Hence, we may not even know yet whether we should honor/do ranges.
1503 if (http
->request
->range
) {
1504 /* offset in range specs does not count the prefix of an http msg */
1505 /* check: reply was parsed and range iterator was initialized */
1506 assert(http
->range_iter
.valid
);
1507 /* filter out data according to range specs */
1508 assert (canPackMoreRanges());
1510 int64_t start
; /* offset of still missing data */
1511 assert(http
->range_iter
.currentSpec());
1512 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1513 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1514 debugs(33, 3, "clientPackMoreRanges: out:"
1515 " start: " << start
<<
1516 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1517 " [" << http
->range_iter
.currentSpec()->offset
<<
1518 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1519 " len: " << http
->range_iter
.currentSpec()->length
<<
1520 " debt: " << http
->range_iter
.debt());
1521 if (http
->range_iter
.currentSpec()->length
!= -1)
1522 assert(http
->out
.offset
<= start
); /* we did not miss it */
1527 } else if (reply
&& reply
->content_range
) {
1528 /* request does not have ranges, but reply does */
1529 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1530 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1532 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1535 return http
->out
.offset
;
1539 ClientSocketContext::pullData()
1541 debugs(33, 5, reply
<< " written " << http
->out
.size
<< " into " << clientConnection
);
1543 /* More data will be coming from the stream. */
1544 StoreIOBuffer readBuffer
;
1545 /* XXX: Next requested byte in the range sequence */
1546 /* XXX: length = getmaximumrangelenfgth */
1547 readBuffer
.offset
= getNextRangeOffset();
1548 readBuffer
.length
= HTTP_REQBUF_SZ
;
1549 readBuffer
.data
= reqbuf
;
1550 /* we may note we have reached the end of the wanted ranges */
1551 clientStreamRead(getTail(), http
, readBuffer
);
1554 /** Adapt stream status to account for Range cases
1557 clientStream_status_t
1558 ClientSocketContext::socketState()
1560 switch (clientStreamStatus(getTail(), http
)) {
1563 /* check for range support ending */
1565 if (http
->request
->range
) {
1566 /* check: reply was parsed and range iterator was initialized */
1567 assert(http
->range_iter
.valid
);
1568 /* filter out data according to range specs */
1570 if (!canPackMoreRanges()) {
1571 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1572 "range sequence on " << clientConnection
);
1573 // we got everything we wanted from the store
1574 return STREAM_COMPLETE
;
1576 } else if (reply
&& reply
->content_range
) {
1577 /* reply has content-range, but Squid is not managing ranges */
1578 const int64_t &bytesSent
= http
->out
.offset
;
1579 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1581 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1582 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1583 reply
->content_range
->spec
.offset
<< ")");
1585 // did we get at least what we expected, based on range specs?
1587 if (bytesSent
== bytesExpected
) // got everything
1588 return STREAM_COMPLETE
;
1590 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1591 return STREAM_UNPLANNED_COMPLETE
;
1596 case STREAM_COMPLETE
:
1597 return STREAM_COMPLETE
;
1599 case STREAM_UNPLANNED_COMPLETE
:
1600 return STREAM_UNPLANNED_COMPLETE
;
1603 return STREAM_FAILED
;
1606 fatal ("unreachable code\n");
1610 /// remembers the abnormal connection termination for logging purposes
1612 ClientSocketContext::noteIoError(const int xerrno
)
1615 http
->logType
.err
.timedout
= (xerrno
== ETIMEDOUT
);
1616 // aborted even if xerrno is zero (which means read abort/eof)
1617 http
->logType
.err
.aborted
= (xerrno
!= ETIMEDOUT
);
1622 ClientSocketContext::doClose()
1624 clientConnection
->close();
1627 /// called when we encounter a response-related error
1629 ClientSocketContext::initiateClose(const char *reason
)
1631 debugs(33, 4, clientConnection
<< " because " << reason
);
1632 http
->getConn()->stopSending(reason
); // closes ASAP
1636 ConnStateData::stopSending(const char *error
)
1638 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1639 "; old receiving error: " <<
1640 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1642 if (const char *oldError
= stoppedSending()) {
1643 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1644 return; // nothing has changed as far as this connection is concerned
1646 stoppedSending_
= error
;
1648 if (!stoppedReceiving()) {
1649 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1650 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1651 " request body bytes with " << inBuf
.length() << " unused");
1652 return; // wait for the request receiver to finish reading
1656 clientConnection
->close();
1660 ConnStateData::afterClientWrite(size_t size
)
1662 if (pipeline
.empty())
1665 pipeline
.front()->writeComplete(size
);
1668 // TODO: make this only need size parameter, ConnStateData handles the rest
1670 ClientSocketContext::writeComplete(size_t size
)
1672 const StoreEntry
*entry
= http
->storeEntry();
1673 debugs(33, 5, clientConnection
<< ", sz " << size
<<
1674 ", off " << (http
->out
.size
+ size
) << ", len " <<
1675 (entry
? entry
->objectLen() : 0));
1677 http
->out
.size
+= size
;
1678 clientUpdateSocketStats(http
->logType
, size
);
1680 if (clientHttpRequestStatus(clientConnection
->fd
, http
)) {
1681 initiateClose("failure or true request status");
1682 /* Do we leak here ? */
1686 switch (socketState()) {
1692 case STREAM_COMPLETE
: {
1693 debugs(33, 5, clientConnection
<< " Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1694 ConnStateData
*c
= http
->getConn();
1695 if (!http
->request
->flags
.proxyKeepalive
)
1696 clientConnection
->close();
1702 case STREAM_UNPLANNED_COMPLETE
:
1703 initiateClose("STREAM_UNPLANNED_COMPLETE");
1707 initiateClose("STREAM_FAILED");
1711 fatal("Hit unreachable code in ClientSocketContext::writeComplete\n");
1715 ClientSocketContext
*
1716 ConnStateData::abortRequestParsing(const char *const uri
)
1718 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1719 http
->req_sz
= inBuf
.length();
1720 http
->uri
= xstrdup(uri
);
1721 setLogUri (http
, uri
);
1722 ClientSocketContext
*context
= new ClientSocketContext(clientConnection
, http
);
1723 StoreIOBuffer tempBuffer
;
1724 tempBuffer
.data
= context
->reqbuf
;
1725 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1726 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1727 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1728 clientSocketDetach
, context
, tempBuffer
);
1733 ConnStateData::startShutdown()
1735 // RegisteredRunner API callback - Squid has been shut down
1737 // if connection is idle terminate it now,
1738 // otherwise wait for grace period to end
1739 if (pipeline
.empty())
1744 ConnStateData::endingShutdown()
1746 // RegisteredRunner API callback - Squid shutdown grace period is over
1748 // force the client connection to close immediately
1749 // swanSong() in the close handler will cleanup.
1750 if (Comm::IsConnOpen(clientConnection
))
1751 clientConnection
->close();
1753 // deregister now to ensure finalShutdown() does not kill us prematurely.
1754 // fd_table purge will cleanup if close handler was not fast enough.
1755 DeregisterRunner(this);
1759 skipLeadingSpace(char *aString
)
1761 char *result
= aString
;
1763 while (xisspace(*aString
))
1770 * 'end' defaults to NULL for backwards compatibility
1771 * remove default value if we ever get rid of NULL-terminated
1775 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1778 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1782 for (; end
> uriAndHTTPVersion
; --end
) {
1783 if (*end
== '\n' || *end
== '\r')
1786 if (xisspace(*end
)) {
1787 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1798 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1800 safe_free(http
->log_uri
);
1803 // The uri is already clean just dump it.
1804 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1807 switch (Config
.uri_whitespace
) {
1808 case URI_WHITESPACE_ALLOW
:
1809 flags
|= RFC1738_ESCAPE_NOSPACE
;
1811 case URI_WHITESPACE_ENCODE
:
1812 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1813 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1816 case URI_WHITESPACE_CHOP
: {
1817 flags
|= RFC1738_ESCAPE_NOSPACE
;
1818 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1819 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1820 int pos
= strcspn(http
->log_uri
, w_space
);
1821 http
->log_uri
[pos
] = '\0';
1825 case URI_WHITESPACE_DENY
:
1826 case URI_WHITESPACE_STRIP
:
1829 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1833 if (!xisspace(*t
)) {
1840 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
1849 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1851 int vhost
= conn
->port
->vhost
;
1852 int vport
= conn
->port
->vport
;
1853 static char ipbuf
[MAX_IPSTRLEN
];
1855 http
->flags
.accel
= true;
1857 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1859 static const SBuf
cache_object("cache_object://");
1860 if (hp
->requestUri().startsWith(cache_object
))
1861 return; /* already in good shape */
1863 // XXX: re-use proper URL parser for this
1864 SBuf url
= hp
->requestUri(); // use full provided URI if we abort
1865 do { // use a loop so we can break out of it
1866 ::Parser::Tokenizer
tok(url
);
1867 if (tok
.skip('/')) // origin-form URL already.
1870 if (conn
->port
->vhost
)
1871 return; /* already in good shape */
1873 // skip the URI scheme
1874 static const CharacterSet uriScheme
= CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1875 static const SBuf
uriSchemeEnd("://");
1876 if (!tok
.skipAll(uriScheme
) || !tok
.skip(uriSchemeEnd
))
1879 // skip the authority segment
1880 // RFC 3986 complex nested ABNF for "authority" boils down to this:
1881 static const CharacterSet authority
= CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
1882 CharacterSet::HEXDIG
+ CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1883 if (!tok
.skipAll(authority
))
1886 static const SBuf
slashUri("/");
1887 const SBuf t
= tok
.remaining();
1890 else if (t
[0]=='/') // looks like path
1892 else if (t
[0]=='?' || t
[0]=='#') { // looks like query or fragment. fix '/'
1895 } // else do nothing. invalid path
1899 #if SHOULD_REJECT_UNKNOWN_URLS
1900 // reject URI which are not well-formed even after the processing above
1901 if (url
.isEmpty() || url
[0] != '/') {
1902 hp
->parseStatusCode
= Http::scBadRequest
;
1903 return conn
->abortRequestParsing("error:invalid-request");
1908 vport
= http
->getConn()->clientConnection
->local
.port();
1910 const bool switchedToHttps
= conn
->switchedToHttps();
1911 const bool tryHostHeader
= vhost
|| switchedToHttps
;
1913 if (tryHostHeader
&& (host
= hp
->getHeaderField("Host"))) {
1914 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
1919 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
1920 strncpy(thost
, host
, (t
-host
));
1921 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
1924 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
1927 } // else nothing to alter port-wise.
1928 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+ strlen(host
);
1929 http
->uri
= (char *)xcalloc(url_sz
, 1);
1930 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
, AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(url
));
1931 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
1932 } else if (conn
->port
->defaultsite
/* && !vhost */) {
1933 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
1934 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1935 strlen(conn
->port
->defaultsite
);
1936 http
->uri
= (char *)xcalloc(url_sz
, 1);
1940 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
1942 snprintf(http
->uri
, url_sz
, "%s://%s%s" SQUIDSBUFPH
,
1943 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
1944 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
1945 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
1946 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
1947 /* Put the local socket IP address as the hostname, with whatever vport we found */
1948 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1949 http
->uri
= (char *)xcalloc(url_sz
, 1);
1950 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1951 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
1952 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(),
1953 ipbuf
, vport
, SQUIDSBUFPRINT(url
));
1954 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
1959 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1961 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
1962 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
1963 return; /* already in good shape */
1965 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1967 if (const char *host
= hp
->getHeaderField("Host")) {
1968 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
1970 http
->uri
= (char *)xcalloc(url_sz
, 1);
1971 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
,
1972 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(hp
->requestUri()));
1973 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
1975 /* Put the local socket IP address as the hostname. */
1976 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
1977 http
->uri
= (char *)xcalloc(url_sz
, 1);
1978 static char ipbuf
[MAX_IPSTRLEN
];
1979 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
1980 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
1981 AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).c_str(),
1982 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SQUIDSBUFPRINT(hp
->requestUri()));
1983 debugs(33, 5, "TRANSPARENT REWRITE: " << http
->uri
);
1987 /** Parse an HTTP request
1989 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
1990 * to 1 if the request was correctly parsed.
1991 * \param[in] csd a ConnStateData. The caller must make sure it is not null
1992 * \param[in] hp an Http1::RequestParser
1993 * \param[out] mehtod_p will be set as a side-effect of the parsing.
1994 * Pointed-to value will be set to Http::METHOD_NONE in case of
1996 * \param[out] http_ver will be set as a side-effect of the parsing
1997 * \return NULL on incomplete requests,
1998 * a ClientSocketContext structure on success or failure.
2000 ClientSocketContext
*
2001 parseHttpRequest(ConnStateData
*csd
, const Http1::RequestParserPointer
&hp
)
2003 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
2005 const bool parsedOk
= hp
->parse(csd
->inBuf
);
2007 if (csd
->port
->flags
.isIntercepted() && Config
.accessList
.on_unsupported_protocol
)
2008 csd
->preservedClientData
= csd
->inBuf
;
2009 // sync the buffers after parsing.
2010 csd
->inBuf
= hp
->remaining();
2012 if (hp
->needsMoreData()) {
2013 debugs(33, 5, "Incomplete request, waiting for end of request line");
2018 if (hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
|| hp
->parseStatusCode
== Http::scUriTooLong
)
2019 return csd
->abortRequestParsing("error:request-too-large");
2021 return csd
->abortRequestParsing("error:invalid-request");
2025 /* We know the whole request is in parser now */
2026 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2027 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
2028 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
2032 /* deny CONNECT via accelerated ports */
2033 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
2034 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
2035 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2036 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2037 return csd
->abortRequestParsing("error:method-not-allowed");
2040 /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific
2041 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
2042 * If seen it signals a broken client or proxy has corrupted the traffic.
2044 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
2045 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
2046 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2047 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2048 return csd
->abortRequestParsing("error:method-not-allowed");
2051 if (hp
->method() == Http::METHOD_NONE
) {
2052 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2053 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2054 return csd
->abortRequestParsing("error:unsupported-request-method");
2057 // Process headers after request line
2058 debugs(33, 3, "complete request received. " <<
2059 "prefix_sz = " << hp
->messageHeaderSize() <<
2060 ", request-line-size=" << hp
->firstLineSize() <<
2061 ", mime-header-size=" << hp
->headerBlockSize() <<
2062 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
2064 /* Ok, all headers are received */
2065 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
2067 http
->req_sz
= hp
->messageHeaderSize();
2068 ClientSocketContext
*result
= new ClientSocketContext(csd
->clientConnection
, http
);
2070 StoreIOBuffer tempBuffer
;
2071 tempBuffer
.data
= result
->reqbuf
;
2072 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2074 ClientStreamData newServer
= new clientReplyContext(http
);
2075 ClientStreamData newClient
= result
;
2076 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2077 clientReplyStatus
, newServer
, clientSocketRecipient
,
2078 clientSocketDetach
, newClient
, tempBuffer
);
2081 debugs(33,5, "Prepare absolute URL from " <<
2082 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2083 /* Rewrite the URL in transparent or accelerator mode */
2084 /* NP: there are several cases to traverse here:
2085 * - standard mode (forward proxy)
2086 * - transparent mode (TPROXY)
2087 * - transparent mode with failures
2088 * - intercept mode (NAT)
2089 * - intercept mode with failures
2090 * - accelerator mode (reverse proxy)
2091 * - internal relative-URL
2092 * - mixed combos of the above with internal URL
2093 * - remote interception with PROXY protocol
2094 * - remote reverse-proxy with PROXY protocol
2096 if (csd
->transparent()) {
2097 /* intercept or transparent mode, properly working with no failures */
2098 prepareTransparentURL(csd
, http
, hp
);
2100 } else if (internalCheck(hp
->requestUri())) { // NP: only matches relative-URI
2101 /* internal URL mode */
2102 /* prepend our name & port */
2103 http
->uri
= xstrdup(internalLocalUri(NULL
, hp
->requestUri()));
2104 // We just re-wrote the URL. Must replace the Host: header.
2105 // But have not parsed there yet!! flag for local-only handling.
2106 http
->flags
.internal
= true;
2108 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2109 /* accelerator mode */
2110 prepareAcceleratedURL(csd
, http
, hp
);
2114 /* No special rewrites have been applied above, use the
2115 * requested url. may be rewritten later, so make extra room */
2116 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
2117 http
->uri
= (char *)xcalloc(url_sz
, 1);
2118 SBufToCstring(http
->uri
, hp
->requestUri());
2121 result
->flags
.parsed_ok
= 1;
2126 ConnStateData::connFinishedWithConn(int size
)
2129 if (pipeline
.empty() && inBuf
.isEmpty()) {
2130 /* no current or pending requests */
2131 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2133 } else if (!Config
.onoff
.half_closed_clients
) {
2134 /* admin doesn't want to support half-closed client sockets */
2135 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2136 pipeline
.terminateAll(0);
2145 ConnStateData::consumeInput(const size_t byteCount
)
2147 assert(byteCount
> 0 && byteCount
<= inBuf
.length());
2148 inBuf
.consume(byteCount
);
2149 debugs(33, 5, "inBuf has " << inBuf
.length() << " unused bytes");
2153 ConnStateData::clientAfterReadingRequests()
2155 // Were we expecting to read more request body from half-closed connection?
2156 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2157 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2158 clientConnection
->close();
2167 ConnStateData::quitAfterError(HttpRequest
*request
)
2169 // From HTTP p.o.v., we do not have to close after every error detected
2170 // at the client-side, but many such errors do require closure and the
2171 // client-side code is bad at handling errors so we play it safe.
2173 request
->flags
.proxyKeepalive
= false;
2174 flags
.readMore
= false;
2175 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2179 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2181 ClientHttpRequest
*http
= context
->http
;
2186 assert(sslServerBump
->entry
);
2187 // Did we create an error entry while processing CONNECT?
2188 if (!sslServerBump
->entry
->isEmpty()) {
2189 quitAfterError(http
->request
);
2191 // Get the saved error entry and send it to the client by replacing the
2192 // ClientHttpRequest store entry with it.
2193 clientStreamNode
*node
= context
->getClientReplyContext();
2194 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2196 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2197 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
2199 // save the original request for logging purposes
2200 if (!context
->http
->al
->request
) {
2201 context
->http
->al
->request
= http
->request
;
2202 HTTPMSGLOCK(context
->http
->al
->request
);
2205 // Get error details from the fake certificate-peeking request.
2206 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2207 context
->pullData();
2211 // In bump-server-first mode, we have not necessarily seen the intended
2212 // server name at certificate-peeking time. Check for domain mismatch now,
2213 // when we can extract the intended name from the bumped HTTP request.
2214 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2215 HttpRequest
*request
= http
->request
;
2216 if (!Ssl::checkX509ServerValidity(srvCert
, request
->url
.host())) {
2217 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2218 "does not match domainname " << request
->url
.host());
2220 bool allowDomainMismatch
= false;
2221 if (Config
.ssl_client
.cert_error
) {
2222 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2223 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2224 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2225 delete check
.sslErrors
;
2226 check
.sslErrors
= NULL
;
2229 if (!allowDomainMismatch
) {
2230 quitAfterError(request
);
2232 clientStreamNode
*node
= context
->getClientReplyContext();
2233 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2234 assert (repContext
);
2236 // Fill the server IP and hostname for error page generation.
2237 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2238 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->url
.host());
2240 // Create an error object and fill it
2241 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2242 err
->src_addr
= clientConnection
->remote
;
2243 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2244 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2246 err
->detail
= errDetail
;
2247 // Save the original request for logging purposes.
2248 if (!context
->http
->al
->request
) {
2249 context
->http
->al
->request
= request
;
2250 HTTPMSGLOCK(context
->http
->al
->request
);
2252 repContext
->setReplyToError(request
->method
, err
);
2253 assert(context
->http
->out
.offset
== 0);
2254 context
->pullData();
2262 #endif // USE_OPENSSL
2265 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
2266 * or false otherwise
2269 clientTunnelOnError(ConnStateData
*conn
, ClientSocketContext
*context
, HttpRequest
*request
, const HttpRequestMethod
& method
, err_type requestError
, Http::StatusCode errStatusCode
, const char *requestErrorBytes
)
2271 if (conn
->port
->flags
.isIntercepted() &&
2272 Config
.accessList
.on_unsupported_protocol
&& conn
->pipeline
.nrequests
<= 1) {
2273 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
, NULL
);
2274 checklist
.requestErrorType
= requestError
;
2275 checklist
.src_addr
= conn
->clientConnection
->remote
;
2276 checklist
.my_addr
= conn
->clientConnection
->local
;
2277 checklist
.conn(conn
);
2278 allow_t answer
= checklist
.fastCheck();
2279 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
2280 debugs(33, 3, "Request will be tunneled to server");
2282 // XXX: Either the context is finished() or it should stay queued.
2283 // The below may leak client streams BodyPipe objects. BUT, we need
2284 // to check if client-streams detatch is safe to do here (finished() will detatch).
2285 assert(conn
->pipeline
.front() == context
); // XXX: still assumes HTTP/1 semantics
2286 conn
->pipeline
.popMe(ClientSocketContextPointer(context
));
2288 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2289 conn
->fakeAConnectRequest("unknown-protocol", conn
->preservedClientData
);
2292 debugs(33, 3, "Continue with returning the error: " << requestError
);
2297 conn
->quitAfterError(request
);
2298 clientStreamNode
*node
= context
->getClientReplyContext();
2299 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2300 assert (repContext
);
2302 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
2304 assert(context
->http
->out
.offset
== 0);
2305 context
->pullData();
2306 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
2311 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
2315 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2316 * to here because calling comm_reset_close() causes http to
2317 * be freed before accessing.
2319 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2320 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2321 conn
->flags
.readMore
= false;
2322 comm_reset_close(conn
->clientConnection
);
2327 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, ClientSocketContext
*context
)
2329 ClientHttpRequest
*http
= context
->http
;
2330 bool chunked
= false;
2331 bool mustReplyToOptions
= false;
2332 bool unsupportedTe
= false;
2333 bool expectBody
= false;
2335 // We already have the request parsed and checked, so we
2336 // only need to go through the final body/conn setup to doCallouts().
2337 assert(http
->request
);
2338 HttpRequest::Pointer request
= http
->request
;
2340 // temporary hack to avoid splitting this huge function with sensitive code
2341 const bool isFtp
= !hp
;
2343 // Some blobs below are still HTTP-specific, but we would have to rewrite
2344 // this entire function to remove them from the FTP code path. Connection
2345 // setup and body_pipe preparation blobs are needed for FTP.
2347 request
->clientConnectionManager
= conn
;
2349 request
->flags
.accelerated
= http
->flags
.accel
;
2350 request
->flags
.sslBumped
=conn
->switchedToHttps();
2351 if (!conn
->connectionless()) {
2352 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2353 // TODO: decouple http->flags.accel from request->flags.sslBumped
2354 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2355 !conn
->port
->allow_direct
: 0;
2358 if (request
->flags
.sslBumped
) {
2359 if (conn
->getAuth() != NULL
)
2360 request
->auth_user_request
= conn
->getAuth();
2365 * If transparent or interception mode is working clone the transparent and interception flags
2366 * from the port settings to the request.
2368 if (http
->clientConnection
!= NULL
) {
2369 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2370 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2371 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
2372 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
2373 if (Config
.accessList
.spoof_client_ip
) {
2374 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2375 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2378 request
->flags
.spoofClientIp
= true;
2380 request
->flags
.spoofClientIp
= false;
2383 if (internalCheck(request
->url
.path())) {
2384 if (internalHostnameIs(request
->url
.host()) && request
->url
.port() == getMyPort()) {
2385 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true));
2386 http
->flags
.internal
= true;
2387 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->url
.path())) {
2388 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (global_internal_static on)");
2389 request
->url
.setScheme(AnyP::PROTO_HTTP
);
2390 request
->url
.host(internalHostname());
2391 request
->url
.port(getMyPort());
2392 http
->flags
.internal
= true;
2394 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (not this proxy)");
2397 request
->flags
.internal
= http
->flags
.internal
;
2398 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2399 if (!conn
->connectionless()) {
2400 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2401 #if FOLLOW_X_FORWARDED_FOR
2402 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2403 // not a details about teh TCP connection itself
2404 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2405 #endif /* FOLLOW_X_FORWARDED_FOR */
2406 request
->my_addr
= conn
->clientConnection
->local
;
2407 request
->myportname
= conn
->port
->name
;
2411 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
2412 // for now Squid only supports HTTP requests
2413 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
2414 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
2415 request
->http_ver
.major
= http_ver
.major
;
2416 request
->http_ver
.minor
= http_ver
.minor
;
2419 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2420 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2421 request
->clientConnectionManager
= conn
;
2423 if (request
->header
.chunked()) {
2425 } else if (request
->header
.has(Http::HdrType::TRANSFER_ENCODING
)) {
2426 const String te
= request
->header
.getList(Http::HdrType::TRANSFER_ENCODING
);
2427 // HTTP/1.1 requires chunking to be the last encoding if there is one
2428 unsupportedTe
= te
.size() && te
!= "identity";
2429 } // else implied identity coding
2431 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
2432 (request
->header
.getInt64(Http::HdrType::MAX_FORWARDS
) == 0);
2433 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2434 clientStreamNode
*node
= context
->getClientReplyContext();
2435 conn
->quitAfterError(request
.getRaw());
2436 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2437 assert (repContext
);
2438 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2439 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2440 assert(context
->http
->out
.offset
== 0);
2441 context
->pullData();
2442 clientProcessRequestFinished(conn
, request
);
2446 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2447 clientStreamNode
*node
= context
->getClientReplyContext();
2448 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2449 assert (repContext
);
2450 conn
->quitAfterError(request
.getRaw());
2451 repContext
->setReplyToError(ERR_INVALID_REQ
,
2452 Http::scLengthRequired
, request
->method
, NULL
,
2453 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2454 assert(context
->http
->out
.offset
== 0);
2455 context
->pullData();
2456 clientProcessRequestFinished(conn
, request
);
2460 clientSetKeepaliveFlag(http
);
2461 // Let tunneling code be fully responsible for CONNECT requests
2462 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2463 context
->mayUseConnection(true);
2464 conn
->flags
.readMore
= false;
2468 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
2469 clientProcessRequestFinished(conn
, request
);
2474 /* Do we expect a request-body? */
2475 expectBody
= chunked
|| request
->content_length
> 0;
2476 if (!context
->mayUseConnection() && expectBody
) {
2477 request
->body_pipe
= conn
->expectRequestBody(
2478 chunked
? -1 : request
->content_length
);
2480 /* Is it too large? */
2481 if (!chunked
&& // if chunked, we will check as we accumulate
2482 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2483 clientStreamNode
*node
= context
->getClientReplyContext();
2484 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2485 assert (repContext
);
2486 conn
->quitAfterError(request
.getRaw());
2487 repContext
->setReplyToError(ERR_TOO_BIG
,
2488 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
2489 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2490 assert(context
->http
->out
.offset
== 0);
2491 context
->pullData();
2492 clientProcessRequestFinished(conn
, request
);
2497 // We may stop producing, comm_close, and/or call setReplyToError()
2498 // below, so quit on errors to avoid http->doCallouts()
2499 if (!conn
->handleRequestBodyData()) {
2500 clientProcessRequestFinished(conn
, request
);
2504 if (!request
->body_pipe
->productionEnded()) {
2505 debugs(33, 5, "need more request body");
2506 context
->mayUseConnection(true);
2507 assert(conn
->flags
.readMore
);
2512 http
->calloutContext
= new ClientRequestContext(http
);
2516 clientProcessRequestFinished(conn
, request
);
2520 ConnStateData::pipelinePrefetchMax() const
2522 // TODO: Support pipelined requests through pinned connections.
2525 return Config
.pipeline_max_prefetch
;
2529 * Limit the number of concurrent requests.
2530 * \return true when there are available position(s) in the pipeline queue for another request.
2531 * \return false when the pipeline queue is full or disabled.
2534 ConnStateData::concurrentRequestQueueFilled() const
2536 const int existingRequestCount
= pipeline
.count();
2538 // default to the configured pipeline size.
2539 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2541 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
2543 const int internalRequest
= 0;
2545 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
2547 // when queue filled already we cant add more.
2548 if (existingRequestCount
>= concurrentRequestLimit
) {
2549 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2550 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2558 * Perform proxy_protocol_access ACL tests on the client which
2559 * connected to PROXY protocol port to see if we trust the
2560 * sender enough to accept their PROXY header claim.
2563 ConnStateData::proxyProtocolValidateClient()
2565 if (!Config
.accessList
.proxyProtocol
)
2566 return proxyProtocolError("PROXY client not permitted by default ACL");
2568 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
2569 ch
.src_addr
= clientConnection
->remote
;
2570 ch
.my_addr
= clientConnection
->local
;
2573 if (ch
.fastCheck() != ACCESS_ALLOWED
)
2574 return proxyProtocolError("PROXY client not permitted by ACLs");
2580 * Perform cleanup on PROXY protocol errors.
2581 * If header parsing hits a fatal error terminate the connection,
2582 * otherwise wait for more data.
2585 ConnStateData::proxyProtocolError(const char *msg
)
2588 // This is important to know, but maybe not so much that flooding the log is okay.
2589 #if QUIET_PROXY_PROTOCOL
2590 // display the first of every 32 occurances at level 1, the others at level 2.
2591 static uint8_t hide
= 0;
2592 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
2594 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
2601 /// magic octet prefix for PROXY protocol version 1
2602 static const SBuf
Proxy1p0magic("PROXY ", 6);
2604 /// magic octet prefix for PROXY protocol version 2
2605 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
2608 * Test the connection read buffer for PROXY protocol header.
2609 * Version 1 and 2 header currently supported.
2612 ConnStateData::parseProxyProtocolHeader()
2614 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
2616 // detect and parse PROXY/2.0 protocol header
2617 if (inBuf
.startsWith(Proxy2p0magic
))
2618 return parseProxy2p0();
2620 // detect and parse PROXY/1.0 protocol header
2621 if (inBuf
.startsWith(Proxy1p0magic
))
2622 return parseProxy1p0();
2624 // detect and terminate other protocols
2625 if (inBuf
.length() >= Proxy2p0magic
.length()) {
2626 // PROXY/1.0 magic is shorter, so we know that
2627 // the input does not start with any PROXY magic
2628 return proxyProtocolError("PROXY protocol error: invalid header");
2631 // TODO: detect short non-magic prefixes earlier to avoid
2632 // waiting for more data which may never come
2634 // not enough bytes to parse yet.
2638 /// parse the PROXY/1.0 protocol header from the connection read buffer
2640 ConnStateData::parseProxy1p0()
2642 ::Parser::Tokenizer
tok(inBuf
);
2643 tok
.skip(Proxy1p0magic
);
2645 // skip to first LF (assumes it is part of CRLF)
2646 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
2648 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
2649 if (tok
.skip('\n')) {
2650 // found valid header
2651 inBuf
= tok
.remaining();
2652 needProxyProtocolHeader_
= false;
2653 // reset the tokenizer to work on found line only.
2656 return false; // no LF yet
2658 } else // protocol error only if there are more than 107 bytes prefix header
2659 return proxyProtocolError(inBuf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
2661 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
2662 if (tok
.skip(tcpName
)) {
2664 // skip TCP/IP version number
2665 static const CharacterSet
tcpVersions("TCP-version","46");
2666 if (!tok
.skipOne(tcpVersions
))
2667 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
2669 // skip SP after protocol version
2671 return proxyProtocolError("PROXY/1.0 error: missing SP");
2674 int64_t porta
, portb
;
2675 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
2677 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
2678 // leave the LF until later.
2679 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
2680 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
2681 tok
.int64(porta
) && tok
.skip(' ') &&
2685 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
2687 // parse IP and port strings
2688 Ip::Address originalClient
, originalDest
;
2690 if (!originalClient
.GetHostByName(ipa
.c_str()))
2691 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
2693 if (!originalDest
.GetHostByName(ipb
.c_str()))
2694 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
2696 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
2697 originalClient
.port(static_cast<uint16_t>(porta
));
2699 return proxyProtocolError("PROXY/1.0 error: invalid src port");
2701 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
2702 originalDest
.port(static_cast<uint16_t>(portb
));
2704 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
2706 // we have original client and destination details now
2707 // replace the client connection values
2708 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
2709 clientConnection
->local
= originalDest
;
2710 clientConnection
->remote
= originalClient
;
2711 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2712 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2713 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2715 // repeat fetch ensuring the new client FQDN can be logged
2716 if (Config
.onoff
.log_fqdn
)
2717 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2721 } else if (tok
.skip(unknown
)) {
2722 // found valid but unusable header
2726 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2731 /// parse the PROXY/2.0 protocol header from the connection read buffer
2733 ConnStateData::parseProxy2p0()
2735 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2736 if (inBuf
.length() < prefixLen
+ 4)
2737 return false; // need more bytes
2739 if ((inBuf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2740 return proxyProtocolError("PROXY/2.0 error: invalid version");
2742 const char command
= (inBuf
[prefixLen
] & 0x0F);
2743 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2744 return proxyProtocolError("PROXY/2.0 error: invalid command");
2746 const char family
= (inBuf
[prefixLen
+1] & 0xF0) >>4;
2747 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2748 return proxyProtocolError("PROXY/2.0 error: invalid family");
2750 const char proto
= (inBuf
[prefixLen
+1] & 0x0F);
2751 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2752 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2754 const char *clen
= inBuf
.rawContent() + prefixLen
+ 2;
2756 memcpy(&len
, clen
, sizeof(len
));
2759 if (inBuf
.length() < prefixLen
+ 4 + len
)
2760 return false; // need more bytes
2762 inBuf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2763 const SBuf extra
= inBuf
.consume(len
);
2764 needProxyProtocolHeader_
= false; // found successfully
2766 // LOCAL connections do nothing with the extras
2767 if (command
== 0x00/* LOCAL*/)
2771 struct { /* for TCP/UDP over IPv4, len = 12 */
2772 struct in_addr src_addr
;
2773 struct in_addr dst_addr
;
2777 struct { /* for TCP/UDP over IPv6, len = 36 */
2778 struct in6_addr src_addr
;
2779 struct in6_addr dst_addr
;
2784 struct { /* for AF_UNIX sockets, len = 216 */
2785 uint8_t src_addr
[108];
2786 uint8_t dst_addr
[108];
2792 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2794 // replace the client connection values
2795 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2798 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2799 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2800 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2801 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2802 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2803 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2806 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2807 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2808 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2809 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2810 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2811 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2813 default: // do nothing
2816 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2818 // repeat fetch ensuring the new client FQDN can be logged
2819 if (Config
.onoff
.log_fqdn
)
2820 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2826 ConnStateData::receivedFirstByte()
2828 if (receivedFirstByte_
)
2831 receivedFirstByte_
= true;
2832 // Set timeout to Config.Timeout.request
2833 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
2834 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
2835 TimeoutDialer
, this, ConnStateData::requestTimeout
);
2836 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
2840 * Attempt to parse one or more requests from the input buffer.
2841 * Returns true after completing parsing of at least one request [header]. That
2842 * includes cases where parsing ended with an error (e.g., a huge request).
2845 ConnStateData::clientParseRequests()
2847 bool parsed_req
= false;
2849 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2851 // Loop while we have read bytes that are not needed for producing the body
2852 // On errors, bodyPipe may become nil, but readMore will be cleared
2853 while (!inBuf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2855 /* Don't try to parse if the buffer is empty */
2856 if (inBuf
.isEmpty())
2859 /* Limit the number of concurrent requests */
2860 if (concurrentRequestQueueFilled())
2863 // try to parse the PROXY protocol header magic bytes
2864 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
2867 if (ClientSocketContext
*context
= parseOneRequest()) {
2868 debugs(33, 5, clientConnection
<< ": done parsing a request");
2870 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2871 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2872 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2874 context
->registerWithConn();
2876 processParsedRequest(context
);
2878 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2880 if (context
->mayUseConnection()) {
2881 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2885 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
2886 inBuf
.length() << " < " << Config
.maxRequestHeaderSize
);
2887 Must(inBuf
.length() < Config
.maxRequestHeaderSize
);
2892 /* XXX where to 'finish' the parsing pass? */
2897 ConnStateData::afterClientRead()
2899 /* Process next request */
2900 if (pipeline
.empty())
2901 fd_note(clientConnection
->fd
, "Reading next request");
2903 if (!clientParseRequests()) {
2907 * If the client here is half closed and we failed
2908 * to parse a request, close the connection.
2909 * The above check with connFinishedWithConn() only
2910 * succeeds _if_ the buffer is empty which it won't
2911 * be if we have an incomplete request.
2912 * XXX: This duplicates ConnStateData::kick
2914 if (pipeline
.empty() && commIsHalfClosed(clientConnection
->fd
)) {
2915 debugs(33, 5, clientConnection
<< ": half-closed connection, no completed request parsed, connection closing.");
2916 clientConnection
->close();
2924 clientAfterReadingRequests();
2928 * called when new request data has been read from the socket
2930 * \retval false called comm_close or setReplyToError (the caller should bail)
2931 * \retval true we did not call comm_close or setReplyToError
2934 ConnStateData::handleReadData()
2936 // if we are reading a body, stuff data into the body pipe
2937 if (bodyPipe
!= NULL
)
2938 return handleRequestBodyData();
2943 * called when new request body data has been buffered in inBuf
2944 * may close the connection if we were closing and piped everything out
2946 * \retval false called comm_close or setReplyToError (the caller should bail)
2947 * \retval true we did not call comm_close or setReplyToError
2950 ConnStateData::handleRequestBodyData()
2952 assert(bodyPipe
!= NULL
);
2954 if (bodyParser
) { // chunked encoding
2955 if (const err_type error
= handleChunkedRequestBody()) {
2956 abortChunkedRequestBody(error
);
2959 } else { // identity encoding
2960 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
2961 const size_t putSize
= bodyPipe
->putMoreData(inBuf
.c_str(), inBuf
.length());
2963 consumeInput(putSize
);
2965 if (!bodyPipe
->mayNeedMoreData()) {
2966 // BodyPipe will clear us automagically when we produced everything
2972 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
2974 if (const char *reason
= stoppedSending()) {
2975 /* we've finished reading like good clients,
2976 * now do the close that initiateClose initiated.
2978 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
2979 clientConnection
->close();
2987 /// parses available chunked encoded body bytes, checks size, returns errors
2989 ConnStateData::handleChunkedRequestBody()
2991 debugs(33, 7, "chunked from " << clientConnection
<< ": " << inBuf
.length());
2993 try { // the parser will throw on errors
2995 if (inBuf
.isEmpty()) // nothing to do
2998 BodyPipeCheckout
bpc(*bodyPipe
);
2999 bodyParser
->setPayloadBuffer(&bpc
.buf
);
3000 const bool parsed
= bodyParser
->parse(inBuf
);
3001 inBuf
= bodyParser
->remaining(); // sync buffers
3004 // dechunk then check: the size limit applies to _dechunked_ content
3005 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3009 finishDechunkingRequest(true);
3011 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3014 // if chunk parser needs data, then the body pipe must need it too
3015 Must(!bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3017 // if parser needs more space and we can consume nothing, we will stall
3018 Must(!bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3019 } catch (...) { // TODO: be more specific
3020 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3021 return ERR_INVALID_REQ
;
3024 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3028 /// quit on errors related to chunked request body handling
3030 ConnStateData::abortChunkedRequestBody(const err_type error
)
3032 finishDechunkingRequest(false);
3034 // XXX: The code below works if we fail during initial request parsing,
3035 // but if we fail when the server connection is used already, the server may send
3036 // us its response too, causing various assertions. How to prevent that?
3037 #if WE_KNOW_HOW_TO_SEND_ERRORS
3038 ClientSocketContext::Pointer context
= pipeline
.front();
3039 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3040 clientStreamNode
*node
= context
->getClientReplyContext();
3041 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3043 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3044 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
3045 repContext
->setReplyToError(error
, scode
,
3046 repContext
->http
->request
->method
,
3047 repContext
->http
->uri
,
3049 repContext
->http
->request
,
3051 context
->pullData();
3053 // close or otherwise we may get stuck as nobody will notice the error?
3054 comm_reset_close(clientConnection
);
3057 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3058 comm_reset_close(clientConnection
);
3060 flags
.readMore
= false;
3064 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3066 // request reader may get stuck waiting for space if nobody consumes body
3067 if (bodyPipe
!= NULL
)
3068 bodyPipe
->enableAutoConsumption();
3073 /** general lifetime handler for HTTP requests */
3075 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3077 if (!Comm::IsConnOpen(io
.conn
))
3080 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
3082 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
3083 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
3084 receivedFirstByte();
3087 } else if (fd_table
[io
.conn
->fd
].ssl
== NULL
)
3090 const HttpRequestMethod method
;
3091 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
3092 // Tunnel established. Set receivedFirstByte to avoid loop.
3093 receivedFirstByte();
3099 * Just close the connection to not confuse browsers
3100 * using persistent connections. Some browsers open
3101 * a connection and then do not use it until much
3102 * later (presumeably because the request triggering
3103 * the open has already been completed on another
3106 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3111 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3113 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3114 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3115 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3116 http
->logType
.err
.timedout
= true;
3117 if (Comm::IsConnOpen(io
.conn
))
3121 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3122 AsyncJob("ConnStateData"), // kids overwrite
3124 bodyParser(nullptr),
3126 sslBumpMode(Ssl::bumpEnd
),
3128 needProxyProtocolHeader_(false),
3130 switchedToHttps_(false),
3131 sslServerBump(NULL
),
3132 signAlgorithm(Ssl::algSignTrusted
),
3134 stoppedSending_(NULL
),
3135 stoppedReceiving_(NULL
)
3137 flags
.readMore
= true; // kids may overwrite
3138 flags
.swanSang
= false;
3140 pinning
.host
= NULL
;
3142 pinning
.pinned
= false;
3143 pinning
.auth
= false;
3144 pinning
.zeroReply
= false;
3145 pinning
.peer
= NULL
;
3147 // store the details required for creating more MasterXaction objects as new requests come in
3148 if (xact
->tcpClient
!= NULL
)
3149 log_addr
= xact
->tcpClient
->remote
;
3151 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3153 // register to receive notice of Squid signal events
3154 // which may affect long persisting client connections
3155 RegisterRunner(this);
3159 ConnStateData::start()
3161 BodyProducer::start();
3162 HttpControlMsgSink::start();
3164 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3165 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3166 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3167 int i
= IP_PMTUDISC_DONT
;
3168 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3169 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3171 static bool reported
= false;
3174 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3180 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3181 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3182 comm_add_close_handler(clientConnection
->fd
, call
);
3184 if (Config
.onoff
.log_fqdn
)
3185 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3188 if (Ident::TheConfig
.identLookup
) {
3189 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3190 identChecklist
.src_addr
= clientConnection
->remote
;
3191 identChecklist
.my_addr
= clientConnection
->local
;
3192 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3193 Ident::Start(clientConnection
, clientIdentDone
, this);
3197 clientdbEstablished(clientConnection
->remote
, 1);
3199 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
3200 if (needProxyProtocolHeader_
) {
3201 if (!proxyProtocolValidateClient()) // will close the connection on failure
3206 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
3208 if (Config
.onoff
.client_db
) {
3209 /* it was said several times that client write limiter does not work if client_db is disabled */
3211 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3212 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3214 // TODO: we check early to limit error response bandwith but we
3215 // should recheck when we can honor delay_pool_uses_indirect
3216 // TODO: we should also pass the port details for myportname here.
3217 ch
.src_addr
= clientConnection
->remote
;
3218 ch
.my_addr
= clientConnection
->local
;
3220 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3222 /* pools require explicit 'allow' to assign a client into them */
3223 if (pools
[pool
].access
) {
3224 ch
.changeAcl(pools
[pool
].access
);
3225 allow_t answer
= ch
.fastCheck();
3226 if (answer
== ACCESS_ALLOWED
) {
3228 /* request client information from db after we did all checks
3229 this will save hash lookup if client failed checks */
3230 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
3233 /* put client info in FDE */
3234 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
3236 /* setup write limiter for this request */
3237 const double burst
= floor(0.5 +
3238 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3239 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3242 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3249 // kids must extend to actually start doing something (e.g., reading)
3252 /** Handle a new connection on an HTTP socket. */
3254 httpAccept(const CommAcceptCbParams
¶ms
)
3256 MasterXaction::Pointer xact
= params
.xaction
;
3257 AnyP::PortCfgPointer s
= xact
->squidPort
;
3259 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3261 if (params
.flag
!= Comm::OK
) {
3262 // Its possible the call was still queued when the client disconnected
3263 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3267 debugs(33, 4, params
.conn
<< ": accepted");
3268 fd_note(params
.conn
->fd
, "client http connect");
3270 if (s
->tcp_keepalive
.enabled
)
3271 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3273 ++incoming_sockets_accepted
;
3275 // Socket is ready, setup the connection manager to start using it
3276 ConnStateData
*connState
= Http::NewServer(xact
);
3277 AsyncJob::Start(connState
); // usually async-calls readSomeData()
3282 /** Create SSL connection structure and update fd_table */
3283 static Security::SessionPointer
3284 httpsCreate(const Comm::ConnectionPointer
&conn
, Security::ContextPtr sslContext
)
3286 if (auto ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
3287 debugs(33, 5, "will negotate SSL on " << conn
);
3297 * \retval 1 on success
3298 * \retval 0 when needs more data
3299 * \retval -1 on error
3302 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
3304 int fd
= conn
->clientConnection
->fd
;
3305 auto ssl
= fd_table
[fd
].ssl
;
3309 if ((ret
= SSL_accept(ssl
)) <= 0) {
3310 const int xerrno
= errno
;
3311 const int ssl_error
= SSL_get_error(ssl
, ret
);
3313 switch (ssl_error
) {
3315 case SSL_ERROR_WANT_READ
:
3316 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, conn
, 0);
3319 case SSL_ERROR_WANT_WRITE
:
3320 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, conn
, 0);
3323 case SSL_ERROR_SYSCALL
:
3325 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
3327 debugs(83, (xerrno
== ECONNRESET
) ? 1 : 2, "Error negotiating SSL connection on FD " << fd
<< ": " <<
3328 (xerrno
== 0 ? ERR_error_string(ssl_error
, NULL
) : xstrerr(xerrno
)));
3332 case SSL_ERROR_ZERO_RETURN
:
3333 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3337 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
3338 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3339 " (" << ssl_error
<< "/" << ret
<< ")");
3348 /** negotiate an SSL connection */
3350 clientNegotiateSSL(int fd
, void *data
)
3352 ConnStateData
*conn
= (ConnStateData
*)data
;
3354 auto ssl
= fd_table
[fd
].ssl
;
3357 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
3358 if (ret
< 0) // An error
3359 conn
->clientConnection
->close();
3363 if (SSL_session_reused(ssl
)) {
3364 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3365 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3367 if (do_debug(83, 4)) {
3368 /* Write out the SSL session details.. actually the call below, but
3369 * OpenSSL headers do strange typecasts confusing GCC.. */
3370 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3371 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3372 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
);
3374 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3376 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3377 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3378 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3379 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3380 * Because there are two possible usable cast, if you get an error here, try the other
3381 * commented line. */
3383 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3384 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3388 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3391 /* Note: This does not automatically fflush the log file.. */
3394 debugs(83, 2, "clientNegotiateSSL: New session " <<
3395 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3396 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3400 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3401 SSL_get_cipher(ssl
));
3403 client_cert
= SSL_get_peer_certificate(ssl
);
3405 if (client_cert
!= NULL
) {
3406 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3407 " client certificate: subject: " <<
3408 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3410 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3411 " client certificate: issuer: " <<
3412 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3414 X509_free(client_cert
);
3416 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3417 " has no certificate.");
3420 #if defined(TLSEXT_NAMETYPE_host_name)
3421 if (!conn
->serverBump()) {
3422 // when in bumpClientFirst mode, get the server name from SNI
3423 if (const char *server
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))
3424 conn
->resetSslCommonName(server
);
3428 conn
->readSomeData();
3432 * If Security::ContextPtr is given, starts reading the TLS handshake.
3433 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPtr.
3436 httpsEstablish(ConnStateData
*connState
, Security::ContextPtr sslContext
)
3438 Security::SessionPointer ssl
= nullptr;
3440 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3442 if (!sslContext
|| !(ssl
= httpsCreate(details
, sslContext
)))
3445 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3446 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3447 connState
, ConnStateData::requestTimeout
);
3448 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3450 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3454 * A callback function to use with the ACLFilledChecklist callback.
3455 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3456 * else reverts the connection to tunnel mode.
3459 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3461 ConnStateData
*connState
= (ConnStateData
*) data
;
3463 // if the connection is closed or closing, just return.
3464 if (!connState
->isOpen())
3467 // Require both a match and a positive bump mode to work around exceptional
3468 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3469 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
3470 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
3471 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3473 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3474 connState
->sslBumpMode
= Ssl::bumpNone
;
3476 connState
->fakeAConnectRequest("ssl-bump", connState
->inBuf
);
3479 /** handle a new HTTPS connection */
3481 httpsAccept(const CommAcceptCbParams
¶ms
)
3483 MasterXaction::Pointer xact
= params
.xaction
;
3484 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3486 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3488 if (params
.flag
!= Comm::OK
) {
3489 // Its possible the call was still queued when the client disconnected
3490 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3494 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3495 fd_note(params
.conn
->fd
, "client https connect");
3497 if (s
->tcp_keepalive
.enabled
) {
3498 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3501 ++incoming_sockets_accepted
;
3503 // Socket is ready, setup the connection manager to start using it
3504 ConnStateData
*connState
= Https::NewServer(xact
);
3505 AsyncJob::Start(connState
); // usually async-calls postHttpsAccept()
3509 ConnStateData::postHttpsAccept()
3511 if (port
->flags
.tunnelSslBumping
) {
3512 debugs(33, 5, "accept transparent connection: " << clientConnection
);
3514 if (!Config
.accessList
.ssl_bump
) {
3515 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
3519 // Create a fake HTTP request for ssl_bump ACL check,
3520 // using tproxy/intercept provided destination IP and port.
3521 HttpRequest
*request
= new HttpRequest();
3522 static char ip
[MAX_IPSTRLEN
];
3523 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3524 request
->url
.host(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
3525 request
->url
.port(clientConnection
->local
.port());
3526 request
->myportname
= port
->name
;
3528 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3529 acl_checklist
->src_addr
= clientConnection
->remote
;
3530 acl_checklist
->my_addr
= port
->s
;
3531 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
3534 httpsEstablish(this, port
->secure
.staticContext
.get());
3539 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
3541 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3542 state_data
->sslCrtdHandleReply(reply
);
3546 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
3549 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply
);
3553 if (reply
.result
== Helper::BrokenHelper
) {
3554 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3555 } else if (!reply
.other().hasContent()) {
3556 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3558 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3559 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3560 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3562 if (reply
.result
!= Helper::Okay
) {
3563 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3565 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3566 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3567 doPeekAndSpliceStep();
3568 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3569 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
3571 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3573 auto ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3574 getSslContextDone(ctx
, true);
3580 getSslContextDone(NULL
);
3583 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3585 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
3587 // fake certificate adaptation requires bump-server-first mode
3588 if (!sslServerBump
) {
3589 assert(port
->signingCert
.get());
3590 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3591 if (port
->signPkey
.get())
3592 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3593 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3597 // In case of an error while connecting to the secure server, use a fake
3598 // trusted certificate, with no mimicked fields and no adaptation
3599 // algorithms. There is nothing we can mimic so we want to minimize the
3600 // number of warnings the user will have to see to get to the error page.
3601 assert(sslServerBump
->entry
);
3602 if (sslServerBump
->entry
->isEmpty()) {
3603 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3604 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3606 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3607 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3608 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3610 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3611 // If the algorithm already set, then ignore it.
3612 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3613 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3614 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3617 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3618 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3619 const char *param
= ca
->param
;
3621 // For parameterless CN adaptation, use hostname from the
3623 if (ca
->alg
== Ssl::algSetCommonName
) {
3625 param
= sslConnectHostOrIp
.termedBuf();
3626 certProperties
.commonName
= param
;
3627 certProperties
.setCommonName
= true;
3628 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3629 certProperties
.setValidAfter
= true;
3630 else if (ca
->alg
== Ssl::algSetValidBefore
)
3631 certProperties
.setValidBefore
= true;
3633 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3634 alg
<< " param: " << (param
? param
: "-"));
3638 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3639 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3640 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3641 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3645 } else {// if (!sslServerBump->entry->isEmpty())
3646 // Use trusted certificate for a Squid-generated error
3647 // or the user would have to add a security exception
3648 // just to see the error page. We will close the connection
3649 // so that the trust is not extended to non-Squid content.
3650 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3653 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3655 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3656 assert(port
->untrustedSigningCert
.get());
3657 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3658 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3660 assert(port
->signingCert
.get());
3661 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3663 if (port
->signPkey
.get())
3664 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3666 signAlgorithm
= certProperties
.signAlgorithm
;
3668 certProperties
.signHash
= Ssl::DefaultSignHash
;
3672 ConnStateData::getSslContextStart()
3674 // XXX starting SSL with a pipeline of requests still waiting for non-SSL replies?
3675 assert(pipeline
.count() < 2); // the CONNECT is okay for now. Anything else is a bug.
3676 pipeline
.terminateAll(0);
3677 /* careful: terminateAll(0) above frees request, host, etc. */
3679 if (port
->generateHostCertificates
) {
3680 Ssl::CertificateProperties certProperties
;
3681 buildSslCertGenerationParams(certProperties
);
3682 sslBumpCertKey
= certProperties
.dbKey().c_str();
3683 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3685 // Disable caching for bumpPeekAndSplice mode
3686 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
3687 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3688 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3689 Security::ContextPtr dynCtx
= nullptr;
3690 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3691 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3692 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3693 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3694 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3695 getSslContextDone(dynCtx
);
3698 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3700 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3703 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3709 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3710 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3711 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3712 request_message
.composeRequest(certProperties
);
3713 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3714 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3716 } catch (const std::exception
&e
) {
3717 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3718 "request for " << certProperties
.commonName
<<
3719 " certificate: " << e
.what() << "; will now block to " <<
3720 "generate that certificate.");
3721 // fall through to do blocking in-process generation.
3723 #endif // USE_SSL_CRTD
3725 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3726 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3727 doPeekAndSpliceStep();
3728 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3729 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3730 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3732 auto dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3733 getSslContextDone(dynCtx
, true);
3737 getSslContextDone(NULL
);
3741 ConnStateData::getSslContextDone(Security::ContextPtr sslContext
, bool isNew
)
3743 // Try to add generated ssl context to storage.
3744 if (port
->generateHostCertificates
&& isNew
) {
3746 if (signAlgorithm
== Ssl::algSignTrusted
) {
3747 // Add signing certificate to the certificates chain
3748 X509
*cert
= port
->signingCert
.get();
3749 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3750 // increase the certificate lock
3751 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3753 const int ssl_error
= ERR_get_error();
3754 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3756 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3758 //else it is self-signed or untrusted do not attrach any certificate
3760 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3761 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3763 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3764 // If it is not in storage delete after using. Else storage deleted it.
3765 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3768 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3772 // If generated ssl context = NULL, try to use static ssl context.
3774 if (!port
->secure
.staticContext
) {
3775 debugs(83, DBG_IMPORTANT
, "Closing " << clientConnection
->remote
<< " as lacking TLS context");
3776 clientConnection
->close();
3779 debugs(33, 5, "Using static TLS context.");
3780 sslContext
= port
->secure
.staticContext
.get();
3784 if (!httpsCreate(clientConnection
, sslContext
))
3787 // bumped intercepted conns should already have Config.Timeout.request set
3788 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3789 // to make sure the connection does not get stuck on non-SSL clients.
3790 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3791 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3792 this, ConnStateData::requestTimeout
);
3793 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3795 // Disable the client read handler until CachePeer selection is complete
3796 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3797 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3798 switchedToHttps_
= true;
3802 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3804 assert(!switchedToHttps_
);
3806 sslConnectHostOrIp
= request
->url
.host();
3807 resetSslCommonName(request
->url
.host());
3809 // We are going to read new request
3810 flags
.readMore
= true;
3811 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3813 // keep version major.minor details the same.
3814 // but we are now performing the HTTPS handshake traffic
3815 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
3817 // If sslServerBump is set, then we have decided to deny CONNECT
3818 // and now want to switch to SSL to send the error to the client
3819 // without even peeking at the origin server certificate.
3820 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3821 request
->flags
.sslPeek
= true;
3822 sslServerBump
= new Ssl::ServerBump(request
);
3824 // will call httpsPeeked() with certificate and connection, eventually
3825 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3827 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
3828 request
->flags
.sslPeek
= true;
3829 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
3830 startPeekAndSplice();
3834 // otherwise, use sslConnectHostOrIp
3835 getSslContextStart();
3839 ConnStateData::spliceOnError(const err_type err
)
3841 if (Config
.accessList
.on_unsupported_protocol
) {
3842 assert(serverBump());
3843 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
3844 checklist
.requestErrorType
= err
;
3845 checklist
.conn(this);
3846 allow_t answer
= checklist
.fastCheck();
3847 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
3855 /** negotiate an SSL connection */
3857 clientPeekAndSpliceSSL(int fd
, void *data
)
3859 ConnStateData
*conn
= (ConnStateData
*)data
;
3860 auto ssl
= fd_table
[fd
].ssl
;
3862 debugs(83, 5, "Start peek and splice on FD " << fd
);
3865 if ((ret
= Squid_SSL_accept(conn
, clientPeekAndSpliceSSL
)) < 0)
3866 debugs(83, 2, "SSL_accept failed.");
3868 BIO
*b
= SSL_get_rbio(ssl
);
3870 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3872 const err_type err
= bio
->noSslClient() ? ERR_PROTOCOL_UNKNOWN
: ERR_SECURE_ACCEPT_FAIL
;
3873 if (!conn
->spliceOnError(err
))
3874 conn
->clientConnection
->close();
3878 if (bio
->rBufData().contentSize() > 0)
3879 conn
->receivedFirstByte();
3881 if (bio
->gotHello()) {
3882 if (conn
->serverBump()) {
3883 Ssl::Bio::sslFeatures
const &features
= bio
->getFeatures();
3884 if (!features
.serverName
.isEmpty()) {
3885 conn
->serverBump()->clientSni
= features
.serverName
;
3886 conn
->resetSslCommonName(features
.serverName
.c_str());
3890 debugs(83, 5, "I got hello. Start forwarding the request!!! ");
3891 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3892 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
3893 conn
->startPeekAndSpliceDone();
3898 void ConnStateData::startPeekAndSplice()
3900 // will call httpsPeeked() with certificate and connection, eventually
3901 auto unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
3902 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
3904 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
3907 // commSetConnTimeout() was called for this request before we switched.
3908 // Fix timeout to request_start_timeout
3909 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3910 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3911 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3912 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
3913 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
3914 // a bumbed "connect" request on non transparent port.
3915 receivedFirstByte_
= false;
3917 // Disable the client read handler until CachePeer selection is complete
3918 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3919 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientPeekAndSpliceSSL
, this, 0);
3920 switchedToHttps_
= true;
3922 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3923 BIO
*b
= SSL_get_rbio(ssl
);
3924 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3928 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
3930 ConnStateData
*connState
= (ConnStateData
*) data
;
3932 // if the connection is closed or closing, just return.
3933 if (!connState
->isOpen())
3936 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
3937 assert(connState
->serverBump());
3938 Ssl::BumpMode bumpAction
;
3939 if (answer
== ACCESS_ALLOWED
) {
3940 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
3942 bumpAction
= Ssl::bumpSplice
;
3944 connState
->serverBump()->act
.step2
= bumpAction
;
3945 connState
->sslBumpMode
= bumpAction
;
3947 if (bumpAction
== Ssl::bumpTerminate
) {
3948 connState
->clientConnection
->close();
3949 } else if (bumpAction
!= Ssl::bumpSplice
) {
3950 connState
->startPeekAndSpliceDone();
3952 connState
->splice();
3956 ConnStateData::splice()
3958 //Normally we can splice here, because we just got client hello message
3959 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3960 BIO
*b
= SSL_get_rbio(ssl
);
3961 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
3962 MemBuf
const &rbuf
= bio
->rBufData();
3963 debugs(83,5, "Bio for " << clientConnection
<< " read " << rbuf
.contentSize() << " helo bytes");
3965 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
3966 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
3968 if (transparent()) {
3969 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
3970 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
3971 transferProtocol
= Http::ProtocolVersion();
3972 // XXX: copy from MemBuf reallocates, not a regression since old code did too
3974 temp
.append(rbuf
.content(), rbuf
.contentSize());
3975 fakeAConnectRequest("intercepted TLS spliced", temp
);
3977 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
3979 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
3980 transferProtocol
= Http::ProtocolVersion();
3981 // inBuf still has the "CONNECT ..." request data, reset it to SSL hello message
3982 inBuf
.append(rbuf
.content(), rbuf
.contentSize());
3983 ClientSocketContext::Pointer context
= pipeline
.front();
3984 ClientHttpRequest
*http
= context
->http
;
3990 ConnStateData::startPeekAndSpliceDone()
3992 // This is the Step2 of the SSL bumping
3993 assert(sslServerBump
);
3994 if (sslServerBump
->step
== Ssl::bumpStep1
) {
3995 sslServerBump
->step
= Ssl::bumpStep2
;
3996 // Run a accessList check to check if want to splice or continue bumping
3998 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
3999 //acl_checklist->src_addr = params.conn->remote;
4000 //acl_checklist->my_addr = s->s;
4001 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpNone
));
4002 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpClientFirst
));
4003 acl_checklist
->banAction(allow_t(ACCESS_ALLOWED
, Ssl::bumpServerFirst
));
4004 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
4008 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4012 ConnStateData::doPeekAndSpliceStep()
4014 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
4015 BIO
*b
= SSL_get_rbio(ssl
);
4017 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4019 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
4022 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
4023 switchedToHttps_
= true;
4027 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4029 Must(sslServerBump
!= NULL
);
4031 if (Comm::IsConnOpen(serverConnection
)) {
4032 pinConnection(serverConnection
, NULL
, NULL
, false);
4034 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4036 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4038 // copy error detail from bump-server-first request to CONNECT request
4039 if (!pipeline
.empty() && pipeline
.front()->http
!= nullptr && pipeline
.front()->http
->request
)
4040 pipeline
.front()->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4043 getSslContextStart();
4046 #endif /* USE_OPENSSL */
4049 ConnStateData::fakeAConnectRequest(const char *reason
, const SBuf
&payload
)
4051 // fake a CONNECT request to force connState to tunnel
4054 if (serverBump() && !serverBump()->clientSni
.isEmpty()) {
4055 connectHost
.assign(serverBump()->clientSni
);
4056 if (clientConnection
->local
.port() > 0)
4057 connectHost
.appendf(":%d",clientConnection
->local
.port());
4061 static char ip
[MAX_IPSTRLEN
];
4062 connectHost
.assign(clientConnection
->local
.toUrl(ip
, sizeof(ip
)));
4064 // Pre-pend this fake request to the TLS bits already in the buffer
4066 retStr
.append("CONNECT ");
4067 retStr
.append(connectHost
);
4068 retStr
.append(" HTTP/1.1\r\nHost: ");
4069 retStr
.append(connectHost
);
4070 retStr
.append("\r\n\r\n");
4071 retStr
.append(payload
);
4073 bool ret
= handleReadData();
4075 ret
= clientParseRequests();
4078 debugs(33, 2, "Failed to start fake CONNECT request for " << reason
<< " connection: " << clientConnection
);
4079 clientConnection
->close();
4083 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4085 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4087 if (!Comm::IsConnOpen(c
)) {
4088 Must(NHttpSockets
> 0); // we tried to open some
4089 --NHttpSockets
; // there will be fewer sockets than planned
4090 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4092 if (!NHttpSockets
) // we could not open any listen sockets at all
4093 fatalf("Unable to open %s",FdNote(portType
));
4100 /// find any unused HttpSockets[] slot and store fd there or return false
4102 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4105 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4106 if ((found
= HttpSockets
[i
] < 0))
4107 HttpSockets
[i
] = conn
->fd
;
4113 clientHttpConnectionsOpen(void)
4115 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4116 const char *scheme
= AnyP::UriScheme(s
->transport
.protocol
).c_str();
4118 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4119 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many '" << scheme
<< "_port' lines.");
4120 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4125 if (s
->flags
.tunnelSslBumping
) {
4126 if (!Config
.accessList
.ssl_bump
) {
4127 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme
<< "_port " << s
->s
);
4128 s
->flags
.tunnelSslBumping
= false;
4130 if (!s
->secure
.staticContext
&& !s
->generateHostCertificates
) {
4131 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at " << scheme
<< "_port " << s
->s
<< " due to TLS initialization failure.");
4132 s
->flags
.tunnelSslBumping
= false;
4133 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
)
4134 s
->secure
.encryptTransport
= false;
4136 if (s
->flags
.tunnelSslBumping
) {
4137 // Create ssl_ctx cache for this port.
4138 auto sz
= s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
;
4139 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, sz
);
4143 if (s
->secure
.encryptTransport
&& !s
->secure
.staticContext
) {
4144 debugs(1, DBG_CRITICAL
, "ERROR: Ignoring " << scheme
<< "_port " << s
->s
<< " due to TLS context initialization failure.");
4149 // Fill out a Comm::Connection which IPC will open as a listener for us
4150 // then pass back when active so we can start a TcpAcceptor subscription.
4151 s
->listenConn
= new Comm::Connection
;
4152 s
->listenConn
->local
= s
->s
;
4154 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4155 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4157 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4158 if (s
->transport
.protocol
== AnyP::PROTO_HTTP
) {
4159 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4160 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
4161 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4163 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4164 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4165 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4168 } else if (s
->transport
.protocol
== AnyP::PROTO_HTTPS
) {
4169 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4170 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
4171 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4173 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4174 ListeningStartedDialer(&clientListenerConnectionOpened
,
4175 s
, Ipc::fdnHttpsSocket
, sub
));
4176 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4180 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4186 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
4188 // Fill out a Comm::Connection which IPC will open as a listener for us
4189 port
->listenConn
= new Comm::Connection
;
4190 port
->listenConn
->local
= port
->s
;
4191 port
->listenConn
->flags
=
4193 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4194 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4196 // route new connections to subCall
4197 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4198 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4199 AsyncCall::Pointer listenCall
=
4200 asyncCall(33, 2, "clientListenerConnectionOpened",
4201 ListeningStartedDialer(&clientListenerConnectionOpened
,
4202 port
, fdNote
, sub
));
4203 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
4205 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
4206 HttpSockets
[NHttpSockets
] = -1;
4210 /// process clientHttpConnectionsOpen result
4212 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4216 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4219 Must(Comm::IsConnOpen(s
->listenConn
));
4221 // TCP: setup a job to handle accept() with subscribed handler
4222 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
4224 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4225 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4226 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4227 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4228 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4229 << FdNote(portTypeNote
) << " connections at "
4232 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4236 clientOpenListenSockets(void)
4238 clientHttpConnectionsOpen();
4239 Ftp::StartListening();
4241 if (NHttpSockets
< 1)
4242 fatal("No HTTP, HTTPS, or FTP ports configured");
4246 clientConnectionsClose()
4248 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4249 if (s
->listenConn
!= NULL
) {
4250 debugs(1, DBG_IMPORTANT
, "Closing HTTP(S) port " << s
->listenConn
->local
);
4251 s
->listenConn
->close();
4252 s
->listenConn
= NULL
;
4256 Ftp::StopListening();
4258 // TODO see if we can drop HttpSockets array entirely */
4259 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4260 HttpSockets
[i
] = -1;
4267 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4269 const char *vary
= request
->vary_headers
;
4270 int has_vary
= entry
->getReply()->header
.has(Http::HdrType::VARY
);
4271 #if X_ACCELERATOR_VARY
4274 entry
->getReply()->header
.has(Http::HdrType::HDR_X_ACCELERATOR_VARY
);
4277 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4279 /* Oops... something odd is going on here.. */
4280 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4281 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4282 safe_free(request
->vary_headers
);
4287 /* This is not a varying object */
4291 /* virtual "vary" object found. Calculate the vary key and
4292 * continue the search
4294 vary
= httpMakeVaryMark(request
, entry
->getReply());
4297 request
->vary_headers
= xstrdup(vary
);
4300 /* Ouch.. we cannot handle this kind of variance */
4301 /* XXX This cannot really happen, but just to be complete */
4306 vary
= httpMakeVaryMark(request
, entry
->getReply());
4309 request
->vary_headers
= xstrdup(vary
);
4313 /* Ouch.. we cannot handle this kind of variance */
4314 /* XXX This cannot really happen, but just to be complete */
4316 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4319 /* Oops.. we have already been here and still haven't
4320 * found the requested variant. Bail out
4322 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4323 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4329 ACLFilledChecklist
*
4330 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4332 ConnStateData
* conn
= http
->getConn();
4333 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4334 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4337 * hack for ident ACL. It needs to get full addresses, and a place to store
4338 * the ident result on persistent connections...
4340 /* connection oriented auth also needs these two lines for it's operation. */
4345 ConnStateData::transparent() const
4347 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4351 ConnStateData::expectRequestBody(int64_t size
)
4353 bodyPipe
= new BodyPipe(this);
4355 bodyPipe
->setBodySize(size
);
4357 startDechunkingRequest();
4362 ConnStateData::mayNeedToReadMoreBody() const
4365 return 0; // request without a body or read/produced all body bytes
4367 if (!bodyPipe
->bodySizeKnown())
4368 return -1; // probably need to read more, but we cannot be sure
4370 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4371 const int64_t haveAvailable
= static_cast<int64_t>(inBuf
.length());
4373 if (needToProduce
<= haveAvailable
)
4374 return 0; // we have read what we need (but are waiting for pipe space)
4376 return needToProduce
- haveAvailable
;
4380 ConnStateData::stopReceiving(const char *error
)
4382 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4383 "; old sending error: " <<
4384 (stoppedSending() ? stoppedSending_
: "none"));
4386 if (const char *oldError
= stoppedReceiving()) {
4387 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4388 return; // nothing has changed as far as this connection is concerned
4391 stoppedReceiving_
= error
;
4393 if (const char *sendError
= stoppedSending()) {
4394 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4395 clientConnection
->close();
4400 ConnStateData::expectNoForwarding()
4402 if (bodyPipe
!= NULL
) {
4403 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4404 bodyPipe
->expectNoConsumption();
4408 /// initialize dechunking state
4410 ConnStateData::startDechunkingRequest()
4412 Must(bodyPipe
!= NULL
);
4413 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4414 assert(!bodyParser
);
4415 bodyParser
= new Http1::TeChunkedParser
;
4418 /// put parsed content into input buffer and clean up
4420 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4422 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4424 if (bodyPipe
!= NULL
) {
4425 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4426 BodyPipe::Pointer myPipe
= bodyPipe
;
4427 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4428 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4430 Must(myPipe
->bodySizeKnown());
4431 ClientSocketContext::Pointer context
= pipeline
.front();
4432 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4433 context
->http
->request
->setContentLength(myPipe
->bodySize());
4441 // XXX: this is an HTTP/1-only operation
4443 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4446 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4450 // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them
4451 if (!pipeline
.empty()) {
4452 HttpReply::Pointer
rep(msg
.reply
);
4454 // remember the callback
4455 cbControlMsgSent
= msg
.cbSuccess
;
4457 typedef CommCbMemFunT
<HttpControlMsgSink
, CommIoCbParams
> Dialer
;
4458 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, HttpControlMsgSink::wroteControlMsg
);
4460 writeControlMsgAndCall(rep
.getRaw(), call
);
4464 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4465 clientConnection
->close();
4468 /// Our close handler called by Comm when the pinned connection is closed
4470 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4472 // FwdState might repin a failed connection sooner than this close
4473 // callback is called for the failed connection.
4474 assert(pinning
.serverConnection
== io
.conn
);
4475 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4476 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4477 pinning
.serverConnection
->noteClosure();
4478 unpinConnection(false);
4480 if (sawZeroReply
&& clientConnection
!= NULL
) {
4481 debugs(33, 3, "Closing client connection on pinned zero reply.");
4482 clientConnection
->close();
4488 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
4490 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
4491 pinning
.serverConnection
->fd
!= pinServer
->fd
)
4492 pinNewConnection(pinServer
, request
, aPeer
, auth
);
4495 startPinnedConnectionMonitoring();
4499 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4501 unpinConnection(true); // closes pinned connection, if any, and resets fields
4503 pinning
.serverConnection
= pinServer
;
4505 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4507 Must(pinning
.serverConnection
!= NULL
);
4509 // when pinning an SSL bumped connection, the request may be NULL
4510 const char *pinnedHost
= "[unknown]";
4512 pinning
.host
= xstrdup(request
->url
.host());
4513 pinning
.port
= request
->url
.port();
4514 pinnedHost
= pinning
.host
;
4516 pinning
.port
= pinServer
->remote
.port();
4518 pinning
.pinned
= true;
4520 pinning
.peer
= cbdataReference(aPeer
);
4521 pinning
.auth
= auth
;
4522 char stmp
[MAX_IPSTRLEN
];
4523 char desc
[FD_DESC_SZ
];
4524 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4525 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4526 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4527 clientConnection
->fd
);
4528 fd_note(pinning
.serverConnection
->fd
, desc
);
4530 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4531 pinning
.closeHandler
= JobCallback(33, 5,
4532 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4533 // remember the pinned connection so that cb does not unpin a fresher one
4534 typedef CommCloseCbParams Params
;
4535 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4536 params
.conn
= pinning
.serverConnection
;
4537 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4540 /// [re]start monitoring pinned connection for peer closures so that we can
4541 /// propagate them to an _idle_ client pinned to that peer
4543 ConnStateData::startPinnedConnectionMonitoring()
4545 if (pinning
.readHandler
!= NULL
)
4546 return; // already monitoring
4548 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4549 pinning
.readHandler
= JobCallback(33, 3,
4550 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4551 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
4555 ConnStateData::stopPinnedConnectionMonitoring()
4557 if (pinning
.readHandler
!= NULL
) {
4558 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4559 pinning
.readHandler
= NULL
;
4565 ConnStateData::handleIdleClientPinnedTlsRead()
4567 // A ready-for-reading connection means that the TLS server either closed
4568 // the connection, sent us some unexpected HTTP data, or started TLS
4569 // renegotiations. We should close the connection except for the last case.
4571 Must(pinning
.serverConnection
!= nullptr);
4572 SSL
*ssl
= fd_table
[pinning
.serverConnection
->fd
].ssl
;
4577 const int readResult
= SSL_read(ssl
, buf
, sizeof(buf
));
4579 if (readResult
> 0 || SSL_pending(ssl
) > 0) {
4580 debugs(83, 2, pinning
.serverConnection
<< " TLS application data read");
4584 switch(const int error
= SSL_get_error(ssl
, readResult
)) {
4585 case SSL_ERROR_WANT_WRITE
:
4586 debugs(83, DBG_IMPORTANT
, pinning
.serverConnection
<< " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection");
4587 // fall through to restart monitoring, for now
4588 case SSL_ERROR_NONE
:
4589 case SSL_ERROR_WANT_READ
:
4590 startPinnedConnectionMonitoring();
4594 debugs(83, 2, pinning
.serverConnection
<< " TLS error: " << error
);
4603 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4604 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4606 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4608 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4610 if (io
.flag
== Comm::ERR_CLOSING
)
4611 return; // close handler will clean up
4613 Must(pinning
.serverConnection
== io
.conn
);
4616 if (handleIdleClientPinnedTlsRead())
4620 const bool clientIsIdle
= pipeline
.empty();
4622 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4623 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4625 pinning
.serverConnection
->close();
4627 // If we are still sending data to the client, do not close now. When we are done sending,
4628 // ConnStateData::kick() checks pinning.serverConnection and will close.
4629 // However, if we are idle, then we must close to inform the idle client and minimize races.
4630 if (clientIsIdle
&& clientConnection
!= NULL
)
4631 clientConnection
->close();
4634 const Comm::ConnectionPointer
4635 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4637 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4640 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4642 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->url
.host()) != 0)
4644 else if (request
&& pinning
.port
!= request
->url
.port())
4646 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4648 else if (aPeer
!= pinning
.peer
)
4652 /* The pinning info is not safe, remove any pinning info */
4653 unpinConnection(true);
4656 return pinning
.serverConnection
;
4659 Comm::ConnectionPointer
4660 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4662 debugs(33, 7, pinning
.serverConnection
);
4663 if (validatePinnedConnection(request
, aPeer
) != NULL
)
4664 stopPinnedConnectionMonitoring();
4666 return pinning
.serverConnection
; // closed if validation failed
4670 ConnStateData::unpinConnection(const bool andClose
)
4672 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4675 cbdataReferenceDone(pinning
.peer
);
4677 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4678 if (pinning
.closeHandler
!= NULL
) {
4679 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4680 pinning
.closeHandler
= NULL
;
4683 stopPinnedConnectionMonitoring();
4685 // close the server side socket if requested
4687 pinning
.serverConnection
->close();
4688 pinning
.serverConnection
= NULL
;
4691 safe_free(pinning
.host
);
4693 pinning
.zeroReply
= false;
4695 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4696 * connection has gone away */