2 * Copyright (C) 1996-2014 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
) {
524 packerToMemInit(&p
, &mb
);
525 request
->header
.packInto(&p
);
526 //This is the request after adaptation or redirection
527 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
529 // the virgin request is saved to aLogEntry->request
530 if (aLogEntry
->request
) {
533 packerToMemInit(&p
, &mb
);
534 aLogEntry
->request
->header
.packInto(&p
);
535 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
539 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
543 packerToMemInit(&p
, &mb
);
544 ah
->lastMeta
.packInto(&p
);
545 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
554 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
556 ih
->processingTime(aLogEntry
->icap
.processingTime
);
559 aLogEntry
->http
.method
= request
->method
;
560 aLogEntry
->http
.version
= request
->http_ver
;
561 aLogEntry
->hier
= request
->hier
;
562 if (request
->content_length
> 0) // negative when no body or unknown length
563 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
564 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
566 // Adapted request, if any, inherits and then collects all the stats, but
567 // the virgin request gets logged instead; copy the stats to log them.
568 // TODO: avoid losses by keeping these stats in a shared history object?
569 if (aLogEntry
->request
) {
570 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
571 aLogEntry
->request
->errType
= request
->errType
;
572 aLogEntry
->request
->errDetail
= request
->errDetail
;
577 ClientHttpRequest::logRequest()
579 if (!out
.size
&& !logType
)
580 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
582 al
->icp
.opcode
= ICP_INVALID
;
584 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
587 al
->http
.code
= al
->reply
->sline
.status();
588 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
589 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
590 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
591 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
594 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
596 if (loggingEntry() && loggingEntry()->mem_obj
&& loggingEntry()->objectLen() >= 0)
597 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
599 al
->http
.clientRequestSz
.header
= req_sz
;
600 al
->http
.clientReplySz
.header
= out
.headers_sz
;
601 // XXX: calculate without payload encoding or headers !!
602 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
604 al
->cache
.highOffset
= out
.offset
;
606 al
->cache
.code
= logType
;
608 tvSub(al
->cache
.trTime
, al
->cache
.start_time
, current_time
);
611 prepareLogWithRequestDetails(request
, al
);
613 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
614 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
618 /* This is broken. Fails if the connection has been closed. Needs
619 * to snarf the ssl details some place earlier..
621 if (getConn() != NULL
)
622 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
627 // The al->notes and request->notes must point to the same object.
628 (void)SyncNotes(*al
, *request
);
629 typedef Notes::iterator ACAMLI
;
630 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
631 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
632 NotePairs
¬es
= SyncNotes(*al
, *request
);
633 notes
.add((*i
)->key
.termedBuf(), value
);
634 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
638 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
640 checklist
.reply
= al
->reply
;
641 HTTPMSGLOCK(checklist
.reply
);
645 al
->adapted_request
= request
;
646 HTTPMSGLOCK(al
->adapted_request
);
648 accessLogLog(al
, &checklist
);
650 bool updatePerformanceCounters
= true;
651 if (Config
.accessList
.stats_collection
) {
652 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
654 statsCheck
.reply
= al
->reply
;
655 HTTPMSGLOCK(statsCheck
.reply
);
657 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
660 if (updatePerformanceCounters
) {
664 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
665 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
670 ClientHttpRequest::freeResources()
674 safe_free(redirect
.location
);
675 range_iter
.boundary
.clean();
676 HTTPMSGUNLOCK(request
);
678 if (client_stream
.tail
)
679 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
683 httpRequestFree(void *data
)
685 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
686 assert(http
!= NULL
);
691 ConnStateData::areAllContextsForThisConnection() const
693 ClientSocketContext::Pointer context
= getCurrentContext();
695 while (context
.getRaw()) {
696 if (context
->http
->getConn() != this)
699 context
= context
->next
;
706 ConnStateData::freeAllContexts()
708 ClientSocketContext::Pointer context
;
710 while ((context
= getCurrentContext()).getRaw() != NULL
) {
711 assert(getCurrentContext() !=
712 getCurrentContext()->next
);
713 context
->connIsFinished();
714 assert (context
!= currentobject
);
718 /// propagates abort event to all contexts
720 ConnStateData::notifyAllContexts(int xerrno
)
722 typedef ClientSocketContext::Pointer CSCP
;
723 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
724 c
->noteIoError(xerrno
);
727 /* This is a handler normally called by comm_close() */
728 void ConnStateData::connStateClosed(const CommCloseCbParams
&)
730 deleteThis("ConnStateData::connStateClosed");
735 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
739 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
745 // clobered with self-pointer
746 // NP: something nasty is going on in Squid, but harmless.
748 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
753 * Connection-auth relies on a single set of credentials being preserved
754 * for all requests on a connection once they have been setup.
755 * There are several things which need to happen to preserve security
756 * when connection-auth credentials change unexpectedly or are unset.
758 * 1) auth helper released from any active state
760 * They can only be reserved by a handshake process which this
761 * connection can now never complete.
762 * This prevents helpers hanging when their connections close.
764 * 2) pinning is expected to be removed and server conn closed
766 * The upstream link is authenticated with the same credentials.
767 * Expecting the same level of consistency we should have received.
768 * This prevents upstream being faced with multiple or missing
769 * credentials after authentication.
770 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
771 * we just trigger that cleanup here via comm_reset_close() or
772 * ConnStateData::stopReceiving()
774 * 3) the connection needs to close.
776 * This prevents attackers injecting requests into a connection,
777 * or gateways wrongly multiplexing users into a single connection.
779 * When credentials are missing closure needs to follow an auth
780 * challenge for best recovery by the client.
782 * When credentials change there is nothing we can do but abort as
783 * fast as possible. Sending TCP RST instead of an HTTP response
784 * is the best-case action.
787 // clobbered with nul-pointer
789 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
790 auth_
->releaseAuthServer();
792 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
793 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
794 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
795 stopReceiving("connection-auth removed");
799 // clobbered with alternative credentials
801 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
802 auth_
->releaseAuthServer();
804 // this is a fatal type of problem.
805 // Close the connection immediately with TCP RST to abort all traffic flow
806 comm_reset_close(clientConnection
);
814 // cleans up before destructor is called
816 ConnStateData::swanSong()
818 debugs(33, 2, HERE
<< clientConnection
);
819 flags
.readMore
= false;
820 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
821 assert(areAllContextsForThisConnection());
824 unpinConnection(true);
826 if (Comm::IsConnOpen(clientConnection
))
827 clientConnection
->close();
830 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
831 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
834 BodyProducer::swanSong();
835 flags
.swanSang
= true;
839 ConnStateData::isOpen() const
841 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
842 Comm::IsConnOpen(clientConnection
) &&
843 !fd_table
[clientConnection
->fd
].closing();
846 ConnStateData::~ConnStateData()
848 debugs(33, 3, HERE
<< clientConnection
);
851 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
854 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
856 if (bodyPipe
!= NULL
)
857 stopProducingFor(bodyPipe
, false);
860 delete sslServerBump
;
865 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
866 * This is the client-side persistent connection flag. We need
867 * to set this relatively early in the request processing
868 * to handle hacks for broken servers and clients.
871 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
873 HttpRequest
*request
= http
->request
;
875 debugs(33, 3, "http_ver = " << request
->http_ver
);
876 debugs(33, 3, "method = " << request
->method
);
878 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
879 request
->flags
.proxyKeepalive
= request
->persistent();
883 clientIsContentLengthValid(HttpRequest
* r
)
885 switch (r
->method
.id()) {
887 case Http::METHOD_GET
:
889 case Http::METHOD_HEAD
:
890 /* We do not want to see a request entity on GET/HEAD requests */
891 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
894 /* For other types of requests we don't care */
902 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
904 if (Config
.maxRequestBodySize
&&
905 bodyLength
> Config
.maxRequestBodySize
)
906 return 1; /* too large */
913 connIsUsable(ConnStateData
* conn
)
915 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
923 // careful: the "current" context may be gone if we wrote an early response
924 ClientSocketContext::Pointer
925 ConnStateData::getCurrentContext() const
927 return currentobject
;
931 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
933 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
934 assert(flags
.deferred
== 0);
936 deferredparams
.node
= node
;
937 deferredparams
.rep
= rep
;
938 deferredparams
.queuedBuffer
= receivedData
;
943 ClientSocketContext::startOfOutput() const
945 return http
->out
.size
== 0;
949 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
951 /*the size of available range can always fit in a size_t type*/
952 size_t maximum
= (size_t)available
.size();
954 if (!http
->request
->range
)
957 assert (canPackMoreRanges());
959 if (http
->range_iter
.debt() == -1)
962 assert (http
->range_iter
.debt() > 0);
964 /* TODO this + the last line could be a range intersection calculation */
965 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
968 return min(http
->range_iter
.debt(), (int64_t)maximum
);
972 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
974 http
->out
.offset
+= bytes
;
976 if (!http
->request
->range
)
979 if (http
->range_iter
.debt() != -1) {
980 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
981 assert (http
->range_iter
.debt() >= 0);
984 /* debt() always stops at -1, below that is a bug */
985 assert (http
->range_iter
.debt() >= -1);
989 ClientHttpRequest::multipartRangeRequest() const
991 return request
->multipartRangeRequest();
995 ClientSocketContext::multipartRangeRequest() const
997 return http
->multipartRangeRequest();
1001 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1003 assert(rep
== NULL
);
1005 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1006 size_t length
= lengthToSend(bodyData
.range());
1007 noteSentBodyBytes (length
);
1008 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1009 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1010 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1016 if (multipartRangeRequest())
1017 packRange(bodyData
, &mb
);
1019 packChunk(bodyData
, mb
);
1021 if (mb
.contentSize()) {
1023 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1024 CommIoCbPtrFun(clientWriteComplete
, this));
1025 Comm::Write(clientConnection
, &mb
, call
);
1027 writeComplete(clientConnection
, NULL
, 0, Comm::OK
);
1031 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1032 * if bodyData is empty.
1035 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1037 const uint64_t length
=
1038 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1039 noteSentBodyBytes(length
);
1041 mb
.Printf("%" PRIX64
"\r\n", length
);
1042 mb
.append(bodyData
.data
, length
);
1046 /** put terminating boundary for multiparts */
1048 clientPackTermBound(String boundary
, MemBuf
* mb
)
1050 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1051 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1054 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1056 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1058 HttpHeader
hdr(hoReply
);
1064 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1065 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1066 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1068 /* stuff the header with required entries and pack it */
1070 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1071 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1073 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1075 packerToMemInit(&p
, mb
);
1083 /* append <crlf> (we packed a header, not a reply) */
1088 * extracts a "range" from *buf and appends them to mb, updating
1089 * all offsets and such.
1092 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1094 HttpHdrRangeIter
* i
= &http
->range_iter
;
1095 Range
<int64_t> available (source
.range());
1096 char const *buf
= source
.data
;
1098 while (i
->currentSpec() && available
.size()) {
1099 const size_t copy_sz
= lengthToSend(available
);
1103 * intersection of "have" and "need" ranges must not be empty
1105 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1106 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1109 * put boundary and headers at the beginning of a range in a
1113 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1114 assert(http
->memObject());
1116 http
->memObject()->getReply(), /* original reply */
1117 i
->currentSpec(), /* current range */
1118 i
->boundary
, /* boundary, the same for all */
1125 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1127 noteSentBodyBytes (copy_sz
);
1129 mb
->append(buf
, copy_sz
);
1134 available
.start
+= copy_sz
;
1140 if (!canPackMoreRanges()) {
1141 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1144 /* put terminating boundary for multiparts */
1145 clientPackTermBound(i
->boundary
, mb
);
1150 int64_t nextOffset
= getNextRangeOffset();
1152 assert (nextOffset
>= http
->out
.offset
);
1154 int64_t skip
= nextOffset
- http
->out
.offset
;
1156 /* adjust for not to be transmitted bytes */
1157 http
->out
.offset
= nextOffset
;
1159 if (available
.size() <= (uint64_t)skip
)
1162 available
.start
+= skip
;
1171 /** returns expected content length for multi-range replies
1172 * note: assumes that httpHdrRangeCanonize has already been called
1173 * warning: assumes that HTTP headers for individual ranges at the
1174 * time of the actuall assembly will be exactly the same as
1175 * the headers when clientMRangeCLen() is called */
1177 ClientHttpRequest::mRangeCLen()
1182 assert(memObject());
1185 HttpHdrRange::iterator pos
= request
->range
->begin();
1187 while (pos
!= request
->range
->end()) {
1188 /* account for headers for this range */
1190 clientPackRangeHdr(memObject()->getReply(),
1191 *pos
, range_iter
.boundary
, &mb
);
1194 /* account for range content */
1195 clen
+= (*pos
)->length
;
1197 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1201 /* account for the terminating boundary */
1204 clientPackTermBound(range_iter
.boundary
, &mb
);
1214 * returns true if If-Range specs match reply, false otherwise
1217 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1219 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1220 /* check for parsing falure */
1227 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1228 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1229 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1232 return 0; /* entity has no etag to compare with! */
1234 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1235 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1236 return 0; /* must use strong validator for sub-range requests */
1239 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1242 /* got modification time? */
1243 if (spec
.time
>= 0) {
1244 return http
->storeEntry()->lastmod
<= spec
.time
;
1247 assert(0); /* should not happen */
1252 * generates a "unique" boundary string for multipart responses
1253 * the caller is responsible for cleaning the string */
1255 ClientHttpRequest::rangeBoundaryStr() const
1258 String
b(APP_FULLNAME
);
1260 key
= storeEntry()->getMD5Text();
1261 b
.append(key
, strlen(key
));
1265 /** adds appropriate Range headers if needed */
1267 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1269 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1270 const char *range_err
= NULL
;
1271 HttpRequest
*request
= http
->request
;
1272 assert(request
->range
);
1273 /* check if we still want to do ranges */
1275 int64_t roffLimit
= request
->getRangeOffsetLimit();
1278 range_err
= "no [parse-able] reply";
1279 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1280 range_err
= "wrong status code";
1281 else if (hdr
->has(HDR_CONTENT_RANGE
))
1282 range_err
= "origin server does ranges";
1283 else if (rep
->content_length
< 0)
1284 range_err
= "unknown length";
1285 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1286 range_err
= "INCONSISTENT length"; /* a bug? */
1288 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1291 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1292 range_err
= "If-Range match failed";
1293 else if (!http
->request
->range
->canonize(rep
))
1294 range_err
= "canonization failed";
1295 else if (http
->request
->range
->isComplex())
1296 range_err
= "too complex range header";
1297 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1298 range_err
= "range outside range_offset_limit";
1300 /* get rid of our range specs on error */
1302 /* XXX We do this here because we need canonisation etc. However, this current
1303 * code will lead to incorrect store offset requests - the store will have the
1304 * offset data, but we won't be requesting it.
1305 * So, we can either re-request, or generate an error
1307 http
->request
->ignoreRange(range_err
);
1309 /* XXX: TODO: Review, this unconditional set may be wrong. */
1310 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1311 // web server responded with a valid, but unexpected range.
1312 // will (try-to) forward as-is.
1313 //TODO: we should cope with multirange request/responses
1314 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1315 request
->range
->contains(rep
->content_range
->spec
) :
1317 const int spec_count
= http
->request
->range
->specs
.size();
1318 int64_t actual_clen
= -1;
1320 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1321 spec_count
<< " virgin clen: " << rep
->content_length
);
1322 assert(spec_count
> 0);
1323 /* append appropriate header(s) */
1325 if (spec_count
== 1) {
1326 if (!replyMatchRequest
) {
1327 hdr
->delById(HDR_CONTENT_RANGE
);
1328 hdr
->putContRange(rep
->content_range
);
1329 actual_clen
= rep
->content_length
;
1330 //http->range_iter.pos = rep->content_range->spec.begin();
1331 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1332 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1335 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1337 /* append Content-Range */
1339 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1340 /* No content range, so this was a full object we are
1343 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1346 /* set new Content-Length to the actual number of bytes
1347 * transmitted in the message-body */
1348 actual_clen
= (*pos
)->length
;
1352 /* generate boundary string */
1353 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1354 /* delete old Content-Type, add ours */
1355 hdr
->delById(HDR_CONTENT_TYPE
);
1356 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1357 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1358 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1359 /* Content-Length is not required in multipart responses
1360 * but it is always nice to have one */
1361 actual_clen
= http
->mRangeCLen();
1362 /* http->out needs to start where we want data at */
1363 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1366 /* replace Content-Length header */
1367 assert(actual_clen
>= 0);
1369 hdr
->delById(HDR_CONTENT_LENGTH
);
1371 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1373 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1375 /* And start the range iter off */
1376 http
->range_iter
.updateSpec();
1381 ClientSocketContext::prepareReply(HttpReply
* rep
)
1385 if (http
->request
->range
)
1386 buildRangeHeader(rep
);
1390 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1394 MemBuf
*mb
= rep
->pack();
1396 // dump now, so we dont output any body.
1397 debugs(11, 2, "HTTP Client " << clientConnection
);
1398 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1400 /* Save length of headers for persistent conn checks */
1401 http
->out
.headers_sz
= mb
->contentSize();
1404 headersLog(0, 0, http
->request
->method
, rep
);
1407 if (bodyData
.data
&& bodyData
.length
) {
1408 if (multipartRangeRequest())
1409 packRange(bodyData
, mb
);
1410 else if (http
->request
->flags
.chunkedReply
) {
1411 packChunk(bodyData
, *mb
);
1413 size_t length
= lengthToSend(bodyData
.range());
1414 noteSentBodyBytes (length
);
1416 mb
->append(bodyData
.data
, length
);
1421 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1422 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1423 CommIoCbPtrFun(clientWriteComplete
, this));
1424 Comm::Write(clientConnection
, mb
, call
);
1429 * Write a chunk of data to a client socket. If the reply is present,
1430 * send the reply headers down the wire too, and clean them up when
1433 * The request is one backed by a connection, not an internal request.
1434 * data context is not NULL
1435 * There are no more entries in the stream chain.
1438 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1439 HttpReply
* rep
, StoreIOBuffer receivedData
)
1441 /* Test preconditions */
1442 assert(node
!= NULL
);
1443 PROF_start(clientSocketRecipient
);
1444 /* TODO: handle this rather than asserting
1445 * - it should only ever happen if we cause an abort and
1446 * the callback chain loops back to here, so we can simply return.
1447 * However, that itself shouldn't happen, so it stays as an assert for now.
1449 assert(cbdataReferenceValid(node
));
1450 assert(node
->node
.next
== NULL
);
1451 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1452 assert(context
!= NULL
);
1453 assert(connIsUsable(http
->getConn()));
1455 /* TODO: check offset is what we asked for */
1457 if (context
!= http
->getConn()->getCurrentContext())
1458 context
->deferRecipientForLater(node
, rep
, receivedData
);
1460 http
->getConn()->handleReply(rep
, receivedData
);
1462 PROF_stop(clientSocketRecipient
);
1466 * Called when a downstream node is no longer interested in
1467 * our data. As we are a terminal node, this means on aborts
1471 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1473 /* Test preconditions */
1474 assert(node
!= NULL
);
1475 /* TODO: handle this rather than asserting
1476 * - it should only ever happen if we cause an abort and
1477 * the callback chain loops back to here, so we can simply return.
1478 * However, that itself shouldn't happen, so it stays as an assert for now.
1480 assert(cbdataReferenceValid(node
));
1481 /* Set null by ContextFree */
1482 assert(node
->node
.next
== NULL
);
1483 /* this is the assert discussed above */
1484 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1485 /* We are only called when the client socket shutsdown.
1486 * Tell the prev pipeline member we're finished
1488 clientStreamDetach(node
, http
);
1492 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int xerrno
, void *data
)
1494 debugs(33,7, "schedule clientWriteComplete");
1495 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1499 ConnStateData::readNextRequest()
1501 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1503 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1505 * Set the timeout BEFORE calling readSomeData().
1507 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1508 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1509 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1510 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
1513 /** Please don't do anything with the FD past here! */
1517 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1519 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1521 /** If the client stream is waiting on a socket write to occur, then */
1523 if (deferredRequest
->flags
.deferred
) {
1524 /** NO data is allowed to have been sent. */
1525 assert(deferredRequest
->http
->out
.size
== 0);
1527 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1528 deferredRequest
->http
,
1529 deferredRequest
->deferredparams
.rep
,
1530 deferredRequest
->deferredparams
.queuedBuffer
);
1533 /** otherwise, the request is still active in a callbacksomewhere,
1538 /// called when we have successfully finished writing the response
1540 ClientSocketContext::keepaliveNextRequest()
1542 ConnStateData
* conn
= http
->getConn();
1544 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1547 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1548 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1549 conn
->clientConnection
->close();
1554 * We are done with the response, and we are either still receiving request
1555 * body (early response!) or have already stopped receiving anything.
1557 * If we are still receiving, then clientParseRequest() below will fail.
1558 * (XXX: but then we will call readNextRequest() which may succeed and
1559 * execute a smuggled request as we are not done with the current request).
1561 * If we stopped because we got everything, then try the next request.
1563 * If we stopped receiving because of an error, then close now to avoid
1564 * getting stuck and to prevent accidental request smuggling.
1567 if (const char *reason
= conn
->stoppedReceiving()) {
1568 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1569 conn
->clientConnection
->close();
1574 * Attempt to parse a request from the request buffer.
1575 * If we've been fed a pipelined request it may already
1576 * be in our read buffer.
1579 * This needs to fall through - if we're unlucky and parse the _last_ request
1580 * from our read buffer we may never re-register for another client read.
1583 if (conn
->clientParseRequests()) {
1584 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1588 * Either we need to kick-start another read or, if we have
1589 * a half-closed connection, kill it after the last request.
1590 * This saves waiting for half-closed connections to finished being
1591 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1592 * the keepalive "Waiting for next request" state.
1594 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1595 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1596 conn
->clientConnection
->close();
1600 ClientSocketContext::Pointer deferredRequest
;
1603 * At this point we either have a parsed request (which we've
1604 * kicked off the processing for) or not. If we have a deferred
1605 * request (parsed but deferred for pipeling processing reasons)
1606 * then look at processing it. If not, simply kickstart
1610 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1611 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1612 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1613 } else if (conn
->flags
.readMore
) {
1614 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1615 conn
->readNextRequest();
1617 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1618 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1623 clientUpdateSocketStats(LogTags logType
, size_t size
)
1628 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1630 if (logTypeIsATcpHit(logType
))
1631 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1635 * increments iterator "i"
1636 * used by clientPackMoreRanges
1638 \retval true there is still data available to pack more ranges
1642 ClientSocketContext::canPackMoreRanges() const
1644 /** first update iterator "i" if needed */
1646 if (!http
->range_iter
.debt()) {
1647 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1649 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1650 ++http
->range_iter
.pos
;
1652 http
->range_iter
.updateSpec();
1655 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1657 /* paranoid sync condition */
1658 /* continue condition: need_more_data */
1659 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1660 return http
->range_iter
.currentSpec() ? true : false;
1664 ClientSocketContext::getNextRangeOffset() const
1666 debugs (33, 5, "range: " << http
->request
->range
<<
1667 "; http offset " << http
->out
.offset
<<
1668 "; reply " << reply
);
1670 // XXX: This method is called from many places, including pullData() which
1671 // may be called before prepareReply() [on some Squid-generated errors].
1672 // Hence, we may not even know yet whether we should honor/do ranges.
1674 if (http
->request
->range
) {
1675 /* offset in range specs does not count the prefix of an http msg */
1676 /* check: reply was parsed and range iterator was initialized */
1677 assert(http
->range_iter
.valid
);
1678 /* filter out data according to range specs */
1679 assert (canPackMoreRanges());
1681 int64_t start
; /* offset of still missing data */
1682 assert(http
->range_iter
.currentSpec());
1683 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1684 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1685 debugs(33, 3, "clientPackMoreRanges: out:"
1686 " start: " << start
<<
1687 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1688 " [" << http
->range_iter
.currentSpec()->offset
<<
1689 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1690 " len: " << http
->range_iter
.currentSpec()->length
<<
1691 " debt: " << http
->range_iter
.debt());
1692 if (http
->range_iter
.currentSpec()->length
!= -1)
1693 assert(http
->out
.offset
<= start
); /* we did not miss it */
1698 } else if (reply
&& reply
->content_range
) {
1699 /* request does not have ranges, but reply does */
1700 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1701 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1703 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1706 return http
->out
.offset
;
1710 ClientSocketContext::pullData()
1712 debugs(33, 5, reply
<< " written " << http
->out
.size
<< " into " << clientConnection
);
1714 /* More data will be coming from the stream. */
1715 StoreIOBuffer readBuffer
;
1716 /* XXX: Next requested byte in the range sequence */
1717 /* XXX: length = getmaximumrangelenfgth */
1718 readBuffer
.offset
= getNextRangeOffset();
1719 readBuffer
.length
= HTTP_REQBUF_SZ
;
1720 readBuffer
.data
= reqbuf
;
1721 /* we may note we have reached the end of the wanted ranges */
1722 clientStreamRead(getTail(), http
, readBuffer
);
1725 /** Adapt stream status to account for Range cases
1728 clientStream_status_t
1729 ClientSocketContext::socketState()
1731 switch (clientStreamStatus(getTail(), http
)) {
1734 /* check for range support ending */
1736 if (http
->request
->range
) {
1737 /* check: reply was parsed and range iterator was initialized */
1738 assert(http
->range_iter
.valid
);
1739 /* filter out data according to range specs */
1741 if (!canPackMoreRanges()) {
1742 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1743 "range sequence on " << clientConnection
);
1744 // we got everything we wanted from the store
1745 return STREAM_COMPLETE
;
1747 } else if (reply
&& reply
->content_range
) {
1748 /* reply has content-range, but Squid is not managing ranges */
1749 const int64_t &bytesSent
= http
->out
.offset
;
1750 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1752 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1753 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1754 reply
->content_range
->spec
.offset
<< ")");
1756 // did we get at least what we expected, based on range specs?
1758 if (bytesSent
== bytesExpected
) // got everything
1759 return STREAM_COMPLETE
;
1761 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1762 return STREAM_UNPLANNED_COMPLETE
;
1767 case STREAM_COMPLETE
:
1768 return STREAM_COMPLETE
;
1770 case STREAM_UNPLANNED_COMPLETE
:
1771 return STREAM_UNPLANNED_COMPLETE
;
1774 return STREAM_FAILED
;
1777 fatal ("unreachable code\n");
1782 * A write has just completed to the client, or we have just realised there is
1783 * no more data to send.
1786 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, Comm::Flag errflag
, int, void *data
)
1788 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1789 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1792 /// remembers the abnormal connection termination for logging purposes
1794 ClientSocketContext::noteIoError(const int xerrno
)
1797 if (xerrno
== ETIMEDOUT
)
1798 http
->al
->http
.timedout
= true;
1799 else // even if xerrno is zero (which means read abort/eof)
1800 http
->al
->http
.aborted
= true;
1805 ClientSocketContext::doClose()
1807 clientConnection
->close();
1810 /// called when we encounter a response-related error
1812 ClientSocketContext::initiateClose(const char *reason
)
1814 http
->getConn()->stopSending(reason
); // closes ASAP
1818 ConnStateData::stopSending(const char *error
)
1820 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1821 "; old receiving error: " <<
1822 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1824 if (const char *oldError
= stoppedSending()) {
1825 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1826 return; // nothing has changed as far as this connection is concerned
1828 stoppedSending_
= error
;
1830 if (!stoppedReceiving()) {
1831 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1832 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1833 " request body bytes with " << in
.buf
.length() << " unused");
1834 return; // wait for the request receiver to finish reading
1838 clientConnection
->close();
1842 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
)
1844 const StoreEntry
*entry
= http
->storeEntry();
1845 http
->out
.size
+= size
;
1846 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1847 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1848 (entry
? entry
->objectLen() : 0));
1849 clientUpdateSocketStats(http
->logType
, size
);
1851 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
1853 if (errflag
== Comm::ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1856 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1857 initiateClose("failure or true request status");
1858 /* Do we leak here ? */
1862 switch (socketState()) {
1868 case STREAM_COMPLETE
:
1869 debugs(33, 5, conn
<< "Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1870 if (http
->request
->flags
.proxyKeepalive
)
1871 keepaliveNextRequest();
1873 initiateClose("STREAM_COMPLETE NOKEEPALIVE");
1876 case STREAM_UNPLANNED_COMPLETE
:
1877 initiateClose("STREAM_UNPLANNED_COMPLETE");
1881 initiateClose("STREAM_FAILED");
1885 fatal("Hit unreachable code in clientWriteComplete\n");
1889 ClientSocketContext
*
1890 ConnStateData::abortRequestParsing(const char *const uri
)
1892 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1893 http
->req_sz
= in
.buf
.length();
1894 http
->uri
= xstrdup(uri
);
1895 setLogUri (http
, uri
);
1896 ClientSocketContext
*context
= new ClientSocketContext(clientConnection
, http
);
1897 StoreIOBuffer tempBuffer
;
1898 tempBuffer
.data
= context
->reqbuf
;
1899 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1900 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1901 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1902 clientSocketDetach
, context
, tempBuffer
);
1907 skipLeadingSpace(char *aString
)
1909 char *result
= aString
;
1911 while (xisspace(*aString
))
1918 * 'end' defaults to NULL for backwards compatibility
1919 * remove default value if we ever get rid of NULL-terminated
1923 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1926 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1930 for (; end
> uriAndHTTPVersion
; --end
) {
1931 if (*end
== '\n' || *end
== '\r')
1934 if (xisspace(*end
)) {
1935 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1946 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1948 safe_free(http
->log_uri
);
1951 // The uri is already clean just dump it.
1952 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1955 switch (Config
.uri_whitespace
) {
1956 case URI_WHITESPACE_ALLOW
:
1957 flags
|= RFC1738_ESCAPE_NOSPACE
;
1959 case URI_WHITESPACE_ENCODE
:
1960 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1961 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1964 case URI_WHITESPACE_CHOP
: {
1965 flags
|= RFC1738_ESCAPE_NOSPACE
;
1966 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1967 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1968 int pos
= strcspn(http
->log_uri
, w_space
);
1969 http
->log_uri
[pos
] = '\0';
1973 case URI_WHITESPACE_DENY
:
1974 case URI_WHITESPACE_STRIP
:
1977 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1981 if (!xisspace(*t
)) {
1988 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
1997 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1999 int vhost
= conn
->port
->vhost
;
2000 int vport
= conn
->port
->vport
;
2001 static char ipbuf
[MAX_IPSTRLEN
];
2003 http
->flags
.accel
= true;
2005 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2007 static const SBuf
cache_object("cache_object://");
2008 if (hp
->requestUri().startsWith(cache_object
))
2009 return; /* already in good shape */
2011 // XXX: re-use proper URL parser for this
2012 SBuf url
= hp
->requestUri(); // use full provided URI if we abort
2013 do { // use a loop so we can break out of it
2014 ::Parser::Tokenizer
tok(url
);
2015 if (tok
.skip('/')) // origin-form URL already.
2018 if (conn
->port
->vhost
)
2019 return; /* already in good shape */
2021 // skip the URI scheme
2022 static const CharacterSet uriScheme
= CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
2023 static const SBuf
uriSchemeEnd("://");
2024 if (!tok
.skipAll(uriScheme
) || !tok
.skip(uriSchemeEnd
))
2027 // skip the authority segment
2028 // RFC 3986 complex nested ABNF for "authority" boils down to this:
2029 static const CharacterSet authority
= CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
2030 CharacterSet::HEXDIG
+ CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
2031 if (!tok
.skipAll(authority
))
2034 static const SBuf
slashUri("/");
2035 const SBuf t
= tok
.remaining();
2038 else if (t
[0]=='/') // looks like path
2040 else if (t
[0]=='?' || t
[0]=='#') { // looks like query or fragment. fix '/'
2043 } // else do nothing. invalid path
2047 #if SHOULD_REJECT_UNKNOWN_URLS
2048 // reject URI which are not well-formed even after the processing above
2049 if (url
.isEmpty() || url
[0] != '/') {
2050 hp
->request_parse_status
= Http::scBadRequest
;
2051 return conn
->abortRequestParsing("error:invalid-request");
2056 vport
= http
->getConn()->clientConnection
->local
.port();
2058 const bool switchedToHttps
= conn
->switchedToHttps();
2059 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2061 if (tryHostHeader
&& (host
= hp
->getHeaderField("Host"))) {
2062 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2067 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2068 strncpy(thost
, host
, (t
-host
));
2069 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2072 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2075 } // else nothing to alter port-wise.
2076 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+ strlen(host
);
2077 http
->uri
= (char *)xcalloc(url_sz
, 1);
2078 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
, AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(url
));
2079 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
2080 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2081 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2082 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
2083 strlen(conn
->port
->defaultsite
);
2084 http
->uri
= (char *)xcalloc(url_sz
, 1);
2088 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2090 snprintf(http
->uri
, url_sz
, "%s://%s%s" SQUIDSBUFPH
,
2091 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
2092 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
2093 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2094 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
2095 /* Put the local socket IP address as the hostname, with whatever vport we found */
2096 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
2097 http
->uri
= (char *)xcalloc(url_sz
, 1);
2098 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2099 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
2100 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(),
2101 ipbuf
, vport
, SQUIDSBUFPRINT(url
));
2102 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
2107 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
2109 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
2110 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
2111 return; /* already in good shape */
2113 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2115 if (const char *host
= hp
->getHeaderField("Host")) {
2116 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
2118 http
->uri
= (char *)xcalloc(url_sz
, 1);
2119 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
,
2120 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(hp
->requestUri()));
2121 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
2123 /* Put the local socket IP address as the hostname. */
2124 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
2125 http
->uri
= (char *)xcalloc(url_sz
, 1);
2126 static char ipbuf
[MAX_IPSTRLEN
];
2127 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2128 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
2129 AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).c_str(),
2130 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SQUIDSBUFPRINT(hp
->requestUri()));
2131 debugs(33, 5, "TRANSPARENT REWRITE: " << http
->uri
);
2135 /** Parse an HTTP request
2137 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2138 * to 1 if the request was correctly parsed.
2139 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2140 * \param[in] hp an Http1::RequestParser
2141 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2142 * Pointed-to value will be set to Http::METHOD_NONE in case of
2144 * \param[out] http_ver will be set as a side-effect of the parsing
2145 * \return NULL on incomplete requests,
2146 * a ClientSocketContext structure on success or failure.
2148 ClientSocketContext
*
2149 parseHttpRequest(ConnStateData
*csd
, const Http1::RequestParserPointer
&hp
)
2151 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
2153 const bool parsedOk
= hp
->parse(csd
->in
.buf
);
2155 // sync the buffers after parsing.
2156 csd
->in
.buf
= hp
->remaining();
2158 if (hp
->needsMoreData()) {
2159 debugs(33, 5, "Incomplete request, waiting for end of request line");
2164 if (hp
->request_parse_status
== Http::scRequestHeaderFieldsTooLarge
|| hp
->request_parse_status
== Http::scUriTooLong
)
2165 return csd
->abortRequestParsing("error:request-too-large");
2167 return csd
->abortRequestParsing("error:invalid-request");
2171 /* We know the whole request is in parser now */
2172 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2173 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
2174 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
2178 /* deny CONNECT via accelerated ports */
2179 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
2180 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
2181 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2182 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2183 return csd
->abortRequestParsing("error:method-not-allowed");
2186 /* draft-ietf-httpbis-http2-16 section 11.6 registers the method PRI as HTTP/2 specific
2187 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
2188 * If seen it signals a broken client or proxy has corrupted the traffic.
2190 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
2191 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
2192 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2193 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2194 return csd
->abortRequestParsing("error:method-not-allowed");
2197 if (hp
->method() == Http::METHOD_NONE
) {
2198 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2199 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2200 return csd
->abortRequestParsing("error:unsupported-request-method");
2203 // Process headers after request line
2204 debugs(33, 3, "complete request received. " <<
2205 "prefix_sz = " << hp
->messageHeaderSize() <<
2206 ", request-line-size=" << hp
->firstLineSize() <<
2207 ", mime-header-size=" << hp
->headerBlockSize() <<
2208 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
2210 /* Ok, all headers are received */
2211 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
2213 http
->req_sz
= hp
->messageHeaderSize();
2214 ClientSocketContext
*result
= new ClientSocketContext(csd
->clientConnection
, http
);
2216 StoreIOBuffer tempBuffer
;
2217 tempBuffer
.data
= result
->reqbuf
;
2218 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2220 ClientStreamData newServer
= new clientReplyContext(http
);
2221 ClientStreamData newClient
= result
;
2222 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2223 clientReplyStatus
, newServer
, clientSocketRecipient
,
2224 clientSocketDetach
, newClient
, tempBuffer
);
2227 // XXX: c_str() does re-allocate but here replaces explicit malloc/free.
2228 // when internalCheck() accepts SBuf removing this will be a net gain for performance.
2229 SBuf
tmp(hp
->requestUri());
2230 const char *url
= tmp
.c_str();
2232 debugs(33,5, HERE
<< "repare absolute URL from " <<
2233 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2234 /* Rewrite the URL in transparent or accelerator mode */
2235 /* NP: there are several cases to traverse here:
2236 * - standard mode (forward proxy)
2237 * - transparent mode (TPROXY)
2238 * - transparent mode with failures
2239 * - intercept mode (NAT)
2240 * - intercept mode with failures
2241 * - accelerator mode (reverse proxy)
2243 * - mixed combos of the above with internal URL
2244 * - remote interception with PROXY protocol
2245 * - remote reverse-proxy with PROXY protocol
2247 if (csd
->transparent()) {
2248 /* intercept or transparent mode, properly working with no failures */
2249 prepareTransparentURL(csd
, http
, hp
);
2251 } else if (internalCheck(url
)) {
2252 /* internal URL mode */
2253 /* prepend our name & port */
2254 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2255 // We just re-wrote the URL. Must replace the Host: header.
2256 // But have not parsed there yet!! flag for local-only handling.
2257 http
->flags
.internal
= true;
2259 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2260 /* accelerator mode */
2261 prepareAcceleratedURL(csd
, http
, hp
);
2265 /* No special rewrites have been applied above, use the
2266 * requested url. may be rewritten later, so make extra room */
2267 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
2268 http
->uri
= (char *)xcalloc(url_sz
, 1);
2269 strcpy(http
->uri
, url
);
2272 result
->flags
.parsed_ok
= 1;
2277 ConnStateData::In::maybeMakeSpaceAvailable()
2279 if (buf
.spaceSize() < 2) {
2280 const SBuf::size_type haveCapacity
= buf
.length() + buf
.spaceSize();
2281 if (haveCapacity
>= Config
.maxRequestBufferSize
) {
2282 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2285 if (haveCapacity
== 0) {
2286 // haveCapacity is based on the SBuf visible window of the MemBlob buffer, which may fill up.
2287 // at which point bump the buffer back to default. This allocates a new MemBlob with any un-parsed bytes.
2288 buf
.reserveCapacity(CLIENT_REQ_BUF_SZ
);
2290 const SBuf::size_type wantCapacity
= min(static_cast<SBuf::size_type
>(Config
.maxRequestBufferSize
), haveCapacity
*2);
2291 buf
.reserveCapacity(wantCapacity
);
2293 debugs(33, 2, "growing request buffer: available=" << buf
.spaceSize() << " used=" << buf
.length());
2295 return (buf
.spaceSize() >= 2);
2299 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2301 ClientSocketContext::Pointer
*S
;
2303 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2311 ConnStateData::getConcurrentRequestCount() const
2314 ClientSocketContext::Pointer
*T
;
2316 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2317 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2322 ConnStateData::connFinishedWithConn(int size
)
2325 if (getConcurrentRequestCount() == 0 && in
.buf
.isEmpty()) {
2326 /* no current or pending requests */
2327 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2329 } else if (!Config
.onoff
.half_closed_clients
) {
2330 /* admin doesn't want to support half-closed client sockets */
2331 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2332 notifyAllContexts(0); // no specific error implies abort
2341 ConnStateData::consumeInput(const size_t byteCount
)
2343 assert(byteCount
> 0 && byteCount
<= in
.buf
.length());
2344 in
.buf
.consume(byteCount
);
2345 debugs(33, 5, "in.buf has " << in
.buf
.length() << " unused bytes");
2349 ConnStateData::clientAfterReadingRequests()
2351 // Were we expecting to read more request body from half-closed connection?
2352 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2353 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2354 clientConnection
->close();
2363 ConnStateData::quitAfterError(HttpRequest
*request
)
2365 // From HTTP p.o.v., we do not have to close after every error detected
2366 // at the client-side, but many such errors do require closure and the
2367 // client-side code is bad at handling errors so we play it safe.
2369 request
->flags
.proxyKeepalive
= false;
2370 flags
.readMore
= false;
2371 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2375 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2377 ClientHttpRequest
*http
= context
->http
;
2382 assert(sslServerBump
->entry
);
2383 // Did we create an error entry while processing CONNECT?
2384 if (!sslServerBump
->entry
->isEmpty()) {
2385 quitAfterError(http
->request
);
2387 // Get the saved error entry and send it to the client by replacing the
2388 // ClientHttpRequest store entry with it.
2389 clientStreamNode
*node
= context
->getClientReplyContext();
2390 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2392 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2393 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
2395 // save the original request for logging purposes
2396 if (!context
->http
->al
->request
) {
2397 context
->http
->al
->request
= http
->request
;
2398 HTTPMSGLOCK(context
->http
->al
->request
);
2401 // Get error details from the fake certificate-peeking request.
2402 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2403 context
->pullData();
2407 // In bump-server-first mode, we have not necessarily seen the intended
2408 // server name at certificate-peeking time. Check for domain mismatch now,
2409 // when we can extract the intended name from the bumped HTTP request.
2410 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2411 HttpRequest
*request
= http
->request
;
2412 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2413 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2414 "does not match domainname " << request
->GetHost());
2416 bool allowDomainMismatch
= false;
2417 if (Config
.ssl_client
.cert_error
) {
2418 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2419 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2420 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2421 delete check
.sslErrors
;
2422 check
.sslErrors
= NULL
;
2425 if (!allowDomainMismatch
) {
2426 quitAfterError(request
);
2428 clientStreamNode
*node
= context
->getClientReplyContext();
2429 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2430 assert (repContext
);
2432 // Fill the server IP and hostname for error page generation.
2433 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2434 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2436 // Create an error object and fill it
2437 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2438 err
->src_addr
= clientConnection
->remote
;
2439 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2440 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2442 err
->detail
= errDetail
;
2443 // Save the original request for logging purposes.
2444 if (!context
->http
->al
->request
) {
2445 context
->http
->al
->request
= request
;
2446 HTTPMSGLOCK(context
->http
->al
->request
);
2448 repContext
->setReplyToError(request
->method
, err
);
2449 assert(context
->http
->out
.offset
== 0);
2450 context
->pullData();
2458 #endif // USE_OPENSSL
2461 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
2465 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2466 * to here because calling comm_reset_close() causes http to
2467 * be freed before accessing.
2469 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2470 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2471 conn
->flags
.readMore
= false;
2472 comm_reset_close(conn
->clientConnection
);
2477 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, ClientSocketContext
*context
)
2479 ClientHttpRequest
*http
= context
->http
;
2480 bool chunked
= false;
2481 bool mustReplyToOptions
= false;
2482 bool unsupportedTe
= false;
2483 bool expectBody
= false;
2485 // We already have the request parsed and checked, so we
2486 // only need to go through the final body/conn setup to doCallouts().
2487 assert(http
->request
);
2488 HttpRequest::Pointer request
= http
->request
;
2490 // temporary hack to avoid splitting this huge function with sensitive code
2491 const bool isFtp
= !hp
;
2493 // Some blobs below are still HTTP-specific, but we would have to rewrite
2494 // this entire function to remove them from the FTP code path. Connection
2495 // setup and body_pipe preparation blobs are needed for FTP.
2497 request
->clientConnectionManager
= conn
;
2499 request
->flags
.accelerated
= http
->flags
.accel
;
2500 request
->flags
.sslBumped
=conn
->switchedToHttps();
2501 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2502 // TODO: decouple http->flags.accel from request->flags.sslBumped
2503 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2504 !conn
->port
->allow_direct
: 0;
2506 if (request
->flags
.sslBumped
) {
2507 if (conn
->getAuth() != NULL
)
2508 request
->auth_user_request
= conn
->getAuth();
2513 * If transparent or interception mode is working clone the transparent and interception flags
2514 * from the port settings to the request.
2516 if (http
->clientConnection
!= NULL
) {
2517 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2518 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2519 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
2520 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
2521 if (Config
.accessList
.spoof_client_ip
) {
2522 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2523 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2526 request
->flags
.spoofClientIp
= true;
2528 request
->flags
.spoofClientIp
= false;
2531 if (internalCheck(request
->urlpath
.termedBuf())) {
2532 if (internalHostnameIs(request
->GetHost()) && request
->port
== getMyPort()) {
2533 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2534 ':' << request
->port
);
2535 http
->flags
.internal
= true;
2536 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2537 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2538 ':' << request
->port
<< " (global_internal_static on)");
2539 request
->SetHost(internalHostname());
2540 request
->port
= getMyPort();
2541 http
->flags
.internal
= true;
2543 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2544 ':' << request
->port
<< " (not this proxy)");
2547 request
->flags
.internal
= http
->flags
.internal
;
2548 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2549 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2550 #if FOLLOW_X_FORWARDED_FOR
2551 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2552 // not a details about teh TCP connection itself
2553 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2554 #endif /* FOLLOW_X_FORWARDED_FOR */
2555 request
->my_addr
= conn
->clientConnection
->local
;
2556 request
->myportname
= conn
->port
->name
;
2559 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
2560 // for now Squid only supports HTTP requests
2561 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
2562 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
2563 request
->http_ver
.major
= http_ver
.major
;
2564 request
->http_ver
.minor
= http_ver
.minor
;
2567 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2568 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2569 request
->clientConnectionManager
= conn
;
2571 if (request
->header
.chunked()) {
2573 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2574 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2575 // HTTP/1.1 requires chunking to be the last encoding if there is one
2576 unsupportedTe
= te
.size() && te
!= "identity";
2577 } // else implied identity coding
2579 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
2580 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2581 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2582 clientStreamNode
*node
= context
->getClientReplyContext();
2583 conn
->quitAfterError(request
.getRaw());
2584 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2585 assert (repContext
);
2586 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2587 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2588 assert(context
->http
->out
.offset
== 0);
2589 context
->pullData();
2590 clientProcessRequestFinished(conn
, request
);
2594 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2595 clientStreamNode
*node
= context
->getClientReplyContext();
2596 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2597 assert (repContext
);
2598 conn
->quitAfterError(request
.getRaw());
2599 repContext
->setReplyToError(ERR_INVALID_REQ
,
2600 Http::scLengthRequired
, request
->method
, NULL
,
2601 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2602 assert(context
->http
->out
.offset
== 0);
2603 context
->pullData();
2604 clientProcessRequestFinished(conn
, request
);
2608 if (request
->header
.has(HDR_EXPECT
)) {
2609 const String expect
= request
->header
.getList(HDR_EXPECT
);
2610 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2611 if (!supportedExpect
) {
2612 clientStreamNode
*node
= context
->getClientReplyContext();
2613 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2614 assert (repContext
);
2615 conn
->quitAfterError(request
.getRaw());
2616 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2617 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2618 assert(context
->http
->out
.offset
== 0);
2619 context
->pullData();
2620 clientProcessRequestFinished(conn
, request
);
2625 clientSetKeepaliveFlag(http
);
2626 // Let tunneling code be fully responsible for CONNECT requests
2627 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2628 context
->mayUseConnection(true);
2629 conn
->flags
.readMore
= false;
2633 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
2634 clientProcessRequestFinished(conn
, request
);
2639 /* Do we expect a request-body? */
2640 expectBody
= chunked
|| request
->content_length
> 0;
2641 if (!context
->mayUseConnection() && expectBody
) {
2642 request
->body_pipe
= conn
->expectRequestBody(
2643 chunked
? -1 : request
->content_length
);
2645 /* Is it too large? */
2646 if (!chunked
&& // if chunked, we will check as we accumulate
2647 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2648 clientStreamNode
*node
= context
->getClientReplyContext();
2649 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2650 assert (repContext
);
2651 conn
->quitAfterError(request
.getRaw());
2652 repContext
->setReplyToError(ERR_TOO_BIG
,
2653 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
2654 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2655 assert(context
->http
->out
.offset
== 0);
2656 context
->pullData();
2657 clientProcessRequestFinished(conn
, request
);
2662 // We may stop producing, comm_close, and/or call setReplyToError()
2663 // below, so quit on errors to avoid http->doCallouts()
2664 if (!conn
->handleRequestBodyData()) {
2665 clientProcessRequestFinished(conn
, request
);
2669 if (!request
->body_pipe
->productionEnded()) {
2670 debugs(33, 5, "need more request body");
2671 context
->mayUseConnection(true);
2672 assert(conn
->flags
.readMore
);
2677 http
->calloutContext
= new ClientRequestContext(http
);
2681 clientProcessRequestFinished(conn
, request
);
2685 ConnStateData::pipelinePrefetchMax() const
2687 return Config
.pipeline_max_prefetch
;
2691 * Limit the number of concurrent requests.
2692 * \return true when there are available position(s) in the pipeline queue for another request.
2693 * \return false when the pipeline queue is full or disabled.
2696 ConnStateData::concurrentRequestQueueFilled() const
2698 const int existingRequestCount
= getConcurrentRequestCount();
2700 // default to the configured pipeline size.
2701 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2702 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1;
2704 // when queue filled already we cant add more.
2705 if (existingRequestCount
>= concurrentRequestLimit
) {
2706 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2707 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2715 * Perform proxy_protocol_access ACL tests on the client which
2716 * connected to PROXY protocol port to see if we trust the
2717 * sender enough to accept their PROXY header claim.
2720 ConnStateData::proxyProtocolValidateClient()
2722 if (!Config
.accessList
.proxyProtocol
)
2723 return proxyProtocolError("PROXY client not permitted by default ACL");
2725 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
2726 ch
.src_addr
= clientConnection
->remote
;
2727 ch
.my_addr
= clientConnection
->local
;
2730 if (ch
.fastCheck() != ACCESS_ALLOWED
)
2731 return proxyProtocolError("PROXY client not permitted by ACLs");
2737 * Perform cleanup on PROXY protocol errors.
2738 * If header parsing hits a fatal error terminate the connection,
2739 * otherwise wait for more data.
2742 ConnStateData::proxyProtocolError(const char *msg
)
2745 // This is important to know, but maybe not so much that flooding the log is okay.
2746 #if QUIET_PROXY_PROTOCOL
2747 // display the first of every 32 occurances at level 1, the others at level 2.
2748 static uint8_t hide
= 0;
2749 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
2751 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
2758 /// magic octet prefix for PROXY protocol version 1
2759 static const SBuf
Proxy1p0magic("PROXY ", 6);
2761 /// magic octet prefix for PROXY protocol version 2
2762 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
2765 * Test the connection read buffer for PROXY protocol header.
2766 * Version 1 and 2 header currently supported.
2769 ConnStateData::parseProxyProtocolHeader()
2771 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
2773 // detect and parse PROXY/2.0 protocol header
2774 if (in
.buf
.startsWith(Proxy2p0magic
))
2775 return parseProxy2p0();
2777 // detect and parse PROXY/1.0 protocol header
2778 if (in
.buf
.startsWith(Proxy1p0magic
))
2779 return parseProxy1p0();
2781 // detect and terminate other protocols
2782 if (in
.buf
.length() >= Proxy2p0magic
.length()) {
2783 // PROXY/1.0 magic is shorter, so we know that
2784 // the input does not start with any PROXY magic
2785 return proxyProtocolError("PROXY protocol error: invalid header");
2788 // TODO: detect short non-magic prefixes earlier to avoid
2789 // waiting for more data which may never come
2791 // not enough bytes to parse yet.
2795 /// parse the PROXY/1.0 protocol header from the connection read buffer
2797 ConnStateData::parseProxy1p0()
2799 ::Parser::Tokenizer
tok(in
.buf
);
2800 tok
.skip(Proxy1p0magic
);
2802 // skip to first LF (assumes it is part of CRLF)
2803 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
2805 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
2806 if (tok
.skip('\n')) {
2807 // found valid header
2808 in
.buf
= tok
.remaining();
2809 needProxyProtocolHeader_
= false;
2810 // reset the tokenizer to work on found line only.
2813 return false; // no LF yet
2815 } else // protocol error only if there are more than 107 bytes prefix header
2816 return proxyProtocolError(in
.buf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
2818 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
2819 if (tok
.skip(tcpName
)) {
2821 // skip TCP/IP version number
2822 static const CharacterSet
tcpVersions("TCP-version","46");
2823 if (!tok
.skipOne(tcpVersions
))
2824 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
2826 // skip SP after protocol version
2828 return proxyProtocolError("PROXY/1.0 error: missing SP");
2831 int64_t porta
, portb
;
2832 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
2834 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
2835 // leave the LF until later.
2836 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
2837 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
2838 tok
.int64(porta
) && tok
.skip(' ') &&
2842 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
2844 // parse IP and port strings
2845 Ip::Address originalClient
, originalDest
;
2847 if (!originalClient
.GetHostByName(ipa
.c_str()))
2848 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
2850 if (!originalDest
.GetHostByName(ipb
.c_str()))
2851 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
2853 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
2854 originalClient
.port(static_cast<uint16_t>(porta
));
2856 return proxyProtocolError("PROXY/1.0 error: invalid src port");
2858 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
2859 originalDest
.port(static_cast<uint16_t>(portb
));
2861 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
2863 // we have original client and destination details now
2864 // replace the client connection values
2865 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
2866 clientConnection
->local
= originalDest
;
2867 clientConnection
->remote
= originalClient
;
2868 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2869 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2871 // repeat fetch ensuring the new client FQDN can be logged
2872 if (Config
.onoff
.log_fqdn
)
2873 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2877 } else if (tok
.skip(unknown
)) {
2878 // found valid but unusable header
2882 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2887 /// parse the PROXY/2.0 protocol header from the connection read buffer
2889 ConnStateData::parseProxy2p0()
2891 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2892 if (in
.buf
.length() < prefixLen
+ 4)
2893 return false; // need more bytes
2895 if ((in
.buf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2896 return proxyProtocolError("PROXY/2.0 error: invalid version");
2898 const char command
= (in
.buf
[prefixLen
] & 0x0F);
2899 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2900 return proxyProtocolError("PROXY/2.0 error: invalid command");
2902 const char family
= (in
.buf
[prefixLen
+1] & 0xF0) >>4;
2903 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2904 return proxyProtocolError("PROXY/2.0 error: invalid family");
2906 const char proto
= (in
.buf
[prefixLen
+1] & 0x0F);
2907 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2908 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2910 const char *clen
= in
.buf
.rawContent() + prefixLen
+ 2;
2912 memcpy(&len
, clen
, sizeof(len
));
2915 if (in
.buf
.length() < prefixLen
+ 4 + len
)
2916 return false; // need more bytes
2918 in
.buf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2919 const SBuf extra
= in
.buf
.consume(len
);
2920 needProxyProtocolHeader_
= false; // found successfully
2922 // LOCAL connections do nothing with the extras
2923 if (command
== 0x00/* LOCAL*/)
2927 struct { /* for TCP/UDP over IPv4, len = 12 */
2928 struct in_addr src_addr
;
2929 struct in_addr dst_addr
;
2933 struct { /* for TCP/UDP over IPv6, len = 36 */
2934 struct in6_addr src_addr
;
2935 struct in6_addr dst_addr
;
2940 struct { /* for AF_UNIX sockets, len = 216 */
2941 uint8_t src_addr
[108];
2942 uint8_t dst_addr
[108];
2948 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2950 // replace the client connection values
2951 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2954 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2955 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2956 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2957 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2958 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2961 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2962 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2963 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2964 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2965 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2967 default: // do nothing
2970 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2972 // repeat fetch ensuring the new client FQDN can be logged
2973 if (Config
.onoff
.log_fqdn
)
2974 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2980 * Attempt to parse one or more requests from the input buffer.
2981 * Returns true after completing parsing of at least one request [header]. That
2982 * includes cases where parsing ended with an error (e.g., a huge request).
2985 ConnStateData::clientParseRequests()
2987 bool parsed_req
= false;
2989 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2991 // Loop while we have read bytes that are not needed for producing the body
2992 // On errors, bodyPipe may become nil, but readMore will be cleared
2993 while (!in
.buf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2995 /* Don't try to parse if the buffer is empty */
2996 if (in
.buf
.isEmpty())
2999 /* Limit the number of concurrent requests */
3000 if (concurrentRequestQueueFilled())
3003 /*Do not read more requests if persistent connection lifetime exceeded*/
3004 if (Config
.Timeout
.pconnLifetime
&& clientConnection
->lifeTime() > Config
.Timeout
.pconnLifetime
) {
3005 flags
.readMore
= false;
3009 // try to parse the PROXY protocol header magic bytes
3010 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
3013 if (ClientSocketContext
*context
= parseOneRequest()) {
3014 debugs(33, 5, clientConnection
<< ": done parsing a request");
3016 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3017 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
3018 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3020 context
->registerWithConn();
3022 processParsedRequest(context
);
3024 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3026 if (context
->mayUseConnection()) {
3027 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3031 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
3032 in
.buf
.length() << " < " << Config
.maxRequestHeaderSize
);
3033 Must(in
.buf
.length() < Config
.maxRequestHeaderSize
);
3038 /* XXX where to 'finish' the parsing pass? */
3043 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3045 debugs(33,5, io
.conn
);
3049 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
3050 if (io
.flag
== Comm::ERR_CLOSING
) {
3051 debugs(33,5, io
.conn
<< " closing Bailout.");
3055 assert(Comm::IsConnOpen(clientConnection
));
3056 assert(io
.conn
->fd
== clientConnection
->fd
);
3059 * Don't reset the timeout value here. The value should be
3060 * counting Config.Timeout.request and applies to the request
3061 * as a whole, not individual read() calls.
3062 * Plus, it breaks our lame *HalfClosed() detection
3065 CommIoCbParams
rd(this); // will be expanded with ReadNow results
3067 switch (Comm::ReadNow(rd
, in
.buf
)) {
3068 case Comm::INPROGRESS
:
3069 if (in
.buf
.isEmpty())
3070 debugs(33, 2, io
.conn
<< ": no data to process, " << xstrerr(rd
.xerrno
));
3075 kb_incr(&(statCounter
.client_http
.kbytes_in
), rd
.size
);
3076 // may comm_close or setReplyToError
3077 if (!handleReadData())
3080 /* Continue to process previously read data */
3083 case Comm::ENDFILE
: // close detected by 0-byte read
3084 debugs(33, 5, io
.conn
<< " closed?");
3086 if (connFinishedWithConn(rd
.size
)) {
3087 clientConnection
->close();
3091 /* It might be half-closed, we can't tell */
3092 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3093 commMarkHalfClosed(io
.conn
->fd
);
3094 fd_note(io
.conn
->fd
, "half-closed");
3096 /* There is one more close check at the end, to detect aborted
3097 * (partial) requests. At this point we can't tell if the request
3101 /* Continue to process previously read data */
3104 // case Comm::COMM_ERROR:
3105 default: // no other flags should ever occur
3106 debugs(33, 2, io
.conn
<< ": got flag " << rd
.flag
<< "; " << xstrerr(rd
.xerrno
));
3107 notifyAllContexts(rd
.xerrno
);
3112 /* Process next request */
3113 if (getConcurrentRequestCount() == 0)
3114 fd_note(io
.fd
, "Reading next request");
3116 if (!clientParseRequests()) {
3120 * If the client here is half closed and we failed
3121 * to parse a request, close the connection.
3122 * The above check with connFinishedWithConn() only
3123 * succeeds _if_ the buffer is empty which it won't
3124 * be if we have an incomplete request.
3125 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3127 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3128 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3129 clientConnection
->close();
3137 clientAfterReadingRequests();
3141 * called when new request data has been read from the socket
3143 * \retval false called comm_close or setReplyToError (the caller should bail)
3144 * \retval true we did not call comm_close or setReplyToError
3147 ConnStateData::handleReadData()
3149 // if we are reading a body, stuff data into the body pipe
3150 if (bodyPipe
!= NULL
)
3151 return handleRequestBodyData();
3156 * called when new request body data has been buffered in in.buf
3157 * may close the connection if we were closing and piped everything out
3159 * \retval false called comm_close or setReplyToError (the caller should bail)
3160 * \retval true we did not call comm_close or setReplyToError
3163 ConnStateData::handleRequestBodyData()
3165 assert(bodyPipe
!= NULL
);
3169 if (in
.bodyParser
) { // chunked encoding
3170 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3171 abortChunkedRequestBody(error
);
3174 } else { // identity encoding
3175 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3176 putSize
= bodyPipe
->putMoreData(in
.buf
.c_str(), in
.buf
.length());
3177 if (!bodyPipe
->mayNeedMoreData()) {
3178 // BodyPipe will clear us automagically when we produced everything
3184 consumeInput(putSize
);
3187 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3189 if (const char *reason
= stoppedSending()) {
3190 /* we've finished reading like good clients,
3191 * now do the close that initiateClose initiated.
3193 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3194 clientConnection
->close();
3202 /// parses available chunked encoded body bytes, checks size, returns errors
3204 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3206 debugs(33, 7, "chunked from " << clientConnection
<< ": " << in
.buf
.length());
3208 try { // the parser will throw on errors
3210 if (in
.buf
.isEmpty()) // nothing to do
3213 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3214 // add one because MemBuf will assert if it cannot 0-terminate
3215 raw
.init(in
.buf
.length(), in
.buf
.length()+1);
3216 raw
.append(in
.buf
.c_str(), in
.buf
.length());
3218 const mb_size_t wasContentSize
= raw
.contentSize();
3219 BodyPipeCheckout
bpc(*bodyPipe
);
3220 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3222 putSize
= wasContentSize
- raw
.contentSize();
3224 // dechunk then check: the size limit applies to _dechunked_ content
3225 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3229 finishDechunkingRequest(true);
3231 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3234 // if chunk parser needs data, then the body pipe must need it too
3235 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3237 // if parser needs more space and we can consume nothing, we will stall
3238 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3239 } catch (...) { // TODO: be more specific
3240 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3241 return ERR_INVALID_REQ
;
3244 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3248 /// quit on errors related to chunked request body handling
3250 ConnStateData::abortChunkedRequestBody(const err_type error
)
3252 finishDechunkingRequest(false);
3254 // XXX: The code below works if we fail during initial request parsing,
3255 // but if we fail when the server connection is used already, the server may send
3256 // us its response too, causing various assertions. How to prevent that?
3257 #if WE_KNOW_HOW_TO_SEND_ERRORS
3258 ClientSocketContext::Pointer context
= getCurrentContext();
3259 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3260 clientStreamNode
*node
= context
->getClientReplyContext();
3261 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3263 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3264 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
3265 repContext
->setReplyToError(error
, scode
,
3266 repContext
->http
->request
->method
,
3267 repContext
->http
->uri
,
3269 repContext
->http
->request
,
3271 context
->pullData();
3273 // close or otherwise we may get stuck as nobody will notice the error?
3274 comm_reset_close(clientConnection
);
3277 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3278 comm_reset_close(clientConnection
);
3280 flags
.readMore
= false;
3284 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3286 // request reader may get stuck waiting for space if nobody consumes body
3287 if (bodyPipe
!= NULL
)
3288 bodyPipe
->enableAutoConsumption();
3293 /** general lifetime handler for HTTP requests */
3295 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3298 * Just close the connection to not confuse browsers
3299 * using persistent connections. Some browsers open
3300 * a connection and then do not use it until much
3301 * later (presumeably because the request triggering
3302 * the open has already been completed on another
3305 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3310 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3312 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3313 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3314 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3315 http
->al
->http
.timedout
= true;
3316 if (Comm::IsConnOpen(io
.conn
))
3320 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3321 AsyncJob("ConnStateData"), // kids overwrite
3324 sslBumpMode(Ssl::bumpEnd
),
3326 needProxyProtocolHeader_(false),
3328 switchedToHttps_(false),
3329 sslServerBump(NULL
),
3330 signAlgorithm(Ssl::algSignTrusted
),
3332 stoppedSending_(NULL
),
3333 stoppedReceiving_(NULL
)
3335 flags
.readMore
= true; // kids may overwrite
3336 flags
.swanSang
= false;
3338 pinning
.host
= NULL
;
3340 pinning
.pinned
= false;
3341 pinning
.auth
= false;
3342 pinning
.zeroReply
= false;
3343 pinning
.peer
= NULL
;
3345 // store the details required for creating more MasterXaction objects as new requests come in
3346 clientConnection
= xact
->tcpClient
;
3347 port
= xact
->squidPort
;
3348 transferProtocol
= port
->transport
; // default to the *_port protocol= setting. may change later.
3349 log_addr
= xact
->tcpClient
->remote
;
3350 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3354 ConnStateData::start()
3356 BodyProducer::start();
3357 HttpControlMsgSink::start();
3359 // ensure a buffer is present for this connection
3360 in
.maybeMakeSpaceAvailable();
3362 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3363 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3364 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3365 int i
= IP_PMTUDISC_DONT
;
3366 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3367 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3369 static bool reported
= false;
3372 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3378 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3379 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3380 comm_add_close_handler(clientConnection
->fd
, call
);
3382 if (Config
.onoff
.log_fqdn
)
3383 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3386 if (Ident::TheConfig
.identLookup
) {
3387 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3388 identChecklist
.src_addr
= clientConnection
->remote
;
3389 identChecklist
.my_addr
= clientConnection
->local
;
3390 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3391 Ident::Start(clientConnection
, clientIdentDone
, this);
3395 clientdbEstablished(clientConnection
->remote
, 1);
3397 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
3398 if (needProxyProtocolHeader_
) {
3399 if (!proxyProtocolValidateClient()) // will close the connection on failure
3404 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
3406 if (Config
.onoff
.client_db
) {
3407 /* it was said several times that client write limiter does not work if client_db is disabled */
3409 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3410 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3412 // TODO: we check early to limit error response bandwith but we
3413 // should recheck when we can honor delay_pool_uses_indirect
3414 // TODO: we should also pass the port details for myportname here.
3415 ch
.src_addr
= clientConnection
->remote
;
3416 ch
.my_addr
= clientConnection
->local
;
3418 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3420 /* pools require explicit 'allow' to assign a client into them */
3421 if (pools
[pool
].access
) {
3422 ch
.accessList
= pools
[pool
].access
;
3423 allow_t answer
= ch
.fastCheck();
3424 if (answer
== ACCESS_ALLOWED
) {
3426 /* request client information from db after we did all checks
3427 this will save hash lookup if client failed checks */
3428 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
3431 /* put client info in FDE */
3432 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
3434 /* setup write limiter for this request */
3435 const double burst
= floor(0.5 +
3436 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3437 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3440 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3447 // kids must extend to actually start doing something (e.g., reading)
3450 /** Handle a new connection on an HTTP socket. */
3452 httpAccept(const CommAcceptCbParams
¶ms
)
3454 MasterXaction::Pointer xact
= params
.xaction
;
3455 AnyP::PortCfgPointer s
= xact
->squidPort
;
3457 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3459 if (params
.flag
!= Comm::OK
) {
3460 // Its possible the call was still queued when the client disconnected
3461 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3465 debugs(33, 4, params
.conn
<< ": accepted");
3466 fd_note(params
.conn
->fd
, "client http connect");
3468 if (s
->tcp_keepalive
.enabled
)
3469 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3471 ++incoming_sockets_accepted
;
3473 // Socket is ready, setup the connection manager to start using it
3474 ConnStateData
*connState
= Http::NewServer(xact
);
3475 AsyncJob::Start(connState
); // usually async-calls readSomeData()
3480 /** Create SSL connection structure and update fd_table */
3482 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3484 if (SSL
*ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
3485 debugs(33, 5, "will negotate SSL on " << conn
);
3494 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
3496 int fd
= conn
->clientConnection
->fd
;
3497 SSL
*ssl
= fd_table
[fd
].ssl
;
3500 if ((ret
= SSL_accept(ssl
)) <= 0) {
3501 int ssl_error
= SSL_get_error(ssl
, ret
);
3503 switch (ssl_error
) {
3505 case SSL_ERROR_WANT_READ
:
3506 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, conn
, 0);
3509 case SSL_ERROR_WANT_WRITE
:
3510 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, conn
, 0);
3513 case SSL_ERROR_SYSCALL
:
3516 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
3522 if (errno
== ECONNRESET
)
3525 debugs(83, hard
? 1 : 2, "Error negotiating SSL connection on FD " <<
3526 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3533 case SSL_ERROR_ZERO_RETURN
:
3534 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3539 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
3540 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3541 " (" << ssl_error
<< "/" << ret
<< ")");
3551 /** negotiate an SSL connection */
3553 clientNegotiateSSL(int fd
, void *data
)
3555 ConnStateData
*conn
= (ConnStateData
*)data
;
3557 SSL
*ssl
= fd_table
[fd
].ssl
;
3559 if (!Squid_SSL_accept(conn
, clientNegotiateSSL
))
3562 if (SSL_session_reused(ssl
)) {
3563 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3564 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3566 if (do_debug(83, 4)) {
3567 /* Write out the SSL session details.. actually the call below, but
3568 * OpenSSL headers do strange typecasts confusing GCC.. */
3569 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3570 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3571 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
);
3573 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3575 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3576 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3577 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3578 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3579 * Because there are two possible usable cast, if you get an error here, try the other
3580 * commented line. */
3582 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3583 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3587 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3590 /* Note: This does not automatically fflush the log file.. */
3593 debugs(83, 2, "clientNegotiateSSL: New session " <<
3594 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3595 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3599 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3600 SSL_get_cipher(ssl
));
3602 client_cert
= SSL_get_peer_certificate(ssl
);
3604 if (client_cert
!= NULL
) {
3605 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3606 " client certificate: subject: " <<
3607 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3609 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3610 " client certificate: issuer: " <<
3611 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3613 X509_free(client_cert
);
3615 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3616 " has no certificate.");
3619 conn
->readSomeData();
3623 * If SSL_CTX is given, starts reading the SSL handshake.
3624 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3627 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3631 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3633 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3636 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3637 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3638 connState
, ConnStateData::requestTimeout
);
3639 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3642 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3644 char buf
[MAX_IPSTRLEN
];
3645 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3646 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3647 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3648 fakeRequest
->port
= details
->local
.port();
3649 fakeRequest
->clientConnectionManager
= connState
;
3650 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3651 #if FOLLOW_X_FORWARDED_FOR
3652 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3654 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3655 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3656 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3657 fakeRequest
->myportname
= connState
->port
->name
;
3658 if (fakeRequest
->flags
.interceptTproxy
) {
3659 if (Config
.accessList
.spoof_client_ip
) {
3660 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3661 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3663 fakeRequest
->flags
.spoofClientIp
= true;
3665 fakeRequest
->flags
.spoofClientIp
= false;
3666 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3667 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3672 * A callback function to use with the ACLFilledChecklist callback.
3673 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3674 * else reverts the connection to tunnel mode.
3677 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3679 ConnStateData
*connState
= (ConnStateData
*) data
;
3681 // if the connection is closed or closing, just return.
3682 if (!connState
->isOpen())
3685 // Require both a match and a positive bump mode to work around exceptional
3686 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3687 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
3688 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
3689 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3691 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3692 connState
->sslBumpMode
= Ssl::bumpNone
;
3695 // fake a CONNECT request to force connState to tunnel
3696 static char ip
[MAX_IPSTRLEN
];
3697 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3698 // Pre-pend this fake request to the TLS bits already in the buffer
3700 retStr
.append("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n");
3701 connState
->in
.buf
= retStr
.append(connState
->in
.buf
);
3702 bool ret
= connState
->handleReadData();
3704 ret
= connState
->clientParseRequests();
3707 debugs(33, 2, "Failed to start fake CONNECT request for SSL bumped connection: " << connState
->clientConnection
);
3708 connState
->clientConnection
->close();
3712 /** handle a new HTTPS connection */
3714 httpsAccept(const CommAcceptCbParams
¶ms
)
3716 MasterXaction::Pointer xact
= params
.xaction
;
3717 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3719 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3721 if (params
.flag
!= Comm::OK
) {
3722 // Its possible the call was still queued when the client disconnected
3723 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3727 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3728 fd_note(params
.conn
->fd
, "client https connect");
3730 if (s
->tcp_keepalive
.enabled
) {
3731 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3734 ++incoming_sockets_accepted
;
3736 // Socket is ready, setup the connection manager to start using it
3737 ConnStateData
*connState
= Https::NewServer(xact
);
3738 AsyncJob::Start(connState
); // usually async-calls postHttpsAccept()
3742 ConnStateData::postHttpsAccept()
3744 if (port
->flags
.tunnelSslBumping
) {
3745 debugs(33, 5, "accept transparent connection: " << clientConnection
);
3747 if (!Config
.accessList
.ssl_bump
) {
3748 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
3752 // Create a fake HTTP request for ssl_bump ACL check,
3753 // using tproxy/intercept provided destination IP and port.
3754 HttpRequest
*request
= new HttpRequest();
3755 static char ip
[MAX_IPSTRLEN
];
3756 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3757 request
->SetHost(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
3758 request
->port
= clientConnection
->local
.port();
3759 request
->myportname
= port
->name
;
3761 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3762 acl_checklist
->src_addr
= clientConnection
->remote
;
3763 acl_checklist
->my_addr
= port
->s
;
3764 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
3767 SSL_CTX
*sslContext
= port
->staticSslContext
.get();
3768 httpsEstablish(this, sslContext
, Ssl::bumpNone
);
3773 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
3775 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3776 state_data
->sslCrtdHandleReply(reply
);
3780 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
3782 if (reply
.result
== Helper::BrokenHelper
) {
3783 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3784 } else if (!reply
.other().hasContent()) {
3785 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3787 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3788 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3789 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3791 if (reply
.result
!= Helper::Okay
) {
3792 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3794 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3795 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3796 doPeekAndSpliceStep();
3797 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
3798 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
3800 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3802 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3803 getSslContextDone(ctx
, true);
3809 getSslContextDone(NULL
);
3812 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3814 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3816 // fake certificate adaptation requires bump-server-first mode
3817 if (!sslServerBump
) {
3818 assert(port
->signingCert
.get());
3819 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3820 if (port
->signPkey
.get())
3821 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3822 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3826 // In case of an error while connecting to the secure server, use a fake
3827 // trusted certificate, with no mimicked fields and no adaptation
3828 // algorithms. There is nothing we can mimic so we want to minimize the
3829 // number of warnings the user will have to see to get to the error page.
3830 assert(sslServerBump
->entry
);
3831 if (sslServerBump
->entry
->isEmpty()) {
3832 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3833 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3835 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3836 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3837 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3839 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3840 // If the algorithm already set, then ignore it.
3841 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3842 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3843 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3846 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3847 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3848 const char *param
= ca
->param
;
3850 // For parameterless CN adaptation, use hostname from the
3852 if (ca
->alg
== Ssl::algSetCommonName
) {
3854 param
= sslConnectHostOrIp
.termedBuf();
3855 certProperties
.commonName
= param
;
3856 certProperties
.setCommonName
= true;
3857 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3858 certProperties
.setValidAfter
= true;
3859 else if (ca
->alg
== Ssl::algSetValidBefore
)
3860 certProperties
.setValidBefore
= true;
3862 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3863 alg
<< " param: " << (param
? param
: "-"));
3867 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3868 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3869 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3870 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3874 } else {// if (!sslServerBump->entry->isEmpty())
3875 // Use trusted certificate for a Squid-generated error
3876 // or the user would have to add a security exception
3877 // just to see the error page. We will close the connection
3878 // so that the trust is not extended to non-Squid content.
3879 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3882 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3884 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3885 assert(port
->untrustedSigningCert
.get());
3886 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3887 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3889 assert(port
->signingCert
.get());
3890 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3892 if (port
->signPkey
.get())
3893 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3895 signAlgorithm
= certProperties
.signAlgorithm
;
3897 certProperties
.signHash
= Ssl::DefaultSignHash
;
3901 ConnStateData::getSslContextStart()
3903 assert(areAllContextsForThisConnection());
3905 /* careful: freeAllContexts() above frees request, host, etc. */
3907 if (port
->generateHostCertificates
) {
3908 Ssl::CertificateProperties certProperties
;
3909 buildSslCertGenerationParams(certProperties
);
3910 sslBumpCertKey
= certProperties
.dbKey().c_str();
3911 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3913 // Disable caching for bumpPeekAndSplice mode
3914 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
3915 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3916 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3917 SSL_CTX
* dynCtx
= NULL
;
3918 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3919 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3920 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3921 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3922 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3923 getSslContextDone(dynCtx
);
3926 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3928 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3931 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3937 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3938 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3939 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3940 request_message
.composeRequest(certProperties
);
3941 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3942 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3944 } catch (const std::exception
&e
) {
3945 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3946 "request for " << certProperties
.commonName
<<
3947 " certificate: " << e
.what() << "; will now block to " <<
3948 "generate that certificate.");
3949 // fall through to do blocking in-process generation.
3951 #endif // USE_SSL_CRTD
3953 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3954 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3955 doPeekAndSpliceStep();
3956 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
3957 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3958 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3960 SSL_CTX
*dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3961 getSslContextDone(dynCtx
, true);
3965 getSslContextDone(NULL
);
3969 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3971 // Try to add generated ssl context to storage.
3972 if (port
->generateHostCertificates
&& isNew
) {
3974 if (signAlgorithm
== Ssl::algSignTrusted
) {
3975 // Add signing certificate to the certificates chain
3976 X509
*cert
= port
->signingCert
.get();
3977 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3978 // increase the certificate lock
3979 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3981 const int ssl_error
= ERR_get_error();
3982 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3984 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3986 //else it is self-signed or untrusted do not attrach any certificate
3988 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3989 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3991 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3992 // If it is not in storage delete after using. Else storage deleted it.
3993 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3996 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
4000 // If generated ssl context = NULL, try to use static ssl context.
4002 if (!port
->staticSslContext
) {
4003 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
4004 clientConnection
->close();
4007 debugs(33, 5, HERE
<< "Using static ssl context.");
4008 sslContext
= port
->staticSslContext
.get();
4012 if (!httpsCreate(clientConnection
, sslContext
))
4015 // bumped intercepted conns should already have Config.Timeout.request set
4016 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
4017 // to make sure the connection does not get stuck on non-SSL clients.
4018 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
4019 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
4020 this, ConnStateData::requestTimeout
);
4021 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
4023 // Disable the client read handler until CachePeer selection is complete
4024 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4025 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
4026 switchedToHttps_
= true;
4030 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
4032 assert(!switchedToHttps_
);
4034 sslConnectHostOrIp
= request
->GetHost();
4035 sslCommonName
= request
->GetHost();
4037 // We are going to read new request
4038 flags
.readMore
= true;
4039 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
4041 // keep version major.minor details the same.
4042 // but we are now performing the HTTPS handshake traffic
4043 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
4045 // If sslServerBump is set, then we have decided to deny CONNECT
4046 // and now want to switch to SSL to send the error to the client
4047 // without even peeking at the origin server certificate.
4048 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
4049 request
->flags
.sslPeek
= true;
4050 sslServerBump
= new Ssl::ServerBump(request
);
4052 // will call httpsPeeked() with certificate and connection, eventually
4053 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4055 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
4056 request
->flags
.sslPeek
= true;
4057 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
4058 startPeekAndSplice();
4062 // otherwise, use sslConnectHostOrIp
4063 getSslContextStart();
4066 /** negotiate an SSL connection */
4068 clientPeekAndSpliceSSL(int fd
, void *data
)
4070 ConnStateData
*conn
= (ConnStateData
*)data
;
4071 SSL
*ssl
= fd_table
[fd
].ssl
;
4073 debugs(83, 5, "Start peek and splice on FD " << fd
);
4075 if (!Squid_SSL_accept(conn
, clientPeekAndSpliceSSL
))
4076 debugs(83, 2, "SSL_accept failed.");
4078 BIO
*b
= SSL_get_rbio(ssl
);
4080 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4081 if (bio
->gotHello()) {
4082 if (conn
->serverBump()) {
4083 Ssl::Bio::sslFeatures
const &features
= bio
->getFeatures();
4084 if (!features
.serverName
.isEmpty())
4085 conn
->serverBump()->clientSni
= features
.serverName
;
4088 debugs(83, 5, "I got hello. Start forwarding the request!!! ");
4089 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4090 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
4091 conn
->startPeekAndSpliceDone();
4096 void ConnStateData::startPeekAndSplice()
4098 // will call httpsPeeked() with certificate and connection, eventually
4099 SSL_CTX
*unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
4100 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
4102 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
4105 // commSetConnTimeout() was called for this request before we switched.
4107 // Disable the client read handler until CachePeer selection is complete
4108 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4109 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientPeekAndSpliceSSL
, this, 0);
4110 switchedToHttps_
= true;
4112 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4113 BIO
*b
= SSL_get_rbio(ssl
);
4114 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4118 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
4120 ConnStateData
*connState
= (ConnStateData
*) data
;
4122 // if the connection is closed or closing, just return.
4123 if (!connState
->isOpen())
4126 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
4127 assert(connState
->serverBump());
4128 Ssl::BumpMode bumpAction
;
4129 if (answer
== ACCESS_ALLOWED
) {
4130 if (answer
.kind
== Ssl::bumpNone
)
4131 bumpAction
= Ssl::bumpSplice
;
4132 else if (answer
.kind
== Ssl::bumpClientFirst
|| answer
.kind
== Ssl::bumpServerFirst
)
4133 bumpAction
= Ssl::bumpBump
;
4135 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
4137 bumpAction
= Ssl::bumpSplice
;
4139 connState
->serverBump()->act
.step2
= bumpAction
;
4140 connState
->sslBumpMode
= bumpAction
;
4142 if (bumpAction
== Ssl::bumpTerminate
) {
4143 comm_close(connState
->clientConnection
->fd
);
4144 } else if (bumpAction
!= Ssl::bumpSplice
) {
4145 connState
->startPeekAndSpliceDone();
4147 //Normally we can splice here, because we just got client hello message
4148 SSL
*ssl
= fd_table
[connState
->clientConnection
->fd
].ssl
;
4149 BIO
*b
= SSL_get_rbio(ssl
);
4150 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4151 MemBuf
const &rbuf
= bio
->rBufData();
4152 debugs(83,5, "Bio for " << connState
->clientConnection
<< " read " << rbuf
.contentSize() << " helo bytes");
4154 fd_table
[connState
->clientConnection
->fd
].read_method
= &default_read_method
;
4155 fd_table
[connState
->clientConnection
->fd
].write_method
= &default_write_method
;
4157 if (connState
->transparent()) {
4158 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
4159 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
4160 connState
->transferProtocol
= Http::ProtocolVersion();
4161 // fake a CONNECT request to force connState to tunnel
4162 static char ip
[MAX_IPSTRLEN
];
4163 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
4164 connState
->in
.buf
.assign("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n").append(rbuf
.content(), rbuf
.contentSize());
4165 bool ret
= connState
->handleReadData();
4167 ret
= connState
->clientParseRequests();
4170 debugs(33, 2, "Failed to start fake CONNECT request for ssl spliced connection: " << connState
->clientConnection
);
4171 connState
->clientConnection
->close();
4174 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
4176 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
4177 connState
->transferProtocol
= Http::ProtocolVersion();
4178 // in.buf still has the "CONNECT ..." request data, reset it to SSL hello message
4179 connState
->in
.buf
.append(rbuf
.content(), rbuf
.contentSize());
4180 ClientSocketContext::Pointer context
= connState
->getCurrentContext();
4181 ClientHttpRequest
*http
= context
->http
;
4182 tunnelStart(http
, &http
->out
.size
, &http
->al
->http
.code
, http
->al
);
4188 ConnStateData::startPeekAndSpliceDone()
4190 // This is the Step2 of the SSL bumping
4191 assert(sslServerBump
);
4192 if (sslServerBump
->step
== Ssl::bumpStep1
) {
4193 sslServerBump
->step
= Ssl::bumpStep2
;
4194 // Run a accessList check to check if want to splice or continue bumping
4196 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
4197 //acl_checklist->src_addr = params.conn->remote;
4198 //acl_checklist->my_addr = s->s;
4199 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
4203 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4207 ConnStateData::doPeekAndSpliceStep()
4209 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4210 BIO
*b
= SSL_get_rbio(ssl
);
4212 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4214 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
4217 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
4218 switchedToHttps_
= true;
4222 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4224 Must(sslServerBump
!= NULL
);
4226 if (Comm::IsConnOpen(serverConnection
)) {
4227 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
4229 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
4230 assert(serverCert
.get() != NULL
);
4231 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4232 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4233 " bumped: " << *serverConnection
);
4235 pinConnection(serverConnection
, NULL
, NULL
, false);
4237 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4239 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4240 Ip::Address intendedDest
;
4241 intendedDest
= sslConnectHostOrIp
.termedBuf();
4242 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4244 // Squid serves its own error page and closes, so we want
4245 // a CN that causes no additional browser errors. Possible
4246 // only when bumping CONNECT with a user-typed address.
4247 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4248 sslCommonName
= sslConnectHostOrIp
;
4249 else if (sslServerBump
->serverCert
.get())
4250 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4252 // copy error detail from bump-server-first request to CONNECT request
4253 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4254 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4257 getSslContextStart();
4260 #endif /* USE_OPENSSL */
4262 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4264 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4266 if (!Comm::IsConnOpen(c
)) {
4267 Must(NHttpSockets
> 0); // we tried to open some
4268 --NHttpSockets
; // there will be fewer sockets than planned
4269 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4271 if (!NHttpSockets
) // we could not open any listen sockets at all
4272 fatalf("Unable to open %s",FdNote(portType
));
4279 /// find any unused HttpSockets[] slot and store fd there or return false
4281 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4284 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4285 if ((found
= HttpSockets
[i
] < 0))
4286 HttpSockets
[i
] = conn
->fd
;
4292 clientHttpConnectionsOpen(void)
4294 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4295 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4296 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4297 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4302 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4303 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4304 s
->flags
.tunnelSslBumping
= false;
4307 if (s
->flags
.tunnelSslBumping
&&
4308 !s
->staticSslContext
&&
4309 !s
->generateHostCertificates
) {
4310 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4311 s
->flags
.tunnelSslBumping
= false;
4313 if (s
->flags
.tunnelSslBumping
) {
4314 // Create ssl_ctx cache for this port.
4315 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4319 // Fill out a Comm::Connection which IPC will open as a listener for us
4320 // then pass back when active so we can start a TcpAcceptor subscription.
4321 s
->listenConn
= new Comm::Connection
;
4322 s
->listenConn
->local
= s
->s
;
4323 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4325 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4326 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4327 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
4328 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4330 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4331 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4332 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4334 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4341 clientHttpsConnectionsOpen(void)
4343 for (AnyP::PortCfgPointer s
= HttpsPortList
; s
!= NULL
; s
= s
->next
) {
4344 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4345 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4346 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4350 if (!s
->staticSslContext
) {
4351 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4352 " due to SSL initialization failure.");
4356 // TODO: merge with similar code in clientHttpConnectionsOpen()
4357 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4358 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4359 s
->flags
.tunnelSslBumping
= false;
4362 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4363 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4364 s
->flags
.tunnelSslBumping
= false;
4367 if (s
->flags
.tunnelSslBumping
) {
4368 // Create ssl_ctx cache for this port.
4369 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4372 // Fill out a Comm::Connection which IPC will open as a listener for us
4373 s
->listenConn
= new Comm::Connection
;
4374 s
->listenConn
->local
= s
->s
;
4375 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4376 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4378 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4379 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4380 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
4381 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4383 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4384 ListeningStartedDialer(&clientListenerConnectionOpened
,
4385 s
, Ipc::fdnHttpsSocket
, sub
));
4386 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4387 HttpSockets
[NHttpSockets
] = -1;
4394 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
4396 // Fill out a Comm::Connection which IPC will open as a listener for us
4397 port
->listenConn
= new Comm::Connection
;
4398 port
->listenConn
->local
= port
->s
;
4399 port
->listenConn
->flags
=
4401 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4402 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4404 // route new connections to subCall
4405 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4406 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4407 AsyncCall::Pointer listenCall
=
4408 asyncCall(33, 2, "clientListenerConnectionOpened",
4409 ListeningStartedDialer(&clientListenerConnectionOpened
,
4410 port
, fdNote
, sub
));
4411 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
4413 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
4414 HttpSockets
[NHttpSockets
] = -1;
4418 /// process clientHttpConnectionsOpen result
4420 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4424 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4427 Must(Comm::IsConnOpen(s
->listenConn
));
4429 // TCP: setup a job to handle accept() with subscribed handler
4430 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
4432 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4433 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4434 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4435 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4436 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4437 << FdNote(portTypeNote
) << " connections at "
4440 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4444 clientOpenListenSockets(void)
4446 clientHttpConnectionsOpen();
4448 clientHttpsConnectionsOpen();
4450 Ftp::StartListening();
4452 if (NHttpSockets
< 1)
4453 fatal("No HTTP, HTTPS, or FTP ports configured");
4457 clientConnectionsClose()
4459 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4460 if (s
->listenConn
!= NULL
) {
4461 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4462 s
->listenConn
->close();
4463 s
->listenConn
= NULL
;
4468 for (AnyP::PortCfgPointer s
= HttpsPortList
; s
!= NULL
; s
= s
->next
) {
4469 if (s
->listenConn
!= NULL
) {
4470 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4471 s
->listenConn
->close();
4472 s
->listenConn
= NULL
;
4477 Ftp::StopListening();
4479 // TODO see if we can drop HttpSockets array entirely */
4480 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4481 HttpSockets
[i
] = -1;
4488 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4490 const char *vary
= request
->vary_headers
;
4491 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4492 #if X_ACCELERATOR_VARY
4495 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4498 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4500 /* Oops... something odd is going on here.. */
4501 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4502 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4503 safe_free(request
->vary_headers
);
4508 /* This is not a varying object */
4512 /* virtual "vary" object found. Calculate the vary key and
4513 * continue the search
4515 vary
= httpMakeVaryMark(request
, entry
->getReply());
4518 request
->vary_headers
= xstrdup(vary
);
4521 /* Ouch.. we cannot handle this kind of variance */
4522 /* XXX This cannot really happen, but just to be complete */
4527 vary
= httpMakeVaryMark(request
, entry
->getReply());
4530 request
->vary_headers
= xstrdup(vary
);
4534 /* Ouch.. we cannot handle this kind of variance */
4535 /* XXX This cannot really happen, but just to be complete */
4537 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4540 /* Oops.. we have already been here and still haven't
4541 * found the requested variant. Bail out
4543 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4544 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4550 ACLFilledChecklist
*
4551 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4553 ConnStateData
* conn
= http
->getConn();
4554 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4555 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4558 * hack for ident ACL. It needs to get full addresses, and a place to store
4559 * the ident result on persistent connections...
4561 /* connection oriented auth also needs these two lines for it's operation. */
4566 ConnStateData::transparent() const
4568 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4572 ConnStateData::reading() const
4574 return reader
!= NULL
;
4578 ConnStateData::stopReading()
4581 Comm::ReadCancel(clientConnection
->fd
, reader
);
4587 ConnStateData::expectRequestBody(int64_t size
)
4589 bodyPipe
= new BodyPipe(this);
4591 bodyPipe
->setBodySize(size
);
4593 startDechunkingRequest();
4598 ConnStateData::mayNeedToReadMoreBody() const
4601 return 0; // request without a body or read/produced all body bytes
4603 if (!bodyPipe
->bodySizeKnown())
4604 return -1; // probably need to read more, but we cannot be sure
4606 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4607 const int64_t haveAvailable
= static_cast<int64_t>(in
.buf
.length());
4609 if (needToProduce
<= haveAvailable
)
4610 return 0; // we have read what we need (but are waiting for pipe space)
4612 return needToProduce
- haveAvailable
;
4616 ConnStateData::stopReceiving(const char *error
)
4618 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4619 "; old sending error: " <<
4620 (stoppedSending() ? stoppedSending_
: "none"));
4622 if (const char *oldError
= stoppedReceiving()) {
4623 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4624 return; // nothing has changed as far as this connection is concerned
4627 stoppedReceiving_
= error
;
4629 if (const char *sendError
= stoppedSending()) {
4630 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4631 clientConnection
->close();
4636 ConnStateData::expectNoForwarding()
4638 if (bodyPipe
!= NULL
) {
4639 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4640 bodyPipe
->expectNoConsumption();
4644 /// initialize dechunking state
4646 ConnStateData::startDechunkingRequest()
4648 Must(bodyPipe
!= NULL
);
4649 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4650 assert(!in
.bodyParser
);
4651 in
.bodyParser
= new ChunkedCodingParser
;
4654 /// put parsed content into input buffer and clean up
4656 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4658 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4660 if (bodyPipe
!= NULL
) {
4661 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4662 BodyPipe::Pointer myPipe
= bodyPipe
;
4663 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4664 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4666 Must(myPipe
->bodySizeKnown());
4667 ClientSocketContext::Pointer context
= getCurrentContext();
4668 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4669 context
->http
->request
->setContentLength(myPipe
->bodySize());
4673 delete in
.bodyParser
;
4674 in
.bodyParser
= NULL
;
4677 ConnStateData::In::In() :
4682 ConnStateData::In::~In()
4684 delete bodyParser
; // TODO: pool
4688 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4691 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4695 ClientSocketContext::Pointer context
= getCurrentContext();
4696 if (context
!= NULL
) {
4697 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4701 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4702 clientConnection
->close();
4705 /// Our close handler called by Comm when the pinned connection is closed
4707 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4709 // FwdState might repin a failed connection sooner than this close
4710 // callback is called for the failed connection.
4711 assert(pinning
.serverConnection
== io
.conn
);
4712 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4713 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4714 unpinConnection(false);
4716 if (sawZeroReply
&& clientConnection
!= NULL
) {
4717 debugs(33, 3, "Closing client connection on pinned zero reply.");
4718 clientConnection
->close();
4724 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
4726 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
4727 pinning
.serverConnection
->fd
!= pinServer
->fd
)
4728 pinNewConnection(pinServer
, request
, aPeer
, auth
);
4731 startPinnedConnectionMonitoring();
4735 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4737 unpinConnection(true); // closes pinned connection, if any, and resets fields
4739 pinning
.serverConnection
= pinServer
;
4741 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4743 Must(pinning
.serverConnection
!= NULL
);
4745 // when pinning an SSL bumped connection, the request may be NULL
4746 const char *pinnedHost
= "[unknown]";
4748 pinning
.host
= xstrdup(request
->GetHost());
4749 pinning
.port
= request
->port
;
4750 pinnedHost
= pinning
.host
;
4752 pinning
.port
= pinServer
->remote
.port();
4754 pinning
.pinned
= true;
4756 pinning
.peer
= cbdataReference(aPeer
);
4757 pinning
.auth
= auth
;
4758 char stmp
[MAX_IPSTRLEN
];
4759 char desc
[FD_DESC_SZ
];
4760 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4761 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4762 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4763 clientConnection
->fd
);
4764 fd_note(pinning
.serverConnection
->fd
, desc
);
4766 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4767 pinning
.closeHandler
= JobCallback(33, 5,
4768 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4769 // remember the pinned connection so that cb does not unpin a fresher one
4770 typedef CommCloseCbParams Params
;
4771 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4772 params
.conn
= pinning
.serverConnection
;
4773 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4776 /// [re]start monitoring pinned connection for peer closures so that we can
4777 /// propagate them to an _idle_ client pinned to that peer
4779 ConnStateData::startPinnedConnectionMonitoring()
4781 if (pinning
.readHandler
!= NULL
)
4782 return; // already monitoring
4784 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4785 pinning
.readHandler
= JobCallback(33, 3,
4786 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4787 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
4791 ConnStateData::stopPinnedConnectionMonitoring()
4793 if (pinning
.readHandler
!= NULL
) {
4794 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4795 pinning
.readHandler
= NULL
;
4799 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4800 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4802 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4804 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4806 if (io
.flag
== Comm::ERR_CLOSING
)
4807 return; // close handler will clean up
4809 // We could use getConcurrentRequestCount(), but this may be faster.
4810 const bool clientIsIdle
= !getCurrentContext();
4812 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4813 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4815 assert(pinning
.serverConnection
== io
.conn
);
4816 pinning
.serverConnection
->close();
4818 // If we are still sending data to the client, do not close now. When we are done sending,
4819 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4820 // However, if we are idle, then we must close to inform the idle client and minimize races.
4821 if (clientIsIdle
&& clientConnection
!= NULL
)
4822 clientConnection
->close();
4825 const Comm::ConnectionPointer
4826 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4828 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4831 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4833 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4835 else if (request
&& pinning
.port
!= request
->port
)
4837 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4839 else if (aPeer
!= pinning
.peer
)
4843 /* The pinning info is not safe, remove any pinning info */
4844 unpinConnection(true);
4847 return pinning
.serverConnection
;
4850 Comm::ConnectionPointer
4851 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4853 debugs(33, 7, pinning
.serverConnection
);
4854 if (validatePinnedConnection(request
, aPeer
) != NULL
)
4855 stopPinnedConnectionMonitoring();
4857 return pinning
.serverConnection
; // closed if validation failed
4861 ConnStateData::unpinConnection(const bool andClose
)
4863 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4866 cbdataReferenceDone(pinning
.peer
);
4868 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4869 if (pinning
.closeHandler
!= NULL
) {
4870 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4871 pinning
.closeHandler
= NULL
;
4874 stopPinnedConnectionMonitoring();
4876 // close the server side socket if requested
4878 pinning
.serverConnection
->close();
4879 pinning
.serverConnection
= NULL
;
4882 safe_free(pinning
.host
);
4884 pinning
.zeroReply
= false;
4886 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4887 * connection has gone away */