2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 33 Client-side Routines */
12 \defgroup ClientSide Client-Side Logics
14 \section cserrors Errors and client side
16 \par Problem the first:
17 * the store entry is no longer authoritative on the
18 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
19 * of client_side_reply.c.
20 * Problem the second: resources are wasted if we delay in cleaning up.
21 * Problem the third we can't depend on a connection close to clean up.
23 \par Nice thing the first:
24 * Any step in the stream can callback with data
25 * representing an error.
26 * Nice thing the second: once you stop requesting reads from upstream,
27 * upstream can be stopped too.
30 * Error has a callback mechanism to hand over a membuf
31 * with the error content. The failing node pushes that back as the
32 * reply. Can this be generalised to reduce duplicate efforts?
33 * A: Possibly. For now, only one location uses this.
34 * How to deal with pre-stream errors?
35 * Tell client_side_reply that we *want* an error page before any
36 * stream calls occur. Then we simply read as normal.
39 \section pconn_logic Persistent connection logic:
42 * requests (httpClientRequest structs) get added to the connection
43 * list, with the current one being chr
46 * The request is *immediately* kicked off, and data flows through
47 * to clientSocketRecipient.
50 * If the data that arrives at clientSocketRecipient is not for the current
51 * request, clientSocketRecipient simply returns, without requesting more
52 * data, or sending it.
55 * ClientKeepAliveNextRequest will then detect the presence of data in
56 * the next ClientHttpRequest, and will send it, restablishing the
61 #include "acl/FilledChecklist.h"
62 #include "anyp/PortCfg.h"
63 #include "base/Subscription.h"
64 #include "base/TextException.h"
65 #include "CachePeer.h"
66 #include "client_db.h"
67 #include "client_side.h"
68 #include "client_side_reply.h"
69 #include "client_side_request.h"
70 #include "ClientRequestContext.h"
71 #include "clientStream.h"
73 #include "comm/Connection.h"
74 #include "comm/Loops.h"
75 #include "comm/Read.h"
76 #include "comm/TcpAcceptor.h"
77 #include "comm/Write.h"
78 #include "CommCalls.h"
79 #include "errorpage.h"
82 #include "fqdncache.h"
86 #include "helper/Reply.h"
88 #include "http/one/RequestParser.h"
89 #include "http/one/TeChunkedParser.h"
90 #include "HttpHdrContRange.h"
91 #include "HttpHeaderTools.h"
92 #include "HttpReply.h"
93 #include "HttpRequest.h"
94 #include "ident/Config.h"
95 #include "ident/Ident.h"
97 #include "ipc/FdNotes.h"
98 #include "ipc/StartListening.h"
99 #include "log/access_log.h"
101 #include "MemObject.h"
102 #include "mime_header.h"
103 #include "parser/Tokenizer.h"
104 #include "profiler/Profiler.h"
106 #include "servers/forward.h"
107 #include "SquidConfig.h"
108 #include "SquidTime.h"
109 #include "StatCounters.h"
110 #include "StatHist.h"
112 #include "TimeOrTag.h"
117 #include "auth/UserRequest.h"
120 #include "ClientInfo.h"
124 #include "ssl/context_storage.h"
125 #include "ssl/gadgets.h"
126 #include "ssl/helper.h"
127 #include "ssl/ProxyCerts.h"
128 #include "ssl/ServerBump.h"
129 #include "ssl/support.h"
132 #include "ssl/certificate_db.h"
133 #include "ssl/crtd_message.h"
136 // for tvSubUsec() which should be in SquidTime.h
144 #define comm_close comm_lingering_close
147 /// dials clientListenerConnectionOpened call
148 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
151 typedef void (*Handler
)(AnyP::PortCfgPointer
&portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
152 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfgPointer
&aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
153 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
155 virtual void print(std::ostream
&os
) const {
157 ", " << FdNote(portTypeNote
) << " port=" << (void*)&portCfg
<< ')';
160 virtual bool canDial(AsyncCall
&) const { return true; }
161 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
167 AnyP::PortCfgPointer portCfg
; ///< from HttpPortList
168 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
169 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
172 static void clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
174 /* our socket-related context */
176 CBDATA_CLASS_INIT(ClientSocketContext
);
178 /* Local functions */
179 static 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(const LogTags
&logType
, int svc_time
);
193 static void clientUpdateStatCounters(const LogTags
&logType
);
194 static void clientUpdateHierCounters(HierarchyLogEntry
*);
195 static bool clientPingHasFinished(ping_data
const *aPing
);
196 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
197 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
198 static void clientUpdateSocketStats(const LogTags
&logType
, size_t size
);
200 char *skipLeadingSpace(char *aString
);
203 ClientSocketContext::getTail() const
205 if (http
->client_stream
.tail
)
206 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
212 ClientSocketContext::getClientReplyContext() const
214 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
218 ClientSocketContext::getConn() const
220 return http
->getConn();
224 * This routine should be called to grow the in.buf and then
228 ConnStateData::readSomeData()
233 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
235 // we can only read if there is more than 1 byte of space free
236 if (Config
.maxRequestBufferSize
- in
.buf
.length() < 2)
239 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
240 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
241 Comm::Read(clientConnection
, reader
);
245 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
247 ClientSocketContext::Pointer
*tempContextPointer
;
248 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
249 assert(conn
->getCurrentContext() != NULL
);
250 /* Unlink us from the connection request list */
251 tempContextPointer
= & conn
->currentobject
;
253 while (tempContextPointer
->getRaw()) {
254 if (*tempContextPointer
== this)
257 tempContextPointer
= &(*tempContextPointer
)->next
;
260 assert(tempContextPointer
->getRaw() != NULL
);
261 *tempContextPointer
= next
;
265 ClientSocketContext::~ClientSocketContext()
267 clientStreamNode
*node
= getTail();
270 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
273 /* We are *always* the tail - prevent recursive free */
274 assert(this == streamContext
);
280 deRegisterWithConn();
282 httpRequestFree(http
);
284 /* clean up connection links to us */
285 assert(this != next
.getRaw());
289 ClientSocketContext::registerWithConn()
291 assert (!connRegistered_
);
293 assert (http
->getConn() != NULL
);
294 connRegistered_
= true;
295 http
->getConn()->addContextToQueue(this);
299 ClientSocketContext::deRegisterWithConn()
301 assert (connRegistered_
);
302 removeFromConnectionList(http
->getConn());
303 connRegistered_
= false;
307 ClientSocketContext::connIsFinished()
310 assert (http
->getConn() != NULL
);
311 deRegisterWithConn();
312 /* we can't handle any more stream data - detach */
313 clientStreamDetach(getTail(), http
);
316 ClientSocketContext::ClientSocketContext(const Comm::ConnectionPointer
&aConn
, ClientHttpRequest
*aReq
) :
317 clientConnection(aConn
),
322 mayUseConnection_ (false),
323 connRegistered_ (false)
325 assert(http
!= NULL
);
326 memset (reqbuf
, '\0', sizeof (reqbuf
));
329 deferredparams
.node
= NULL
;
330 deferredparams
.rep
= NULL
;
334 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
336 HttpReply::Pointer
rep(msg
.reply
);
339 // remember the callback
340 cbControlMsgSent
= msg
.cbSuccess
;
342 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
343 CommIoCbPtrFun(&WroteControlMsg
, this));
345 getConn()->writeControlMsgAndCall(this, rep
.getRaw(), call
);
348 /// called when we wrote the 1xx response
350 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, Comm::Flag errflag
, int xerrno
)
352 if (errflag
== Comm::ERR_CLOSING
)
355 if (errflag
== Comm::OK
) {
356 ScheduleCallHere(cbControlMsgSent
);
360 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
361 // no error notification: see HttpControlMsg.h for rationale and
362 // note that some errors are detected elsewhere (e.g., close handler)
364 // close on 1xx errors to be conservative and to simplify the code
365 // (if we do not close, we must notify the source of a failure!)
368 // XXX: writeControlMsgAndCall() should handle writer-specific writing
369 // results, including errors and then call us with success/failure outcome.
372 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
374 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, Comm::Flag errflag
, int xerrno
, void *data
)
376 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
377 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
382 clientIdentDone(const char *ident
, void *data
)
384 ConnStateData
*conn
= (ConnStateData
*)data
;
385 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
390 clientUpdateStatCounters(const LogTags
&logType
)
392 ++statCounter
.client_http
.requests
;
394 if (logType
.isTcpHit())
395 ++statCounter
.client_http
.hits
;
397 if (logType
.oldType
== LOG_TCP_HIT
)
398 ++statCounter
.client_http
.disk_hits
;
399 else if (logType
.oldType
== LOG_TCP_MEM_HIT
)
400 ++statCounter
.client_http
.mem_hits
;
404 clientUpdateStatHistCounters(const LogTags
&logType
, int svc_time
)
406 statCounter
.client_http
.allSvcTime
.count(svc_time
);
408 * The idea here is not to be complete, but to get service times
409 * for only well-defined types. For example, we don't include
410 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
411 * (we *tried* to validate it, but failed).
414 switch (logType
.oldType
) {
416 case LOG_TCP_REFRESH_UNMODIFIED
:
417 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
420 case LOG_TCP_IMS_HIT
:
421 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
426 case LOG_TCP_MEM_HIT
:
428 case LOG_TCP_OFFLINE_HIT
:
429 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
434 case LOG_TCP_CLIENT_REFRESH_MISS
:
435 statCounter
.client_http
.missSvcTime
.count(svc_time
);
439 /* make compiler warnings go away */
445 clientPingHasFinished(ping_data
const *aPing
)
447 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
454 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
458 switch (someEntry
->code
) {
459 #if USE_CACHE_DIGESTS
464 ++ statCounter
.cd
.times_used
;
472 case FIRST_PARENT_MISS
:
474 case CLOSEST_PARENT_MISS
:
475 ++ statCounter
.icp
.times_used
;
476 i
= &someEntry
->ping
;
478 if (clientPingHasFinished(i
))
479 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
482 ++ statCounter
.icp
.query_timeouts
;
489 ++ statCounter
.netdb
.times_used
;
499 ClientHttpRequest::updateCounters()
501 clientUpdateStatCounters(logType
);
503 if (request
->errType
!= ERR_NONE
)
504 ++ statCounter
.client_http
.errors
;
506 clientUpdateStatHistCounters(logType
,
507 tvSubMsec(al
->cache
.start_time
, current_time
));
509 clientUpdateHierCounters(&request
->hier
);
513 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
516 assert(aLogEntry
!= NULL
);
518 if (Config
.onoff
.log_mime_hdrs
) {
521 request
->header
.packInto(&mb
);
522 //This is the request after adaptation or redirection
523 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
525 // the virgin request is saved to aLogEntry->request
526 if (aLogEntry
->request
) {
528 aLogEntry
->request
->header
.packInto(&mb
);
529 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
533 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
536 ah
->lastMeta
.packInto(&mb
);
537 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
545 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
547 ih
->processingTime(aLogEntry
->icap
.processingTime
);
550 aLogEntry
->http
.method
= request
->method
;
551 aLogEntry
->http
.version
= request
->http_ver
;
552 aLogEntry
->hier
= request
->hier
;
553 if (request
->content_length
> 0) // negative when no body or unknown length
554 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
555 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
557 // Adapted request, if any, inherits and then collects all the stats, but
558 // the virgin request gets logged instead; copy the stats to log them.
559 // TODO: avoid losses by keeping these stats in a shared history object?
560 if (aLogEntry
->request
) {
561 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
562 aLogEntry
->request
->errType
= request
->errType
;
563 aLogEntry
->request
->errDetail
= request
->errDetail
;
568 ClientHttpRequest::logRequest()
570 if (!out
.size
&& logType
.oldType
== LOG_TAG_NONE
)
571 debugs(33, 5, "logging half-baked transaction: " << log_uri
);
573 al
->icp
.opcode
= ICP_INVALID
;
575 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
578 al
->http
.code
= al
->reply
->sline
.status();
579 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
580 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
581 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
582 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
585 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
587 if (loggingEntry() && loggingEntry()->mem_obj
&& loggingEntry()->objectLen() >= 0)
588 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
590 al
->http
.clientRequestSz
.header
= req_sz
;
591 al
->http
.clientReplySz
.header
= out
.headers_sz
;
592 // XXX: calculate without payload encoding or headers !!
593 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
595 al
->cache
.highOffset
= out
.offset
;
597 al
->cache
.code
= logType
;
599 tvSub(al
->cache
.trTime
, al
->cache
.start_time
, current_time
);
602 prepareLogWithRequestDetails(request
, al
);
604 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
605 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
609 /* This is broken. Fails if the connection has been closed. Needs
610 * to snarf the ssl details some place earlier..
612 if (getConn() != NULL
)
613 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
617 /* Add notes (if we have a request to annotate) */
619 // The al->notes and request->notes must point to the same object.
620 (void)SyncNotes(*al
, *request
);
621 for (auto i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
622 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
623 NotePairs
¬es
= SyncNotes(*al
, *request
);
624 notes
.add((*i
)->key
.termedBuf(), value
);
625 debugs(33, 3, (*i
)->key
.termedBuf() << " " << value
);
630 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
632 checklist
.reply
= al
->reply
;
633 HTTPMSGLOCK(checklist
.reply
);
637 al
->adapted_request
= request
;
638 HTTPMSGLOCK(al
->adapted_request
);
640 accessLogLog(al
, &checklist
);
642 bool updatePerformanceCounters
= true;
643 if (Config
.accessList
.stats_collection
) {
644 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
646 statsCheck
.reply
= al
->reply
;
647 HTTPMSGLOCK(statsCheck
.reply
);
649 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
652 if (updatePerformanceCounters
) {
656 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
657 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
662 ClientHttpRequest::freeResources()
666 safe_free(redirect
.location
);
667 range_iter
.boundary
.clean();
668 HTTPMSGUNLOCK(request
);
670 if (client_stream
.tail
)
671 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
675 httpRequestFree(void *data
)
677 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
678 assert(http
!= NULL
);
683 ConnStateData::areAllContextsForThisConnection() const
685 ClientSocketContext::Pointer context
= getCurrentContext();
687 while (context
.getRaw()) {
688 if (context
->http
->getConn() != this)
691 context
= context
->next
;
698 ConnStateData::freeAllContexts()
700 ClientSocketContext::Pointer context
;
702 while ((context
= getCurrentContext()).getRaw() != NULL
) {
703 assert(getCurrentContext() !=
704 getCurrentContext()->next
);
705 context
->connIsFinished();
706 assert (context
!= currentobject
);
710 /// propagates abort event to all contexts
712 ConnStateData::notifyAllContexts(int xerrno
)
714 typedef ClientSocketContext::Pointer CSCP
;
715 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
716 c
->noteIoError(xerrno
);
719 /* This is a handler normally called by comm_close() */
720 void ConnStateData::connStateClosed(const CommCloseCbParams
&)
722 deleteThis("ConnStateData::connStateClosed");
727 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
731 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
737 // clobered with self-pointer
738 // NP: something nasty is going on in Squid, but harmless.
740 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
745 * Connection-auth relies on a single set of credentials being preserved
746 * for all requests on a connection once they have been setup.
747 * There are several things which need to happen to preserve security
748 * when connection-auth credentials change unexpectedly or are unset.
750 * 1) auth helper released from any active state
752 * They can only be reserved by a handshake process which this
753 * connection can now never complete.
754 * This prevents helpers hanging when their connections close.
756 * 2) pinning is expected to be removed and server conn closed
758 * The upstream link is authenticated with the same credentials.
759 * Expecting the same level of consistency we should have received.
760 * This prevents upstream being faced with multiple or missing
761 * credentials after authentication.
762 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
763 * we just trigger that cleanup here via comm_reset_close() or
764 * ConnStateData::stopReceiving()
766 * 3) the connection needs to close.
768 * This prevents attackers injecting requests into a connection,
769 * or gateways wrongly multiplexing users into a single connection.
771 * When credentials are missing closure needs to follow an auth
772 * challenge for best recovery by the client.
774 * When credentials change there is nothing we can do but abort as
775 * fast as possible. Sending TCP RST instead of an HTTP response
776 * is the best-case action.
779 // clobbered with nul-pointer
781 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
782 auth_
->releaseAuthServer();
784 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
785 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
786 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
787 stopReceiving("connection-auth removed");
791 // clobbered with alternative credentials
793 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
794 auth_
->releaseAuthServer();
796 // this is a fatal type of problem.
797 // Close the connection immediately with TCP RST to abort all traffic flow
798 comm_reset_close(clientConnection
);
806 // cleans up before destructor is called
808 ConnStateData::swanSong()
810 debugs(33, 2, HERE
<< clientConnection
);
811 flags
.readMore
= false;
812 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
813 assert(areAllContextsForThisConnection());
816 unpinConnection(true);
818 if (Comm::IsConnOpen(clientConnection
))
819 clientConnection
->close();
822 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
823 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
826 BodyProducer::swanSong();
827 flags
.swanSang
= true;
831 ConnStateData::isOpen() const
833 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
834 Comm::IsConnOpen(clientConnection
) &&
835 !fd_table
[clientConnection
->fd
].closing();
838 ConnStateData::~ConnStateData()
840 debugs(33, 3, HERE
<< clientConnection
);
843 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
846 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
848 if (bodyPipe
!= NULL
)
849 stopProducingFor(bodyPipe
, false);
852 delete sslServerBump
;
857 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
858 * This is the client-side persistent connection flag. We need
859 * to set this relatively early in the request processing
860 * to handle hacks for broken servers and clients.
863 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
865 HttpRequest
*request
= http
->request
;
867 debugs(33, 3, "http_ver = " << request
->http_ver
);
868 debugs(33, 3, "method = " << request
->method
);
870 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
871 request
->flags
.proxyKeepalive
= request
->persistent();
875 clientIsContentLengthValid(HttpRequest
* r
)
877 switch (r
->method
.id()) {
879 case Http::METHOD_GET
:
881 case Http::METHOD_HEAD
:
882 /* We do not want to see a request entity on GET/HEAD requests */
883 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
886 /* For other types of requests we don't care */
894 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
896 if (Config
.maxRequestBodySize
&&
897 bodyLength
> Config
.maxRequestBodySize
)
898 return 1; /* too large */
903 // careful: the "current" context may be gone if we wrote an early response
904 ClientSocketContext::Pointer
905 ConnStateData::getCurrentContext() const
907 return currentobject
;
911 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
913 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
914 assert(flags
.deferred
== 0);
916 deferredparams
.node
= node
;
917 deferredparams
.rep
= rep
;
918 deferredparams
.queuedBuffer
= receivedData
;
923 ClientSocketContext::startOfOutput() const
925 return http
->out
.size
== 0;
929 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
931 /*the size of available range can always fit in a size_t type*/
932 size_t maximum
= (size_t)available
.size();
934 if (!http
->request
->range
)
937 assert (canPackMoreRanges());
939 if (http
->range_iter
.debt() == -1)
942 assert (http
->range_iter
.debt() > 0);
944 /* TODO this + the last line could be a range intersection calculation */
945 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
948 return min(http
->range_iter
.debt(), (int64_t)maximum
);
952 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
954 http
->out
.offset
+= bytes
;
956 if (!http
->request
->range
)
959 if (http
->range_iter
.debt() != -1) {
960 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
961 assert (http
->range_iter
.debt() >= 0);
964 /* debt() always stops at -1, below that is a bug */
965 assert (http
->range_iter
.debt() >= -1);
969 ClientHttpRequest::multipartRangeRequest() const
971 return request
->multipartRangeRequest();
975 ClientSocketContext::multipartRangeRequest() const
977 return http
->multipartRangeRequest();
981 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
985 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
986 size_t length
= lengthToSend(bodyData
.range());
987 noteSentBodyBytes (length
);
988 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
989 CommIoCbPtrFun(clientWriteBodyComplete
, this));
990 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
996 if (multipartRangeRequest())
997 packRange(bodyData
, &mb
);
999 packChunk(bodyData
, mb
);
1001 if (mb
.contentSize()) {
1003 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1004 CommIoCbPtrFun(clientWriteComplete
, this));
1005 Comm::Write(clientConnection
, &mb
, call
);
1007 writeComplete(clientConnection
, NULL
, 0, Comm::OK
);
1011 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1012 * if bodyData is empty.
1015 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1017 const uint64_t length
=
1018 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1019 noteSentBodyBytes(length
);
1021 mb
.appendf("%" PRIX64
"\r\n", length
);
1022 mb
.append(bodyData
.data
, length
);
1023 mb
.append("\r\n", 2);
1026 /** put terminating boundary for multiparts */
1028 clientPackTermBound(String boundary
, MemBuf
* mb
)
1030 mb
->appendf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1031 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1034 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1036 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1038 HttpHeader
hdr(hoReply
);
1043 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1044 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1045 mb
->appendf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1047 /* stuff the header with required entries and pack it */
1049 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1050 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1052 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1057 /* append <crlf> (we packed a header, not a reply) */
1058 mb
->append("\r\n", 2);
1062 * extracts a "range" from *buf and appends them to mb, updating
1063 * all offsets and such.
1066 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1068 HttpHdrRangeIter
* i
= &http
->range_iter
;
1069 Range
<int64_t> available (source
.range());
1070 char const *buf
= source
.data
;
1072 while (i
->currentSpec() && available
.size()) {
1073 const size_t copy_sz
= lengthToSend(available
);
1077 * intersection of "have" and "need" ranges must not be empty
1079 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1080 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1083 * put boundary and headers at the beginning of a range in a
1087 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1088 assert(http
->memObject());
1090 http
->memObject()->getReply(), /* original reply */
1091 i
->currentSpec(), /* current range */
1092 i
->boundary
, /* boundary, the same for all */
1099 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1101 noteSentBodyBytes (copy_sz
);
1103 mb
->append(buf
, copy_sz
);
1108 available
.start
+= copy_sz
;
1114 if (!canPackMoreRanges()) {
1115 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1118 /* put terminating boundary for multiparts */
1119 clientPackTermBound(i
->boundary
, mb
);
1124 int64_t nextOffset
= getNextRangeOffset();
1126 assert (nextOffset
>= http
->out
.offset
);
1128 int64_t skip
= nextOffset
- http
->out
.offset
;
1130 /* adjust for not to be transmitted bytes */
1131 http
->out
.offset
= nextOffset
;
1133 if (available
.size() <= (uint64_t)skip
)
1136 available
.start
+= skip
;
1145 /** returns expected content length for multi-range replies
1146 * note: assumes that httpHdrRangeCanonize has already been called
1147 * warning: assumes that HTTP headers for individual ranges at the
1148 * time of the actuall assembly will be exactly the same as
1149 * the headers when clientMRangeCLen() is called */
1151 ClientHttpRequest::mRangeCLen()
1156 assert(memObject());
1159 HttpHdrRange::iterator pos
= request
->range
->begin();
1161 while (pos
!= request
->range
->end()) {
1162 /* account for headers for this range */
1164 clientPackRangeHdr(memObject()->getReply(),
1165 *pos
, range_iter
.boundary
, &mb
);
1168 /* account for range content */
1169 clen
+= (*pos
)->length
;
1171 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1175 /* account for the terminating boundary */
1178 clientPackTermBound(range_iter
.boundary
, &mb
);
1188 * returns true if If-Range specs match reply, false otherwise
1191 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1193 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1194 /* check for parsing falure */
1201 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1202 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1203 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1206 return 0; /* entity has no etag to compare with! */
1208 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1209 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1210 return 0; /* must use strong validator for sub-range requests */
1213 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1216 /* got modification time? */
1217 if (spec
.time
>= 0) {
1218 return http
->storeEntry()->lastmod
<= spec
.time
;
1221 assert(0); /* should not happen */
1226 * generates a "unique" boundary string for multipart responses
1227 * the caller is responsible for cleaning the string */
1229 ClientHttpRequest::rangeBoundaryStr() const
1232 String
b(APP_FULLNAME
);
1234 key
= storeEntry()->getMD5Text();
1235 b
.append(key
, strlen(key
));
1239 /** adds appropriate Range headers if needed */
1241 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1243 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1244 const char *range_err
= NULL
;
1245 HttpRequest
*request
= http
->request
;
1246 assert(request
->range
);
1247 /* check if we still want to do ranges */
1249 int64_t roffLimit
= request
->getRangeOffsetLimit();
1252 range_err
= "no [parse-able] reply";
1253 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1254 range_err
= "wrong status code";
1255 else if (hdr
->has(HDR_CONTENT_RANGE
))
1256 range_err
= "origin server does ranges";
1257 else if (rep
->content_length
< 0)
1258 range_err
= "unknown length";
1259 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1260 range_err
= "INCONSISTENT length"; /* a bug? */
1262 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1265 else if (http
->logType
.isTcpHit() && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1266 range_err
= "If-Range match failed";
1267 else if (!http
->request
->range
->canonize(rep
))
1268 range_err
= "canonization failed";
1269 else if (http
->request
->range
->isComplex())
1270 range_err
= "too complex range header";
1271 else if (!http
->logType
.isTcpHit() && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1272 range_err
= "range outside range_offset_limit";
1274 /* get rid of our range specs on error */
1276 /* XXX We do this here because we need canonisation etc. However, this current
1277 * code will lead to incorrect store offset requests - the store will have the
1278 * offset data, but we won't be requesting it.
1279 * So, we can either re-request, or generate an error
1281 http
->request
->ignoreRange(range_err
);
1283 /* XXX: TODO: Review, this unconditional set may be wrong. */
1284 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1285 // web server responded with a valid, but unexpected range.
1286 // will (try-to) forward as-is.
1287 //TODO: we should cope with multirange request/responses
1288 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1289 request
->range
->contains(rep
->content_range
->spec
) :
1291 const int spec_count
= http
->request
->range
->specs
.size();
1292 int64_t actual_clen
= -1;
1294 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1295 spec_count
<< " virgin clen: " << rep
->content_length
);
1296 assert(spec_count
> 0);
1297 /* append appropriate header(s) */
1299 if (spec_count
== 1) {
1300 if (!replyMatchRequest
) {
1301 hdr
->delById(HDR_CONTENT_RANGE
);
1302 hdr
->putContRange(rep
->content_range
);
1303 actual_clen
= rep
->content_length
;
1304 //http->range_iter.pos = rep->content_range->spec.begin();
1305 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1306 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1309 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1311 /* append Content-Range */
1313 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1314 /* No content range, so this was a full object we are
1317 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1320 /* set new Content-Length to the actual number of bytes
1321 * transmitted in the message-body */
1322 actual_clen
= (*pos
)->length
;
1326 /* generate boundary string */
1327 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1328 /* delete old Content-Type, add ours */
1329 hdr
->delById(HDR_CONTENT_TYPE
);
1330 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1331 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1332 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1333 /* Content-Length is not required in multipart responses
1334 * but it is always nice to have one */
1335 actual_clen
= http
->mRangeCLen();
1336 /* http->out needs to start where we want data at */
1337 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1340 /* replace Content-Length header */
1341 assert(actual_clen
>= 0);
1343 hdr
->delById(HDR_CONTENT_LENGTH
);
1345 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1347 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1349 /* And start the range iter off */
1350 http
->range_iter
.updateSpec();
1355 ClientSocketContext::prepareReply(HttpReply
* rep
)
1359 if (http
->request
->range
)
1360 buildRangeHeader(rep
);
1364 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1368 MemBuf
*mb
= rep
->pack();
1370 // dump now, so we dont output any body.
1371 debugs(11, 2, "HTTP Client " << clientConnection
);
1372 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1374 /* Save length of headers for persistent conn checks */
1375 http
->out
.headers_sz
= mb
->contentSize();
1378 headersLog(0, 0, http
->request
->method
, rep
);
1381 if (bodyData
.data
&& bodyData
.length
) {
1382 if (multipartRangeRequest())
1383 packRange(bodyData
, mb
);
1384 else if (http
->request
->flags
.chunkedReply
) {
1385 packChunk(bodyData
, *mb
);
1387 size_t length
= lengthToSend(bodyData
.range());
1388 noteSentBodyBytes (length
);
1390 mb
->append(bodyData
.data
, length
);
1395 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1396 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1397 CommIoCbPtrFun(clientWriteComplete
, this));
1398 Comm::Write(clientConnection
, mb
, call
);
1403 * Write a chunk of data to a client socket. If the reply is present,
1404 * send the reply headers down the wire too, and clean them up when
1407 * The request is one backed by a connection, not an internal request.
1408 * data context is not NULL
1409 * There are no more entries in the stream chain.
1412 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1413 HttpReply
* rep
, StoreIOBuffer receivedData
)
1415 // dont tryt to deliver if client already ABORTED
1416 if (!http
->getConn() || !cbdataReferenceValid(http
->getConn()) || !Comm::IsConnOpen(http
->getConn()->clientConnection
))
1419 /* Test preconditions */
1420 assert(node
!= NULL
);
1421 PROF_start(clientSocketRecipient
);
1422 /* TODO: handle this rather than asserting
1423 * - it should only ever happen if we cause an abort and
1424 * the callback chain loops back to here, so we can simply return.
1425 * However, that itself shouldn't happen, so it stays as an assert for now.
1427 assert(cbdataReferenceValid(node
));
1428 assert(node
->node
.next
== NULL
);
1429 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1430 assert(context
!= NULL
);
1432 /* TODO: check offset is what we asked for */
1434 if (context
!= http
->getConn()->getCurrentContext())
1435 context
->deferRecipientForLater(node
, rep
, receivedData
);
1437 http
->getConn()->handleReply(rep
, receivedData
);
1439 PROF_stop(clientSocketRecipient
);
1443 * Called when a downstream node is no longer interested in
1444 * our data. As we are a terminal node, this means on aborts
1448 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1450 /* Test preconditions */
1451 assert(node
!= NULL
);
1452 /* TODO: handle this rather than asserting
1453 * - it should only ever happen if we cause an abort and
1454 * the callback chain loops back to here, so we can simply return.
1455 * However, that itself shouldn't happen, so it stays as an assert for now.
1457 assert(cbdataReferenceValid(node
));
1458 /* Set null by ContextFree */
1459 assert(node
->node
.next
== NULL
);
1460 /* this is the assert discussed above */
1461 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1462 /* We are only called when the client socket shutsdown.
1463 * Tell the prev pipeline member we're finished
1465 clientStreamDetach(node
, http
);
1469 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int xerrno
, void *data
)
1471 debugs(33,7, "schedule clientWriteComplete");
1472 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1476 ConnStateData::readNextRequest()
1478 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1480 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1482 * Set the timeout BEFORE calling readSomeData().
1484 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1485 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1486 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1487 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
1490 /** Please don't do anything with the FD past here! */
1494 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1496 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1498 /** If the client stream is waiting on a socket write to occur, then */
1500 if (deferredRequest
->flags
.deferred
) {
1501 /** NO data is allowed to have been sent. */
1502 assert(deferredRequest
->http
->out
.size
== 0);
1504 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1505 deferredRequest
->http
,
1506 deferredRequest
->deferredparams
.rep
,
1507 deferredRequest
->deferredparams
.queuedBuffer
);
1510 /** otherwise, the request is still active in a callbacksomewhere,
1515 /// called when we have successfully finished writing the response
1517 ClientSocketContext::keepaliveNextRequest()
1519 ConnStateData
* conn
= http
->getConn();
1521 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1524 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1525 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1526 conn
->clientConnection
->close();
1531 * We are done with the response, and we are either still receiving request
1532 * body (early response!) or have already stopped receiving anything.
1534 * If we are still receiving, then clientParseRequest() below will fail.
1535 * (XXX: but then we will call readNextRequest() which may succeed and
1536 * execute a smuggled request as we are not done with the current request).
1538 * If we stopped because we got everything, then try the next request.
1540 * If we stopped receiving because of an error, then close now to avoid
1541 * getting stuck and to prevent accidental request smuggling.
1544 if (const char *reason
= conn
->stoppedReceiving()) {
1545 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1546 conn
->clientConnection
->close();
1551 * Attempt to parse a request from the request buffer.
1552 * If we've been fed a pipelined request it may already
1553 * be in our read buffer.
1556 * This needs to fall through - if we're unlucky and parse the _last_ request
1557 * from our read buffer we may never re-register for another client read.
1560 if (conn
->clientParseRequests()) {
1561 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1565 * Either we need to kick-start another read or, if we have
1566 * a half-closed connection, kill it after the last request.
1567 * This saves waiting for half-closed connections to finished being
1568 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1569 * the keepalive "Waiting for next request" state.
1571 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1572 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1573 conn
->clientConnection
->close();
1577 ClientSocketContext::Pointer deferredRequest
;
1580 * At this point we either have a parsed request (which we've
1581 * kicked off the processing for) or not. If we have a deferred
1582 * request (parsed but deferred for pipeling processing reasons)
1583 * then look at processing it. If not, simply kickstart
1587 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1588 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1589 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1590 } else if (conn
->flags
.readMore
) {
1591 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1592 conn
->readNextRequest();
1594 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1595 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1600 clientUpdateSocketStats(const LogTags
&logType
, size_t size
)
1605 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1607 if (logType
.isTcpHit())
1608 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1612 * increments iterator "i"
1613 * used by clientPackMoreRanges
1615 \retval true there is still data available to pack more ranges
1619 ClientSocketContext::canPackMoreRanges() const
1621 /** first update iterator "i" if needed */
1623 if (!http
->range_iter
.debt()) {
1624 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1626 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1627 ++http
->range_iter
.pos
;
1629 http
->range_iter
.updateSpec();
1632 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1634 /* paranoid sync condition */
1635 /* continue condition: need_more_data */
1636 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1637 return http
->range_iter
.currentSpec() ? true : false;
1641 ClientSocketContext::getNextRangeOffset() const
1643 debugs (33, 5, "range: " << http
->request
->range
<<
1644 "; http offset " << http
->out
.offset
<<
1645 "; reply " << reply
);
1647 // XXX: This method is called from many places, including pullData() which
1648 // may be called before prepareReply() [on some Squid-generated errors].
1649 // Hence, we may not even know yet whether we should honor/do ranges.
1651 if (http
->request
->range
) {
1652 /* offset in range specs does not count the prefix of an http msg */
1653 /* check: reply was parsed and range iterator was initialized */
1654 assert(http
->range_iter
.valid
);
1655 /* filter out data according to range specs */
1656 assert (canPackMoreRanges());
1658 int64_t start
; /* offset of still missing data */
1659 assert(http
->range_iter
.currentSpec());
1660 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1661 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1662 debugs(33, 3, "clientPackMoreRanges: out:"
1663 " start: " << start
<<
1664 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1665 " [" << http
->range_iter
.currentSpec()->offset
<<
1666 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1667 " len: " << http
->range_iter
.currentSpec()->length
<<
1668 " debt: " << http
->range_iter
.debt());
1669 if (http
->range_iter
.currentSpec()->length
!= -1)
1670 assert(http
->out
.offset
<= start
); /* we did not miss it */
1675 } else if (reply
&& reply
->content_range
) {
1676 /* request does not have ranges, but reply does */
1677 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1678 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1680 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1683 return http
->out
.offset
;
1687 ClientSocketContext::pullData()
1689 debugs(33, 5, reply
<< " written " << http
->out
.size
<< " into " << clientConnection
);
1691 /* More data will be coming from the stream. */
1692 StoreIOBuffer readBuffer
;
1693 /* XXX: Next requested byte in the range sequence */
1694 /* XXX: length = getmaximumrangelenfgth */
1695 readBuffer
.offset
= getNextRangeOffset();
1696 readBuffer
.length
= HTTP_REQBUF_SZ
;
1697 readBuffer
.data
= reqbuf
;
1698 /* we may note we have reached the end of the wanted ranges */
1699 clientStreamRead(getTail(), http
, readBuffer
);
1702 /** Adapt stream status to account for Range cases
1705 clientStream_status_t
1706 ClientSocketContext::socketState()
1708 switch (clientStreamStatus(getTail(), http
)) {
1711 /* check for range support ending */
1713 if (http
->request
->range
) {
1714 /* check: reply was parsed and range iterator was initialized */
1715 assert(http
->range_iter
.valid
);
1716 /* filter out data according to range specs */
1718 if (!canPackMoreRanges()) {
1719 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1720 "range sequence on " << clientConnection
);
1721 // we got everything we wanted from the store
1722 return STREAM_COMPLETE
;
1724 } else if (reply
&& reply
->content_range
) {
1725 /* reply has content-range, but Squid is not managing ranges */
1726 const int64_t &bytesSent
= http
->out
.offset
;
1727 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1729 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1730 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1731 reply
->content_range
->spec
.offset
<< ")");
1733 // did we get at least what we expected, based on range specs?
1735 if (bytesSent
== bytesExpected
) // got everything
1736 return STREAM_COMPLETE
;
1738 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1739 return STREAM_UNPLANNED_COMPLETE
;
1744 case STREAM_COMPLETE
:
1745 return STREAM_COMPLETE
;
1747 case STREAM_UNPLANNED_COMPLETE
:
1748 return STREAM_UNPLANNED_COMPLETE
;
1751 return STREAM_FAILED
;
1754 fatal ("unreachable code\n");
1759 * A write has just completed to the client, or we have just realised there is
1760 * no more data to send.
1763 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, Comm::Flag errflag
, int, void *data
)
1765 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1766 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1769 /// remembers the abnormal connection termination for logging purposes
1771 ClientSocketContext::noteIoError(const int xerrno
)
1774 http
->logType
.err
.timedout
= (xerrno
== ETIMEDOUT
);
1775 // aborted even if xerrno is zero (which means read abort/eof)
1776 http
->logType
.err
.aborted
= (xerrno
!= ETIMEDOUT
);
1781 ClientSocketContext::doClose()
1783 clientConnection
->close();
1786 /// called when we encounter a response-related error
1788 ClientSocketContext::initiateClose(const char *reason
)
1790 http
->getConn()->stopSending(reason
); // closes ASAP
1794 ConnStateData::stopSending(const char *error
)
1796 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1797 "; old receiving error: " <<
1798 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1800 if (const char *oldError
= stoppedSending()) {
1801 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1802 return; // nothing has changed as far as this connection is concerned
1804 stoppedSending_
= error
;
1806 if (!stoppedReceiving()) {
1807 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1808 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1809 " request body bytes with " << in
.buf
.length() << " unused");
1810 return; // wait for the request receiver to finish reading
1814 clientConnection
->close();
1818 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
)
1820 const StoreEntry
*entry
= http
->storeEntry();
1821 http
->out
.size
+= size
;
1822 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1823 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1824 (entry
? entry
->objectLen() : 0));
1825 clientUpdateSocketStats(http
->logType
, size
);
1827 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
1829 if (errflag
== Comm::ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1832 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1833 initiateClose("failure or true request status");
1834 /* Do we leak here ? */
1838 switch (socketState()) {
1844 case STREAM_COMPLETE
:
1845 debugs(33, 5, conn
<< " Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1846 if (http
->request
->flags
.proxyKeepalive
)
1847 keepaliveNextRequest();
1849 initiateClose("STREAM_COMPLETE NOKEEPALIVE");
1852 case STREAM_UNPLANNED_COMPLETE
:
1853 initiateClose("STREAM_UNPLANNED_COMPLETE");
1857 initiateClose("STREAM_FAILED");
1861 fatal("Hit unreachable code in clientWriteComplete\n");
1865 ClientSocketContext
*
1866 ConnStateData::abortRequestParsing(const char *const uri
)
1868 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1869 http
->req_sz
= in
.buf
.length();
1870 http
->uri
= xstrdup(uri
);
1871 setLogUri (http
, uri
);
1872 ClientSocketContext
*context
= new ClientSocketContext(clientConnection
, http
);
1873 StoreIOBuffer tempBuffer
;
1874 tempBuffer
.data
= context
->reqbuf
;
1875 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1876 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1877 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1878 clientSocketDetach
, context
, tempBuffer
);
1883 skipLeadingSpace(char *aString
)
1885 char *result
= aString
;
1887 while (xisspace(*aString
))
1894 * 'end' defaults to NULL for backwards compatibility
1895 * remove default value if we ever get rid of NULL-terminated
1899 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1902 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1906 for (; end
> uriAndHTTPVersion
; --end
) {
1907 if (*end
== '\n' || *end
== '\r')
1910 if (xisspace(*end
)) {
1911 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1922 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1924 safe_free(http
->log_uri
);
1927 // The uri is already clean just dump it.
1928 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1931 switch (Config
.uri_whitespace
) {
1932 case URI_WHITESPACE_ALLOW
:
1933 flags
|= RFC1738_ESCAPE_NOSPACE
;
1935 case URI_WHITESPACE_ENCODE
:
1936 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1937 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1940 case URI_WHITESPACE_CHOP
: {
1941 flags
|= RFC1738_ESCAPE_NOSPACE
;
1942 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1943 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1944 int pos
= strcspn(http
->log_uri
, w_space
);
1945 http
->log_uri
[pos
] = '\0';
1949 case URI_WHITESPACE_DENY
:
1950 case URI_WHITESPACE_STRIP
:
1953 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1957 if (!xisspace(*t
)) {
1964 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
1973 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1975 int vhost
= conn
->port
->vhost
;
1976 int vport
= conn
->port
->vport
;
1977 static char ipbuf
[MAX_IPSTRLEN
];
1979 http
->flags
.accel
= true;
1981 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1983 static const SBuf
cache_object("cache_object://");
1984 if (hp
->requestUri().startsWith(cache_object
))
1985 return; /* already in good shape */
1987 // XXX: re-use proper URL parser for this
1988 SBuf url
= hp
->requestUri(); // use full provided URI if we abort
1989 do { // use a loop so we can break out of it
1990 ::Parser::Tokenizer
tok(url
);
1991 if (tok
.skip('/')) // origin-form URL already.
1994 if (conn
->port
->vhost
)
1995 return; /* already in good shape */
1997 // skip the URI scheme
1998 static const CharacterSet uriScheme
= CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
1999 static const SBuf
uriSchemeEnd("://");
2000 if (!tok
.skipAll(uriScheme
) || !tok
.skip(uriSchemeEnd
))
2003 // skip the authority segment
2004 // RFC 3986 complex nested ABNF for "authority" boils down to this:
2005 static const CharacterSet authority
= CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
2006 CharacterSet::HEXDIG
+ CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
2007 if (!tok
.skipAll(authority
))
2010 static const SBuf
slashUri("/");
2011 const SBuf t
= tok
.remaining();
2014 else if (t
[0]=='/') // looks like path
2016 else if (t
[0]=='?' || t
[0]=='#') { // looks like query or fragment. fix '/'
2019 } // else do nothing. invalid path
2023 #if SHOULD_REJECT_UNKNOWN_URLS
2024 // reject URI which are not well-formed even after the processing above
2025 if (url
.isEmpty() || url
[0] != '/') {
2026 hp
->parseStatusCode
= Http::scBadRequest
;
2027 return conn
->abortRequestParsing("error:invalid-request");
2032 vport
= http
->getConn()->clientConnection
->local
.port();
2034 const bool switchedToHttps
= conn
->switchedToHttps();
2035 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2037 if (tryHostHeader
&& (host
= hp
->getHeaderField("Host"))) {
2038 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2043 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2044 strncpy(thost
, host
, (t
-host
));
2045 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2048 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2051 } // else nothing to alter port-wise.
2052 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+ strlen(host
);
2053 http
->uri
= (char *)xcalloc(url_sz
, 1);
2054 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
, AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(url
));
2055 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
2056 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2057 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2058 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
2059 strlen(conn
->port
->defaultsite
);
2060 http
->uri
= (char *)xcalloc(url_sz
, 1);
2064 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2066 snprintf(http
->uri
, url_sz
, "%s://%s%s" SQUIDSBUFPH
,
2067 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
2068 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
2069 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2070 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
2071 /* Put the local socket IP address as the hostname, with whatever vport we found */
2072 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
2073 http
->uri
= (char *)xcalloc(url_sz
, 1);
2074 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2075 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
2076 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(),
2077 ipbuf
, vport
, SQUIDSBUFPRINT(url
));
2078 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
2083 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
2085 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
2086 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
2087 return; /* already in good shape */
2089 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2091 if (const char *host
= hp
->getHeaderField("Host")) {
2092 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
2094 http
->uri
= (char *)xcalloc(url_sz
, 1);
2095 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
,
2096 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(hp
->requestUri()));
2097 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
2099 /* Put the local socket IP address as the hostname. */
2100 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
2101 http
->uri
= (char *)xcalloc(url_sz
, 1);
2102 static char ipbuf
[MAX_IPSTRLEN
];
2103 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2104 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
2105 AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).c_str(),
2106 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SQUIDSBUFPRINT(hp
->requestUri()));
2107 debugs(33, 5, "TRANSPARENT REWRITE: " << http
->uri
);
2111 /** Parse an HTTP request
2113 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2114 * to 1 if the request was correctly parsed.
2115 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2116 * \param[in] hp an Http1::RequestParser
2117 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2118 * Pointed-to value will be set to Http::METHOD_NONE in case of
2120 * \param[out] http_ver will be set as a side-effect of the parsing
2121 * \return NULL on incomplete requests,
2122 * a ClientSocketContext structure on success or failure.
2124 ClientSocketContext
*
2125 parseHttpRequest(ConnStateData
*csd
, const Http1::RequestParserPointer
&hp
)
2127 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
2129 const bool parsedOk
= hp
->parse(csd
->in
.buf
);
2131 if (csd
->port
->flags
.isIntercepted() && Config
.accessList
.on_unsupported_protocol
)
2132 csd
->preservedClientData
= csd
->in
.buf
;
2133 // sync the buffers after parsing.
2134 csd
->in
.buf
= hp
->remaining();
2136 if (hp
->needsMoreData()) {
2137 debugs(33, 5, "Incomplete request, waiting for end of request line");
2142 if (hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
|| hp
->parseStatusCode
== Http::scUriTooLong
)
2143 return csd
->abortRequestParsing("error:request-too-large");
2145 return csd
->abortRequestParsing("error:invalid-request");
2149 /* We know the whole request is in parser now */
2150 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2151 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
2152 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
2156 /* deny CONNECT via accelerated ports */
2157 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
2158 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
2159 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2160 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2161 return csd
->abortRequestParsing("error:method-not-allowed");
2164 /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific
2165 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
2166 * If seen it signals a broken client or proxy has corrupted the traffic.
2168 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
2169 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
2170 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2171 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2172 return csd
->abortRequestParsing("error:method-not-allowed");
2175 if (hp
->method() == Http::METHOD_NONE
) {
2176 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2177 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2178 return csd
->abortRequestParsing("error:unsupported-request-method");
2181 // Process headers after request line
2182 debugs(33, 3, "complete request received. " <<
2183 "prefix_sz = " << hp
->messageHeaderSize() <<
2184 ", request-line-size=" << hp
->firstLineSize() <<
2185 ", mime-header-size=" << hp
->headerBlockSize() <<
2186 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
2188 /* Ok, all headers are received */
2189 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
2191 http
->req_sz
= hp
->messageHeaderSize();
2192 ClientSocketContext
*result
= new ClientSocketContext(csd
->clientConnection
, http
);
2194 StoreIOBuffer tempBuffer
;
2195 tempBuffer
.data
= result
->reqbuf
;
2196 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2198 ClientStreamData newServer
= new clientReplyContext(http
);
2199 ClientStreamData newClient
= result
;
2200 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2201 clientReplyStatus
, newServer
, clientSocketRecipient
,
2202 clientSocketDetach
, newClient
, tempBuffer
);
2205 debugs(33,5, "Prepare absolute URL from " <<
2206 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2207 /* Rewrite the URL in transparent or accelerator mode */
2208 /* NP: there are several cases to traverse here:
2209 * - standard mode (forward proxy)
2210 * - transparent mode (TPROXY)
2211 * - transparent mode with failures
2212 * - intercept mode (NAT)
2213 * - intercept mode with failures
2214 * - accelerator mode (reverse proxy)
2215 * - internal relative-URL
2216 * - mixed combos of the above with internal URL
2217 * - remote interception with PROXY protocol
2218 * - remote reverse-proxy with PROXY protocol
2220 if (csd
->transparent()) {
2221 /* intercept or transparent mode, properly working with no failures */
2222 prepareTransparentURL(csd
, http
, hp
);
2224 } else if (internalCheck(hp
->requestUri())) { // NP: only matches relative-URI
2225 /* internal URL mode */
2226 /* prepend our name & port */
2227 http
->uri
= xstrdup(internalLocalUri(NULL
, hp
->requestUri()));
2228 // We just re-wrote the URL. Must replace the Host: header.
2229 // But have not parsed there yet!! flag for local-only handling.
2230 http
->flags
.internal
= true;
2232 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2233 /* accelerator mode */
2234 prepareAcceleratedURL(csd
, http
, hp
);
2238 /* No special rewrites have been applied above, use the
2239 * requested url. may be rewritten later, so make extra room */
2240 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
2241 http
->uri
= (char *)xcalloc(url_sz
, 1);
2242 xstrncpy(http
->uri
, hp
->requestUri().rawContent(), hp
->requestUri().length()+1);
2245 result
->flags
.parsed_ok
= 1;
2250 ConnStateData::In::maybeMakeSpaceAvailable()
2252 if (buf
.spaceSize() < 2) {
2253 const SBuf::size_type haveCapacity
= buf
.length() + buf
.spaceSize();
2254 if (haveCapacity
>= Config
.maxRequestBufferSize
) {
2255 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2258 if (haveCapacity
== 0) {
2259 // haveCapacity is based on the SBuf visible window of the MemBlob buffer, which may fill up.
2260 // at which point bump the buffer back to default. This allocates a new MemBlob with any un-parsed bytes.
2261 buf
.reserveCapacity(CLIENT_REQ_BUF_SZ
);
2263 const SBuf::size_type wantCapacity
= min(static_cast<SBuf::size_type
>(Config
.maxRequestBufferSize
), haveCapacity
*2);
2264 buf
.reserveCapacity(wantCapacity
);
2266 debugs(33, 2, "growing request buffer: available=" << buf
.spaceSize() << " used=" << buf
.length());
2268 return (buf
.spaceSize() >= 2);
2272 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2274 ClientSocketContext::Pointer
*S
;
2276 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2284 ConnStateData::getConcurrentRequestCount() const
2287 ClientSocketContext::Pointer
*T
;
2289 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2290 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2295 ConnStateData::connFinishedWithConn(int size
)
2298 if (getConcurrentRequestCount() == 0 && in
.buf
.isEmpty()) {
2299 /* no current or pending requests */
2300 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2302 } else if (!Config
.onoff
.half_closed_clients
) {
2303 /* admin doesn't want to support half-closed client sockets */
2304 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2305 notifyAllContexts(0); // no specific error implies abort
2314 ConnStateData::consumeInput(const size_t byteCount
)
2316 assert(byteCount
> 0 && byteCount
<= in
.buf
.length());
2317 in
.buf
.consume(byteCount
);
2318 debugs(33, 5, "in.buf has " << in
.buf
.length() << " unused bytes");
2322 ConnStateData::clientAfterReadingRequests()
2324 // Were we expecting to read more request body from half-closed connection?
2325 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2326 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2327 clientConnection
->close();
2336 ConnStateData::quitAfterError(HttpRequest
*request
)
2338 // From HTTP p.o.v., we do not have to close after every error detected
2339 // at the client-side, but many such errors do require closure and the
2340 // client-side code is bad at handling errors so we play it safe.
2342 request
->flags
.proxyKeepalive
= false;
2343 flags
.readMore
= false;
2344 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2348 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2350 ClientHttpRequest
*http
= context
->http
;
2355 assert(sslServerBump
->entry
);
2356 // Did we create an error entry while processing CONNECT?
2357 if (!sslServerBump
->entry
->isEmpty()) {
2358 quitAfterError(http
->request
);
2360 // Get the saved error entry and send it to the client by replacing the
2361 // ClientHttpRequest store entry with it.
2362 clientStreamNode
*node
= context
->getClientReplyContext();
2363 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2365 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2366 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
2368 // save the original request for logging purposes
2369 if (!context
->http
->al
->request
) {
2370 context
->http
->al
->request
= http
->request
;
2371 HTTPMSGLOCK(context
->http
->al
->request
);
2374 // Get error details from the fake certificate-peeking request.
2375 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2376 context
->pullData();
2380 // In bump-server-first mode, we have not necessarily seen the intended
2381 // server name at certificate-peeking time. Check for domain mismatch now,
2382 // when we can extract the intended name from the bumped HTTP request.
2383 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2384 HttpRequest
*request
= http
->request
;
2385 if (!Ssl::checkX509ServerValidity(srvCert
, request
->url
.host())) {
2386 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2387 "does not match domainname " << request
->url
.host());
2389 bool allowDomainMismatch
= false;
2390 if (Config
.ssl_client
.cert_error
) {
2391 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2392 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2393 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2394 delete check
.sslErrors
;
2395 check
.sslErrors
= NULL
;
2398 if (!allowDomainMismatch
) {
2399 quitAfterError(request
);
2401 clientStreamNode
*node
= context
->getClientReplyContext();
2402 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2403 assert (repContext
);
2405 // Fill the server IP and hostname for error page generation.
2406 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2407 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->url
.host());
2409 // Create an error object and fill it
2410 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2411 err
->src_addr
= clientConnection
->remote
;
2412 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2413 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2415 err
->detail
= errDetail
;
2416 // Save the original request for logging purposes.
2417 if (!context
->http
->al
->request
) {
2418 context
->http
->al
->request
= request
;
2419 HTTPMSGLOCK(context
->http
->al
->request
);
2421 repContext
->setReplyToError(request
->method
, err
);
2422 assert(context
->http
->out
.offset
== 0);
2423 context
->pullData();
2431 #endif // USE_OPENSSL
2434 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
2435 * or false otherwise
2438 clientTunnelOnError(ConnStateData
*conn
, ClientSocketContext
*context
, HttpRequest
*request
, const HttpRequestMethod
& method
, err_type requestError
, Http::StatusCode errStatusCode
, const char *requestErrorBytes
)
2440 if (conn
->port
->flags
.isIntercepted() &&
2441 Config
.accessList
.on_unsupported_protocol
&& conn
->nrequests
<= 1) {
2442 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
, NULL
);
2443 checklist
.requestErrorType
= requestError
;
2444 checklist
.src_addr
= conn
->clientConnection
->remote
;
2445 checklist
.my_addr
= conn
->clientConnection
->local
;
2446 checklist
.conn(conn
);
2447 allow_t answer
= checklist
.fastCheck();
2448 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
2449 debugs(33, 3, "Request will be tunneled to server");
2451 context
->removeFromConnectionList(conn
);
2452 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2455 if (conn
->preservedClientData
.length())
2456 preReadData
.append(conn
->preservedClientData
);
2457 static char ip
[MAX_IPSTRLEN
];
2458 conn
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
2459 conn
->in
.buf
.assign("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n").append(preReadData
);
2461 bool ret
= conn
->handleReadData();
2463 ret
= conn
->clientParseRequests();
2466 debugs(33, 2, "Failed to start fake CONNECT request for on_unsupported_protocol: " << conn
->clientConnection
);
2467 conn
->clientConnection
->close();
2471 debugs(33, 3, "Continue with returning the error: " << requestError
);
2476 conn
->quitAfterError(request
);
2477 clientStreamNode
*node
= context
->getClientReplyContext();
2478 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2479 assert (repContext
);
2481 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
2483 assert(context
->http
->out
.offset
== 0);
2484 context
->pullData();
2485 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
2490 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
2494 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2495 * to here because calling comm_reset_close() causes http to
2496 * be freed before accessing.
2498 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2499 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2500 conn
->flags
.readMore
= false;
2501 comm_reset_close(conn
->clientConnection
);
2506 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, ClientSocketContext
*context
)
2508 ClientHttpRequest
*http
= context
->http
;
2509 bool chunked
= false;
2510 bool mustReplyToOptions
= false;
2511 bool unsupportedTe
= false;
2512 bool expectBody
= false;
2514 // We already have the request parsed and checked, so we
2515 // only need to go through the final body/conn setup to doCallouts().
2516 assert(http
->request
);
2517 HttpRequest::Pointer request
= http
->request
;
2519 // temporary hack to avoid splitting this huge function with sensitive code
2520 const bool isFtp
= !hp
;
2522 // Some blobs below are still HTTP-specific, but we would have to rewrite
2523 // this entire function to remove them from the FTP code path. Connection
2524 // setup and body_pipe preparation blobs are needed for FTP.
2526 request
->clientConnectionManager
= conn
;
2528 request
->flags
.accelerated
= http
->flags
.accel
;
2529 request
->flags
.sslBumped
=conn
->switchedToHttps();
2530 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2531 // TODO: decouple http->flags.accel from request->flags.sslBumped
2532 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2533 !conn
->port
->allow_direct
: 0;
2535 if (request
->flags
.sslBumped
) {
2536 if (conn
->getAuth() != NULL
)
2537 request
->auth_user_request
= conn
->getAuth();
2542 * If transparent or interception mode is working clone the transparent and interception flags
2543 * from the port settings to the request.
2545 if (http
->clientConnection
!= NULL
) {
2546 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2547 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2548 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
2549 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
2550 if (Config
.accessList
.spoof_client_ip
) {
2551 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2552 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2555 request
->flags
.spoofClientIp
= true;
2557 request
->flags
.spoofClientIp
= false;
2560 if (internalCheck(request
->url
.path())) {
2561 if (internalHostnameIs(request
->url
.host()) && request
->url
.port() == getMyPort()) {
2562 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true));
2563 http
->flags
.internal
= true;
2564 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->url
.path())) {
2565 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (global_internal_static on)");
2566 request
->url
.setScheme(AnyP::PROTO_HTTP
);
2567 request
->url
.host(internalHostname());
2568 request
->url
.port(getMyPort());
2569 http
->flags
.internal
= true;
2571 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->url
.authority(true) << " (not this proxy)");
2574 request
->flags
.internal
= http
->flags
.internal
;
2575 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2576 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2577 #if FOLLOW_X_FORWARDED_FOR
2578 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2579 // not a details about teh TCP connection itself
2580 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2581 #endif /* FOLLOW_X_FORWARDED_FOR */
2582 request
->my_addr
= conn
->clientConnection
->local
;
2583 request
->myportname
= conn
->port
->name
;
2586 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
2587 // for now Squid only supports HTTP requests
2588 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
2589 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
2590 request
->http_ver
.major
= http_ver
.major
;
2591 request
->http_ver
.minor
= http_ver
.minor
;
2594 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2595 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2596 request
->clientConnectionManager
= conn
;
2598 if (request
->header
.chunked()) {
2600 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2601 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2602 // HTTP/1.1 requires chunking to be the last encoding if there is one
2603 unsupportedTe
= te
.size() && te
!= "identity";
2604 } // else implied identity coding
2606 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
2607 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2608 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2609 clientStreamNode
*node
= context
->getClientReplyContext();
2610 conn
->quitAfterError(request
.getRaw());
2611 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2612 assert (repContext
);
2613 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2614 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2615 assert(context
->http
->out
.offset
== 0);
2616 context
->pullData();
2617 clientProcessRequestFinished(conn
, request
);
2621 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2622 clientStreamNode
*node
= context
->getClientReplyContext();
2623 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2624 assert (repContext
);
2625 conn
->quitAfterError(request
.getRaw());
2626 repContext
->setReplyToError(ERR_INVALID_REQ
,
2627 Http::scLengthRequired
, request
->method
, NULL
,
2628 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2629 assert(context
->http
->out
.offset
== 0);
2630 context
->pullData();
2631 clientProcessRequestFinished(conn
, request
);
2635 clientSetKeepaliveFlag(http
);
2636 // Let tunneling code be fully responsible for CONNECT requests
2637 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2638 context
->mayUseConnection(true);
2639 conn
->flags
.readMore
= false;
2643 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
2644 clientProcessRequestFinished(conn
, request
);
2649 /* Do we expect a request-body? */
2650 expectBody
= chunked
|| request
->content_length
> 0;
2651 if (!context
->mayUseConnection() && expectBody
) {
2652 request
->body_pipe
= conn
->expectRequestBody(
2653 chunked
? -1 : request
->content_length
);
2655 /* Is it too large? */
2656 if (!chunked
&& // if chunked, we will check as we accumulate
2657 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2658 clientStreamNode
*node
= context
->getClientReplyContext();
2659 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2660 assert (repContext
);
2661 conn
->quitAfterError(request
.getRaw());
2662 repContext
->setReplyToError(ERR_TOO_BIG
,
2663 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
2664 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2665 assert(context
->http
->out
.offset
== 0);
2666 context
->pullData();
2667 clientProcessRequestFinished(conn
, request
);
2672 // We may stop producing, comm_close, and/or call setReplyToError()
2673 // below, so quit on errors to avoid http->doCallouts()
2674 if (!conn
->handleRequestBodyData()) {
2675 clientProcessRequestFinished(conn
, request
);
2679 if (!request
->body_pipe
->productionEnded()) {
2680 debugs(33, 5, "need more request body");
2681 context
->mayUseConnection(true);
2682 assert(conn
->flags
.readMore
);
2687 http
->calloutContext
= new ClientRequestContext(http
);
2691 clientProcessRequestFinished(conn
, request
);
2695 ConnStateData::pipelinePrefetchMax() const
2697 // TODO: Support pipelined requests through pinned connections.
2700 return Config
.pipeline_max_prefetch
;
2704 * Limit the number of concurrent requests.
2705 * \return true when there are available position(s) in the pipeline queue for another request.
2706 * \return false when the pipeline queue is full or disabled.
2709 ConnStateData::concurrentRequestQueueFilled() const
2711 const int existingRequestCount
= getConcurrentRequestCount();
2713 // default to the configured pipeline size.
2714 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2716 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
2718 const int internalRequest
= 0;
2720 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
2722 // when queue filled already we cant add more.
2723 if (existingRequestCount
>= concurrentRequestLimit
) {
2724 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2725 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2733 * Perform proxy_protocol_access ACL tests on the client which
2734 * connected to PROXY protocol port to see if we trust the
2735 * sender enough to accept their PROXY header claim.
2738 ConnStateData::proxyProtocolValidateClient()
2740 if (!Config
.accessList
.proxyProtocol
)
2741 return proxyProtocolError("PROXY client not permitted by default ACL");
2743 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
2744 ch
.src_addr
= clientConnection
->remote
;
2745 ch
.my_addr
= clientConnection
->local
;
2748 if (ch
.fastCheck() != ACCESS_ALLOWED
)
2749 return proxyProtocolError("PROXY client not permitted by ACLs");
2755 * Perform cleanup on PROXY protocol errors.
2756 * If header parsing hits a fatal error terminate the connection,
2757 * otherwise wait for more data.
2760 ConnStateData::proxyProtocolError(const char *msg
)
2763 // This is important to know, but maybe not so much that flooding the log is okay.
2764 #if QUIET_PROXY_PROTOCOL
2765 // display the first of every 32 occurances at level 1, the others at level 2.
2766 static uint8_t hide
= 0;
2767 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
2769 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
2776 /// magic octet prefix for PROXY protocol version 1
2777 static const SBuf
Proxy1p0magic("PROXY ", 6);
2779 /// magic octet prefix for PROXY protocol version 2
2780 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
2783 * Test the connection read buffer for PROXY protocol header.
2784 * Version 1 and 2 header currently supported.
2787 ConnStateData::parseProxyProtocolHeader()
2789 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
2791 // detect and parse PROXY/2.0 protocol header
2792 if (in
.buf
.startsWith(Proxy2p0magic
))
2793 return parseProxy2p0();
2795 // detect and parse PROXY/1.0 protocol header
2796 if (in
.buf
.startsWith(Proxy1p0magic
))
2797 return parseProxy1p0();
2799 // detect and terminate other protocols
2800 if (in
.buf
.length() >= Proxy2p0magic
.length()) {
2801 // PROXY/1.0 magic is shorter, so we know that
2802 // the input does not start with any PROXY magic
2803 return proxyProtocolError("PROXY protocol error: invalid header");
2806 // TODO: detect short non-magic prefixes earlier to avoid
2807 // waiting for more data which may never come
2809 // not enough bytes to parse yet.
2813 /// parse the PROXY/1.0 protocol header from the connection read buffer
2815 ConnStateData::parseProxy1p0()
2817 ::Parser::Tokenizer
tok(in
.buf
);
2818 tok
.skip(Proxy1p0magic
);
2820 // skip to first LF (assumes it is part of CRLF)
2821 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
2823 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
2824 if (tok
.skip('\n')) {
2825 // found valid header
2826 in
.buf
= tok
.remaining();
2827 needProxyProtocolHeader_
= false;
2828 // reset the tokenizer to work on found line only.
2831 return false; // no LF yet
2833 } else // protocol error only if there are more than 107 bytes prefix header
2834 return proxyProtocolError(in
.buf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
2836 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
2837 if (tok
.skip(tcpName
)) {
2839 // skip TCP/IP version number
2840 static const CharacterSet
tcpVersions("TCP-version","46");
2841 if (!tok
.skipOne(tcpVersions
))
2842 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
2844 // skip SP after protocol version
2846 return proxyProtocolError("PROXY/1.0 error: missing SP");
2849 int64_t porta
, portb
;
2850 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
2852 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
2853 // leave the LF until later.
2854 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
2855 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
2856 tok
.int64(porta
) && tok
.skip(' ') &&
2860 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
2862 // parse IP and port strings
2863 Ip::Address originalClient
, originalDest
;
2865 if (!originalClient
.GetHostByName(ipa
.c_str()))
2866 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
2868 if (!originalDest
.GetHostByName(ipb
.c_str()))
2869 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
2871 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
2872 originalClient
.port(static_cast<uint16_t>(porta
));
2874 return proxyProtocolError("PROXY/1.0 error: invalid src port");
2876 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
2877 originalDest
.port(static_cast<uint16_t>(portb
));
2879 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
2881 // we have original client and destination details now
2882 // replace the client connection values
2883 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
2884 clientConnection
->local
= originalDest
;
2885 clientConnection
->remote
= originalClient
;
2886 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2887 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2888 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2890 // repeat fetch ensuring the new client FQDN can be logged
2891 if (Config
.onoff
.log_fqdn
)
2892 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2896 } else if (tok
.skip(unknown
)) {
2897 // found valid but unusable header
2901 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2906 /// parse the PROXY/2.0 protocol header from the connection read buffer
2908 ConnStateData::parseProxy2p0()
2910 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2911 if (in
.buf
.length() < prefixLen
+ 4)
2912 return false; // need more bytes
2914 if ((in
.buf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2915 return proxyProtocolError("PROXY/2.0 error: invalid version");
2917 const char command
= (in
.buf
[prefixLen
] & 0x0F);
2918 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2919 return proxyProtocolError("PROXY/2.0 error: invalid command");
2921 const char family
= (in
.buf
[prefixLen
+1] & 0xF0) >>4;
2922 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2923 return proxyProtocolError("PROXY/2.0 error: invalid family");
2925 const char proto
= (in
.buf
[prefixLen
+1] & 0x0F);
2926 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2927 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2929 const char *clen
= in
.buf
.rawContent() + prefixLen
+ 2;
2931 memcpy(&len
, clen
, sizeof(len
));
2934 if (in
.buf
.length() < prefixLen
+ 4 + len
)
2935 return false; // need more bytes
2937 in
.buf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2938 const SBuf extra
= in
.buf
.consume(len
);
2939 needProxyProtocolHeader_
= false; // found successfully
2941 // LOCAL connections do nothing with the extras
2942 if (command
== 0x00/* LOCAL*/)
2946 struct { /* for TCP/UDP over IPv4, len = 12 */
2947 struct in_addr src_addr
;
2948 struct in_addr dst_addr
;
2952 struct { /* for TCP/UDP over IPv6, len = 36 */
2953 struct in6_addr src_addr
;
2954 struct in6_addr dst_addr
;
2959 struct { /* for AF_UNIX sockets, len = 216 */
2960 uint8_t src_addr
[108];
2961 uint8_t dst_addr
[108];
2967 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2969 // replace the client connection values
2970 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2973 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2974 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2975 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2976 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2977 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2978 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2981 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2982 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
2983 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
2984 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
2985 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2986 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2988 default: // do nothing
2991 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
2993 // repeat fetch ensuring the new client FQDN can be logged
2994 if (Config
.onoff
.log_fqdn
)
2995 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3001 ConnStateData::receivedFirstByte()
3003 if (receivedFirstByte_
)
3006 receivedFirstByte_
= true;
3007 // Set timeout to Config.Timeout.request
3008 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3009 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3010 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3011 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3015 * Attempt to parse one or more requests from the input buffer.
3016 * Returns true after completing parsing of at least one request [header]. That
3017 * includes cases where parsing ended with an error (e.g., a huge request).
3020 ConnStateData::clientParseRequests()
3022 bool parsed_req
= false;
3024 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
3026 // Loop while we have read bytes that are not needed for producing the body
3027 // On errors, bodyPipe may become nil, but readMore will be cleared
3028 while (!in
.buf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
3030 /* Don't try to parse if the buffer is empty */
3031 if (in
.buf
.isEmpty())
3034 /* Limit the number of concurrent requests */
3035 if (concurrentRequestQueueFilled())
3038 // try to parse the PROXY protocol header magic bytes
3039 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
3042 if (ClientSocketContext
*context
= parseOneRequest()) {
3043 debugs(33, 5, clientConnection
<< ": done parsing a request");
3045 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3046 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
3047 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3049 context
->registerWithConn();
3051 processParsedRequest(context
);
3053 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3055 if (context
->mayUseConnection()) {
3056 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3060 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
3061 in
.buf
.length() << " < " << Config
.maxRequestHeaderSize
);
3062 Must(in
.buf
.length() < Config
.maxRequestHeaderSize
);
3067 /* XXX where to 'finish' the parsing pass? */
3072 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3074 debugs(33,5, io
.conn
);
3078 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
3079 if (io
.flag
== Comm::ERR_CLOSING
) {
3080 debugs(33,5, io
.conn
<< " closing Bailout.");
3084 assert(Comm::IsConnOpen(clientConnection
));
3085 assert(io
.conn
->fd
== clientConnection
->fd
);
3088 * Don't reset the timeout value here. The value should be
3089 * counting Config.Timeout.request and applies to the request
3090 * as a whole, not individual read() calls.
3091 * Plus, it breaks our lame *HalfClosed() detection
3094 in
.maybeMakeSpaceAvailable();
3095 CommIoCbParams
rd(this); // will be expanded with ReadNow results
3097 switch (Comm::ReadNow(rd
, in
.buf
)) {
3098 case Comm::INPROGRESS
:
3099 if (in
.buf
.isEmpty())
3100 debugs(33, 2, io
.conn
<< ": no data to process, " << xstrerr(rd
.xerrno
));
3105 kb_incr(&(statCounter
.client_http
.kbytes_in
), rd
.size
);
3106 if (!receivedFirstByte_
)
3107 receivedFirstByte();
3108 // may comm_close or setReplyToError
3109 if (!handleReadData())
3112 /* Continue to process previously read data */
3115 case Comm::ENDFILE
: // close detected by 0-byte read
3116 debugs(33, 5, io
.conn
<< " closed?");
3118 if (connFinishedWithConn(rd
.size
)) {
3119 clientConnection
->close();
3123 /* It might be half-closed, we can't tell */
3124 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3125 commMarkHalfClosed(io
.conn
->fd
);
3126 fd_note(io
.conn
->fd
, "half-closed");
3128 /* There is one more close check at the end, to detect aborted
3129 * (partial) requests. At this point we can't tell if the request
3133 /* Continue to process previously read data */
3136 // case Comm::COMM_ERROR:
3137 default: // no other flags should ever occur
3138 debugs(33, 2, io
.conn
<< ": got flag " << rd
.flag
<< "; " << xstrerr(rd
.xerrno
));
3139 notifyAllContexts(rd
.xerrno
);
3144 /* Process next request */
3145 if (getConcurrentRequestCount() == 0)
3146 fd_note(io
.fd
, "Reading next request");
3148 if (!clientParseRequests()) {
3152 * If the client here is half closed and we failed
3153 * to parse a request, close the connection.
3154 * The above check with connFinishedWithConn() only
3155 * succeeds _if_ the buffer is empty which it won't
3156 * be if we have an incomplete request.
3157 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3159 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3160 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3161 clientConnection
->close();
3169 clientAfterReadingRequests();
3173 * called when new request data has been read from the socket
3175 * \retval false called comm_close or setReplyToError (the caller should bail)
3176 * \retval true we did not call comm_close or setReplyToError
3179 ConnStateData::handleReadData()
3181 // if we are reading a body, stuff data into the body pipe
3182 if (bodyPipe
!= NULL
)
3183 return handleRequestBodyData();
3188 * called when new request body data has been buffered in in.buf
3189 * may close the connection if we were closing and piped everything out
3191 * \retval false called comm_close or setReplyToError (the caller should bail)
3192 * \retval true we did not call comm_close or setReplyToError
3195 ConnStateData::handleRequestBodyData()
3197 assert(bodyPipe
!= NULL
);
3199 if (in
.bodyParser
) { // chunked encoding
3200 if (const err_type error
= handleChunkedRequestBody()) {
3201 abortChunkedRequestBody(error
);
3204 } else { // identity encoding
3205 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3206 const size_t putSize
= bodyPipe
->putMoreData(in
.buf
.c_str(), in
.buf
.length());
3208 consumeInput(putSize
);
3210 if (!bodyPipe
->mayNeedMoreData()) {
3211 // BodyPipe will clear us automagically when we produced everything
3217 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3219 if (const char *reason
= stoppedSending()) {
3220 /* we've finished reading like good clients,
3221 * now do the close that initiateClose initiated.
3223 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3224 clientConnection
->close();
3232 /// parses available chunked encoded body bytes, checks size, returns errors
3234 ConnStateData::handleChunkedRequestBody()
3236 debugs(33, 7, "chunked from " << clientConnection
<< ": " << in
.buf
.length());
3238 try { // the parser will throw on errors
3240 if (in
.buf
.isEmpty()) // nothing to do
3243 BodyPipeCheckout
bpc(*bodyPipe
);
3244 in
.bodyParser
->setPayloadBuffer(&bpc
.buf
);
3245 const bool parsed
= in
.bodyParser
->parse(in
.buf
);
3246 in
.buf
= in
.bodyParser
->remaining(); // sync buffers
3249 // dechunk then check: the size limit applies to _dechunked_ content
3250 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3254 finishDechunkingRequest(true);
3256 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3259 // if chunk parser needs data, then the body pipe must need it too
3260 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3262 // if parser needs more space and we can consume nothing, we will stall
3263 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3264 } catch (...) { // TODO: be more specific
3265 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3266 return ERR_INVALID_REQ
;
3269 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3273 /// quit on errors related to chunked request body handling
3275 ConnStateData::abortChunkedRequestBody(const err_type error
)
3277 finishDechunkingRequest(false);
3279 // XXX: The code below works if we fail during initial request parsing,
3280 // but if we fail when the server connection is used already, the server may send
3281 // us its response too, causing various assertions. How to prevent that?
3282 #if WE_KNOW_HOW_TO_SEND_ERRORS
3283 ClientSocketContext::Pointer context
= getCurrentContext();
3284 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3285 clientStreamNode
*node
= context
->getClientReplyContext();
3286 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3288 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3289 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
3290 repContext
->setReplyToError(error
, scode
,
3291 repContext
->http
->request
->method
,
3292 repContext
->http
->uri
,
3294 repContext
->http
->request
,
3296 context
->pullData();
3298 // close or otherwise we may get stuck as nobody will notice the error?
3299 comm_reset_close(clientConnection
);
3302 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3303 comm_reset_close(clientConnection
);
3305 flags
.readMore
= false;
3309 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3311 // request reader may get stuck waiting for space if nobody consumes body
3312 if (bodyPipe
!= NULL
)
3313 bodyPipe
->enableAutoConsumption();
3318 /** general lifetime handler for HTTP requests */
3320 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3322 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
3324 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
3325 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
3326 receivedFirstByte();
3329 } else if (fd_table
[io
.conn
->fd
].ssl
== NULL
)
3332 const HttpRequestMethod method
;
3333 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
3334 // Tunnel established. Set receivedFirstByte to avoid loop.
3335 receivedFirstByte();
3341 * Just close the connection to not confuse browsers
3342 * using persistent connections. Some browsers open
3343 * a connection and then do not use it until much
3344 * later (presumeably because the request triggering
3345 * the open has already been completed on another
3348 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3353 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3355 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3356 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3357 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3358 http
->logType
.err
.timedout
= true;
3359 if (Comm::IsConnOpen(io
.conn
))
3363 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3364 AsyncJob("ConnStateData"), // kids overwrite
3367 sslBumpMode(Ssl::bumpEnd
),
3369 needProxyProtocolHeader_(false),
3371 switchedToHttps_(false),
3372 sslServerBump(NULL
),
3373 signAlgorithm(Ssl::algSignTrusted
),
3375 stoppedSending_(NULL
),
3376 stoppedReceiving_(NULL
),
3377 receivedFirstByte_(false)
3379 flags
.readMore
= true; // kids may overwrite
3380 flags
.swanSang
= false;
3382 pinning
.host
= NULL
;
3384 pinning
.pinned
= false;
3385 pinning
.auth
= false;
3386 pinning
.zeroReply
= false;
3387 pinning
.peer
= NULL
;
3389 // store the details required for creating more MasterXaction objects as new requests come in
3390 clientConnection
= xact
->tcpClient
;
3391 port
= xact
->squidPort
;
3392 transferProtocol
= port
->transport
; // default to the *_port protocol= setting. may change later.
3393 log_addr
= xact
->tcpClient
->remote
;
3394 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3398 ConnStateData::start()
3400 BodyProducer::start();
3401 HttpControlMsgSink::start();
3403 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3404 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3405 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3406 int i
= IP_PMTUDISC_DONT
;
3407 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3408 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3410 static bool reported
= false;
3413 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3419 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3420 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3421 comm_add_close_handler(clientConnection
->fd
, call
);
3423 if (Config
.onoff
.log_fqdn
)
3424 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3427 if (Ident::TheConfig
.identLookup
) {
3428 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3429 identChecklist
.src_addr
= clientConnection
->remote
;
3430 identChecklist
.my_addr
= clientConnection
->local
;
3431 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3432 Ident::Start(clientConnection
, clientIdentDone
, this);
3436 clientdbEstablished(clientConnection
->remote
, 1);
3438 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
3439 if (needProxyProtocolHeader_
) {
3440 if (!proxyProtocolValidateClient()) // will close the connection on failure
3445 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
3447 if (Config
.onoff
.client_db
) {
3448 /* it was said several times that client write limiter does not work if client_db is disabled */
3450 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3451 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3453 // TODO: we check early to limit error response bandwith but we
3454 // should recheck when we can honor delay_pool_uses_indirect
3455 // TODO: we should also pass the port details for myportname here.
3456 ch
.src_addr
= clientConnection
->remote
;
3457 ch
.my_addr
= clientConnection
->local
;
3459 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3461 /* pools require explicit 'allow' to assign a client into them */
3462 if (pools
[pool
].access
) {
3463 ch
.accessList
= pools
[pool
].access
;
3464 allow_t answer
= ch
.fastCheck();
3465 if (answer
== ACCESS_ALLOWED
) {
3467 /* request client information from db after we did all checks
3468 this will save hash lookup if client failed checks */
3469 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
3472 /* put client info in FDE */
3473 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
3475 /* setup write limiter for this request */
3476 const double burst
= floor(0.5 +
3477 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3478 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3481 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3488 // kids must extend to actually start doing something (e.g., reading)
3491 /** Handle a new connection on an HTTP socket. */
3493 httpAccept(const CommAcceptCbParams
¶ms
)
3495 MasterXaction::Pointer xact
= params
.xaction
;
3496 AnyP::PortCfgPointer s
= xact
->squidPort
;
3498 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3500 if (params
.flag
!= Comm::OK
) {
3501 // Its possible the call was still queued when the client disconnected
3502 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3506 debugs(33, 4, params
.conn
<< ": accepted");
3507 fd_note(params
.conn
->fd
, "client http connect");
3509 if (s
->tcp_keepalive
.enabled
)
3510 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3512 ++incoming_sockets_accepted
;
3514 // Socket is ready, setup the connection manager to start using it
3515 ConnStateData
*connState
= Http::NewServer(xact
);
3516 AsyncJob::Start(connState
); // usually async-calls readSomeData()
3521 /** Create SSL connection structure and update fd_table */
3522 static Security::SessionPointer
3523 httpsCreate(const Comm::ConnectionPointer
&conn
, Security::ContextPointer sslContext
)
3525 if (auto ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
3526 debugs(33, 5, "will negotate SSL on " << conn
);
3536 * \retval 1 on success
3537 * \retval 0 when needs more data
3538 * \retval -1 on error
3541 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
3543 int fd
= conn
->clientConnection
->fd
;
3544 auto ssl
= fd_table
[fd
].ssl
;
3548 if ((ret
= SSL_accept(ssl
)) <= 0) {
3549 const int xerrno
= errno
;
3550 const int ssl_error
= SSL_get_error(ssl
, ret
);
3552 switch (ssl_error
) {
3554 case SSL_ERROR_WANT_READ
:
3555 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, conn
, 0);
3558 case SSL_ERROR_WANT_WRITE
:
3559 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, conn
, 0);
3562 case SSL_ERROR_SYSCALL
:
3564 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
3566 debugs(83, (xerrno
== ECONNRESET
) ? 1 : 2, "Error negotiating SSL connection on FD " << fd
<< ": " <<
3567 (xerrno
== 0 ? ERR_error_string(ssl_error
, NULL
) : xstrerr(xerrno
)));
3571 case SSL_ERROR_ZERO_RETURN
:
3572 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3576 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
3577 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3578 " (" << ssl_error
<< "/" << ret
<< ")");
3587 /** negotiate an SSL connection */
3589 clientNegotiateSSL(int fd
, void *data
)
3591 ConnStateData
*conn
= (ConnStateData
*)data
;
3593 auto ssl
= fd_table
[fd
].ssl
;
3596 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
3597 if (ret
< 0) // An error
3598 conn
->clientConnection
->close();
3602 if (SSL_session_reused(ssl
)) {
3603 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3604 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3606 if (do_debug(83, 4)) {
3607 /* Write out the SSL session details.. actually the call below, but
3608 * OpenSSL headers do strange typecasts confusing GCC.. */
3609 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3610 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3611 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
);
3613 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3615 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3616 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3617 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3618 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3619 * Because there are two possible usable cast, if you get an error here, try the other
3620 * commented line. */
3622 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3623 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3627 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3630 /* Note: This does not automatically fflush the log file.. */
3633 debugs(83, 2, "clientNegotiateSSL: New session " <<
3634 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3635 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3639 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3640 SSL_get_cipher(ssl
));
3642 client_cert
= SSL_get_peer_certificate(ssl
);
3644 if (client_cert
!= NULL
) {
3645 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3646 " client certificate: subject: " <<
3647 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3649 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3650 " client certificate: issuer: " <<
3651 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3653 X509_free(client_cert
);
3655 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3656 " has no certificate.");
3659 #if defined(TLSEXT_NAMETYPE_host_name)
3660 if (!conn
->serverBump()) {
3661 // when in bumpClientFirst mode, get the server name from SNI
3662 if (const char *server
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))
3663 conn
->resetSslCommonName(server
);
3667 conn
->readSomeData();
3671 * If Security::ContextPointer is given, starts reading the TLS handshake.
3672 * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPointer.
3675 httpsEstablish(ConnStateData
*connState
, Security::ContextPointer sslContext
)
3677 Security::SessionPointer ssl
= nullptr;
3679 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3681 if (!sslContext
|| !(ssl
= httpsCreate(details
, sslContext
)))
3684 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3685 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3686 connState
, ConnStateData::requestTimeout
);
3687 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3689 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3693 * A callback function to use with the ACLFilledChecklist callback.
3694 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3695 * else reverts the connection to tunnel mode.
3698 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3700 ConnStateData
*connState
= (ConnStateData
*) data
;
3702 // if the connection is closed or closing, just return.
3703 if (!connState
->isOpen())
3706 // Require both a match and a positive bump mode to work around exceptional
3707 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3708 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
3709 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
3710 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3712 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3713 connState
->sslBumpMode
= Ssl::bumpNone
;
3716 // fake a CONNECT request to force connState to tunnel
3717 static char ip
[MAX_IPSTRLEN
];
3718 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3719 // Pre-pend this fake request to the TLS bits already in the buffer
3721 retStr
.append("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n");
3722 connState
->in
.buf
= retStr
.append(connState
->in
.buf
);
3723 bool ret
= connState
->handleReadData();
3725 ret
= connState
->clientParseRequests();
3728 debugs(33, 2, "Failed to start fake CONNECT request for SSL bumped connection: " << connState
->clientConnection
);
3729 connState
->clientConnection
->close();
3733 /** handle a new HTTPS connection */
3735 httpsAccept(const CommAcceptCbParams
¶ms
)
3737 MasterXaction::Pointer xact
= params
.xaction
;
3738 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3740 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3742 if (params
.flag
!= Comm::OK
) {
3743 // Its possible the call was still queued when the client disconnected
3744 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3748 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3749 fd_note(params
.conn
->fd
, "client https connect");
3751 if (s
->tcp_keepalive
.enabled
) {
3752 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3755 ++incoming_sockets_accepted
;
3757 // Socket is ready, setup the connection manager to start using it
3758 ConnStateData
*connState
= Https::NewServer(xact
);
3759 AsyncJob::Start(connState
); // usually async-calls postHttpsAccept()
3763 ConnStateData::postHttpsAccept()
3765 if (port
->flags
.tunnelSslBumping
) {
3766 debugs(33, 5, "accept transparent connection: " << clientConnection
);
3768 if (!Config
.accessList
.ssl_bump
) {
3769 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
3773 // Create a fake HTTP request for ssl_bump ACL check,
3774 // using tproxy/intercept provided destination IP and port.
3775 HttpRequest
*request
= new HttpRequest();
3776 static char ip
[MAX_IPSTRLEN
];
3777 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3778 request
->url
.host(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
3779 request
->url
.port(clientConnection
->local
.port());
3780 request
->myportname
= port
->name
;
3782 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3783 acl_checklist
->src_addr
= clientConnection
->remote
;
3784 acl_checklist
->my_addr
= port
->s
;
3785 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
3788 Security::ContextPointer sslContext
= port
->staticSslContext
.get();
3789 httpsEstablish(this, sslContext
);
3794 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
3796 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3797 state_data
->sslCrtdHandleReply(reply
);
3801 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
3804 debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply
);
3808 if (reply
.result
== Helper::BrokenHelper
) {
3809 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3810 } else if (!reply
.other().hasContent()) {
3811 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3813 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3814 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3815 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3817 if (reply
.result
!= Helper::Okay
) {
3818 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3820 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3821 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3822 doPeekAndSpliceStep();
3823 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3824 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
3826 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3828 auto ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3829 getSslContextDone(ctx
, true);
3835 getSslContextDone(NULL
);
3838 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3840 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
3842 // fake certificate adaptation requires bump-server-first mode
3843 if (!sslServerBump
) {
3844 assert(port
->signingCert
.get());
3845 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3846 if (port
->signPkey
.get())
3847 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3848 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3852 // In case of an error while connecting to the secure server, use a fake
3853 // trusted certificate, with no mimicked fields and no adaptation
3854 // algorithms. There is nothing we can mimic so we want to minimize the
3855 // number of warnings the user will have to see to get to the error page.
3856 assert(sslServerBump
->entry
);
3857 if (sslServerBump
->entry
->isEmpty()) {
3858 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3859 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3861 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3862 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3863 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3865 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3866 // If the algorithm already set, then ignore it.
3867 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3868 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3869 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3872 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3873 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3874 const char *param
= ca
->param
;
3876 // For parameterless CN adaptation, use hostname from the
3878 if (ca
->alg
== Ssl::algSetCommonName
) {
3880 param
= sslConnectHostOrIp
.termedBuf();
3881 certProperties
.commonName
= param
;
3882 certProperties
.setCommonName
= true;
3883 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3884 certProperties
.setValidAfter
= true;
3885 else if (ca
->alg
== Ssl::algSetValidBefore
)
3886 certProperties
.setValidBefore
= true;
3888 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3889 alg
<< " param: " << (param
? param
: "-"));
3893 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3894 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3895 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3896 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3900 } else {// if (!sslServerBump->entry->isEmpty())
3901 // Use trusted certificate for a Squid-generated error
3902 // or the user would have to add a security exception
3903 // just to see the error page. We will close the connection
3904 // so that the trust is not extended to non-Squid content.
3905 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3908 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3910 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3911 assert(port
->untrustedSigningCert
.get());
3912 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3913 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3915 assert(port
->signingCert
.get());
3916 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3918 if (port
->signPkey
.get())
3919 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3921 signAlgorithm
= certProperties
.signAlgorithm
;
3923 certProperties
.signHash
= Ssl::DefaultSignHash
;
3927 ConnStateData::getSslContextStart()
3929 assert(areAllContextsForThisConnection());
3931 /* careful: freeAllContexts() above frees request, host, etc. */
3933 if (port
->generateHostCertificates
) {
3934 Ssl::CertificateProperties certProperties
;
3935 buildSslCertGenerationParams(certProperties
);
3936 sslBumpCertKey
= certProperties
.dbKey().c_str();
3937 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3939 // Disable caching for bumpPeekAndSplice mode
3940 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
3941 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3942 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3943 Security::ContextPointer dynCtx
= nullptr;
3944 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3945 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3946 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3947 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3948 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3949 getSslContextDone(dynCtx
);
3952 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3954 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3957 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3963 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3964 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3965 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3966 request_message
.composeRequest(certProperties
);
3967 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3968 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3970 } catch (const std::exception
&e
) {
3971 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3972 "request for " << certProperties
.commonName
<<
3973 " certificate: " << e
.what() << "; will now block to " <<
3974 "generate that certificate.");
3975 // fall through to do blocking in-process generation.
3977 #endif // USE_SSL_CRTD
3979 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3980 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3981 doPeekAndSpliceStep();
3982 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
3983 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3984 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3986 auto dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3987 getSslContextDone(dynCtx
, true);
3991 getSslContextDone(NULL
);
3995 ConnStateData::getSslContextDone(Security::ContextPointer sslContext
, bool isNew
)
3997 // Try to add generated ssl context to storage.
3998 if (port
->generateHostCertificates
&& isNew
) {
4000 if (signAlgorithm
== Ssl::algSignTrusted
) {
4001 // Add signing certificate to the certificates chain
4002 X509
*cert
= port
->signingCert
.get();
4003 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
4004 // increase the certificate lock
4005 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
4007 const int ssl_error
= ERR_get_error();
4008 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
4010 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
4012 //else it is self-signed or untrusted do not attrach any certificate
4014 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
4015 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
4017 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
4018 // If it is not in storage delete after using. Else storage deleted it.
4019 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
4022 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
4026 // If generated ssl context = NULL, try to use static ssl context.
4028 if (!port
->staticSslContext
) {
4029 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
4030 clientConnection
->close();
4033 debugs(33, 5, HERE
<< "Using static ssl context.");
4034 sslContext
= port
->staticSslContext
.get();
4038 if (!httpsCreate(clientConnection
, sslContext
))
4041 // bumped intercepted conns should already have Config.Timeout.request set
4042 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
4043 // to make sure the connection does not get stuck on non-SSL clients.
4044 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
4045 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
4046 this, ConnStateData::requestTimeout
);
4047 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
4049 // Disable the client read handler until CachePeer selection is complete
4050 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4051 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
4052 switchedToHttps_
= true;
4056 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
4058 assert(!switchedToHttps_
);
4060 sslConnectHostOrIp
= request
->url
.host();
4061 resetSslCommonName(request
->url
.host());
4063 // We are going to read new request
4064 flags
.readMore
= true;
4065 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
4067 // keep version major.minor details the same.
4068 // but we are now performing the HTTPS handshake traffic
4069 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
4071 // If sslServerBump is set, then we have decided to deny CONNECT
4072 // and now want to switch to SSL to send the error to the client
4073 // without even peeking at the origin server certificate.
4074 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
4075 request
->flags
.sslPeek
= true;
4076 sslServerBump
= new Ssl::ServerBump(request
);
4078 // will call httpsPeeked() with certificate and connection, eventually
4079 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4081 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
4082 request
->flags
.sslPeek
= true;
4083 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
4084 startPeekAndSplice();
4088 // otherwise, use sslConnectHostOrIp
4089 getSslContextStart();
4093 ConnStateData::spliceOnError(const err_type err
)
4095 if (Config
.accessList
.on_unsupported_protocol
) {
4096 assert(serverBump());
4097 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
4098 checklist
.requestErrorType
= err
;
4099 checklist
.conn(this);
4100 allow_t answer
= checklist
.fastCheck();
4101 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
4109 /** negotiate an SSL connection */
4111 clientPeekAndSpliceSSL(int fd
, void *data
)
4113 ConnStateData
*conn
= (ConnStateData
*)data
;
4114 auto ssl
= fd_table
[fd
].ssl
;
4116 debugs(83, 5, "Start peek and splice on FD " << fd
);
4119 if ((ret
= Squid_SSL_accept(conn
, clientPeekAndSpliceSSL
)) < 0)
4120 debugs(83, 2, "SSL_accept failed.");
4122 BIO
*b
= SSL_get_rbio(ssl
);
4124 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4126 const err_type err
= bio
->noSslClient() ? ERR_PROTOCOL_UNKNOWN
: ERR_SECURE_ACCEPT_FAIL
;
4127 if (!conn
->spliceOnError(err
))
4128 conn
->clientConnection
->close();
4132 if (bio
->rBufData().contentSize() > 0)
4133 conn
->receivedFirstByte();
4135 if (bio
->gotHello()) {
4136 if (conn
->serverBump()) {
4137 Ssl::Bio::sslFeatures
const &features
= bio
->getFeatures();
4138 if (!features
.serverName
.isEmpty()) {
4139 conn
->serverBump()->clientSni
= features
.serverName
;
4140 conn
->resetSslCommonName(features
.serverName
.c_str());
4144 debugs(83, 5, "I got hello. Start forwarding the request!!! ");
4145 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4146 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
4147 conn
->startPeekAndSpliceDone();
4152 void ConnStateData::startPeekAndSplice()
4154 // will call httpsPeeked() with certificate and connection, eventually
4155 auto unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
4156 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
4158 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
4161 // commSetConnTimeout() was called for this request before we switched.
4162 // Fix timeout to request_start_timeout
4163 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
4164 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
4165 TimeoutDialer
, this, ConnStateData::requestTimeout
);
4166 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
4167 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
4168 // a bumbed "connect" request on non transparent port.
4169 receivedFirstByte_
= false;
4171 // Disable the client read handler until CachePeer selection is complete
4172 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4173 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientPeekAndSpliceSSL
, this, 0);
4174 switchedToHttps_
= true;
4176 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
4177 BIO
*b
= SSL_get_rbio(ssl
);
4178 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4182 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
4184 ConnStateData
*connState
= (ConnStateData
*) data
;
4186 // if the connection is closed or closing, just return.
4187 if (!connState
->isOpen())
4190 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
4191 assert(connState
->serverBump());
4192 Ssl::BumpMode bumpAction
;
4193 if (answer
== ACCESS_ALLOWED
) {
4194 if (answer
.kind
== Ssl::bumpNone
)
4195 bumpAction
= Ssl::bumpSplice
;
4196 else if (answer
.kind
== Ssl::bumpClientFirst
|| answer
.kind
== Ssl::bumpServerFirst
)
4197 bumpAction
= Ssl::bumpBump
;
4199 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
4201 bumpAction
= Ssl::bumpSplice
;
4203 connState
->serverBump()->act
.step2
= bumpAction
;
4204 connState
->sslBumpMode
= bumpAction
;
4206 if (bumpAction
== Ssl::bumpTerminate
) {
4207 connState
->clientConnection
->close();
4208 } else if (bumpAction
!= Ssl::bumpSplice
) {
4209 connState
->startPeekAndSpliceDone();
4211 connState
->splice();
4215 ConnStateData::splice()
4217 //Normally we can splice here, because we just got client hello message
4218 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
4219 BIO
*b
= SSL_get_rbio(ssl
);
4220 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4221 MemBuf
const &rbuf
= bio
->rBufData();
4222 debugs(83,5, "Bio for " << clientConnection
<< " read " << rbuf
.contentSize() << " helo bytes");
4224 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
4225 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
4227 if (transparent()) {
4228 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
4229 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
4230 transferProtocol
= Http::ProtocolVersion();
4231 // fake a CONNECT request to force connState to tunnel
4232 static char ip
[MAX_IPSTRLEN
];
4233 clientConnection
->local
.toUrl(ip
, sizeof(ip
));
4234 in
.buf
.assign("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n").append(rbuf
.content(), rbuf
.contentSize());
4235 bool ret
= handleReadData();
4237 ret
= clientParseRequests();
4240 debugs(33, 2, "Failed to start fake CONNECT request for ssl spliced connection: " << clientConnection
);
4241 clientConnection
->close();
4244 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
4246 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
4247 transferProtocol
= Http::ProtocolVersion();
4248 // in.buf still has the "CONNECT ..." request data, reset it to SSL hello message
4249 in
.buf
.append(rbuf
.content(), rbuf
.contentSize());
4250 ClientSocketContext::Pointer context
= getCurrentContext();
4251 ClientHttpRequest
*http
= context
->http
;
4252 tunnelStart(http
, &http
->out
.size
, &http
->al
->http
.code
, http
->al
);
4257 ConnStateData::startPeekAndSpliceDone()
4259 // This is the Step2 of the SSL bumping
4260 assert(sslServerBump
);
4261 if (sslServerBump
->step
== Ssl::bumpStep1
) {
4262 sslServerBump
->step
= Ssl::bumpStep2
;
4263 // Run a accessList check to check if want to splice or continue bumping
4265 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
4266 //acl_checklist->src_addr = params.conn->remote;
4267 //acl_checklist->my_addr = s->s;
4268 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
4272 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4276 ConnStateData::doPeekAndSpliceStep()
4278 auto ssl
= fd_table
[clientConnection
->fd
].ssl
;
4279 BIO
*b
= SSL_get_rbio(ssl
);
4281 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4283 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
4286 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
4287 switchedToHttps_
= true;
4291 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4293 Must(sslServerBump
!= NULL
);
4295 if (Comm::IsConnOpen(serverConnection
)) {
4296 pinConnection(serverConnection
, NULL
, NULL
, false);
4298 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4300 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4302 // copy error detail from bump-server-first request to CONNECT request
4303 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4304 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4307 getSslContextStart();
4310 #endif /* USE_OPENSSL */
4312 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4314 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4316 if (!Comm::IsConnOpen(c
)) {
4317 Must(NHttpSockets
> 0); // we tried to open some
4318 --NHttpSockets
; // there will be fewer sockets than planned
4319 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4321 if (!NHttpSockets
) // we could not open any listen sockets at all
4322 fatalf("Unable to open %s",FdNote(portType
));
4329 /// find any unused HttpSockets[] slot and store fd there or return false
4331 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4334 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4335 if ((found
= HttpSockets
[i
] < 0))
4336 HttpSockets
[i
] = conn
->fd
;
4342 clientHttpConnectionsOpen(void)
4344 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4345 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4346 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4347 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4352 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4353 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4354 s
->flags
.tunnelSslBumping
= false;
4357 if (s
->flags
.tunnelSslBumping
&&
4358 !s
->staticSslContext
&&
4359 !s
->generateHostCertificates
) {
4360 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4361 s
->flags
.tunnelSslBumping
= false;
4363 if (s
->flags
.tunnelSslBumping
) {
4364 // Create ssl_ctx cache for this port.
4365 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4369 // Fill out a Comm::Connection which IPC will open as a listener for us
4370 // then pass back when active so we can start a TcpAcceptor subscription.
4371 s
->listenConn
= new Comm::Connection
;
4372 s
->listenConn
->local
= s
->s
;
4373 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4375 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4376 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4377 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
4378 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4380 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4381 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4382 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4384 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4391 clientHttpsConnectionsOpen(void)
4393 for (AnyP::PortCfgPointer s
= HttpsPortList
; s
!= NULL
; s
= s
->next
) {
4394 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4395 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4396 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4400 if (!s
->staticSslContext
) {
4401 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4402 " due to SSL initialization failure.");
4406 // TODO: merge with similar code in clientHttpConnectionsOpen()
4407 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4408 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4409 s
->flags
.tunnelSslBumping
= false;
4412 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4413 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at https_port " << s
->s
<< " due to SSL initialization failure.");
4414 s
->flags
.tunnelSslBumping
= false;
4417 if (s
->flags
.tunnelSslBumping
) {
4418 // Create ssl_ctx cache for this port.
4419 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4422 // Fill out a Comm::Connection which IPC will open as a listener for us
4423 s
->listenConn
= new Comm::Connection
;
4424 s
->listenConn
->local
= s
->s
;
4425 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4426 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4428 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4429 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4430 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
4431 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4433 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4434 ListeningStartedDialer(&clientListenerConnectionOpened
,
4435 s
, Ipc::fdnHttpsSocket
, sub
));
4436 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4437 HttpSockets
[NHttpSockets
] = -1;
4444 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
4446 // Fill out a Comm::Connection which IPC will open as a listener for us
4447 port
->listenConn
= new Comm::Connection
;
4448 port
->listenConn
->local
= port
->s
;
4449 port
->listenConn
->flags
=
4451 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4452 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4454 // route new connections to subCall
4455 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4456 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4457 AsyncCall::Pointer listenCall
=
4458 asyncCall(33, 2, "clientListenerConnectionOpened",
4459 ListeningStartedDialer(&clientListenerConnectionOpened
,
4460 port
, fdNote
, sub
));
4461 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
4463 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
4464 HttpSockets
[NHttpSockets
] = -1;
4468 /// process clientHttpConnectionsOpen result
4470 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4474 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4477 Must(Comm::IsConnOpen(s
->listenConn
));
4479 // TCP: setup a job to handle accept() with subscribed handler
4480 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
4482 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4483 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4484 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4485 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4486 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4487 << FdNote(portTypeNote
) << " connections at "
4490 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4494 clientOpenListenSockets(void)
4496 clientHttpConnectionsOpen();
4498 clientHttpsConnectionsOpen();
4500 Ftp::StartListening();
4502 if (NHttpSockets
< 1)
4503 fatal("No HTTP, HTTPS, or FTP ports configured");
4507 clientConnectionsClose()
4509 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4510 if (s
->listenConn
!= NULL
) {
4511 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4512 s
->listenConn
->close();
4513 s
->listenConn
= NULL
;
4518 for (AnyP::PortCfgPointer s
= HttpsPortList
; s
!= NULL
; s
= s
->next
) {
4519 if (s
->listenConn
!= NULL
) {
4520 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4521 s
->listenConn
->close();
4522 s
->listenConn
= NULL
;
4527 Ftp::StopListening();
4529 // TODO see if we can drop HttpSockets array entirely */
4530 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4531 HttpSockets
[i
] = -1;
4538 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4540 const char *vary
= request
->vary_headers
;
4541 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4542 #if X_ACCELERATOR_VARY
4545 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4548 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4550 /* Oops... something odd is going on here.. */
4551 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4552 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4553 safe_free(request
->vary_headers
);
4558 /* This is not a varying object */
4562 /* virtual "vary" object found. Calculate the vary key and
4563 * continue the search
4565 vary
= httpMakeVaryMark(request
, entry
->getReply());
4568 request
->vary_headers
= xstrdup(vary
);
4571 /* Ouch.. we cannot handle this kind of variance */
4572 /* XXX This cannot really happen, but just to be complete */
4577 vary
= httpMakeVaryMark(request
, entry
->getReply());
4580 request
->vary_headers
= xstrdup(vary
);
4584 /* Ouch.. we cannot handle this kind of variance */
4585 /* XXX This cannot really happen, but just to be complete */
4587 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4590 /* Oops.. we have already been here and still haven't
4591 * found the requested variant. Bail out
4593 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4594 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4600 ACLFilledChecklist
*
4601 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4603 ConnStateData
* conn
= http
->getConn();
4604 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4605 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4608 * hack for ident ACL. It needs to get full addresses, and a place to store
4609 * the ident result on persistent connections...
4611 /* connection oriented auth also needs these two lines for it's operation. */
4616 ConnStateData::transparent() const
4618 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4622 ConnStateData::reading() const
4624 return reader
!= NULL
;
4628 ConnStateData::stopReading()
4631 Comm::ReadCancel(clientConnection
->fd
, reader
);
4637 ConnStateData::expectRequestBody(int64_t size
)
4639 bodyPipe
= new BodyPipe(this);
4641 bodyPipe
->setBodySize(size
);
4643 startDechunkingRequest();
4648 ConnStateData::mayNeedToReadMoreBody() const
4651 return 0; // request without a body or read/produced all body bytes
4653 if (!bodyPipe
->bodySizeKnown())
4654 return -1; // probably need to read more, but we cannot be sure
4656 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4657 const int64_t haveAvailable
= static_cast<int64_t>(in
.buf
.length());
4659 if (needToProduce
<= haveAvailable
)
4660 return 0; // we have read what we need (but are waiting for pipe space)
4662 return needToProduce
- haveAvailable
;
4666 ConnStateData::stopReceiving(const char *error
)
4668 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4669 "; old sending error: " <<
4670 (stoppedSending() ? stoppedSending_
: "none"));
4672 if (const char *oldError
= stoppedReceiving()) {
4673 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4674 return; // nothing has changed as far as this connection is concerned
4677 stoppedReceiving_
= error
;
4679 if (const char *sendError
= stoppedSending()) {
4680 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4681 clientConnection
->close();
4686 ConnStateData::expectNoForwarding()
4688 if (bodyPipe
!= NULL
) {
4689 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4690 bodyPipe
->expectNoConsumption();
4694 /// initialize dechunking state
4696 ConnStateData::startDechunkingRequest()
4698 Must(bodyPipe
!= NULL
);
4699 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4700 assert(!in
.bodyParser
);
4701 in
.bodyParser
= new Http1::TeChunkedParser
;
4704 /// put parsed content into input buffer and clean up
4706 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4708 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4710 if (bodyPipe
!= NULL
) {
4711 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4712 BodyPipe::Pointer myPipe
= bodyPipe
;
4713 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4714 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4716 Must(myPipe
->bodySizeKnown());
4717 ClientSocketContext::Pointer context
= getCurrentContext();
4718 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4719 context
->http
->request
->setContentLength(myPipe
->bodySize());
4723 delete in
.bodyParser
;
4724 in
.bodyParser
= NULL
;
4727 ConnStateData::In::In() :
4732 ConnStateData::In::~In()
4734 delete bodyParser
; // TODO: pool
4738 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4741 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4745 ClientSocketContext::Pointer context
= getCurrentContext();
4746 if (context
!= NULL
) {
4747 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4751 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4752 clientConnection
->close();
4755 /// Our close handler called by Comm when the pinned connection is closed
4757 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4759 // FwdState might repin a failed connection sooner than this close
4760 // callback is called for the failed connection.
4761 assert(pinning
.serverConnection
== io
.conn
);
4762 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4763 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4764 pinning
.serverConnection
->noteClosure();
4765 unpinConnection(false);
4767 if (sawZeroReply
&& clientConnection
!= NULL
) {
4768 debugs(33, 3, "Closing client connection on pinned zero reply.");
4769 clientConnection
->close();
4775 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
4777 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
4778 pinning
.serverConnection
->fd
!= pinServer
->fd
)
4779 pinNewConnection(pinServer
, request
, aPeer
, auth
);
4782 startPinnedConnectionMonitoring();
4786 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4788 unpinConnection(true); // closes pinned connection, if any, and resets fields
4790 pinning
.serverConnection
= pinServer
;
4792 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4794 Must(pinning
.serverConnection
!= NULL
);
4796 // when pinning an SSL bumped connection, the request may be NULL
4797 const char *pinnedHost
= "[unknown]";
4799 pinning
.host
= xstrdup(request
->url
.host());
4800 pinning
.port
= request
->url
.port();
4801 pinnedHost
= pinning
.host
;
4803 pinning
.port
= pinServer
->remote
.port();
4805 pinning
.pinned
= true;
4807 pinning
.peer
= cbdataReference(aPeer
);
4808 pinning
.auth
= auth
;
4809 char stmp
[MAX_IPSTRLEN
];
4810 char desc
[FD_DESC_SZ
];
4811 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4812 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4813 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4814 clientConnection
->fd
);
4815 fd_note(pinning
.serverConnection
->fd
, desc
);
4817 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4818 pinning
.closeHandler
= JobCallback(33, 5,
4819 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4820 // remember the pinned connection so that cb does not unpin a fresher one
4821 typedef CommCloseCbParams Params
;
4822 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4823 params
.conn
= pinning
.serverConnection
;
4824 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4827 /// [re]start monitoring pinned connection for peer closures so that we can
4828 /// propagate them to an _idle_ client pinned to that peer
4830 ConnStateData::startPinnedConnectionMonitoring()
4832 if (pinning
.readHandler
!= NULL
)
4833 return; // already monitoring
4835 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4836 pinning
.readHandler
= JobCallback(33, 3,
4837 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4838 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
4842 ConnStateData::stopPinnedConnectionMonitoring()
4844 if (pinning
.readHandler
!= NULL
) {
4845 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4846 pinning
.readHandler
= NULL
;
4850 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4851 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4853 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4855 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4857 if (io
.flag
== Comm::ERR_CLOSING
)
4858 return; // close handler will clean up
4860 // We could use getConcurrentRequestCount(), but this may be faster.
4861 const bool clientIsIdle
= !getCurrentContext();
4863 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4864 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4866 assert(pinning
.serverConnection
== io
.conn
);
4867 pinning
.serverConnection
->close();
4869 // If we are still sending data to the client, do not close now. When we are done sending,
4870 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4871 // However, if we are idle, then we must close to inform the idle client and minimize races.
4872 if (clientIsIdle
&& clientConnection
!= NULL
)
4873 clientConnection
->close();
4876 const Comm::ConnectionPointer
4877 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4879 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4882 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4884 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->url
.host()) != 0)
4886 else if (request
&& pinning
.port
!= request
->url
.port())
4888 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4890 else if (aPeer
!= pinning
.peer
)
4894 /* The pinning info is not safe, remove any pinning info */
4895 unpinConnection(true);
4898 return pinning
.serverConnection
;
4901 Comm::ConnectionPointer
4902 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4904 debugs(33, 7, pinning
.serverConnection
);
4905 if (validatePinnedConnection(request
, aPeer
) != NULL
)
4906 stopPinnedConnectionMonitoring();
4908 return pinning
.serverConnection
; // closed if validation failed
4912 ConnStateData::unpinConnection(const bool andClose
)
4914 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4917 cbdataReferenceDone(pinning
.peer
);
4919 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4920 if (pinning
.closeHandler
!= NULL
) {
4921 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4922 pinning
.closeHandler
= NULL
;
4925 stopPinnedConnectionMonitoring();
4927 // close the server side socket if requested
4929 pinning
.serverConnection
->close();
4930 pinning
.serverConnection
= NULL
;
4933 safe_free(pinning
.host
);
4935 pinning
.zeroReply
= false;
4937 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4938 * connection has gone away */