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 * ClientKeepAliveNextRequest 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 "ChunkedCodingParser.h"
67 #include "client_db.h"
68 #include "client_side.h"
69 #include "client_side_reply.h"
70 #include "client_side_request.h"
71 #include "ClientRequestContext.h"
72 #include "clientStream.h"
74 #include "comm/Connection.h"
75 #include "comm/Loops.h"
76 #include "comm/Read.h"
77 #include "comm/TcpAcceptor.h"
78 #include "comm/Write.h"
79 #include "CommCalls.h"
80 #include "errorpage.h"
83 #include "fqdncache.h"
87 #include "helper/Reply.h"
89 #include "http/one/RequestParser.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 IOCB clientWriteComplete
;
180 static IOCB clientWriteBodyComplete
;
181 static IOACB httpAccept
;
183 static IOACB httpsAccept
;
185 static CTCB clientLifetimeTimeout
;
187 static IDCB clientIdentDone
;
189 static int clientIsContentLengthValid(HttpRequest
* r
);
190 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
192 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
193 static void clientUpdateStatCounters(LogTags logType
);
194 static void clientUpdateHierCounters(HierarchyLogEntry
*);
195 static bool clientPingHasFinished(ping_data
const *aPing
);
196 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
198 static bool connIsUsable(ConnStateData
* conn
);
200 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
201 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
203 char *skipLeadingSpace(char *aString
);
206 ClientSocketContext::getTail() const
208 if (http
->client_stream
.tail
)
209 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
215 ClientSocketContext::getClientReplyContext() const
217 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
221 ClientSocketContext::getConn() const
223 return http
->getConn();
227 * This routine should be called to grow the in.buf and then
231 ConnStateData::readSomeData()
236 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
238 if (!in
.maybeMakeSpaceAvailable())
241 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
242 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
243 Comm::Read(clientConnection
, reader
);
247 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
249 ClientSocketContext::Pointer
*tempContextPointer
;
250 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
251 assert(conn
->getCurrentContext() != NULL
);
252 /* Unlink us from the connection request list */
253 tempContextPointer
= & conn
->currentobject
;
255 while (tempContextPointer
->getRaw()) {
256 if (*tempContextPointer
== this)
259 tempContextPointer
= &(*tempContextPointer
)->next
;
262 assert(tempContextPointer
->getRaw() != NULL
);
263 *tempContextPointer
= next
;
267 ClientSocketContext::~ClientSocketContext()
269 clientStreamNode
*node
= getTail();
272 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
275 /* We are *always* the tail - prevent recursive free */
276 assert(this == streamContext
);
282 deRegisterWithConn();
284 httpRequestFree(http
);
286 /* clean up connection links to us */
287 assert(this != next
.getRaw());
291 ClientSocketContext::registerWithConn()
293 assert (!connRegistered_
);
295 assert (http
->getConn() != NULL
);
296 connRegistered_
= true;
297 http
->getConn()->addContextToQueue(this);
301 ClientSocketContext::deRegisterWithConn()
303 assert (connRegistered_
);
304 removeFromConnectionList(http
->getConn());
305 connRegistered_
= false;
309 ClientSocketContext::connIsFinished()
312 assert (http
->getConn() != NULL
);
313 deRegisterWithConn();
314 /* we can't handle any more stream data - detach */
315 clientStreamDetach(getTail(), http
);
318 ClientSocketContext::ClientSocketContext(const Comm::ConnectionPointer
&aConn
, ClientHttpRequest
*aReq
) :
319 clientConnection(aConn
),
324 mayUseConnection_ (false),
325 connRegistered_ (false)
327 assert(http
!= NULL
);
328 memset (reqbuf
, '\0', sizeof (reqbuf
));
331 deferredparams
.node
= NULL
;
332 deferredparams
.rep
= NULL
;
336 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
338 HttpReply::Pointer
rep(msg
.reply
);
341 // remember the callback
342 cbControlMsgSent
= msg
.cbSuccess
;
344 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
345 CommIoCbPtrFun(&WroteControlMsg
, this));
347 getConn()->writeControlMsgAndCall(this, rep
.getRaw(), call
);
350 /// called when we wrote the 1xx response
352 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, Comm::Flag errflag
, int xerrno
)
354 if (errflag
== Comm::ERR_CLOSING
)
357 if (errflag
== Comm::OK
) {
358 ScheduleCallHere(cbControlMsgSent
);
362 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
363 // no error notification: see HttpControlMsg.h for rationale and
364 // note that some errors are detected elsewhere (e.g., close handler)
366 // close on 1xx errors to be conservative and to simplify the code
367 // (if we do not close, we must notify the source of a failure!)
370 // XXX: writeControlMsgAndCall() should handle writer-specific writing
371 // results, including errors and then call us with success/failure outcome.
374 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
376 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, Comm::Flag errflag
, int xerrno
, void *data
)
378 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
379 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
384 clientIdentDone(const char *ident
, void *data
)
386 ConnStateData
*conn
= (ConnStateData
*)data
;
387 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
392 clientUpdateStatCounters(LogTags logType
)
394 ++statCounter
.client_http
.requests
;
396 if (logTypeIsATcpHit(logType
))
397 ++statCounter
.client_http
.hits
;
399 if (logType
== LOG_TCP_HIT
)
400 ++statCounter
.client_http
.disk_hits
;
401 else if (logType
== LOG_TCP_MEM_HIT
)
402 ++statCounter
.client_http
.mem_hits
;
406 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
408 statCounter
.client_http
.allSvcTime
.count(svc_time
);
410 * The idea here is not to be complete, but to get service times
411 * for only well-defined types. For example, we don't include
412 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
413 * (we *tried* to validate it, but failed).
418 case LOG_TCP_REFRESH_UNMODIFIED
:
419 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
422 case LOG_TCP_IMS_HIT
:
423 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
428 case LOG_TCP_MEM_HIT
:
430 case LOG_TCP_OFFLINE_HIT
:
431 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
436 case LOG_TCP_CLIENT_REFRESH_MISS
:
437 statCounter
.client_http
.missSvcTime
.count(svc_time
);
441 /* make compiler warnings go away */
447 clientPingHasFinished(ping_data
const *aPing
)
449 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
456 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
460 switch (someEntry
->code
) {
461 #if USE_CACHE_DIGESTS
466 ++ statCounter
.cd
.times_used
;
474 case FIRST_PARENT_MISS
:
476 case CLOSEST_PARENT_MISS
:
477 ++ statCounter
.icp
.times_used
;
478 i
= &someEntry
->ping
;
480 if (clientPingHasFinished(i
))
481 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
484 ++ statCounter
.icp
.query_timeouts
;
491 ++ statCounter
.netdb
.times_used
;
501 ClientHttpRequest::updateCounters()
503 clientUpdateStatCounters(logType
);
505 if (request
->errType
!= ERR_NONE
)
506 ++ statCounter
.client_http
.errors
;
508 clientUpdateStatHistCounters(logType
,
509 tvSubMsec(al
->cache
.start_time
, current_time
));
511 clientUpdateHierCounters(&request
->hier
);
515 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
518 assert(aLogEntry
!= NULL
);
520 if (Config
.onoff
.log_mime_hdrs
) {
523 request
->header
.packInto(&mb
);
524 //This is the request after adaptation or redirection
525 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
527 // the virgin request is saved to aLogEntry->request
528 if (aLogEntry
->request
) {
530 aLogEntry
->request
->header
.packInto(&mb
);
531 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
535 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
538 ah
->lastMeta
.packInto(&mb
);
539 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
547 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
549 ih
->processingTime(aLogEntry
->icap
.processingTime
);
552 aLogEntry
->http
.method
= request
->method
;
553 aLogEntry
->http
.version
= request
->http_ver
;
554 aLogEntry
->hier
= request
->hier
;
555 if (request
->content_length
> 0) // negative when no body or unknown length
556 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
557 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
559 // Adapted request, if any, inherits and then collects all the stats, but
560 // the virgin request gets logged instead; copy the stats to log them.
561 // TODO: avoid losses by keeping these stats in a shared history object?
562 if (aLogEntry
->request
) {
563 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
564 aLogEntry
->request
->errType
= request
->errType
;
565 aLogEntry
->request
->errDetail
= request
->errDetail
;
570 ClientHttpRequest::logRequest()
572 if (!out
.size
&& !logType
)
573 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
575 al
->icp
.opcode
= ICP_INVALID
;
577 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
580 al
->http
.code
= al
->reply
->sline
.status();
581 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
582 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
583 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
584 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
587 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
589 if (loggingEntry() && loggingEntry()->mem_obj
&& loggingEntry()->objectLen() >= 0)
590 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
592 al
->http
.clientRequestSz
.header
= req_sz
;
593 al
->http
.clientReplySz
.header
= out
.headers_sz
;
594 // XXX: calculate without payload encoding or headers !!
595 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
597 al
->cache
.highOffset
= out
.offset
;
599 al
->cache
.code
= logType
;
601 tvSub(al
->cache
.trTime
, al
->cache
.start_time
, current_time
);
604 prepareLogWithRequestDetails(request
, al
);
606 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
607 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
611 /* This is broken. Fails if the connection has been closed. Needs
612 * to snarf the ssl details some place earlier..
614 if (getConn() != NULL
)
615 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
619 /* Add notes (if we have a request to annotate) */
621 // The al->notes and request->notes must point to the same object.
622 (void)SyncNotes(*al
, *request
);
623 for (auto i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
624 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
625 NotePairs
¬es
= SyncNotes(*al
, *request
);
626 notes
.add((*i
)->key
.termedBuf(), value
);
627 debugs(33, 3, (*i
)->key
.termedBuf() << " " << value
);
632 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
634 checklist
.reply
= al
->reply
;
635 HTTPMSGLOCK(checklist
.reply
);
639 al
->adapted_request
= request
;
640 HTTPMSGLOCK(al
->adapted_request
);
642 accessLogLog(al
, &checklist
);
644 bool updatePerformanceCounters
= true;
645 if (Config
.accessList
.stats_collection
) {
646 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
648 statsCheck
.reply
= al
->reply
;
649 HTTPMSGLOCK(statsCheck
.reply
);
651 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
654 if (updatePerformanceCounters
) {
658 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
659 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
664 ClientHttpRequest::freeResources()
668 safe_free(redirect
.location
);
669 range_iter
.boundary
.clean();
670 HTTPMSGUNLOCK(request
);
672 if (client_stream
.tail
)
673 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
677 httpRequestFree(void *data
)
679 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
680 assert(http
!= NULL
);
685 ConnStateData::areAllContextsForThisConnection() const
687 ClientSocketContext::Pointer context
= getCurrentContext();
689 while (context
.getRaw()) {
690 if (context
->http
->getConn() != this)
693 context
= context
->next
;
700 ConnStateData::freeAllContexts()
702 ClientSocketContext::Pointer context
;
704 while ((context
= getCurrentContext()).getRaw() != NULL
) {
705 assert(getCurrentContext() !=
706 getCurrentContext()->next
);
707 context
->connIsFinished();
708 assert (context
!= currentobject
);
712 /// propagates abort event to all contexts
714 ConnStateData::notifyAllContexts(int xerrno
)
716 typedef ClientSocketContext::Pointer CSCP
;
717 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
718 c
->noteIoError(xerrno
);
721 /* This is a handler normally called by comm_close() */
722 void ConnStateData::connStateClosed(const CommCloseCbParams
&)
724 deleteThis("ConnStateData::connStateClosed");
729 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
733 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
739 // clobered with self-pointer
740 // NP: something nasty is going on in Squid, but harmless.
742 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
747 * Connection-auth relies on a single set of credentials being preserved
748 * for all requests on a connection once they have been setup.
749 * There are several things which need to happen to preserve security
750 * when connection-auth credentials change unexpectedly or are unset.
752 * 1) auth helper released from any active state
754 * They can only be reserved by a handshake process which this
755 * connection can now never complete.
756 * This prevents helpers hanging when their connections close.
758 * 2) pinning is expected to be removed and server conn closed
760 * The upstream link is authenticated with the same credentials.
761 * Expecting the same level of consistency we should have received.
762 * This prevents upstream being faced with multiple or missing
763 * credentials after authentication.
764 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
765 * we just trigger that cleanup here via comm_reset_close() or
766 * ConnStateData::stopReceiving()
768 * 3) the connection needs to close.
770 * This prevents attackers injecting requests into a connection,
771 * or gateways wrongly multiplexing users into a single connection.
773 * When credentials are missing closure needs to follow an auth
774 * challenge for best recovery by the client.
776 * When credentials change there is nothing we can do but abort as
777 * fast as possible. Sending TCP RST instead of an HTTP response
778 * is the best-case action.
781 // clobbered with nul-pointer
783 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
784 auth_
->releaseAuthServer();
786 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
787 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
788 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
789 stopReceiving("connection-auth removed");
793 // clobbered with alternative credentials
795 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
796 auth_
->releaseAuthServer();
798 // this is a fatal type of problem.
799 // Close the connection immediately with TCP RST to abort all traffic flow
800 comm_reset_close(clientConnection
);
808 // cleans up before destructor is called
810 ConnStateData::swanSong()
812 debugs(33, 2, HERE
<< clientConnection
);
813 flags
.readMore
= false;
814 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
815 assert(areAllContextsForThisConnection());
818 unpinConnection(true);
820 if (Comm::IsConnOpen(clientConnection
))
821 clientConnection
->close();
824 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
825 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
828 BodyProducer::swanSong();
829 flags
.swanSang
= true;
833 ConnStateData::isOpen() const
835 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
836 Comm::IsConnOpen(clientConnection
) &&
837 !fd_table
[clientConnection
->fd
].closing();
840 ConnStateData::~ConnStateData()
842 debugs(33, 3, HERE
<< clientConnection
);
845 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
848 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
850 if (bodyPipe
!= NULL
)
851 stopProducingFor(bodyPipe
, false);
854 delete sslServerBump
;
859 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
860 * This is the client-side persistent connection flag. We need
861 * to set this relatively early in the request processing
862 * to handle hacks for broken servers and clients.
865 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
867 HttpRequest
*request
= http
->request
;
869 debugs(33, 3, "http_ver = " << request
->http_ver
);
870 debugs(33, 3, "method = " << request
->method
);
872 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
873 request
->flags
.proxyKeepalive
= request
->persistent();
877 clientIsContentLengthValid(HttpRequest
* r
)
879 switch (r
->method
.id()) {
881 case Http::METHOD_GET
:
883 case Http::METHOD_HEAD
:
884 /* We do not want to see a request entity on GET/HEAD requests */
885 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
888 /* For other types of requests we don't care */
896 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
898 if (Config
.maxRequestBodySize
&&
899 bodyLength
> Config
.maxRequestBodySize
)
900 return 1; /* too large */
907 connIsUsable(ConnStateData
* conn
)
909 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
917 // careful: the "current" context may be gone if we wrote an early response
918 ClientSocketContext::Pointer
919 ConnStateData::getCurrentContext() const
921 return currentobject
;
925 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
927 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
928 assert(flags
.deferred
== 0);
930 deferredparams
.node
= node
;
931 deferredparams
.rep
= rep
;
932 deferredparams
.queuedBuffer
= receivedData
;
937 ClientSocketContext::startOfOutput() const
939 return http
->out
.size
== 0;
943 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
945 /*the size of available range can always fit in a size_t type*/
946 size_t maximum
= (size_t)available
.size();
948 if (!http
->request
->range
)
951 assert (canPackMoreRanges());
953 if (http
->range_iter
.debt() == -1)
956 assert (http
->range_iter
.debt() > 0);
958 /* TODO this + the last line could be a range intersection calculation */
959 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
962 return min(http
->range_iter
.debt(), (int64_t)maximum
);
966 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
968 http
->out
.offset
+= bytes
;
970 if (!http
->request
->range
)
973 if (http
->range_iter
.debt() != -1) {
974 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
975 assert (http
->range_iter
.debt() >= 0);
978 /* debt() always stops at -1, below that is a bug */
979 assert (http
->range_iter
.debt() >= -1);
983 ClientHttpRequest::multipartRangeRequest() const
985 return request
->multipartRangeRequest();
989 ClientSocketContext::multipartRangeRequest() const
991 return http
->multipartRangeRequest();
995 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
999 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1000 size_t length
= lengthToSend(bodyData
.range());
1001 noteSentBodyBytes (length
);
1002 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1003 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1004 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1010 if (multipartRangeRequest())
1011 packRange(bodyData
, &mb
);
1013 packChunk(bodyData
, mb
);
1015 if (mb
.contentSize()) {
1017 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1018 CommIoCbPtrFun(clientWriteComplete
, this));
1019 Comm::Write(clientConnection
, &mb
, call
);
1021 writeComplete(clientConnection
, NULL
, 0, Comm::OK
);
1025 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1026 * if bodyData is empty.
1029 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1031 const uint64_t length
=
1032 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1033 noteSentBodyBytes(length
);
1035 mb
.Printf("%" PRIX64
"\r\n", length
);
1036 mb
.append(bodyData
.data
, length
);
1040 /** put terminating boundary for multiparts */
1042 clientPackTermBound(String boundary
, MemBuf
* mb
)
1044 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1045 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1048 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1050 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1052 HttpHeader
hdr(hoReply
);
1057 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1058 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1059 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1061 /* stuff the header with required entries and pack it */
1063 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1064 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1066 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1071 /* append <crlf> (we packed a header, not a reply) */
1072 mb
->append("\r\n", 2);
1076 * extracts a "range" from *buf and appends them to mb, updating
1077 * all offsets and such.
1080 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1082 HttpHdrRangeIter
* i
= &http
->range_iter
;
1083 Range
<int64_t> available (source
.range());
1084 char const *buf
= source
.data
;
1086 while (i
->currentSpec() && available
.size()) {
1087 const size_t copy_sz
= lengthToSend(available
);
1091 * intersection of "have" and "need" ranges must not be empty
1093 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1094 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1097 * put boundary and headers at the beginning of a range in a
1101 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1102 assert(http
->memObject());
1104 http
->memObject()->getReply(), /* original reply */
1105 i
->currentSpec(), /* current range */
1106 i
->boundary
, /* boundary, the same for all */
1113 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1115 noteSentBodyBytes (copy_sz
);
1117 mb
->append(buf
, copy_sz
);
1122 available
.start
+= copy_sz
;
1128 if (!canPackMoreRanges()) {
1129 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1132 /* put terminating boundary for multiparts */
1133 clientPackTermBound(i
->boundary
, mb
);
1138 int64_t nextOffset
= getNextRangeOffset();
1140 assert (nextOffset
>= http
->out
.offset
);
1142 int64_t skip
= nextOffset
- http
->out
.offset
;
1144 /* adjust for not to be transmitted bytes */
1145 http
->out
.offset
= nextOffset
;
1147 if (available
.size() <= (uint64_t)skip
)
1150 available
.start
+= skip
;
1159 /** returns expected content length for multi-range replies
1160 * note: assumes that httpHdrRangeCanonize has already been called
1161 * warning: assumes that HTTP headers for individual ranges at the
1162 * time of the actuall assembly will be exactly the same as
1163 * the headers when clientMRangeCLen() is called */
1165 ClientHttpRequest::mRangeCLen()
1170 assert(memObject());
1173 HttpHdrRange::iterator pos
= request
->range
->begin();
1175 while (pos
!= request
->range
->end()) {
1176 /* account for headers for this range */
1178 clientPackRangeHdr(memObject()->getReply(),
1179 *pos
, range_iter
.boundary
, &mb
);
1182 /* account for range content */
1183 clen
+= (*pos
)->length
;
1185 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1189 /* account for the terminating boundary */
1192 clientPackTermBound(range_iter
.boundary
, &mb
);
1202 * returns true if If-Range specs match reply, false otherwise
1205 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1207 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1208 /* check for parsing falure */
1215 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1216 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1217 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1220 return 0; /* entity has no etag to compare with! */
1222 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1223 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1224 return 0; /* must use strong validator for sub-range requests */
1227 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1230 /* got modification time? */
1231 if (spec
.time
>= 0) {
1232 return http
->storeEntry()->lastmod
<= spec
.time
;
1235 assert(0); /* should not happen */
1240 * generates a "unique" boundary string for multipart responses
1241 * the caller is responsible for cleaning the string */
1243 ClientHttpRequest::rangeBoundaryStr() const
1246 String
b(APP_FULLNAME
);
1248 key
= storeEntry()->getMD5Text();
1249 b
.append(key
, strlen(key
));
1253 /** adds appropriate Range headers if needed */
1255 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1257 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1258 const char *range_err
= NULL
;
1259 HttpRequest
*request
= http
->request
;
1260 assert(request
->range
);
1261 /* check if we still want to do ranges */
1263 int64_t roffLimit
= request
->getRangeOffsetLimit();
1266 range_err
= "no [parse-able] reply";
1267 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1268 range_err
= "wrong status code";
1269 else if (hdr
->has(HDR_CONTENT_RANGE
))
1270 range_err
= "origin server does ranges";
1271 else if (rep
->content_length
< 0)
1272 range_err
= "unknown length";
1273 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1274 range_err
= "INCONSISTENT length"; /* a bug? */
1276 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1279 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1280 range_err
= "If-Range match failed";
1281 else if (!http
->request
->range
->canonize(rep
))
1282 range_err
= "canonization failed";
1283 else if (http
->request
->range
->isComplex())
1284 range_err
= "too complex range header";
1285 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1286 range_err
= "range outside range_offset_limit";
1288 /* get rid of our range specs on error */
1290 /* XXX We do this here because we need canonisation etc. However, this current
1291 * code will lead to incorrect store offset requests - the store will have the
1292 * offset data, but we won't be requesting it.
1293 * So, we can either re-request, or generate an error
1295 http
->request
->ignoreRange(range_err
);
1297 /* XXX: TODO: Review, this unconditional set may be wrong. */
1298 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1299 // web server responded with a valid, but unexpected range.
1300 // will (try-to) forward as-is.
1301 //TODO: we should cope with multirange request/responses
1302 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1303 request
->range
->contains(rep
->content_range
->spec
) :
1305 const int spec_count
= http
->request
->range
->specs
.size();
1306 int64_t actual_clen
= -1;
1308 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1309 spec_count
<< " virgin clen: " << rep
->content_length
);
1310 assert(spec_count
> 0);
1311 /* append appropriate header(s) */
1313 if (spec_count
== 1) {
1314 if (!replyMatchRequest
) {
1315 hdr
->delById(HDR_CONTENT_RANGE
);
1316 hdr
->putContRange(rep
->content_range
);
1317 actual_clen
= rep
->content_length
;
1318 //http->range_iter.pos = rep->content_range->spec.begin();
1319 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1320 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1323 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1325 /* append Content-Range */
1327 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1328 /* No content range, so this was a full object we are
1331 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1334 /* set new Content-Length to the actual number of bytes
1335 * transmitted in the message-body */
1336 actual_clen
= (*pos
)->length
;
1340 /* generate boundary string */
1341 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1342 /* delete old Content-Type, add ours */
1343 hdr
->delById(HDR_CONTENT_TYPE
);
1344 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1345 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1346 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1347 /* Content-Length is not required in multipart responses
1348 * but it is always nice to have one */
1349 actual_clen
= http
->mRangeCLen();
1350 /* http->out needs to start where we want data at */
1351 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1354 /* replace Content-Length header */
1355 assert(actual_clen
>= 0);
1357 hdr
->delById(HDR_CONTENT_LENGTH
);
1359 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1361 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1363 /* And start the range iter off */
1364 http
->range_iter
.updateSpec();
1369 ClientSocketContext::prepareReply(HttpReply
* rep
)
1373 if (http
->request
->range
)
1374 buildRangeHeader(rep
);
1378 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1382 MemBuf
*mb
= rep
->pack();
1384 // dump now, so we dont output any body.
1385 debugs(11, 2, "HTTP Client " << clientConnection
);
1386 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1388 /* Save length of headers for persistent conn checks */
1389 http
->out
.headers_sz
= mb
->contentSize();
1392 headersLog(0, 0, http
->request
->method
, rep
);
1395 if (bodyData
.data
&& bodyData
.length
) {
1396 if (multipartRangeRequest())
1397 packRange(bodyData
, mb
);
1398 else if (http
->request
->flags
.chunkedReply
) {
1399 packChunk(bodyData
, *mb
);
1401 size_t length
= lengthToSend(bodyData
.range());
1402 noteSentBodyBytes (length
);
1404 mb
->append(bodyData
.data
, length
);
1409 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1410 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1411 CommIoCbPtrFun(clientWriteComplete
, this));
1412 Comm::Write(clientConnection
, mb
, call
);
1417 * Write a chunk of data to a client socket. If the reply is present,
1418 * send the reply headers down the wire too, and clean them up when
1421 * The request is one backed by a connection, not an internal request.
1422 * data context is not NULL
1423 * There are no more entries in the stream chain.
1426 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1427 HttpReply
* rep
, StoreIOBuffer receivedData
)
1429 /* Test preconditions */
1430 assert(node
!= NULL
);
1431 PROF_start(clientSocketRecipient
);
1432 /* TODO: handle this rather than asserting
1433 * - it should only ever happen if we cause an abort and
1434 * the callback chain loops back to here, so we can simply return.
1435 * However, that itself shouldn't happen, so it stays as an assert for now.
1437 assert(cbdataReferenceValid(node
));
1438 assert(node
->node
.next
== NULL
);
1439 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1440 assert(context
!= NULL
);
1441 assert(connIsUsable(http
->getConn()));
1443 /* TODO: check offset is what we asked for */
1445 if (context
!= http
->getConn()->getCurrentContext())
1446 context
->deferRecipientForLater(node
, rep
, receivedData
);
1448 http
->getConn()->handleReply(rep
, receivedData
);
1450 PROF_stop(clientSocketRecipient
);
1454 * Called when a downstream node is no longer interested in
1455 * our data. As we are a terminal node, this means on aborts
1459 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1461 /* Test preconditions */
1462 assert(node
!= NULL
);
1463 /* TODO: handle this rather than asserting
1464 * - it should only ever happen if we cause an abort and
1465 * the callback chain loops back to here, so we can simply return.
1466 * However, that itself shouldn't happen, so it stays as an assert for now.
1468 assert(cbdataReferenceValid(node
));
1469 /* Set null by ContextFree */
1470 assert(node
->node
.next
== NULL
);
1471 /* this is the assert discussed above */
1472 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1473 /* We are only called when the client socket shutsdown.
1474 * Tell the prev pipeline member we're finished
1476 clientStreamDetach(node
, http
);
1480 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int xerrno
, void *data
)
1482 debugs(33,7, "schedule clientWriteComplete");
1483 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1487 ConnStateData::readNextRequest()
1489 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1491 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1493 * Set the timeout BEFORE calling readSomeData().
1495 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1496 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1497 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1498 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
1501 /** Please don't do anything with the FD past here! */
1505 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1507 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1509 /** If the client stream is waiting on a socket write to occur, then */
1511 if (deferredRequest
->flags
.deferred
) {
1512 /** NO data is allowed to have been sent. */
1513 assert(deferredRequest
->http
->out
.size
== 0);
1515 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1516 deferredRequest
->http
,
1517 deferredRequest
->deferredparams
.rep
,
1518 deferredRequest
->deferredparams
.queuedBuffer
);
1521 /** otherwise, the request is still active in a callbacksomewhere,
1526 /// called when we have successfully finished writing the response
1528 ClientSocketContext::keepaliveNextRequest()
1530 ConnStateData
* conn
= http
->getConn();
1532 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1535 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1536 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1537 conn
->clientConnection
->close();
1542 * We are done with the response, and we are either still receiving request
1543 * body (early response!) or have already stopped receiving anything.
1545 * If we are still receiving, then clientParseRequest() below will fail.
1546 * (XXX: but then we will call readNextRequest() which may succeed and
1547 * execute a smuggled request as we are not done with the current request).
1549 * If we stopped because we got everything, then try the next request.
1551 * If we stopped receiving because of an error, then close now to avoid
1552 * getting stuck and to prevent accidental request smuggling.
1555 if (const char *reason
= conn
->stoppedReceiving()) {
1556 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1557 conn
->clientConnection
->close();
1562 * Attempt to parse a request from the request buffer.
1563 * If we've been fed a pipelined request it may already
1564 * be in our read buffer.
1567 * This needs to fall through - if we're unlucky and parse the _last_ request
1568 * from our read buffer we may never re-register for another client read.
1571 if (conn
->clientParseRequests()) {
1572 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1576 * Either we need to kick-start another read or, if we have
1577 * a half-closed connection, kill it after the last request.
1578 * This saves waiting for half-closed connections to finished being
1579 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1580 * the keepalive "Waiting for next request" state.
1582 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1583 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1584 conn
->clientConnection
->close();
1588 ClientSocketContext::Pointer deferredRequest
;
1591 * At this point we either have a parsed request (which we've
1592 * kicked off the processing for) or not. If we have a deferred
1593 * request (parsed but deferred for pipeling processing reasons)
1594 * then look at processing it. If not, simply kickstart
1598 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1599 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1600 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1601 } else if (conn
->flags
.readMore
) {
1602 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1603 conn
->readNextRequest();
1605 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1606 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1611 clientUpdateSocketStats(LogTags logType
, size_t size
)
1616 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1618 if (logTypeIsATcpHit(logType
))
1619 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1623 * increments iterator "i"
1624 * used by clientPackMoreRanges
1626 \retval true there is still data available to pack more ranges
1630 ClientSocketContext::canPackMoreRanges() const
1632 /** first update iterator "i" if needed */
1634 if (!http
->range_iter
.debt()) {
1635 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1637 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1638 ++http
->range_iter
.pos
;
1640 http
->range_iter
.updateSpec();
1643 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1645 /* paranoid sync condition */
1646 /* continue condition: need_more_data */
1647 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1648 return http
->range_iter
.currentSpec() ? true : false;
1652 ClientSocketContext::getNextRangeOffset() const
1654 debugs (33, 5, "range: " << http
->request
->range
<<
1655 "; http offset " << http
->out
.offset
<<
1656 "; reply " << reply
);
1658 // XXX: This method is called from many places, including pullData() which
1659 // may be called before prepareReply() [on some Squid-generated errors].
1660 // Hence, we may not even know yet whether we should honor/do ranges.
1662 if (http
->request
->range
) {
1663 /* offset in range specs does not count the prefix of an http msg */
1664 /* check: reply was parsed and range iterator was initialized */
1665 assert(http
->range_iter
.valid
);
1666 /* filter out data according to range specs */
1667 assert (canPackMoreRanges());
1669 int64_t start
; /* offset of still missing data */
1670 assert(http
->range_iter
.currentSpec());
1671 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1672 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1673 debugs(33, 3, "clientPackMoreRanges: out:"
1674 " start: " << start
<<
1675 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1676 " [" << http
->range_iter
.currentSpec()->offset
<<
1677 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1678 " len: " << http
->range_iter
.currentSpec()->length
<<
1679 " debt: " << http
->range_iter
.debt());
1680 if (http
->range_iter
.currentSpec()->length
!= -1)
1681 assert(http
->out
.offset
<= start
); /* we did not miss it */
1686 } else if (reply
&& reply
->content_range
) {
1687 /* request does not have ranges, but reply does */
1688 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1689 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1691 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1694 return http
->out
.offset
;
1698 ClientSocketContext::pullData()
1700 debugs(33, 5, reply
<< " written " << http
->out
.size
<< " into " << clientConnection
);
1702 /* More data will be coming from the stream. */
1703 StoreIOBuffer readBuffer
;
1704 /* XXX: Next requested byte in the range sequence */
1705 /* XXX: length = getmaximumrangelenfgth */
1706 readBuffer
.offset
= getNextRangeOffset();
1707 readBuffer
.length
= HTTP_REQBUF_SZ
;
1708 readBuffer
.data
= reqbuf
;
1709 /* we may note we have reached the end of the wanted ranges */
1710 clientStreamRead(getTail(), http
, readBuffer
);
1713 /** Adapt stream status to account for Range cases
1716 clientStream_status_t
1717 ClientSocketContext::socketState()
1719 switch (clientStreamStatus(getTail(), http
)) {
1722 /* check for range support ending */
1724 if (http
->request
->range
) {
1725 /* check: reply was parsed and range iterator was initialized */
1726 assert(http
->range_iter
.valid
);
1727 /* filter out data according to range specs */
1729 if (!canPackMoreRanges()) {
1730 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1731 "range sequence on " << clientConnection
);
1732 // we got everything we wanted from the store
1733 return STREAM_COMPLETE
;
1735 } else if (reply
&& reply
->content_range
) {
1736 /* reply has content-range, but Squid is not managing ranges */
1737 const int64_t &bytesSent
= http
->out
.offset
;
1738 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1740 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1741 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1742 reply
->content_range
->spec
.offset
<< ")");
1744 // did we get at least what we expected, based on range specs?
1746 if (bytesSent
== bytesExpected
) // got everything
1747 return STREAM_COMPLETE
;
1749 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1750 return STREAM_UNPLANNED_COMPLETE
;
1755 case STREAM_COMPLETE
:
1756 return STREAM_COMPLETE
;
1758 case STREAM_UNPLANNED_COMPLETE
:
1759 return STREAM_UNPLANNED_COMPLETE
;
1762 return STREAM_FAILED
;
1765 fatal ("unreachable code\n");
1770 * A write has just completed to the client, or we have just realised there is
1771 * no more data to send.
1774 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, Comm::Flag errflag
, int, void *data
)
1776 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1777 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1780 /// remembers the abnormal connection termination for logging purposes
1782 ClientSocketContext::noteIoError(const int xerrno
)
1785 if (xerrno
== ETIMEDOUT
)
1786 http
->al
->http
.timedout
= true;
1787 else // even if xerrno is zero (which means read abort/eof)
1788 http
->al
->http
.aborted
= true;
1793 ClientSocketContext::doClose()
1795 clientConnection
->close();
1798 /// called when we encounter a response-related error
1800 ClientSocketContext::initiateClose(const char *reason
)
1802 http
->getConn()->stopSending(reason
); // closes ASAP
1806 ConnStateData::stopSending(const char *error
)
1808 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1809 "; old receiving error: " <<
1810 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1812 if (const char *oldError
= stoppedSending()) {
1813 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1814 return; // nothing has changed as far as this connection is concerned
1816 stoppedSending_
= error
;
1818 if (!stoppedReceiving()) {
1819 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1820 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1821 " request body bytes with " << in
.buf
.length() << " unused");
1822 return; // wait for the request receiver to finish reading
1826 clientConnection
->close();
1830 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
)
1832 const StoreEntry
*entry
= http
->storeEntry();
1833 http
->out
.size
+= size
;
1834 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1835 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1836 (entry
? entry
->objectLen() : 0));
1837 clientUpdateSocketStats(http
->logType
, size
);
1839 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
1841 if (errflag
== Comm::ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1844 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1845 initiateClose("failure or true request status");
1846 /* Do we leak here ? */
1850 switch (socketState()) {
1856 case STREAM_COMPLETE
:
1857 debugs(33, 5, conn
<< "Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1858 if (http
->request
->flags
.proxyKeepalive
)
1859 keepaliveNextRequest();
1861 initiateClose("STREAM_COMPLETE NOKEEPALIVE");
1864 case STREAM_UNPLANNED_COMPLETE
:
1865 initiateClose("STREAM_UNPLANNED_COMPLETE");
1869 initiateClose("STREAM_FAILED");
1873 fatal("Hit unreachable code in clientWriteComplete\n");
1877 ClientSocketContext
*
1878 ConnStateData::abortRequestParsing(const char *const uri
)
1880 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1881 http
->req_sz
= in
.buf
.length();
1882 http
->uri
= xstrdup(uri
);
1883 setLogUri (http
, uri
);
1884 ClientSocketContext
*context
= new ClientSocketContext(clientConnection
, http
);
1885 StoreIOBuffer tempBuffer
;
1886 tempBuffer
.data
= context
->reqbuf
;
1887 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1888 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1889 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1890 clientSocketDetach
, context
, tempBuffer
);
1895 skipLeadingSpace(char *aString
)
1897 char *result
= aString
;
1899 while (xisspace(*aString
))
1906 * 'end' defaults to NULL for backwards compatibility
1907 * remove default value if we ever get rid of NULL-terminated
1911 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1914 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1918 for (; end
> uriAndHTTPVersion
; --end
) {
1919 if (*end
== '\n' || *end
== '\r')
1922 if (xisspace(*end
)) {
1923 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1934 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1936 safe_free(http
->log_uri
);
1939 // The uri is already clean just dump it.
1940 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1943 switch (Config
.uri_whitespace
) {
1944 case URI_WHITESPACE_ALLOW
:
1945 flags
|= RFC1738_ESCAPE_NOSPACE
;
1947 case URI_WHITESPACE_ENCODE
:
1948 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1949 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1952 case URI_WHITESPACE_CHOP
: {
1953 flags
|= RFC1738_ESCAPE_NOSPACE
;
1954 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1955 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1956 int pos
= strcspn(http
->log_uri
, w_space
);
1957 http
->log_uri
[pos
] = '\0';
1961 case URI_WHITESPACE_DENY
:
1962 case URI_WHITESPACE_STRIP
:
1965 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1969 if (!xisspace(*t
)) {
1976 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
1985 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1987 int vhost
= conn
->port
->vhost
;
1988 int vport
= conn
->port
->vport
;
1989 static char ipbuf
[MAX_IPSTRLEN
];
1991 http
->flags
.accel
= true;
1993 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1995 static const SBuf
cache_object("cache_object://");
1996 if (hp
->requestUri().startsWith(cache_object
))
1997 return; /* already in good shape */
1999 // XXX: re-use proper URL parser for this
2000 SBuf url
= hp
->requestUri(); // use full provided URI if we abort
2001 do { // use a loop so we can break out of it
2002 ::Parser::Tokenizer
tok(url
);
2003 if (tok
.skip('/')) // origin-form URL already.
2006 if (conn
->port
->vhost
)
2007 return; /* already in good shape */
2009 // skip the URI scheme
2010 static const CharacterSet uriScheme
= CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
2011 static const SBuf
uriSchemeEnd("://");
2012 if (!tok
.skipAll(uriScheme
) || !tok
.skip(uriSchemeEnd
))
2015 // skip the authority segment
2016 // RFC 3986 complex nested ABNF for "authority" boils down to this:
2017 static const CharacterSet authority
= CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
2018 CharacterSet::HEXDIG
+ CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
2019 if (!tok
.skipAll(authority
))
2022 static const SBuf
slashUri("/");
2023 const SBuf t
= tok
.remaining();
2026 else if (t
[0]=='/') // looks like path
2028 else if (t
[0]=='?' || t
[0]=='#') { // looks like query or fragment. fix '/'
2031 } // else do nothing. invalid path
2035 #if SHOULD_REJECT_UNKNOWN_URLS
2036 // reject URI which are not well-formed even after the processing above
2037 if (url
.isEmpty() || url
[0] != '/') {
2038 hp
->parseStatusCode
= Http::scBadRequest
;
2039 return conn
->abortRequestParsing("error:invalid-request");
2044 vport
= http
->getConn()->clientConnection
->local
.port();
2046 const bool switchedToHttps
= conn
->switchedToHttps();
2047 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2049 if (tryHostHeader
&& (host
= hp
->getHeaderField("Host"))) {
2050 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2055 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2056 strncpy(thost
, host
, (t
-host
));
2057 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2060 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2063 } // else nothing to alter port-wise.
2064 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+ strlen(host
);
2065 http
->uri
= (char *)xcalloc(url_sz
, 1);
2066 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
, AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(url
));
2067 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
2068 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2069 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2070 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
2071 strlen(conn
->port
->defaultsite
);
2072 http
->uri
= (char *)xcalloc(url_sz
, 1);
2076 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2078 snprintf(http
->uri
, url_sz
, "%s://%s%s" SQUIDSBUFPH
,
2079 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
2080 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
2081 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2082 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
2083 /* Put the local socket IP address as the hostname, with whatever vport we found */
2084 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
2085 http
->uri
= (char *)xcalloc(url_sz
, 1);
2086 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2087 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
2088 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(),
2089 ipbuf
, vport
, SQUIDSBUFPRINT(url
));
2090 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
2095 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
2097 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
2098 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
2099 return; /* already in good shape */
2101 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2103 if (const char *host
= hp
->getHeaderField("Host")) {
2104 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
2106 http
->uri
= (char *)xcalloc(url_sz
, 1);
2107 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
,
2108 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(hp
->requestUri()));
2109 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
2111 /* Put the local socket IP address as the hostname. */
2112 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
2113 http
->uri
= (char *)xcalloc(url_sz
, 1);
2114 static char ipbuf
[MAX_IPSTRLEN
];
2115 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2116 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
2117 AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).c_str(),
2118 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SQUIDSBUFPRINT(hp
->requestUri()));
2119 debugs(33, 5, "TRANSPARENT REWRITE: " << http
->uri
);
2123 /** Parse an HTTP request
2125 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2126 * to 1 if the request was correctly parsed.
2127 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2128 * \param[in] hp an Http1::RequestParser
2129 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2130 * Pointed-to value will be set to Http::METHOD_NONE in case of
2132 * \param[out] http_ver will be set as a side-effect of the parsing
2133 * \return NULL on incomplete requests,
2134 * a ClientSocketContext structure on success or failure.
2136 ClientSocketContext
*
2137 parseHttpRequest(ConnStateData
*csd
, const Http1::RequestParserPointer
&hp
)
2139 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
2141 const bool parsedOk
= hp
->parse(csd
->in
.buf
);
2143 if (csd
->port
->flags
.isIntercepted() && Config
.accessList
.on_unsupported_protocol
)
2144 csd
->preservedClientData
= csd
->in
.buf
;
2145 // sync the buffers after parsing.
2146 csd
->in
.buf
= hp
->remaining();
2148 if (hp
->needsMoreData()) {
2149 debugs(33, 5, "Incomplete request, waiting for end of request line");
2154 if (hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
|| hp
->parseStatusCode
== Http::scUriTooLong
)
2155 return csd
->abortRequestParsing("error:request-too-large");
2157 return csd
->abortRequestParsing("error:invalid-request");
2161 /* We know the whole request is in parser now */
2162 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2163 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
2164 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
2168 /* deny CONNECT via accelerated ports */
2169 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
2170 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
2171 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2172 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2173 return csd
->abortRequestParsing("error:method-not-allowed");
2176 /* draft-ietf-httpbis-http2-16 section 11.6 registers the method PRI as HTTP/2 specific
2177 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
2178 * If seen it signals a broken client or proxy has corrupted the traffic.
2180 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
2181 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
2182 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2183 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2184 return csd
->abortRequestParsing("error:method-not-allowed");
2187 if (hp
->method() == Http::METHOD_NONE
) {
2188 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2189 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2190 return csd
->abortRequestParsing("error:unsupported-request-method");
2193 // Process headers after request line
2194 debugs(33, 3, "complete request received. " <<
2195 "prefix_sz = " << hp
->messageHeaderSize() <<
2196 ", request-line-size=" << hp
->firstLineSize() <<
2197 ", mime-header-size=" << hp
->headerBlockSize() <<
2198 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
2200 /* Ok, all headers are received */
2201 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
2203 http
->req_sz
= hp
->messageHeaderSize();
2204 ClientSocketContext
*result
= new ClientSocketContext(csd
->clientConnection
, http
);
2206 StoreIOBuffer tempBuffer
;
2207 tempBuffer
.data
= result
->reqbuf
;
2208 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2210 ClientStreamData newServer
= new clientReplyContext(http
);
2211 ClientStreamData newClient
= result
;
2212 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2213 clientReplyStatus
, newServer
, clientSocketRecipient
,
2214 clientSocketDetach
, newClient
, tempBuffer
);
2217 // XXX: c_str() does re-allocate but here replaces explicit malloc/free.
2218 // when internalCheck() accepts SBuf removing this will be a net gain for performance.
2219 SBuf
tmp(hp
->requestUri());
2220 const char *url
= tmp
.c_str();
2222 debugs(33,5, HERE
<< "repare absolute URL from " <<
2223 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2224 /* Rewrite the URL in transparent or accelerator mode */
2225 /* NP: there are several cases to traverse here:
2226 * - standard mode (forward proxy)
2227 * - transparent mode (TPROXY)
2228 * - transparent mode with failures
2229 * - intercept mode (NAT)
2230 * - intercept mode with failures
2231 * - accelerator mode (reverse proxy)
2233 * - mixed combos of the above with internal URL
2234 * - remote interception with PROXY protocol
2235 * - remote reverse-proxy with PROXY protocol
2237 if (csd
->transparent()) {
2238 /* intercept or transparent mode, properly working with no failures */
2239 prepareTransparentURL(csd
, http
, hp
);
2241 } else if (internalCheck(url
)) {
2242 /* internal URL mode */
2243 /* prepend our name & port */
2244 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2245 // We just re-wrote the URL. Must replace the Host: header.
2246 // But have not parsed there yet!! flag for local-only handling.
2247 http
->flags
.internal
= true;
2249 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2250 /* accelerator mode */
2251 prepareAcceleratedURL(csd
, http
, hp
);
2255 /* No special rewrites have been applied above, use the
2256 * requested url. may be rewritten later, so make extra room */
2257 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
2258 http
->uri
= (char *)xcalloc(url_sz
, 1);
2259 strcpy(http
->uri
, url
);
2262 result
->flags
.parsed_ok
= 1;
2267 ConnStateData::In::maybeMakeSpaceAvailable()
2269 if (buf
.spaceSize() < 2) {
2270 const SBuf::size_type haveCapacity
= buf
.length() + buf
.spaceSize();
2271 if (haveCapacity
>= Config
.maxRequestBufferSize
) {
2272 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2275 if (haveCapacity
== 0) {
2276 // haveCapacity is based on the SBuf visible window of the MemBlob buffer, which may fill up.
2277 // at which point bump the buffer back to default. This allocates a new MemBlob with any un-parsed bytes.
2278 buf
.reserveCapacity(CLIENT_REQ_BUF_SZ
);
2280 const SBuf::size_type wantCapacity
= min(static_cast<SBuf::size_type
>(Config
.maxRequestBufferSize
), haveCapacity
*2);
2281 buf
.reserveCapacity(wantCapacity
);
2283 debugs(33, 2, "growing request buffer: available=" << buf
.spaceSize() << " used=" << buf
.length());
2285 return (buf
.spaceSize() >= 2);
2289 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2291 ClientSocketContext::Pointer
*S
;
2293 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2301 ConnStateData::getConcurrentRequestCount() const
2304 ClientSocketContext::Pointer
*T
;
2306 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2307 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2312 ConnStateData::connFinishedWithConn(int size
)
2315 if (getConcurrentRequestCount() == 0 && in
.buf
.isEmpty()) {
2316 /* no current or pending requests */
2317 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2319 } else if (!Config
.onoff
.half_closed_clients
) {
2320 /* admin doesn't want to support half-closed client sockets */
2321 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2322 notifyAllContexts(0); // no specific error implies abort
2331 ConnStateData::consumeInput(const size_t byteCount
)
2333 assert(byteCount
> 0 && byteCount
<= in
.buf
.length());
2334 in
.buf
.consume(byteCount
);
2335 debugs(33, 5, "in.buf has " << in
.buf
.length() << " unused bytes");
2339 ConnStateData::clientAfterReadingRequests()
2341 // Were we expecting to read more request body from half-closed connection?
2342 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2343 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2344 clientConnection
->close();
2353 ConnStateData::quitAfterError(HttpRequest
*request
)
2355 // From HTTP p.o.v., we do not have to close after every error detected
2356 // at the client-side, but many such errors do require closure and the
2357 // client-side code is bad at handling errors so we play it safe.
2359 request
->flags
.proxyKeepalive
= false;
2360 flags
.readMore
= false;
2361 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2365 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2367 ClientHttpRequest
*http
= context
->http
;
2372 assert(sslServerBump
->entry
);
2373 // Did we create an error entry while processing CONNECT?
2374 if (!sslServerBump
->entry
->isEmpty()) {
2375 quitAfterError(http
->request
);
2377 // Get the saved error entry and send it to the client by replacing the
2378 // ClientHttpRequest store entry with it.
2379 clientStreamNode
*node
= context
->getClientReplyContext();
2380 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2382 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2383 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
2385 // save the original request for logging purposes
2386 if (!context
->http
->al
->request
) {
2387 context
->http
->al
->request
= http
->request
;
2388 HTTPMSGLOCK(context
->http
->al
->request
);
2391 // Get error details from the fake certificate-peeking request.
2392 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2393 context
->pullData();
2397 // In bump-server-first mode, we have not necessarily seen the intended
2398 // server name at certificate-peeking time. Check for domain mismatch now,
2399 // when we can extract the intended name from the bumped HTTP request.
2400 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2401 HttpRequest
*request
= http
->request
;
2402 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2403 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2404 "does not match domainname " << request
->GetHost());
2406 bool allowDomainMismatch
= false;
2407 if (Config
.ssl_client
.cert_error
) {
2408 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2409 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2410 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2411 delete check
.sslErrors
;
2412 check
.sslErrors
= NULL
;
2415 if (!allowDomainMismatch
) {
2416 quitAfterError(request
);
2418 clientStreamNode
*node
= context
->getClientReplyContext();
2419 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2420 assert (repContext
);
2422 // Fill the server IP and hostname for error page generation.
2423 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2424 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2426 // Create an error object and fill it
2427 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2428 err
->src_addr
= clientConnection
->remote
;
2429 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2430 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2432 err
->detail
= errDetail
;
2433 // Save the original request for logging purposes.
2434 if (!context
->http
->al
->request
) {
2435 context
->http
->al
->request
= request
;
2436 HTTPMSGLOCK(context
->http
->al
->request
);
2438 repContext
->setReplyToError(request
->method
, err
);
2439 assert(context
->http
->out
.offset
== 0);
2440 context
->pullData();
2448 #endif // USE_OPENSSL
2451 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
2452 * or false otherwise
2455 clientTunnelOnError(ConnStateData
*conn
, ClientSocketContext
*context
, HttpRequest
*request
, const HttpRequestMethod
& method
, err_type requestError
, Http::StatusCode errStatusCode
, const char *requestErrorBytes
)
2457 if (conn
->port
->flags
.isIntercepted() &&
2458 Config
.accessList
.on_unsupported_protocol
&& conn
->nrequests
<= 1) {
2459 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
, NULL
);
2460 checklist
.requestErrorType
= requestError
;
2461 checklist
.src_addr
= conn
->clientConnection
->remote
;
2462 checklist
.my_addr
= conn
->clientConnection
->local
;
2463 checklist
.conn(conn
);
2464 allow_t answer
= checklist
.fastCheck();
2465 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
2466 debugs(33, 3, "Request will be tunneled to server");
2468 context
->removeFromConnectionList(conn
);
2469 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2472 if (conn
->preservedClientData
.length())
2473 preReadData
.append(conn
->preservedClientData
);
2474 static char ip
[MAX_IPSTRLEN
];
2475 conn
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
2476 conn
->in
.buf
.assign("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n").append(preReadData
);
2478 bool ret
= conn
->handleReadData();
2480 ret
= conn
->clientParseRequests();
2483 debugs(33, 2, "Failed to start fake CONNECT request for on_unsupported_protocol: " << conn
->clientConnection
);
2484 conn
->clientConnection
->close();
2488 debugs(33, 3, "Continue with returning the error: " << requestError
);
2493 conn
->quitAfterError(request
);
2494 clientStreamNode
*node
= context
->getClientReplyContext();
2495 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2496 assert (repContext
);
2498 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
2500 assert(context
->http
->out
.offset
== 0);
2501 context
->pullData();
2502 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
2507 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
2511 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2512 * to here because calling comm_reset_close() causes http to
2513 * be freed before accessing.
2515 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2516 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2517 conn
->flags
.readMore
= false;
2518 comm_reset_close(conn
->clientConnection
);
2523 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, ClientSocketContext
*context
)
2525 ClientHttpRequest
*http
= context
->http
;
2526 bool chunked
= false;
2527 bool mustReplyToOptions
= false;
2528 bool unsupportedTe
= false;
2529 bool expectBody
= false;
2531 // We already have the request parsed and checked, so we
2532 // only need to go through the final body/conn setup to doCallouts().
2533 assert(http
->request
);
2534 HttpRequest::Pointer request
= http
->request
;
2536 // temporary hack to avoid splitting this huge function with sensitive code
2537 const bool isFtp
= !hp
;
2539 // Some blobs below are still HTTP-specific, but we would have to rewrite
2540 // this entire function to remove them from the FTP code path. Connection
2541 // setup and body_pipe preparation blobs are needed for FTP.
2543 request
->clientConnectionManager
= conn
;
2545 request
->flags
.accelerated
= http
->flags
.accel
;
2546 request
->flags
.sslBumped
=conn
->switchedToHttps();
2547 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2548 // TODO: decouple http->flags.accel from request->flags.sslBumped
2549 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2550 !conn
->port
->allow_direct
: 0;
2552 if (request
->flags
.sslBumped
) {
2553 if (conn
->getAuth() != NULL
)
2554 request
->auth_user_request
= conn
->getAuth();
2559 * If transparent or interception mode is working clone the transparent and interception flags
2560 * from the port settings to the request.
2562 if (http
->clientConnection
!= NULL
) {
2563 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2564 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2565 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
2566 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
2567 if (Config
.accessList
.spoof_client_ip
) {
2568 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2569 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2572 request
->flags
.spoofClientIp
= true;
2574 request
->flags
.spoofClientIp
= false;
2577 if (internalCheck(request
->urlpath
.termedBuf())) {
2578 if (internalHostnameIs(request
->GetHost()) && request
->port
== getMyPort()) {
2579 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2580 ':' << request
->port
);
2581 http
->flags
.internal
= true;
2582 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2583 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2584 ':' << request
->port
<< " (global_internal_static on)");
2585 request
->SetHost(internalHostname());
2586 request
->port
= getMyPort();
2587 http
->flags
.internal
= true;
2589 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2590 ':' << request
->port
<< " (not this proxy)");
2593 request
->flags
.internal
= http
->flags
.internal
;
2594 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2595 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2596 #if FOLLOW_X_FORWARDED_FOR
2597 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2598 // not a details about teh TCP connection itself
2599 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2600 #endif /* FOLLOW_X_FORWARDED_FOR */
2601 request
->my_addr
= conn
->clientConnection
->local
;
2602 request
->myportname
= conn
->port
->name
;
2605 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
2606 // for now Squid only supports HTTP requests
2607 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
2608 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
2609 request
->http_ver
.major
= http_ver
.major
;
2610 request
->http_ver
.minor
= http_ver
.minor
;
2613 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2614 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2615 request
->clientConnectionManager
= conn
;
2617 if (request
->header
.chunked()) {
2619 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2620 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2621 // HTTP/1.1 requires chunking to be the last encoding if there is one
2622 unsupportedTe
= te
.size() && te
!= "identity";
2623 } // else implied identity coding
2625 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
2626 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2627 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2628 clientStreamNode
*node
= context
->getClientReplyContext();
2629 conn
->quitAfterError(request
.getRaw());
2630 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2631 assert (repContext
);
2632 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2633 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2634 assert(context
->http
->out
.offset
== 0);
2635 context
->pullData();
2636 clientProcessRequestFinished(conn
, request
);
2640 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2641 clientStreamNode
*node
= context
->getClientReplyContext();
2642 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2643 assert (repContext
);
2644 conn
->quitAfterError(request
.getRaw());
2645 repContext
->setReplyToError(ERR_INVALID_REQ
,
2646 Http::scLengthRequired
, request
->method
, NULL
,
2647 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2648 assert(context
->http
->out
.offset
== 0);
2649 context
->pullData();
2650 clientProcessRequestFinished(conn
, request
);
2654 clientSetKeepaliveFlag(http
);
2655 // Let tunneling code be fully responsible for CONNECT requests
2656 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2657 context
->mayUseConnection(true);
2658 conn
->flags
.readMore
= false;
2662 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
2663 clientProcessRequestFinished(conn
, request
);
2668 /* Do we expect a request-body? */
2669 expectBody
= chunked
|| request
->content_length
> 0;
2670 if (!context
->mayUseConnection() && expectBody
) {
2671 request
->body_pipe
= conn
->expectRequestBody(
2672 chunked
? -1 : request
->content_length
);
2674 /* Is it too large? */
2675 if (!chunked
&& // if chunked, we will check as we accumulate
2676 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2677 clientStreamNode
*node
= context
->getClientReplyContext();
2678 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2679 assert (repContext
);
2680 conn
->quitAfterError(request
.getRaw());
2681 repContext
->setReplyToError(ERR_TOO_BIG
,
2682 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
2683 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2684 assert(context
->http
->out
.offset
== 0);
2685 context
->pullData();
2686 clientProcessRequestFinished(conn
, request
);
2691 // We may stop producing, comm_close, and/or call setReplyToError()
2692 // below, so quit on errors to avoid http->doCallouts()
2693 if (!conn
->handleRequestBodyData()) {
2694 clientProcessRequestFinished(conn
, request
);
2698 if (!request
->body_pipe
->productionEnded()) {
2699 debugs(33, 5, "need more request body");
2700 context
->mayUseConnection(true);
2701 assert(conn
->flags
.readMore
);
2706 http
->calloutContext
= new ClientRequestContext(http
);
2710 clientProcessRequestFinished(conn
, request
);
2714 ConnStateData::pipelinePrefetchMax() const
2716 return Config
.pipeline_max_prefetch
;
2720 * Limit the number of concurrent requests.
2721 * \return true when there are available position(s) in the pipeline queue for another request.
2722 * \return false when the pipeline queue is full or disabled.
2725 ConnStateData::concurrentRequestQueueFilled() const
2727 const int existingRequestCount
= getConcurrentRequestCount();
2729 // default to the configured pipeline size.
2730 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2732 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
2734 const int internalRequest
= 0;
2736 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
2738 // when queue filled already we cant add more.
2739 if (existingRequestCount
>= concurrentRequestLimit
) {
2740 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2741 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2749 * Perform proxy_protocol_access ACL tests on the client which
2750 * connected to PROXY protocol port to see if we trust the
2751 * sender enough to accept their PROXY header claim.
2754 ConnStateData::proxyProtocolValidateClient()
2756 if (!Config
.accessList
.proxyProtocol
)
2757 return proxyProtocolError("PROXY client not permitted by default ACL");
2759 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
2760 ch
.src_addr
= clientConnection
->remote
;
2761 ch
.my_addr
= clientConnection
->local
;
2764 if (ch
.fastCheck() != ACCESS_ALLOWED
)
2765 return proxyProtocolError("PROXY client not permitted by ACLs");
2771 * Perform cleanup on PROXY protocol errors.
2772 * If header parsing hits a fatal error terminate the connection,
2773 * otherwise wait for more data.
2776 ConnStateData::proxyProtocolError(const char *msg
)
2779 // This is important to know, but maybe not so much that flooding the log is okay.
2780 #if QUIET_PROXY_PROTOCOL
2781 // display the first of every 32 occurances at level 1, the others at level 2.
2782 static uint8_t hide
= 0;
2783 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
2785 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
2792 /// magic octet prefix for PROXY protocol version 1
2793 static const SBuf
Proxy1p0magic("PROXY ", 6);
2795 /// magic octet prefix for PROXY protocol version 2
2796 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
2799 * Test the connection read buffer for PROXY protocol header.
2800 * Version 1 and 2 header currently supported.
2803 ConnStateData::parseProxyProtocolHeader()
2805 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
2807 // detect and parse PROXY/2.0 protocol header
2808 if (in
.buf
.startsWith(Proxy2p0magic
))
2809 return parseProxy2p0();
2811 // detect and parse PROXY/1.0 protocol header
2812 if (in
.buf
.startsWith(Proxy1p0magic
))
2813 return parseProxy1p0();
2815 // detect and terminate other protocols
2816 if (in
.buf
.length() >= Proxy2p0magic
.length()) {
2817 // PROXY/1.0 magic is shorter, so we know that
2818 // the input does not start with any PROXY magic
2819 return proxyProtocolError("PROXY protocol error: invalid header");
2822 // TODO: detect short non-magic prefixes earlier to avoid
2823 // waiting for more data which may never come
2825 // not enough bytes to parse yet.
2829 /// parse the PROXY/1.0 protocol header from the connection read buffer
2831 ConnStateData::parseProxy1p0()
2833 ::Parser::Tokenizer
tok(in
.buf
);
2834 tok
.skip(Proxy1p0magic
);
2836 // skip to first LF (assumes it is part of CRLF)
2837 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
2839 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
2840 if (tok
.skip('\n')) {
2841 // found valid header
2842 in
.buf
= tok
.remaining();
2843 needProxyProtocolHeader_
= false;
2844 // reset the tokenizer to work on found line only.
2847 return false; // no LF yet
2849 } else // protocol error only if there are more than 107 bytes prefix header
2850 return proxyProtocolError(in
.buf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
2852 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
2853 if (tok
.skip(tcpName
)) {
2855 // skip TCP/IP version number
2856 static const CharacterSet
tcpVersions("TCP-version","46");
2857 if (!tok
.skipOne(tcpVersions
))
2858 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
2860 // skip SP after protocol version
2862 return proxyProtocolError("PROXY/1.0 error: missing SP");
2865 int64_t porta
, portb
;
2866 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
2868 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
2869 // leave the LF until later.
2870 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
2871 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
2872 tok
.int64(porta
) && tok
.skip(' ') &&
2876 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
2878 // parse IP and port strings
2879 Ip::Address originalClient
, originalDest
;
2881 if (!originalClient
.GetHostByName(ipa
.c_str()))
2882 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
2884 if (!originalDest
.GetHostByName(ipb
.c_str()))
2885 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
2887 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
2888 originalClient
.port(static_cast<uint16_t>(porta
));
2890 return proxyProtocolError("PROXY/1.0 error: invalid src port");
2892 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
2893 originalDest
.port(static_cast<uint16_t>(portb
));
2895 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
2897 // we have original client and destination details now
2898 // replace the client connection values
2899 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
2900 clientConnection
->local
= originalDest
;
2901 clientConnection
->remote
= originalClient
;
2902 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2903 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2905 // repeat fetch ensuring the new client FQDN can be logged
2906 if (Config
.onoff
.log_fqdn
)
2907 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2911 } else if (tok
.skip(unknown
)) {
2912 // found valid but unusable header
2916 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2921 /// parse the PROXY/2.0 protocol header from the connection read buffer
2923 ConnStateData::parseProxy2p0()
2925 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2926 if (in
.buf
.length() < prefixLen
+ 4)
2927 return false; // need more bytes
2929 if ((in
.buf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2930 return proxyProtocolError("PROXY/2.0 error: invalid version");
2932 const char command
= (in
.buf
[prefixLen
] & 0x0F);
2933 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2934 return proxyProtocolError("PROXY/2.0 error: invalid command");
2936 const char family
= (in
.buf
[prefixLen
+1] & 0xF0) >>4;
2937 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2938 return proxyProtocolError("PROXY/2.0 error: invalid family");
2940 const char proto
= (in
.buf
[prefixLen
+1] & 0x0F);
2941 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2942 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2944 const char *clen
= in
.buf
.rawContent() + prefixLen
+ 2;
2946 memcpy(&len
, clen
, sizeof(len
));
2949 if (in
.buf
.length() < prefixLen
+ 4 + len
)
2950 return false; // need more bytes
2952 in
.buf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2953 const SBuf extra
= in
.buf
.consume(len
);
2954 needProxyProtocolHeader_
= false; // found successfully
2956 // LOCAL connections do nothing with the extras
2957 if (command
== 0x00/* LOCAL*/)
2961 struct { /* for TCP/UDP over IPv4, len = 12 */
2962 struct in_addr src_addr
;
2963 struct in_addr dst_addr
;
2967 struct { /* for TCP/UDP over IPv6, len = 36 */
2968 struct in6_addr src_addr
;
2969 struct in6_addr dst_addr
;
2974 struct { /* for AF_UNIX sockets, len = 216 */
2975 uint8_t src_addr
[108];
2976 uint8_t dst_addr
[108];
2982 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2984 // replace the client connection values
2985 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2988 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2989 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2990 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2991 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2992 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2995 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2996 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2997 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2998 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2999 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
3001 default: // do nothing
3004 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
3006 // repeat fetch ensuring the new client FQDN can be logged
3007 if (Config
.onoff
.log_fqdn
)
3008 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3014 ConnStateData::receivedFirstByte()
3016 if (receivedFirstByte_
)
3019 receivedFirstByte_
= true;
3020 // Set timeout to Config.Timeout.request
3021 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3022 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3023 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3024 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3028 * Attempt to parse one or more requests from the input buffer.
3029 * Returns true after completing parsing of at least one request [header]. That
3030 * includes cases where parsing ended with an error (e.g., a huge request).
3033 ConnStateData::clientParseRequests()
3035 bool parsed_req
= false;
3037 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
3039 // Loop while we have read bytes that are not needed for producing the body
3040 // On errors, bodyPipe may become nil, but readMore will be cleared
3041 while (!in
.buf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
3043 /* Don't try to parse if the buffer is empty */
3044 if (in
.buf
.isEmpty())
3047 /* Limit the number of concurrent requests */
3048 if (concurrentRequestQueueFilled())
3051 /*Do not read more requests if persistent connection lifetime exceeded*/
3052 if (Config
.Timeout
.pconnLifetime
&& clientConnection
->lifeTime() > Config
.Timeout
.pconnLifetime
) {
3053 flags
.readMore
= false;
3057 // try to parse the PROXY protocol header magic bytes
3058 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
3061 if (ClientSocketContext
*context
= parseOneRequest()) {
3062 debugs(33, 5, clientConnection
<< ": done parsing a request");
3064 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3065 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
3066 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3068 context
->registerWithConn();
3070 processParsedRequest(context
);
3072 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3074 if (context
->mayUseConnection()) {
3075 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3079 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
3080 in
.buf
.length() << " < " << Config
.maxRequestHeaderSize
);
3081 Must(in
.buf
.length() < Config
.maxRequestHeaderSize
);
3086 /* XXX where to 'finish' the parsing pass? */
3091 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3093 debugs(33,5, io
.conn
);
3097 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
3098 if (io
.flag
== Comm::ERR_CLOSING
) {
3099 debugs(33,5, io
.conn
<< " closing Bailout.");
3103 assert(Comm::IsConnOpen(clientConnection
));
3104 assert(io
.conn
->fd
== clientConnection
->fd
);
3107 * Don't reset the timeout value here. The value should be
3108 * counting Config.Timeout.request and applies to the request
3109 * as a whole, not individual read() calls.
3110 * Plus, it breaks our lame *HalfClosed() detection
3113 CommIoCbParams
rd(this); // will be expanded with ReadNow results
3115 switch (Comm::ReadNow(rd
, in
.buf
)) {
3116 case Comm::INPROGRESS
:
3117 if (in
.buf
.isEmpty())
3118 debugs(33, 2, io
.conn
<< ": no data to process, " << xstrerr(rd
.xerrno
));
3123 kb_incr(&(statCounter
.client_http
.kbytes_in
), rd
.size
);
3124 if (!receivedFirstByte_
)
3125 receivedFirstByte();
3126 // may comm_close or setReplyToError
3127 if (!handleReadData())
3130 /* Continue to process previously read data */
3133 case Comm::ENDFILE
: // close detected by 0-byte read
3134 debugs(33, 5, io
.conn
<< " closed?");
3136 if (connFinishedWithConn(rd
.size
)) {
3137 clientConnection
->close();
3141 /* It might be half-closed, we can't tell */
3142 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3143 commMarkHalfClosed(io
.conn
->fd
);
3144 fd_note(io
.conn
->fd
, "half-closed");
3146 /* There is one more close check at the end, to detect aborted
3147 * (partial) requests. At this point we can't tell if the request
3151 /* Continue to process previously read data */
3154 // case Comm::COMM_ERROR:
3155 default: // no other flags should ever occur
3156 debugs(33, 2, io
.conn
<< ": got flag " << rd
.flag
<< "; " << xstrerr(rd
.xerrno
));
3157 notifyAllContexts(rd
.xerrno
);
3162 /* Process next request */
3163 if (getConcurrentRequestCount() == 0)
3164 fd_note(io
.fd
, "Reading next request");
3166 if (!clientParseRequests()) {
3170 * If the client here is half closed and we failed
3171 * to parse a request, close the connection.
3172 * The above check with connFinishedWithConn() only
3173 * succeeds _if_ the buffer is empty which it won't
3174 * be if we have an incomplete request.
3175 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3177 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3178 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3179 clientConnection
->close();
3187 clientAfterReadingRequests();
3191 * called when new request data has been read from the socket
3193 * \retval false called comm_close or setReplyToError (the caller should bail)
3194 * \retval true we did not call comm_close or setReplyToError
3197 ConnStateData::handleReadData()
3199 // if we are reading a body, stuff data into the body pipe
3200 if (bodyPipe
!= NULL
)
3201 return handleRequestBodyData();
3206 * called when new request body data has been buffered in in.buf
3207 * may close the connection if we were closing and piped everything out
3209 * \retval false called comm_close or setReplyToError (the caller should bail)
3210 * \retval true we did not call comm_close or setReplyToError
3213 ConnStateData::handleRequestBodyData()
3215 assert(bodyPipe
!= NULL
);
3219 if (in
.bodyParser
) { // chunked encoding
3220 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3221 abortChunkedRequestBody(error
);
3224 } else { // identity encoding
3225 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3226 putSize
= bodyPipe
->putMoreData(in
.buf
.c_str(), in
.buf
.length());
3227 if (!bodyPipe
->mayNeedMoreData()) {
3228 // BodyPipe will clear us automagically when we produced everything
3234 consumeInput(putSize
);
3237 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3239 if (const char *reason
= stoppedSending()) {
3240 /* we've finished reading like good clients,
3241 * now do the close that initiateClose initiated.
3243 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3244 clientConnection
->close();
3252 /// parses available chunked encoded body bytes, checks size, returns errors
3254 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3256 debugs(33, 7, "chunked from " << clientConnection
<< ": " << in
.buf
.length());
3258 try { // the parser will throw on errors
3260 if (in
.buf
.isEmpty()) // nothing to do
3263 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3264 // add one because MemBuf will assert if it cannot 0-terminate
3265 raw
.init(in
.buf
.length(), in
.buf
.length()+1);
3266 raw
.append(in
.buf
.c_str(), in
.buf
.length());
3268 const mb_size_t wasContentSize
= raw
.contentSize();
3269 BodyPipeCheckout
bpc(*bodyPipe
);
3270 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3272 putSize
= wasContentSize
- raw
.contentSize();
3274 // dechunk then check: the size limit applies to _dechunked_ content
3275 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3279 finishDechunkingRequest(true);
3281 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3284 // if chunk parser needs data, then the body pipe must need it too
3285 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3287 // if parser needs more space and we can consume nothing, we will stall
3288 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3289 } catch (...) { // TODO: be more specific
3290 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3291 return ERR_INVALID_REQ
;
3294 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3298 /// quit on errors related to chunked request body handling
3300 ConnStateData::abortChunkedRequestBody(const err_type error
)
3302 finishDechunkingRequest(false);
3304 // XXX: The code below works if we fail during initial request parsing,
3305 // but if we fail when the server connection is used already, the server may send
3306 // us its response too, causing various assertions. How to prevent that?
3307 #if WE_KNOW_HOW_TO_SEND_ERRORS
3308 ClientSocketContext::Pointer context
= getCurrentContext();
3309 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3310 clientStreamNode
*node
= context
->getClientReplyContext();
3311 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3313 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3314 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
3315 repContext
->setReplyToError(error
, scode
,
3316 repContext
->http
->request
->method
,
3317 repContext
->http
->uri
,
3319 repContext
->http
->request
,
3321 context
->pullData();
3323 // close or otherwise we may get stuck as nobody will notice the error?
3324 comm_reset_close(clientConnection
);
3327 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3328 comm_reset_close(clientConnection
);
3330 flags
.readMore
= false;
3334 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3336 // request reader may get stuck waiting for space if nobody consumes body
3337 if (bodyPipe
!= NULL
)
3338 bodyPipe
->enableAutoConsumption();
3343 /** general lifetime handler for HTTP requests */
3345 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3347 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
3349 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
3350 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
3351 receivedFirstByte();
3354 } else if (fd_table
[io
.conn
->fd
].ssl
== NULL
)
3357 const HttpRequestMethod method
;
3358 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
3359 // Tunnel established. Set receivedFirstByte to avoid loop.
3360 receivedFirstByte();
3366 * Just close the connection to not confuse browsers
3367 * using persistent connections. Some browsers open
3368 * a connection and then do not use it until much
3369 * later (presumeably because the request triggering
3370 * the open has already been completed on another
3373 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3378 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3380 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3381 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3382 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3383 http
->al
->http
.timedout
= true;
3384 if (Comm::IsConnOpen(io
.conn
))
3388 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3389 AsyncJob("ConnStateData"), // kids overwrite
3392 sslBumpMode(Ssl::bumpEnd
),
3394 needProxyProtocolHeader_(false),
3396 switchedToHttps_(false),
3397 sslServerBump(NULL
),
3398 signAlgorithm(Ssl::algSignTrusted
),
3400 stoppedSending_(NULL
),
3401 stoppedReceiving_(NULL
),
3402 receivedFirstByte_(false)
3404 flags
.readMore
= true; // kids may overwrite
3405 flags
.swanSang
= false;
3407 pinning
.host
= NULL
;
3409 pinning
.pinned
= false;
3410 pinning
.auth
= false;
3411 pinning
.zeroReply
= false;
3412 pinning
.peer
= NULL
;
3414 // store the details required for creating more MasterXaction objects as new requests come in
3415 clientConnection
= xact
->tcpClient
;
3416 port
= xact
->squidPort
;
3417 transferProtocol
= port
->transport
; // default to the *_port protocol= setting. may change later.
3418 log_addr
= xact
->tcpClient
->remote
;
3419 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3423 ConnStateData::start()
3425 BodyProducer::start();
3426 HttpControlMsgSink::start();
3428 // ensure a buffer is present for this connection
3429 in
.maybeMakeSpaceAvailable();
3431 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3432 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3433 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3434 int i
= IP_PMTUDISC_DONT
;
3435 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3436 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3438 static bool reported
= false;
3441 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3447 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3448 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3449 comm_add_close_handler(clientConnection
->fd
, call
);
3451 if (Config
.onoff
.log_fqdn
)
3452 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3455 if (Ident::TheConfig
.identLookup
) {
3456 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3457 identChecklist
.src_addr
= clientConnection
->remote
;
3458 identChecklist
.my_addr
= clientConnection
->local
;
3459 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3460 Ident::Start(clientConnection
, clientIdentDone
, this);
3464 clientdbEstablished(clientConnection
->remote
, 1);
3466 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
3467 if (needProxyProtocolHeader_
) {
3468 if (!proxyProtocolValidateClient()) // will close the connection on failure
3473 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
3475 if (Config
.onoff
.client_db
) {
3476 /* it was said several times that client write limiter does not work if client_db is disabled */
3478 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3479 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3481 // TODO: we check early to limit error response bandwith but we
3482 // should recheck when we can honor delay_pool_uses_indirect
3483 // TODO: we should also pass the port details for myportname here.
3484 ch
.src_addr
= clientConnection
->remote
;
3485 ch
.my_addr
= clientConnection
->local
;
3487 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3489 /* pools require explicit 'allow' to assign a client into them */
3490 if (pools
[pool
].access
) {
3491 ch
.accessList
= pools
[pool
].access
;
3492 allow_t answer
= ch
.fastCheck();
3493 if (answer
== ACCESS_ALLOWED
) {
3495 /* request client information from db after we did all checks
3496 this will save hash lookup if client failed checks */
3497 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
3500 /* put client info in FDE */
3501 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
3503 /* setup write limiter for this request */
3504 const double burst
= floor(0.5 +
3505 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3506 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3509 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3516 // kids must extend to actually start doing something (e.g., reading)
3519 /** Handle a new connection on an HTTP socket. */
3521 httpAccept(const CommAcceptCbParams
¶ms
)
3523 MasterXaction::Pointer xact
= params
.xaction
;
3524 AnyP::PortCfgPointer s
= xact
->squidPort
;
3526 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3528 if (params
.flag
!= Comm::OK
) {
3529 // Its possible the call was still queued when the client disconnected
3530 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3534 debugs(33, 4, params
.conn
<< ": accepted");
3535 fd_note(params
.conn
->fd
, "client http connect");
3537 if (s
->tcp_keepalive
.enabled
)
3538 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3540 ++incoming_sockets_accepted
;
3542 // Socket is ready, setup the connection manager to start using it
3543 ConnStateData
*connState
= Http::NewServer(xact
);
3544 AsyncJob::Start(connState
); // usually async-calls readSomeData()
3549 /** Create SSL connection structure and update fd_table */
3551 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3553 if (SSL
*ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
3554 debugs(33, 5, "will negotate SSL on " << conn
);
3564 * \retval 1 on success
3565 * \retval 0 when needs more data
3566 * \retval -1 on error
3569 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
3571 int fd
= conn
->clientConnection
->fd
;
3572 SSL
*ssl
= fd_table
[fd
].ssl
;
3575 if ((ret
= SSL_accept(ssl
)) <= 0) {
3576 int ssl_error
= SSL_get_error(ssl
, ret
);
3578 switch (ssl_error
) {
3580 case SSL_ERROR_WANT_READ
:
3581 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, conn
, 0);
3584 case SSL_ERROR_WANT_WRITE
:
3585 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, conn
, 0);
3588 case SSL_ERROR_SYSCALL
:
3591 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
3595 if (errno
== ECONNRESET
)
3598 debugs(83, hard
? 1 : 2, "Error negotiating SSL connection on FD " <<
3599 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3603 case SSL_ERROR_ZERO_RETURN
:
3604 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3608 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
3609 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3610 " (" << ssl_error
<< "/" << ret
<< ")");
3619 /** negotiate an SSL connection */
3621 clientNegotiateSSL(int fd
, void *data
)
3623 ConnStateData
*conn
= (ConnStateData
*)data
;
3625 SSL
*ssl
= fd_table
[fd
].ssl
;
3628 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
3629 if (ret
< 0) // An error
3634 if (SSL_session_reused(ssl
)) {
3635 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3636 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3638 if (do_debug(83, 4)) {
3639 /* Write out the SSL session details.. actually the call below, but
3640 * OpenSSL headers do strange typecasts confusing GCC.. */
3641 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3642 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3643 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
);
3645 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3647 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3648 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3649 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3650 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3651 * Because there are two possible usable cast, if you get an error here, try the other
3652 * commented line. */
3654 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3655 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3659 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3662 /* Note: This does not automatically fflush the log file.. */
3665 debugs(83, 2, "clientNegotiateSSL: New session " <<
3666 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3667 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3671 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3672 SSL_get_cipher(ssl
));
3674 client_cert
= SSL_get_peer_certificate(ssl
);
3676 if (client_cert
!= NULL
) {
3677 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3678 " client certificate: subject: " <<
3679 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3681 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3682 " client certificate: issuer: " <<
3683 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3685 X509_free(client_cert
);
3687 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3688 " has no certificate.");
3691 conn
->readSomeData();
3695 * If SSL_CTX is given, starts reading the SSL handshake.
3696 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3699 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3703 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3705 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3708 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3709 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3710 connState
, ConnStateData::requestTimeout
);
3711 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3714 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3716 char buf
[MAX_IPSTRLEN
];
3717 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3718 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3719 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3720 fakeRequest
->port
= details
->local
.port();
3721 fakeRequest
->clientConnectionManager
= connState
;
3722 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3723 #if FOLLOW_X_FORWARDED_FOR
3724 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3726 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3727 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3728 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3729 fakeRequest
->myportname
= connState
->port
->name
;
3730 if (fakeRequest
->flags
.interceptTproxy
) {
3731 if (Config
.accessList
.spoof_client_ip
) {
3732 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3733 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3735 fakeRequest
->flags
.spoofClientIp
= true;
3737 fakeRequest
->flags
.spoofClientIp
= false;
3738 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3739 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3744 * A callback function to use with the ACLFilledChecklist callback.
3745 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3746 * else reverts the connection to tunnel mode.
3749 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3751 ConnStateData
*connState
= (ConnStateData
*) data
;
3753 // if the connection is closed or closing, just return.
3754 if (!connState
->isOpen())
3757 // Require both a match and a positive bump mode to work around exceptional
3758 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3759 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
3760 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
3761 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3763 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3764 connState
->sslBumpMode
= Ssl::bumpNone
;
3767 // fake a CONNECT request to force connState to tunnel
3768 static char ip
[MAX_IPSTRLEN
];
3769 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3770 // Pre-pend this fake request to the TLS bits already in the buffer
3772 retStr
.append("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n");
3773 connState
->in
.buf
= retStr
.append(connState
->in
.buf
);
3774 bool ret
= connState
->handleReadData();
3776 ret
= connState
->clientParseRequests();
3779 debugs(33, 2, "Failed to start fake CONNECT request for SSL bumped connection: " << connState
->clientConnection
);
3780 connState
->clientConnection
->close();
3784 /** handle a new HTTPS connection */
3786 httpsAccept(const CommAcceptCbParams
¶ms
)
3788 MasterXaction::Pointer xact
= params
.xaction
;
3789 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3791 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3793 if (params
.flag
!= Comm::OK
) {
3794 // Its possible the call was still queued when the client disconnected
3795 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3799 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3800 fd_note(params
.conn
->fd
, "client https connect");
3802 if (s
->tcp_keepalive
.enabled
) {
3803 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3806 ++incoming_sockets_accepted
;
3808 // Socket is ready, setup the connection manager to start using it
3809 ConnStateData
*connState
= Https::NewServer(xact
);
3810 AsyncJob::Start(connState
); // usually async-calls postHttpsAccept()
3814 ConnStateData::postHttpsAccept()
3816 if (port
->flags
.tunnelSslBumping
) {
3817 debugs(33, 5, "accept transparent connection: " << clientConnection
);
3819 if (!Config
.accessList
.ssl_bump
) {
3820 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
3824 // Create a fake HTTP request for ssl_bump ACL check,
3825 // using tproxy/intercept provided destination IP and port.
3826 HttpRequest
*request
= new HttpRequest();
3827 static char ip
[MAX_IPSTRLEN
];
3828 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3829 request
->SetHost(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
3830 request
->port
= clientConnection
->local
.port();
3831 request
->myportname
= port
->name
;
3833 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3834 acl_checklist
->src_addr
= clientConnection
->remote
;
3835 acl_checklist
->my_addr
= port
->s
;
3836 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
3839 SSL_CTX
*sslContext
= port
->staticSslContext
.get();
3840 httpsEstablish(this, sslContext
, Ssl::bumpNone
);
3845 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
3847 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3848 state_data
->sslCrtdHandleReply(reply
);
3852 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
3854 if (reply
.result
== Helper::BrokenHelper
) {
3855 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3856 } else if (!reply
.other().hasContent()) {
3857 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3859 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3860 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3861 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3863 if (reply
.result
!= Helper::Okay
) {
3864 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3866 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3867 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3868 doPeekAndSpliceStep();
3869 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
3870 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
3872 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3874 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3875 getSslContextDone(ctx
, true);
3881 getSslContextDone(NULL
);
3884 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3886 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3888 // fake certificate adaptation requires bump-server-first mode
3889 if (!sslServerBump
) {
3890 assert(port
->signingCert
.get());
3891 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3892 if (port
->signPkey
.get())
3893 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3894 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3898 // In case of an error while connecting to the secure server, use a fake
3899 // trusted certificate, with no mimicked fields and no adaptation
3900 // algorithms. There is nothing we can mimic so we want to minimize the
3901 // number of warnings the user will have to see to get to the error page.
3902 assert(sslServerBump
->entry
);
3903 if (sslServerBump
->entry
->isEmpty()) {
3904 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3905 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3907 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3908 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3909 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3911 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3912 // If the algorithm already set, then ignore it.
3913 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3914 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3915 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3918 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3919 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3920 const char *param
= ca
->param
;
3922 // For parameterless CN adaptation, use hostname from the
3924 if (ca
->alg
== Ssl::algSetCommonName
) {
3926 param
= sslConnectHostOrIp
.termedBuf();
3927 certProperties
.commonName
= param
;
3928 certProperties
.setCommonName
= true;
3929 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3930 certProperties
.setValidAfter
= true;
3931 else if (ca
->alg
== Ssl::algSetValidBefore
)
3932 certProperties
.setValidBefore
= true;
3934 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3935 alg
<< " param: " << (param
? param
: "-"));
3939 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3940 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3941 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3942 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3946 } else {// if (!sslServerBump->entry->isEmpty())
3947 // Use trusted certificate for a Squid-generated error
3948 // or the user would have to add a security exception
3949 // just to see the error page. We will close the connection
3950 // so that the trust is not extended to non-Squid content.
3951 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3954 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3956 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3957 assert(port
->untrustedSigningCert
.get());
3958 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3959 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3961 assert(port
->signingCert
.get());
3962 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3964 if (port
->signPkey
.get())
3965 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3967 signAlgorithm
= certProperties
.signAlgorithm
;
3969 certProperties
.signHash
= Ssl::DefaultSignHash
;
3973 ConnStateData::getSslContextStart()
3975 assert(areAllContextsForThisConnection());
3977 /* careful: freeAllContexts() above frees request, host, etc. */
3979 if (port
->generateHostCertificates
) {
3980 Ssl::CertificateProperties certProperties
;
3981 buildSslCertGenerationParams(certProperties
);
3982 sslBumpCertKey
= certProperties
.dbKey().c_str();
3983 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3985 // Disable caching for bumpPeekAndSplice mode
3986 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
3987 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3988 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3989 SSL_CTX
* dynCtx
= NULL
;
3990 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3991 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3992 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3993 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3994 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3995 getSslContextDone(dynCtx
);
3998 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
4000 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
4003 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
4009 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
4010 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
4011 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
4012 request_message
.composeRequest(certProperties
);
4013 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
4014 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
4016 } catch (const std::exception
&e
) {
4017 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
4018 "request for " << certProperties
.commonName
<<
4019 " certificate: " << e
.what() << "; will now block to " <<
4020 "generate that certificate.");
4021 // fall through to do blocking in-process generation.
4023 #endif // USE_SSL_CRTD
4025 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
4026 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
4027 doPeekAndSpliceStep();
4028 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4029 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
4030 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
4032 SSL_CTX
*dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
4033 getSslContextDone(dynCtx
, true);
4037 getSslContextDone(NULL
);
4041 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
4043 // Try to add generated ssl context to storage.
4044 if (port
->generateHostCertificates
&& isNew
) {
4046 if (signAlgorithm
== Ssl::algSignTrusted
) {
4047 // Add signing certificate to the certificates chain
4048 X509
*cert
= port
->signingCert
.get();
4049 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
4050 // increase the certificate lock
4051 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
4053 const int ssl_error
= ERR_get_error();
4054 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
4056 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
4058 //else it is self-signed or untrusted do not attrach any certificate
4060 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
4061 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
4063 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
4064 // If it is not in storage delete after using. Else storage deleted it.
4065 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
4068 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
4072 // If generated ssl context = NULL, try to use static ssl context.
4074 if (!port
->staticSslContext
) {
4075 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
4076 clientConnection
->close();
4079 debugs(33, 5, HERE
<< "Using static ssl context.");
4080 sslContext
= port
->staticSslContext
.get();
4084 if (!httpsCreate(clientConnection
, sslContext
))
4087 // bumped intercepted conns should already have Config.Timeout.request set
4088 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
4089 // to make sure the connection does not get stuck on non-SSL clients.
4090 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
4091 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
4092 this, ConnStateData::requestTimeout
);
4093 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
4095 // Disable the client read handler until CachePeer selection is complete
4096 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4097 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
4098 switchedToHttps_
= true;
4102 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
4104 assert(!switchedToHttps_
);
4106 sslConnectHostOrIp
= request
->GetHost();
4107 sslCommonName
= request
->GetHost();
4109 // We are going to read new request
4110 flags
.readMore
= true;
4111 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
4113 // keep version major.minor details the same.
4114 // but we are now performing the HTTPS handshake traffic
4115 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
4117 // If sslServerBump is set, then we have decided to deny CONNECT
4118 // and now want to switch to SSL to send the error to the client
4119 // without even peeking at the origin server certificate.
4120 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
4121 request
->flags
.sslPeek
= true;
4122 sslServerBump
= new Ssl::ServerBump(request
);
4124 // will call httpsPeeked() with certificate and connection, eventually
4125 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4127 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
4128 request
->flags
.sslPeek
= true;
4129 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
4130 startPeekAndSplice();
4134 // otherwise, use sslConnectHostOrIp
4135 getSslContextStart();
4139 ConnStateData::spliceOnError(const err_type err
)
4141 if (Config
.accessList
.on_unsupported_protocol
) {
4142 assert(serverBump());
4143 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
4144 checklist
.requestErrorType
= err
;
4145 checklist
.conn(this);
4146 allow_t answer
= checklist
.fastCheck();
4147 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
4155 /** negotiate an SSL connection */
4157 clientPeekAndSpliceSSL(int fd
, void *data
)
4159 ConnStateData
*conn
= (ConnStateData
*)data
;
4160 SSL
*ssl
= fd_table
[fd
].ssl
;
4162 debugs(83, 5, "Start peek and splice on FD " << fd
);
4165 if ((ret
= Squid_SSL_accept(conn
, clientPeekAndSpliceSSL
)) < 0)
4166 debugs(83, 2, "SSL_accept failed.");
4168 BIO
*b
= SSL_get_rbio(ssl
);
4170 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4172 const err_type err
= bio
->noSslClient() ? ERR_PROTOCOL_UNKNOWN
: ERR_SECURE_ACCEPT_FAIL
;
4173 if (!conn
->spliceOnError(err
))
4174 conn
->clientConnection
->close();
4178 if (bio
->rBufData().contentSize() > 0)
4179 conn
->receivedFirstByte();
4181 if (bio
->gotHello()) {
4182 if (conn
->serverBump()) {
4183 Ssl::Bio::sslFeatures
const &features
= bio
->getFeatures();
4184 if (!features
.serverName
.isEmpty())
4185 conn
->serverBump()->clientSni
= features
.serverName
;
4188 debugs(83, 5, "I got hello. Start forwarding the request!!! ");
4189 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4190 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
4191 conn
->startPeekAndSpliceDone();
4196 void ConnStateData::startPeekAndSplice()
4198 // will call httpsPeeked() with certificate and connection, eventually
4199 SSL_CTX
*unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
4200 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
4202 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
4205 // commSetConnTimeout() was called for this request before we switched.
4206 // Fix timeout to request_start_timeout
4207 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
4208 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
4209 TimeoutDialer
, this, ConnStateData::requestTimeout
);
4210 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
4211 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
4212 // a bumbed "connect" request on non transparent port.
4213 receivedFirstByte_
= false;
4215 // Disable the client read handler until CachePeer selection is complete
4216 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4217 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientPeekAndSpliceSSL
, this, 0);
4218 switchedToHttps_
= true;
4220 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4221 BIO
*b
= SSL_get_rbio(ssl
);
4222 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4226 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
4228 ConnStateData
*connState
= (ConnStateData
*) data
;
4230 // if the connection is closed or closing, just return.
4231 if (!connState
->isOpen())
4234 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
4235 assert(connState
->serverBump());
4236 Ssl::BumpMode bumpAction
;
4237 if (answer
== ACCESS_ALLOWED
) {
4238 if (answer
.kind
== Ssl::bumpNone
)
4239 bumpAction
= Ssl::bumpSplice
;
4240 else if (answer
.kind
== Ssl::bumpClientFirst
|| answer
.kind
== Ssl::bumpServerFirst
)
4241 bumpAction
= Ssl::bumpBump
;
4243 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
4245 bumpAction
= Ssl::bumpSplice
;
4247 connState
->serverBump()->act
.step2
= bumpAction
;
4248 connState
->sslBumpMode
= bumpAction
;
4250 if (bumpAction
== Ssl::bumpTerminate
) {
4251 comm_close(connState
->clientConnection
->fd
);
4252 } else if (bumpAction
!= Ssl::bumpSplice
) {
4253 connState
->startPeekAndSpliceDone();
4255 connState
->splice();
4259 ConnStateData::splice()
4261 //Normally we can splice here, because we just got client hello message
4262 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4263 BIO
*b
= SSL_get_rbio(ssl
);
4264 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4265 MemBuf
const &rbuf
= bio
->rBufData();
4266 debugs(83,5, "Bio for " << clientConnection
<< " read " << rbuf
.contentSize() << " helo bytes");
4268 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
4269 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
4271 if (transparent()) {
4272 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
4273 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
4274 transferProtocol
= Http::ProtocolVersion();
4275 // fake a CONNECT request to force connState to tunnel
4276 static char ip
[MAX_IPSTRLEN
];
4277 clientConnection
->local
.toUrl(ip
, sizeof(ip
));
4278 in
.buf
.assign("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n").append(rbuf
.content(), rbuf
.contentSize());
4279 bool ret
= handleReadData();
4281 ret
= clientParseRequests();
4284 debugs(33, 2, "Failed to start fake CONNECT request for ssl spliced connection: " << clientConnection
);
4285 clientConnection
->close();
4288 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
4290 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
4291 transferProtocol
= Http::ProtocolVersion();
4292 // in.buf still has the "CONNECT ..." request data, reset it to SSL hello message
4293 in
.buf
.append(rbuf
.content(), rbuf
.contentSize());
4294 ClientSocketContext::Pointer context
= getCurrentContext();
4295 ClientHttpRequest
*http
= context
->http
;
4296 tunnelStart(http
, &http
->out
.size
, &http
->al
->http
.code
, http
->al
);
4301 ConnStateData::startPeekAndSpliceDone()
4303 // This is the Step2 of the SSL bumping
4304 assert(sslServerBump
);
4305 if (sslServerBump
->step
== Ssl::bumpStep1
) {
4306 sslServerBump
->step
= Ssl::bumpStep2
;
4307 // Run a accessList check to check if want to splice or continue bumping
4309 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
4310 //acl_checklist->src_addr = params.conn->remote;
4311 //acl_checklist->my_addr = s->s;
4312 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
4316 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4320 ConnStateData::doPeekAndSpliceStep()
4322 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4323 BIO
*b
= SSL_get_rbio(ssl
);
4325 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4327 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
4330 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
4331 switchedToHttps_
= true;
4335 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4337 Must(sslServerBump
!= NULL
);
4339 if (Comm::IsConnOpen(serverConnection
)) {
4340 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
4342 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
4343 assert(serverCert
.get() != NULL
);
4344 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4345 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4346 " bumped: " << *serverConnection
);
4348 pinConnection(serverConnection
, NULL
, NULL
, false);
4350 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4352 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4353 Ip::Address intendedDest
;
4354 intendedDest
= sslConnectHostOrIp
.termedBuf();
4355 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4357 // Squid serves its own error page and closes, so we want
4358 // a CN that causes no additional browser errors. Possible
4359 // only when bumping CONNECT with a user-typed address.
4360 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4361 sslCommonName
= sslConnectHostOrIp
;
4362 else if (sslServerBump
->serverCert
.get())
4363 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4365 // copy error detail from bump-server-first request to CONNECT request
4366 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4367 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4370 getSslContextStart();
4373 #endif /* USE_OPENSSL */
4375 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4377 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4379 if (!Comm::IsConnOpen(c
)) {
4380 Must(NHttpSockets
> 0); // we tried to open some
4381 --NHttpSockets
; // there will be fewer sockets than planned
4382 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4384 if (!NHttpSockets
) // we could not open any listen sockets at all
4385 fatalf("Unable to open %s",FdNote(portType
));
4392 /// find any unused HttpSockets[] slot and store fd there or return false
4394 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4397 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4398 if ((found
= HttpSockets
[i
] < 0))
4399 HttpSockets
[i
] = conn
->fd
;
4405 clientHttpConnectionsOpen(void)
4407 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4408 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4409 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4410 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4415 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4416 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4417 s
->flags
.tunnelSslBumping
= false;
4420 if (s
->flags
.tunnelSslBumping
&&
4421 !s
->staticSslContext
&&
4422 !s
->generateHostCertificates
) {
4423 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4424 s
->flags
.tunnelSslBumping
= false;
4426 if (s
->flags
.tunnelSslBumping
) {
4427 // Create ssl_ctx cache for this port.
4428 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4432 // Fill out a Comm::Connection which IPC will open as a listener for us
4433 // then pass back when active so we can start a TcpAcceptor subscription.
4434 s
->listenConn
= new Comm::Connection
;
4435 s
->listenConn
->local
= s
->s
;
4436 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4438 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4439 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4440 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
4441 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4443 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4444 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4445 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4447 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4454 clientHttpsConnectionsOpen(void)
4456 for (AnyP::PortCfgPointer s
= HttpsPortList
; s
!= NULL
; s
= s
->next
) {
4457 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4458 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4459 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4463 if (!s
->staticSslContext
) {
4464 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4465 " due to SSL initialization failure.");
4469 // TODO: merge with similar code in clientHttpConnectionsOpen()
4470 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4471 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4472 s
->flags
.tunnelSslBumping
= false;
4475 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4476 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4477 s
->flags
.tunnelSslBumping
= false;
4480 if (s
->flags
.tunnelSslBumping
) {
4481 // Create ssl_ctx cache for this port.
4482 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4485 // Fill out a Comm::Connection which IPC will open as a listener for us
4486 s
->listenConn
= new Comm::Connection
;
4487 s
->listenConn
->local
= s
->s
;
4488 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4489 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4491 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4492 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4493 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
4494 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4496 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4497 ListeningStartedDialer(&clientListenerConnectionOpened
,
4498 s
, Ipc::fdnHttpsSocket
, sub
));
4499 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4500 HttpSockets
[NHttpSockets
] = -1;
4507 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
4509 // Fill out a Comm::Connection which IPC will open as a listener for us
4510 port
->listenConn
= new Comm::Connection
;
4511 port
->listenConn
->local
= port
->s
;
4512 port
->listenConn
->flags
=
4514 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4515 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4517 // route new connections to subCall
4518 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4519 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4520 AsyncCall::Pointer listenCall
=
4521 asyncCall(33, 2, "clientListenerConnectionOpened",
4522 ListeningStartedDialer(&clientListenerConnectionOpened
,
4523 port
, fdNote
, sub
));
4524 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
4526 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
4527 HttpSockets
[NHttpSockets
] = -1;
4531 /// process clientHttpConnectionsOpen result
4533 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4537 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4540 Must(Comm::IsConnOpen(s
->listenConn
));
4542 // TCP: setup a job to handle accept() with subscribed handler
4543 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
4545 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4546 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4547 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4548 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4549 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4550 << FdNote(portTypeNote
) << " connections at "
4553 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4557 clientOpenListenSockets(void)
4559 clientHttpConnectionsOpen();
4561 clientHttpsConnectionsOpen();
4563 Ftp::StartListening();
4565 if (NHttpSockets
< 1)
4566 fatal("No HTTP, HTTPS, or FTP ports configured");
4570 clientConnectionsClose()
4572 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4573 if (s
->listenConn
!= NULL
) {
4574 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4575 s
->listenConn
->close();
4576 s
->listenConn
= NULL
;
4581 for (AnyP::PortCfgPointer s
= HttpsPortList
; s
!= NULL
; s
= s
->next
) {
4582 if (s
->listenConn
!= NULL
) {
4583 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4584 s
->listenConn
->close();
4585 s
->listenConn
= NULL
;
4590 Ftp::StopListening();
4592 // TODO see if we can drop HttpSockets array entirely */
4593 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4594 HttpSockets
[i
] = -1;
4601 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4603 const char *vary
= request
->vary_headers
;
4604 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4605 #if X_ACCELERATOR_VARY
4608 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4611 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4613 /* Oops... something odd is going on here.. */
4614 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4615 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4616 safe_free(request
->vary_headers
);
4621 /* This is not a varying object */
4625 /* virtual "vary" object found. Calculate the vary key and
4626 * continue the search
4628 vary
= httpMakeVaryMark(request
, entry
->getReply());
4631 request
->vary_headers
= xstrdup(vary
);
4634 /* Ouch.. we cannot handle this kind of variance */
4635 /* XXX This cannot really happen, but just to be complete */
4640 vary
= httpMakeVaryMark(request
, entry
->getReply());
4643 request
->vary_headers
= xstrdup(vary
);
4647 /* Ouch.. we cannot handle this kind of variance */
4648 /* XXX This cannot really happen, but just to be complete */
4650 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4653 /* Oops.. we have already been here and still haven't
4654 * found the requested variant. Bail out
4656 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4657 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4663 ACLFilledChecklist
*
4664 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4666 ConnStateData
* conn
= http
->getConn();
4667 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4668 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4671 * hack for ident ACL. It needs to get full addresses, and a place to store
4672 * the ident result on persistent connections...
4674 /* connection oriented auth also needs these two lines for it's operation. */
4679 ConnStateData::transparent() const
4681 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4685 ConnStateData::reading() const
4687 return reader
!= NULL
;
4691 ConnStateData::stopReading()
4694 Comm::ReadCancel(clientConnection
->fd
, reader
);
4700 ConnStateData::expectRequestBody(int64_t size
)
4702 bodyPipe
= new BodyPipe(this);
4704 bodyPipe
->setBodySize(size
);
4706 startDechunkingRequest();
4711 ConnStateData::mayNeedToReadMoreBody() const
4714 return 0; // request without a body or read/produced all body bytes
4716 if (!bodyPipe
->bodySizeKnown())
4717 return -1; // probably need to read more, but we cannot be sure
4719 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4720 const int64_t haveAvailable
= static_cast<int64_t>(in
.buf
.length());
4722 if (needToProduce
<= haveAvailable
)
4723 return 0; // we have read what we need (but are waiting for pipe space)
4725 return needToProduce
- haveAvailable
;
4729 ConnStateData::stopReceiving(const char *error
)
4731 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4732 "; old sending error: " <<
4733 (stoppedSending() ? stoppedSending_
: "none"));
4735 if (const char *oldError
= stoppedReceiving()) {
4736 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4737 return; // nothing has changed as far as this connection is concerned
4740 stoppedReceiving_
= error
;
4742 if (const char *sendError
= stoppedSending()) {
4743 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4744 clientConnection
->close();
4749 ConnStateData::expectNoForwarding()
4751 if (bodyPipe
!= NULL
) {
4752 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4753 bodyPipe
->expectNoConsumption();
4757 /// initialize dechunking state
4759 ConnStateData::startDechunkingRequest()
4761 Must(bodyPipe
!= NULL
);
4762 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4763 assert(!in
.bodyParser
);
4764 in
.bodyParser
= new ChunkedCodingParser
;
4767 /// put parsed content into input buffer and clean up
4769 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4771 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4773 if (bodyPipe
!= NULL
) {
4774 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4775 BodyPipe::Pointer myPipe
= bodyPipe
;
4776 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4777 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4779 Must(myPipe
->bodySizeKnown());
4780 ClientSocketContext::Pointer context
= getCurrentContext();
4781 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4782 context
->http
->request
->setContentLength(myPipe
->bodySize());
4786 delete in
.bodyParser
;
4787 in
.bodyParser
= NULL
;
4790 ConnStateData::In::In() :
4795 ConnStateData::In::~In()
4797 delete bodyParser
; // TODO: pool
4801 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4804 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4808 ClientSocketContext::Pointer context
= getCurrentContext();
4809 if (context
!= NULL
) {
4810 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4814 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4815 clientConnection
->close();
4818 /// Our close handler called by Comm when the pinned connection is closed
4820 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4822 // FwdState might repin a failed connection sooner than this close
4823 // callback is called for the failed connection.
4824 assert(pinning
.serverConnection
== io
.conn
);
4825 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4826 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4827 unpinConnection(false);
4829 if (sawZeroReply
&& clientConnection
!= NULL
) {
4830 debugs(33, 3, "Closing client connection on pinned zero reply.");
4831 clientConnection
->close();
4837 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
4839 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
4840 pinning
.serverConnection
->fd
!= pinServer
->fd
)
4841 pinNewConnection(pinServer
, request
, aPeer
, auth
);
4844 startPinnedConnectionMonitoring();
4848 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4850 unpinConnection(true); // closes pinned connection, if any, and resets fields
4852 pinning
.serverConnection
= pinServer
;
4854 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4856 Must(pinning
.serverConnection
!= NULL
);
4858 // when pinning an SSL bumped connection, the request may be NULL
4859 const char *pinnedHost
= "[unknown]";
4861 pinning
.host
= xstrdup(request
->GetHost());
4862 pinning
.port
= request
->port
;
4863 pinnedHost
= pinning
.host
;
4865 pinning
.port
= pinServer
->remote
.port();
4867 pinning
.pinned
= true;
4869 pinning
.peer
= cbdataReference(aPeer
);
4870 pinning
.auth
= auth
;
4871 char stmp
[MAX_IPSTRLEN
];
4872 char desc
[FD_DESC_SZ
];
4873 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4874 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4875 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4876 clientConnection
->fd
);
4877 fd_note(pinning
.serverConnection
->fd
, desc
);
4879 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4880 pinning
.closeHandler
= JobCallback(33, 5,
4881 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4882 // remember the pinned connection so that cb does not unpin a fresher one
4883 typedef CommCloseCbParams Params
;
4884 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4885 params
.conn
= pinning
.serverConnection
;
4886 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4889 /// [re]start monitoring pinned connection for peer closures so that we can
4890 /// propagate them to an _idle_ client pinned to that peer
4892 ConnStateData::startPinnedConnectionMonitoring()
4894 if (pinning
.readHandler
!= NULL
)
4895 return; // already monitoring
4897 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4898 pinning
.readHandler
= JobCallback(33, 3,
4899 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4900 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
4904 ConnStateData::stopPinnedConnectionMonitoring()
4906 if (pinning
.readHandler
!= NULL
) {
4907 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4908 pinning
.readHandler
= NULL
;
4912 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4913 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4915 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4917 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4919 if (io
.flag
== Comm::ERR_CLOSING
)
4920 return; // close handler will clean up
4922 // We could use getConcurrentRequestCount(), but this may be faster.
4923 const bool clientIsIdle
= !getCurrentContext();
4925 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4926 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4928 assert(pinning
.serverConnection
== io
.conn
);
4929 pinning
.serverConnection
->close();
4931 // If we are still sending data to the client, do not close now. When we are done sending,
4932 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4933 // However, if we are idle, then we must close to inform the idle client and minimize races.
4934 if (clientIsIdle
&& clientConnection
!= NULL
)
4935 clientConnection
->close();
4938 const Comm::ConnectionPointer
4939 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4941 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4944 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4946 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4948 else if (request
&& pinning
.port
!= request
->port
)
4950 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4952 else if (aPeer
!= pinning
.peer
)
4956 /* The pinning info is not safe, remove any pinning info */
4957 unpinConnection(true);
4960 return pinning
.serverConnection
;
4963 Comm::ConnectionPointer
4964 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4966 debugs(33, 7, pinning
.serverConnection
);
4967 if (validatePinnedConnection(request
, aPeer
) != NULL
)
4968 stopPinnedConnectionMonitoring();
4970 return pinning
.serverConnection
; // closed if validation failed
4974 ConnStateData::unpinConnection(const bool andClose
)
4976 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4979 cbdataReferenceDone(pinning
.peer
);
4981 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4982 if (pinning
.closeHandler
!= NULL
) {
4983 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4984 pinning
.closeHandler
= NULL
;
4987 stopPinnedConnectionMonitoring();
4989 // close the server side socket if requested
4991 pinning
.serverConnection
->close();
4992 pinning
.serverConnection
= NULL
;
4995 safe_free(pinning
.host
);
4997 pinning
.zeroReply
= false;
4999 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
5000 * connection has gone away */