2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 33 Client-side Routines */
12 \defgroup ClientSide Client-Side Logics
14 \section cserrors Errors and client side
16 \par Problem the first:
17 * the store entry is no longer authoritative on the
18 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
19 * of client_side_reply.c.
20 * Problem the second: resources are wasted if we delay in cleaning up.
21 * Problem the third we can't depend on a connection close to clean up.
23 \par Nice thing the first:
24 * Any step in the stream can callback with data
25 * representing an error.
26 * Nice thing the second: once you stop requesting reads from upstream,
27 * upstream can be stopped too.
30 * Error has a callback mechanism to hand over a membuf
31 * with the error content. The failing node pushes that back as the
32 * reply. Can this be generalised to reduce duplicate efforts?
33 * A: Possibly. For now, only one location uses this.
34 * How to deal with pre-stream errors?
35 * Tell client_side_reply that we *want* an error page before any
36 * stream calls occur. Then we simply read as normal.
39 \section pconn_logic Persistent connection logic:
42 * requests (httpClientRequest structs) get added to the connection
43 * list, with the current one being chr
46 * The request is *immediately* kicked off, and data flows through
47 * to clientSocketRecipient.
50 * If the data that arrives at clientSocketRecipient is not for the current
51 * request, clientSocketRecipient simply returns, without requesting more
52 * data, or sending it.
55 * ClientKeepAliveNextRequest will then detect the presence of data in
56 * the next ClientHttpRequest, and will send it, restablishing the
61 #include "acl/FilledChecklist.h"
62 #include "anyp/PortCfg.h"
63 #include "base/Subscription.h"
64 #include "base/TextException.h"
65 #include "CachePeer.h"
66 #include "ChunkedCodingParser.h"
67 #include "client_db.h"
68 #include "client_side.h"
69 #include "client_side_reply.h"
70 #include "client_side_request.h"
71 #include "ClientRequestContext.h"
72 #include "clientStream.h"
74 #include "comm/Connection.h"
75 #include "comm/Loops.h"
76 #include "comm/Read.h"
77 #include "comm/TcpAcceptor.h"
78 #include "comm/Write.h"
79 #include "CommCalls.h"
80 #include "errorpage.h"
83 #include "fqdncache.h"
87 #include "helper/Reply.h"
89 #include "http/one/RequestParser.h"
90 #include "HttpHdrContRange.h"
91 #include "HttpHeaderTools.h"
92 #include "HttpReply.h"
93 #include "HttpRequest.h"
94 #include "ident/Config.h"
95 #include "ident/Ident.h"
97 #include "ipc/FdNotes.h"
98 #include "ipc/StartListening.h"
99 #include "log/access_log.h"
101 #include "MemObject.h"
102 #include "mime_header.h"
103 #include "parser/Tokenizer.h"
104 #include "profiler/Profiler.h"
106 #include "servers/forward.h"
107 #include "SquidConfig.h"
108 #include "SquidTime.h"
109 #include "StatCounters.h"
110 #include "StatHist.h"
112 #include "TimeOrTag.h"
117 #include "auth/UserRequest.h"
120 #include "ClientInfo.h"
124 #include "ssl/context_storage.h"
125 #include "ssl/gadgets.h"
126 #include "ssl/helper.h"
127 #include "ssl/ProxyCerts.h"
128 #include "ssl/ServerBump.h"
129 #include "ssl/support.h"
132 #include "ssl/certificate_db.h"
133 #include "ssl/crtd_message.h"
136 // for tvSubUsec() which should be in SquidTime.h
144 #define comm_close comm_lingering_close
147 /// dials clientListenerConnectionOpened call
148 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
151 typedef void (*Handler
)(AnyP::PortCfgPointer
&portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
152 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfgPointer
&aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
153 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
155 virtual void print(std::ostream
&os
) const {
157 ", " << FdNote(portTypeNote
) << " port=" << (void*)&portCfg
<< ')';
160 virtual bool canDial(AsyncCall
&) const { return true; }
161 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
167 AnyP::PortCfgPointer portCfg
; ///< from HttpPortList
168 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
169 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
172 static void clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
174 /* our socket-related context */
176 CBDATA_CLASS_INIT(ClientSocketContext
);
178 /* Local functions */
179 static IOCB clientWriteComplete
;
180 static IOCB clientWriteBodyComplete
;
181 static IOACB httpAccept
;
183 static IOACB httpsAccept
;
185 static CTCB clientLifetimeTimeout
;
187 static IDCB clientIdentDone
;
189 static int clientIsContentLengthValid(HttpRequest
* r
);
190 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
192 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
193 static void clientUpdateStatCounters(LogTags logType
);
194 static void clientUpdateHierCounters(HierarchyLogEntry
*);
195 static bool clientPingHasFinished(ping_data
const *aPing
);
196 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
198 static bool connIsUsable(ConnStateData
* conn
);
200 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
201 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
203 char *skipLeadingSpace(char *aString
);
206 ClientSocketContext::getTail() const
208 if (http
->client_stream
.tail
)
209 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
215 ClientSocketContext::getClientReplyContext() const
217 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
221 ClientSocketContext::getConn() const
223 return http
->getConn();
227 * This routine should be called to grow the in.buf and then
231 ConnStateData::readSomeData()
236 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
238 // we can only read if there is more than 1 byte of space free
239 if (Config
.maxRequestBufferSize
- in
.buf
.length() < 2)
242 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
243 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
244 Comm::Read(clientConnection
, reader
);
248 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
250 ClientSocketContext::Pointer
*tempContextPointer
;
251 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
252 assert(conn
->getCurrentContext() != NULL
);
253 /* Unlink us from the connection request list */
254 tempContextPointer
= & conn
->currentobject
;
256 while (tempContextPointer
->getRaw()) {
257 if (*tempContextPointer
== this)
260 tempContextPointer
= &(*tempContextPointer
)->next
;
263 assert(tempContextPointer
->getRaw() != NULL
);
264 *tempContextPointer
= next
;
268 ClientSocketContext::~ClientSocketContext()
270 clientStreamNode
*node
= getTail();
273 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
276 /* We are *always* the tail - prevent recursive free */
277 assert(this == streamContext
);
283 deRegisterWithConn();
285 httpRequestFree(http
);
287 /* clean up connection links to us */
288 assert(this != next
.getRaw());
292 ClientSocketContext::registerWithConn()
294 assert (!connRegistered_
);
296 assert (http
->getConn() != NULL
);
297 connRegistered_
= true;
298 http
->getConn()->addContextToQueue(this);
302 ClientSocketContext::deRegisterWithConn()
304 assert (connRegistered_
);
305 removeFromConnectionList(http
->getConn());
306 connRegistered_
= false;
310 ClientSocketContext::connIsFinished()
313 assert (http
->getConn() != NULL
);
314 deRegisterWithConn();
315 /* we can't handle any more stream data - detach */
316 clientStreamDetach(getTail(), http
);
319 ClientSocketContext::ClientSocketContext(const Comm::ConnectionPointer
&aConn
, ClientHttpRequest
*aReq
) :
320 clientConnection(aConn
),
325 mayUseConnection_ (false),
326 connRegistered_ (false)
328 assert(http
!= NULL
);
329 memset (reqbuf
, '\0', sizeof (reqbuf
));
332 deferredparams
.node
= NULL
;
333 deferredparams
.rep
= NULL
;
337 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
339 HttpReply::Pointer
rep(msg
.reply
);
342 // remember the callback
343 cbControlMsgSent
= msg
.cbSuccess
;
345 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
346 CommIoCbPtrFun(&WroteControlMsg
, this));
348 getConn()->writeControlMsgAndCall(this, rep
.getRaw(), call
);
351 /// called when we wrote the 1xx response
353 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, Comm::Flag errflag
, int xerrno
)
355 if (errflag
== Comm::ERR_CLOSING
)
358 if (errflag
== Comm::OK
) {
359 ScheduleCallHere(cbControlMsgSent
);
363 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
364 // no error notification: see HttpControlMsg.h for rationale and
365 // note that some errors are detected elsewhere (e.g., close handler)
367 // close on 1xx errors to be conservative and to simplify the code
368 // (if we do not close, we must notify the source of a failure!)
371 // XXX: writeControlMsgAndCall() should handle writer-specific writing
372 // results, including errors and then call us with success/failure outcome.
375 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
377 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, Comm::Flag errflag
, int xerrno
, void *data
)
379 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
380 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
385 clientIdentDone(const char *ident
, void *data
)
387 ConnStateData
*conn
= (ConnStateData
*)data
;
388 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
393 clientUpdateStatCounters(LogTags logType
)
395 ++statCounter
.client_http
.requests
;
397 if (logTypeIsATcpHit(logType
))
398 ++statCounter
.client_http
.hits
;
400 if (logType
== LOG_TCP_HIT
)
401 ++statCounter
.client_http
.disk_hits
;
402 else if (logType
== LOG_TCP_MEM_HIT
)
403 ++statCounter
.client_http
.mem_hits
;
407 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
409 statCounter
.client_http
.allSvcTime
.count(svc_time
);
411 * The idea here is not to be complete, but to get service times
412 * for only well-defined types. For example, we don't include
413 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
414 * (we *tried* to validate it, but failed).
419 case LOG_TCP_REFRESH_UNMODIFIED
:
420 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
423 case LOG_TCP_IMS_HIT
:
424 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
429 case LOG_TCP_MEM_HIT
:
431 case LOG_TCP_OFFLINE_HIT
:
432 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
437 case LOG_TCP_CLIENT_REFRESH_MISS
:
438 statCounter
.client_http
.missSvcTime
.count(svc_time
);
442 /* make compiler warnings go away */
448 clientPingHasFinished(ping_data
const *aPing
)
450 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
457 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
461 switch (someEntry
->code
) {
462 #if USE_CACHE_DIGESTS
467 ++ statCounter
.cd
.times_used
;
475 case FIRST_PARENT_MISS
:
477 case CLOSEST_PARENT_MISS
:
478 ++ statCounter
.icp
.times_used
;
479 i
= &someEntry
->ping
;
481 if (clientPingHasFinished(i
))
482 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
485 ++ statCounter
.icp
.query_timeouts
;
492 ++ statCounter
.netdb
.times_used
;
502 ClientHttpRequest::updateCounters()
504 clientUpdateStatCounters(logType
);
506 if (request
->errType
!= ERR_NONE
)
507 ++ statCounter
.client_http
.errors
;
509 clientUpdateStatHistCounters(logType
,
510 tvSubMsec(al
->cache
.start_time
, current_time
));
512 clientUpdateHierCounters(&request
->hier
);
516 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
519 assert(aLogEntry
!= NULL
);
521 if (Config
.onoff
.log_mime_hdrs
) {
524 request
->header
.packInto(&mb
);
525 //This is the request after adaptation or redirection
526 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
528 // the virgin request is saved to aLogEntry->request
529 if (aLogEntry
->request
) {
531 aLogEntry
->request
->header
.packInto(&mb
);
532 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
536 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
539 ah
->lastMeta
.packInto(&mb
);
540 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
548 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
550 ih
->processingTime(aLogEntry
->icap
.processingTime
);
553 aLogEntry
->http
.method
= request
->method
;
554 aLogEntry
->http
.version
= request
->http_ver
;
555 aLogEntry
->hier
= request
->hier
;
556 if (request
->content_length
> 0) // negative when no body or unknown length
557 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
558 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
560 // Adapted request, if any, inherits and then collects all the stats, but
561 // the virgin request gets logged instead; copy the stats to log them.
562 // TODO: avoid losses by keeping these stats in a shared history object?
563 if (aLogEntry
->request
) {
564 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
565 aLogEntry
->request
->errType
= request
->errType
;
566 aLogEntry
->request
->errDetail
= request
->errDetail
;
571 ClientHttpRequest::logRequest()
573 if (!out
.size
&& !logType
)
574 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
576 al
->icp
.opcode
= ICP_INVALID
;
578 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
581 al
->http
.code
= al
->reply
->sline
.status();
582 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
583 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
584 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
585 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
588 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
590 if (loggingEntry() && loggingEntry()->mem_obj
&& loggingEntry()->objectLen() >= 0)
591 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
593 al
->http
.clientRequestSz
.header
= req_sz
;
594 al
->http
.clientReplySz
.header
= out
.headers_sz
;
595 // XXX: calculate without payload encoding or headers !!
596 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
598 al
->cache
.highOffset
= out
.offset
;
600 al
->cache
.code
= logType
;
602 tvSub(al
->cache
.trTime
, al
->cache
.start_time
, current_time
);
605 prepareLogWithRequestDetails(request
, al
);
607 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
608 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
612 /* This is broken. Fails if the connection has been closed. Needs
613 * to snarf the ssl details some place earlier..
615 if (getConn() != NULL
)
616 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
620 /* Add notes (if we have a request to annotate) */
622 // The al->notes and request->notes must point to the same object.
623 (void)SyncNotes(*al
, *request
);
624 for (auto i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
625 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
626 NotePairs
¬es
= SyncNotes(*al
, *request
);
627 notes
.add((*i
)->key
.termedBuf(), value
);
628 debugs(33, 3, (*i
)->key
.termedBuf() << " " << value
);
633 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
635 checklist
.reply
= al
->reply
;
636 HTTPMSGLOCK(checklist
.reply
);
640 al
->adapted_request
= request
;
641 HTTPMSGLOCK(al
->adapted_request
);
643 accessLogLog(al
, &checklist
);
645 bool updatePerformanceCounters
= true;
646 if (Config
.accessList
.stats_collection
) {
647 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
649 statsCheck
.reply
= al
->reply
;
650 HTTPMSGLOCK(statsCheck
.reply
);
652 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
655 if (updatePerformanceCounters
) {
659 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
660 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
665 ClientHttpRequest::freeResources()
669 safe_free(redirect
.location
);
670 range_iter
.boundary
.clean();
671 HTTPMSGUNLOCK(request
);
673 if (client_stream
.tail
)
674 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
678 httpRequestFree(void *data
)
680 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
681 assert(http
!= NULL
);
686 ConnStateData::areAllContextsForThisConnection() const
688 ClientSocketContext::Pointer context
= getCurrentContext();
690 while (context
.getRaw()) {
691 if (context
->http
->getConn() != this)
694 context
= context
->next
;
701 ConnStateData::freeAllContexts()
703 ClientSocketContext::Pointer context
;
705 while ((context
= getCurrentContext()).getRaw() != NULL
) {
706 assert(getCurrentContext() !=
707 getCurrentContext()->next
);
708 context
->connIsFinished();
709 assert (context
!= currentobject
);
713 /// propagates abort event to all contexts
715 ConnStateData::notifyAllContexts(int xerrno
)
717 typedef ClientSocketContext::Pointer CSCP
;
718 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
719 c
->noteIoError(xerrno
);
722 /* This is a handler normally called by comm_close() */
723 void ConnStateData::connStateClosed(const CommCloseCbParams
&)
725 deleteThis("ConnStateData::connStateClosed");
730 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
734 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
740 // clobered with self-pointer
741 // NP: something nasty is going on in Squid, but harmless.
743 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
748 * Connection-auth relies on a single set of credentials being preserved
749 * for all requests on a connection once they have been setup.
750 * There are several things which need to happen to preserve security
751 * when connection-auth credentials change unexpectedly or are unset.
753 * 1) auth helper released from any active state
755 * They can only be reserved by a handshake process which this
756 * connection can now never complete.
757 * This prevents helpers hanging when their connections close.
759 * 2) pinning is expected to be removed and server conn closed
761 * The upstream link is authenticated with the same credentials.
762 * Expecting the same level of consistency we should have received.
763 * This prevents upstream being faced with multiple or missing
764 * credentials after authentication.
765 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
766 * we just trigger that cleanup here via comm_reset_close() or
767 * ConnStateData::stopReceiving()
769 * 3) the connection needs to close.
771 * This prevents attackers injecting requests into a connection,
772 * or gateways wrongly multiplexing users into a single connection.
774 * When credentials are missing closure needs to follow an auth
775 * challenge for best recovery by the client.
777 * When credentials change there is nothing we can do but abort as
778 * fast as possible. Sending TCP RST instead of an HTTP response
779 * is the best-case action.
782 // clobbered with nul-pointer
784 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
785 auth_
->releaseAuthServer();
787 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
788 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
789 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
790 stopReceiving("connection-auth removed");
794 // clobbered with alternative credentials
796 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
797 auth_
->releaseAuthServer();
799 // this is a fatal type of problem.
800 // Close the connection immediately with TCP RST to abort all traffic flow
801 comm_reset_close(clientConnection
);
809 // cleans up before destructor is called
811 ConnStateData::swanSong()
813 debugs(33, 2, HERE
<< clientConnection
);
814 flags
.readMore
= false;
815 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
816 assert(areAllContextsForThisConnection());
819 unpinConnection(true);
821 if (Comm::IsConnOpen(clientConnection
))
822 clientConnection
->close();
825 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
826 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
829 BodyProducer::swanSong();
830 flags
.swanSang
= true;
834 ConnStateData::isOpen() const
836 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
837 Comm::IsConnOpen(clientConnection
) &&
838 !fd_table
[clientConnection
->fd
].closing();
841 ConnStateData::~ConnStateData()
843 debugs(33, 3, HERE
<< clientConnection
);
846 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
849 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
851 if (bodyPipe
!= NULL
)
852 stopProducingFor(bodyPipe
, false);
855 delete sslServerBump
;
860 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
861 * This is the client-side persistent connection flag. We need
862 * to set this relatively early in the request processing
863 * to handle hacks for broken servers and clients.
866 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
868 HttpRequest
*request
= http
->request
;
870 debugs(33, 3, "http_ver = " << request
->http_ver
);
871 debugs(33, 3, "method = " << request
->method
);
873 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
874 request
->flags
.proxyKeepalive
= request
->persistent();
878 clientIsContentLengthValid(HttpRequest
* r
)
880 switch (r
->method
.id()) {
882 case Http::METHOD_GET
:
884 case Http::METHOD_HEAD
:
885 /* We do not want to see a request entity on GET/HEAD requests */
886 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
889 /* For other types of requests we don't care */
897 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
899 if (Config
.maxRequestBodySize
&&
900 bodyLength
> Config
.maxRequestBodySize
)
901 return 1; /* too large */
908 connIsUsable(ConnStateData
* conn
)
910 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
918 // careful: the "current" context may be gone if we wrote an early response
919 ClientSocketContext::Pointer
920 ConnStateData::getCurrentContext() const
922 return currentobject
;
926 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
928 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
929 assert(flags
.deferred
== 0);
931 deferredparams
.node
= node
;
932 deferredparams
.rep
= rep
;
933 deferredparams
.queuedBuffer
= receivedData
;
938 ClientSocketContext::startOfOutput() const
940 return http
->out
.size
== 0;
944 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
946 /*the size of available range can always fit in a size_t type*/
947 size_t maximum
= (size_t)available
.size();
949 if (!http
->request
->range
)
952 assert (canPackMoreRanges());
954 if (http
->range_iter
.debt() == -1)
957 assert (http
->range_iter
.debt() > 0);
959 /* TODO this + the last line could be a range intersection calculation */
960 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
963 return min(http
->range_iter
.debt(), (int64_t)maximum
);
967 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
969 http
->out
.offset
+= bytes
;
971 if (!http
->request
->range
)
974 if (http
->range_iter
.debt() != -1) {
975 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
976 assert (http
->range_iter
.debt() >= 0);
979 /* debt() always stops at -1, below that is a bug */
980 assert (http
->range_iter
.debt() >= -1);
984 ClientHttpRequest::multipartRangeRequest() const
986 return request
->multipartRangeRequest();
990 ClientSocketContext::multipartRangeRequest() const
992 return http
->multipartRangeRequest();
996 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1000 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1001 size_t length
= lengthToSend(bodyData
.range());
1002 noteSentBodyBytes (length
);
1003 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1004 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1005 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1011 if (multipartRangeRequest())
1012 packRange(bodyData
, &mb
);
1014 packChunk(bodyData
, mb
);
1016 if (mb
.contentSize()) {
1018 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1019 CommIoCbPtrFun(clientWriteComplete
, this));
1020 Comm::Write(clientConnection
, &mb
, call
);
1022 writeComplete(clientConnection
, NULL
, 0, Comm::OK
);
1026 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1027 * if bodyData is empty.
1030 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1032 const uint64_t length
=
1033 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1034 noteSentBodyBytes(length
);
1036 mb
.appendf("%" PRIX64
"\r\n", length
);
1037 mb
.append(bodyData
.data
, length
);
1038 mb
.append("\r\n", 2);
1041 /** put terminating boundary for multiparts */
1043 clientPackTermBound(String boundary
, MemBuf
* mb
)
1045 mb
->appendf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1046 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1049 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1051 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1053 HttpHeader
hdr(hoReply
);
1058 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1059 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1060 mb
->appendf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1062 /* stuff the header with required entries and pack it */
1064 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1065 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1067 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1072 /* append <crlf> (we packed a header, not a reply) */
1073 mb
->append("\r\n", 2);
1077 * extracts a "range" from *buf and appends them to mb, updating
1078 * all offsets and such.
1081 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1083 HttpHdrRangeIter
* i
= &http
->range_iter
;
1084 Range
<int64_t> available (source
.range());
1085 char const *buf
= source
.data
;
1087 while (i
->currentSpec() && available
.size()) {
1088 const size_t copy_sz
= lengthToSend(available
);
1092 * intersection of "have" and "need" ranges must not be empty
1094 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1095 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1098 * put boundary and headers at the beginning of a range in a
1102 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1103 assert(http
->memObject());
1105 http
->memObject()->getReply(), /* original reply */
1106 i
->currentSpec(), /* current range */
1107 i
->boundary
, /* boundary, the same for all */
1114 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1116 noteSentBodyBytes (copy_sz
);
1118 mb
->append(buf
, copy_sz
);
1123 available
.start
+= copy_sz
;
1129 if (!canPackMoreRanges()) {
1130 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1133 /* put terminating boundary for multiparts */
1134 clientPackTermBound(i
->boundary
, mb
);
1139 int64_t nextOffset
= getNextRangeOffset();
1141 assert (nextOffset
>= http
->out
.offset
);
1143 int64_t skip
= nextOffset
- http
->out
.offset
;
1145 /* adjust for not to be transmitted bytes */
1146 http
->out
.offset
= nextOffset
;
1148 if (available
.size() <= (uint64_t)skip
)
1151 available
.start
+= skip
;
1160 /** returns expected content length for multi-range replies
1161 * note: assumes that httpHdrRangeCanonize has already been called
1162 * warning: assumes that HTTP headers for individual ranges at the
1163 * time of the actuall assembly will be exactly the same as
1164 * the headers when clientMRangeCLen() is called */
1166 ClientHttpRequest::mRangeCLen()
1171 assert(memObject());
1174 HttpHdrRange::iterator pos
= request
->range
->begin();
1176 while (pos
!= request
->range
->end()) {
1177 /* account for headers for this range */
1179 clientPackRangeHdr(memObject()->getReply(),
1180 *pos
, range_iter
.boundary
, &mb
);
1183 /* account for range content */
1184 clen
+= (*pos
)->length
;
1186 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1190 /* account for the terminating boundary */
1193 clientPackTermBound(range_iter
.boundary
, &mb
);
1203 * returns true if If-Range specs match reply, false otherwise
1206 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1208 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1209 /* check for parsing falure */
1216 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1217 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1218 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1221 return 0; /* entity has no etag to compare with! */
1223 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1224 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1225 return 0; /* must use strong validator for sub-range requests */
1228 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1231 /* got modification time? */
1232 if (spec
.time
>= 0) {
1233 return http
->storeEntry()->lastmod
<= spec
.time
;
1236 assert(0); /* should not happen */
1241 * generates a "unique" boundary string for multipart responses
1242 * the caller is responsible for cleaning the string */
1244 ClientHttpRequest::rangeBoundaryStr() const
1247 String
b(APP_FULLNAME
);
1249 key
= storeEntry()->getMD5Text();
1250 b
.append(key
, strlen(key
));
1254 /** adds appropriate Range headers if needed */
1256 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1258 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1259 const char *range_err
= NULL
;
1260 HttpRequest
*request
= http
->request
;
1261 assert(request
->range
);
1262 /* check if we still want to do ranges */
1264 int64_t roffLimit
= request
->getRangeOffsetLimit();
1267 range_err
= "no [parse-able] reply";
1268 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1269 range_err
= "wrong status code";
1270 else if (hdr
->has(HDR_CONTENT_RANGE
))
1271 range_err
= "origin server does ranges";
1272 else if (rep
->content_length
< 0)
1273 range_err
= "unknown length";
1274 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1275 range_err
= "INCONSISTENT length"; /* a bug? */
1277 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1280 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1281 range_err
= "If-Range match failed";
1282 else if (!http
->request
->range
->canonize(rep
))
1283 range_err
= "canonization failed";
1284 else if (http
->request
->range
->isComplex())
1285 range_err
= "too complex range header";
1286 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1287 range_err
= "range outside range_offset_limit";
1289 /* get rid of our range specs on error */
1291 /* XXX We do this here because we need canonisation etc. However, this current
1292 * code will lead to incorrect store offset requests - the store will have the
1293 * offset data, but we won't be requesting it.
1294 * So, we can either re-request, or generate an error
1296 http
->request
->ignoreRange(range_err
);
1298 /* XXX: TODO: Review, this unconditional set may be wrong. */
1299 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1300 // web server responded with a valid, but unexpected range.
1301 // will (try-to) forward as-is.
1302 //TODO: we should cope with multirange request/responses
1303 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1304 request
->range
->contains(rep
->content_range
->spec
) :
1306 const int spec_count
= http
->request
->range
->specs
.size();
1307 int64_t actual_clen
= -1;
1309 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1310 spec_count
<< " virgin clen: " << rep
->content_length
);
1311 assert(spec_count
> 0);
1312 /* append appropriate header(s) */
1314 if (spec_count
== 1) {
1315 if (!replyMatchRequest
) {
1316 hdr
->delById(HDR_CONTENT_RANGE
);
1317 hdr
->putContRange(rep
->content_range
);
1318 actual_clen
= rep
->content_length
;
1319 //http->range_iter.pos = rep->content_range->spec.begin();
1320 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1321 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1324 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1326 /* append Content-Range */
1328 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1329 /* No content range, so this was a full object we are
1332 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1335 /* set new Content-Length to the actual number of bytes
1336 * transmitted in the message-body */
1337 actual_clen
= (*pos
)->length
;
1341 /* generate boundary string */
1342 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1343 /* delete old Content-Type, add ours */
1344 hdr
->delById(HDR_CONTENT_TYPE
);
1345 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1346 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1347 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1348 /* Content-Length is not required in multipart responses
1349 * but it is always nice to have one */
1350 actual_clen
= http
->mRangeCLen();
1351 /* http->out needs to start where we want data at */
1352 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1355 /* replace Content-Length header */
1356 assert(actual_clen
>= 0);
1358 hdr
->delById(HDR_CONTENT_LENGTH
);
1360 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1362 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1364 /* And start the range iter off */
1365 http
->range_iter
.updateSpec();
1370 ClientSocketContext::prepareReply(HttpReply
* rep
)
1374 if (http
->request
->range
)
1375 buildRangeHeader(rep
);
1379 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1383 MemBuf
*mb
= rep
->pack();
1385 // dump now, so we dont output any body.
1386 debugs(11, 2, "HTTP Client " << clientConnection
);
1387 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1389 /* Save length of headers for persistent conn checks */
1390 http
->out
.headers_sz
= mb
->contentSize();
1393 headersLog(0, 0, http
->request
->method
, rep
);
1396 if (bodyData
.data
&& bodyData
.length
) {
1397 if (multipartRangeRequest())
1398 packRange(bodyData
, mb
);
1399 else if (http
->request
->flags
.chunkedReply
) {
1400 packChunk(bodyData
, *mb
);
1402 size_t length
= lengthToSend(bodyData
.range());
1403 noteSentBodyBytes (length
);
1405 mb
->append(bodyData
.data
, length
);
1410 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1411 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1412 CommIoCbPtrFun(clientWriteComplete
, this));
1413 Comm::Write(clientConnection
, mb
, call
);
1418 * Write a chunk of data to a client socket. If the reply is present,
1419 * send the reply headers down the wire too, and clean them up when
1422 * The request is one backed by a connection, not an internal request.
1423 * data context is not NULL
1424 * There are no more entries in the stream chain.
1427 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1428 HttpReply
* rep
, StoreIOBuffer receivedData
)
1430 /* Test preconditions */
1431 assert(node
!= NULL
);
1432 PROF_start(clientSocketRecipient
);
1433 /* TODO: handle this rather than asserting
1434 * - it should only ever happen if we cause an abort and
1435 * the callback chain loops back to here, so we can simply return.
1436 * However, that itself shouldn't happen, so it stays as an assert for now.
1438 assert(cbdataReferenceValid(node
));
1439 assert(node
->node
.next
== NULL
);
1440 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1441 assert(context
!= NULL
);
1442 assert(connIsUsable(http
->getConn()));
1444 /* TODO: check offset is what we asked for */
1446 if (context
!= http
->getConn()->getCurrentContext())
1447 context
->deferRecipientForLater(node
, rep
, receivedData
);
1449 http
->getConn()->handleReply(rep
, receivedData
);
1451 PROF_stop(clientSocketRecipient
);
1455 * Called when a downstream node is no longer interested in
1456 * our data. As we are a terminal node, this means on aborts
1460 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1462 /* Test preconditions */
1463 assert(node
!= NULL
);
1464 /* TODO: handle this rather than asserting
1465 * - it should only ever happen if we cause an abort and
1466 * the callback chain loops back to here, so we can simply return.
1467 * However, that itself shouldn't happen, so it stays as an assert for now.
1469 assert(cbdataReferenceValid(node
));
1470 /* Set null by ContextFree */
1471 assert(node
->node
.next
== NULL
);
1472 /* this is the assert discussed above */
1473 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1474 /* We are only called when the client socket shutsdown.
1475 * Tell the prev pipeline member we're finished
1477 clientStreamDetach(node
, http
);
1481 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int xerrno
, void *data
)
1483 debugs(33,7, "schedule clientWriteComplete");
1484 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1488 ConnStateData::readNextRequest()
1490 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1492 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1494 * Set the timeout BEFORE calling readSomeData().
1496 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1497 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1498 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1499 commSetConnTimeout(clientConnection
, clientConnection
->timeLeft(idleTimeout()), timeoutCall
);
1502 /** Please don't do anything with the FD past here! */
1506 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1508 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1510 /** If the client stream is waiting on a socket write to occur, then */
1512 if (deferredRequest
->flags
.deferred
) {
1513 /** NO data is allowed to have been sent. */
1514 assert(deferredRequest
->http
->out
.size
== 0);
1516 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1517 deferredRequest
->http
,
1518 deferredRequest
->deferredparams
.rep
,
1519 deferredRequest
->deferredparams
.queuedBuffer
);
1522 /** otherwise, the request is still active in a callbacksomewhere,
1527 /// called when we have successfully finished writing the response
1529 ClientSocketContext::keepaliveNextRequest()
1531 ConnStateData
* conn
= http
->getConn();
1533 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1536 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1537 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1538 conn
->clientConnection
->close();
1543 * We are done with the response, and we are either still receiving request
1544 * body (early response!) or have already stopped receiving anything.
1546 * If we are still receiving, then clientParseRequest() below will fail.
1547 * (XXX: but then we will call readNextRequest() which may succeed and
1548 * execute a smuggled request as we are not done with the current request).
1550 * If we stopped because we got everything, then try the next request.
1552 * If we stopped receiving because of an error, then close now to avoid
1553 * getting stuck and to prevent accidental request smuggling.
1556 if (const char *reason
= conn
->stoppedReceiving()) {
1557 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1558 conn
->clientConnection
->close();
1563 * Attempt to parse a request from the request buffer.
1564 * If we've been fed a pipelined request it may already
1565 * be in our read buffer.
1568 * This needs to fall through - if we're unlucky and parse the _last_ request
1569 * from our read buffer we may never re-register for another client read.
1572 if (conn
->clientParseRequests()) {
1573 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1577 * Either we need to kick-start another read or, if we have
1578 * a half-closed connection, kill it after the last request.
1579 * This saves waiting for half-closed connections to finished being
1580 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1581 * the keepalive "Waiting for next request" state.
1583 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1584 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1585 conn
->clientConnection
->close();
1589 ClientSocketContext::Pointer deferredRequest
;
1592 * At this point we either have a parsed request (which we've
1593 * kicked off the processing for) or not. If we have a deferred
1594 * request (parsed but deferred for pipeling processing reasons)
1595 * then look at processing it. If not, simply kickstart
1599 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1600 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1601 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1602 } else if (conn
->flags
.readMore
) {
1603 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1604 conn
->readNextRequest();
1606 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1607 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1612 clientUpdateSocketStats(LogTags logType
, size_t size
)
1617 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1619 if (logTypeIsATcpHit(logType
))
1620 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1624 * increments iterator "i"
1625 * used by clientPackMoreRanges
1627 \retval true there is still data available to pack more ranges
1631 ClientSocketContext::canPackMoreRanges() const
1633 /** first update iterator "i" if needed */
1635 if (!http
->range_iter
.debt()) {
1636 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1638 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1639 ++http
->range_iter
.pos
;
1641 http
->range_iter
.updateSpec();
1644 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1646 /* paranoid sync condition */
1647 /* continue condition: need_more_data */
1648 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1649 return http
->range_iter
.currentSpec() ? true : false;
1653 ClientSocketContext::getNextRangeOffset() const
1655 debugs (33, 5, "range: " << http
->request
->range
<<
1656 "; http offset " << http
->out
.offset
<<
1657 "; reply " << reply
);
1659 // XXX: This method is called from many places, including pullData() which
1660 // may be called before prepareReply() [on some Squid-generated errors].
1661 // Hence, we may not even know yet whether we should honor/do ranges.
1663 if (http
->request
->range
) {
1664 /* offset in range specs does not count the prefix of an http msg */
1665 /* check: reply was parsed and range iterator was initialized */
1666 assert(http
->range_iter
.valid
);
1667 /* filter out data according to range specs */
1668 assert (canPackMoreRanges());
1670 int64_t start
; /* offset of still missing data */
1671 assert(http
->range_iter
.currentSpec());
1672 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1673 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1674 debugs(33, 3, "clientPackMoreRanges: out:"
1675 " start: " << start
<<
1676 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1677 " [" << http
->range_iter
.currentSpec()->offset
<<
1678 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1679 " len: " << http
->range_iter
.currentSpec()->length
<<
1680 " debt: " << http
->range_iter
.debt());
1681 if (http
->range_iter
.currentSpec()->length
!= -1)
1682 assert(http
->out
.offset
<= start
); /* we did not miss it */
1687 } else if (reply
&& reply
->content_range
) {
1688 /* request does not have ranges, but reply does */
1689 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1690 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1692 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1695 return http
->out
.offset
;
1699 ClientSocketContext::pullData()
1701 debugs(33, 5, reply
<< " written " << http
->out
.size
<< " into " << clientConnection
);
1703 /* More data will be coming from the stream. */
1704 StoreIOBuffer readBuffer
;
1705 /* XXX: Next requested byte in the range sequence */
1706 /* XXX: length = getmaximumrangelenfgth */
1707 readBuffer
.offset
= getNextRangeOffset();
1708 readBuffer
.length
= HTTP_REQBUF_SZ
;
1709 readBuffer
.data
= reqbuf
;
1710 /* we may note we have reached the end of the wanted ranges */
1711 clientStreamRead(getTail(), http
, readBuffer
);
1714 /** Adapt stream status to account for Range cases
1717 clientStream_status_t
1718 ClientSocketContext::socketState()
1720 switch (clientStreamStatus(getTail(), http
)) {
1723 /* check for range support ending */
1725 if (http
->request
->range
) {
1726 /* check: reply was parsed and range iterator was initialized */
1727 assert(http
->range_iter
.valid
);
1728 /* filter out data according to range specs */
1730 if (!canPackMoreRanges()) {
1731 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1732 "range sequence on " << clientConnection
);
1733 // we got everything we wanted from the store
1734 return STREAM_COMPLETE
;
1736 } else if (reply
&& reply
->content_range
) {
1737 /* reply has content-range, but Squid is not managing ranges */
1738 const int64_t &bytesSent
= http
->out
.offset
;
1739 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1741 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1742 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1743 reply
->content_range
->spec
.offset
<< ")");
1745 // did we get at least what we expected, based on range specs?
1747 if (bytesSent
== bytesExpected
) // got everything
1748 return STREAM_COMPLETE
;
1750 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1751 return STREAM_UNPLANNED_COMPLETE
;
1756 case STREAM_COMPLETE
:
1757 return STREAM_COMPLETE
;
1759 case STREAM_UNPLANNED_COMPLETE
:
1760 return STREAM_UNPLANNED_COMPLETE
;
1763 return STREAM_FAILED
;
1766 fatal ("unreachable code\n");
1771 * A write has just completed to the client, or we have just realised there is
1772 * no more data to send.
1775 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, Comm::Flag errflag
, int, void *data
)
1777 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1778 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1781 /// remembers the abnormal connection termination for logging purposes
1783 ClientSocketContext::noteIoError(const int xerrno
)
1786 if (xerrno
== ETIMEDOUT
)
1787 http
->al
->http
.timedout
= true;
1788 else // even if xerrno is zero (which means read abort/eof)
1789 http
->al
->http
.aborted
= true;
1794 ClientSocketContext::doClose()
1796 clientConnection
->close();
1799 /// called when we encounter a response-related error
1801 ClientSocketContext::initiateClose(const char *reason
)
1803 http
->getConn()->stopSending(reason
); // closes ASAP
1807 ConnStateData::stopSending(const char *error
)
1809 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1810 "; old receiving error: " <<
1811 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1813 if (const char *oldError
= stoppedSending()) {
1814 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1815 return; // nothing has changed as far as this connection is concerned
1817 stoppedSending_
= error
;
1819 if (!stoppedReceiving()) {
1820 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1821 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1822 " request body bytes with " << in
.buf
.length() << " unused");
1823 return; // wait for the request receiver to finish reading
1827 clientConnection
->close();
1831 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
)
1833 const StoreEntry
*entry
= http
->storeEntry();
1834 http
->out
.size
+= size
;
1835 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1836 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1837 (entry
? entry
->objectLen() : 0));
1838 clientUpdateSocketStats(http
->logType
, size
);
1840 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
1842 if (errflag
== Comm::ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1845 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1846 initiateClose("failure or true request status");
1847 /* Do we leak here ? */
1851 switch (socketState()) {
1857 case STREAM_COMPLETE
:
1858 debugs(33, 5, conn
<< "Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1859 if (http
->request
->flags
.proxyKeepalive
)
1860 keepaliveNextRequest();
1862 initiateClose("STREAM_COMPLETE NOKEEPALIVE");
1865 case STREAM_UNPLANNED_COMPLETE
:
1866 initiateClose("STREAM_UNPLANNED_COMPLETE");
1870 initiateClose("STREAM_FAILED");
1874 fatal("Hit unreachable code in clientWriteComplete\n");
1878 ClientSocketContext
*
1879 ConnStateData::abortRequestParsing(const char *const uri
)
1881 ClientHttpRequest
*http
= new ClientHttpRequest(this);
1882 http
->req_sz
= in
.buf
.length();
1883 http
->uri
= xstrdup(uri
);
1884 setLogUri (http
, uri
);
1885 ClientSocketContext
*context
= new ClientSocketContext(clientConnection
, http
);
1886 StoreIOBuffer tempBuffer
;
1887 tempBuffer
.data
= context
->reqbuf
;
1888 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1889 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1890 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1891 clientSocketDetach
, context
, tempBuffer
);
1896 skipLeadingSpace(char *aString
)
1898 char *result
= aString
;
1900 while (xisspace(*aString
))
1907 * 'end' defaults to NULL for backwards compatibility
1908 * remove default value if we ever get rid of NULL-terminated
1912 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1915 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1919 for (; end
> uriAndHTTPVersion
; --end
) {
1920 if (*end
== '\n' || *end
== '\r')
1923 if (xisspace(*end
)) {
1924 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1935 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1937 safe_free(http
->log_uri
);
1940 // The uri is already clean just dump it.
1941 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1944 switch (Config
.uri_whitespace
) {
1945 case URI_WHITESPACE_ALLOW
:
1946 flags
|= RFC1738_ESCAPE_NOSPACE
;
1948 case URI_WHITESPACE_ENCODE
:
1949 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1950 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1953 case URI_WHITESPACE_CHOP
: {
1954 flags
|= RFC1738_ESCAPE_NOSPACE
;
1955 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1956 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1957 int pos
= strcspn(http
->log_uri
, w_space
);
1958 http
->log_uri
[pos
] = '\0';
1962 case URI_WHITESPACE_DENY
:
1963 case URI_WHITESPACE_STRIP
:
1966 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1970 if (!xisspace(*t
)) {
1977 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
1986 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
1988 int vhost
= conn
->port
->vhost
;
1989 int vport
= conn
->port
->vport
;
1990 static char ipbuf
[MAX_IPSTRLEN
];
1992 http
->flags
.accel
= true;
1994 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
1996 static const SBuf
cache_object("cache_object://");
1997 if (hp
->requestUri().startsWith(cache_object
))
1998 return; /* already in good shape */
2000 // XXX: re-use proper URL parser for this
2001 SBuf url
= hp
->requestUri(); // use full provided URI if we abort
2002 do { // use a loop so we can break out of it
2003 ::Parser::Tokenizer
tok(url
);
2004 if (tok
.skip('/')) // origin-form URL already.
2007 if (conn
->port
->vhost
)
2008 return; /* already in good shape */
2010 // skip the URI scheme
2011 static const CharacterSet uriScheme
= CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
2012 static const SBuf
uriSchemeEnd("://");
2013 if (!tok
.skipAll(uriScheme
) || !tok
.skip(uriSchemeEnd
))
2016 // skip the authority segment
2017 // RFC 3986 complex nested ABNF for "authority" boils down to this:
2018 static const CharacterSet authority
= CharacterSet("authority","-._~%:@[]!$&'()*+,;=") +
2019 CharacterSet::HEXDIG
+ CharacterSet::ALPHA
+ CharacterSet::DIGIT
;
2020 if (!tok
.skipAll(authority
))
2023 static const SBuf
slashUri("/");
2024 const SBuf t
= tok
.remaining();
2027 else if (t
[0]=='/') // looks like path
2029 else if (t
[0]=='?' || t
[0]=='#') { // looks like query or fragment. fix '/'
2032 } // else do nothing. invalid path
2036 #if SHOULD_REJECT_UNKNOWN_URLS
2037 // reject URI which are not well-formed even after the processing above
2038 if (url
.isEmpty() || url
[0] != '/') {
2039 hp
->parseStatusCode
= Http::scBadRequest
;
2040 return conn
->abortRequestParsing("error:invalid-request");
2045 vport
= http
->getConn()->clientConnection
->local
.port();
2047 const bool switchedToHttps
= conn
->switchedToHttps();
2048 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2050 if (tryHostHeader
&& (host
= hp
->getHeaderField("Host"))) {
2051 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2056 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2057 strncpy(thost
, host
, (t
-host
));
2058 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2061 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2064 } // else nothing to alter port-wise.
2065 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+ strlen(host
);
2066 http
->uri
= (char *)xcalloc(url_sz
, 1);
2067 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
, AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(url
));
2068 debugs(33, 5, "ACCEL VHOST REWRITE: " << http
->uri
);
2069 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2070 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2071 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
2072 strlen(conn
->port
->defaultsite
);
2073 http
->uri
= (char *)xcalloc(url_sz
, 1);
2077 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2079 snprintf(http
->uri
, url_sz
, "%s://%s%s" SQUIDSBUFPH
,
2080 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, SQUIDSBUFPRINT(url
));
2081 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << http
->uri
);
2082 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2083 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport
);
2084 /* Put the local socket IP address as the hostname, with whatever vport we found */
2085 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
2086 http
->uri
= (char *)xcalloc(url_sz
, 1);
2087 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2088 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
2089 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(),
2090 ipbuf
, vport
, SQUIDSBUFPRINT(url
));
2091 debugs(33, 5, "ACCEL VPORT REWRITE: " << http
->uri
);
2096 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, const Http1::RequestParserPointer
&hp
)
2098 // TODO Must() on URI !empty when the parser supports throw. For now avoid assert().
2099 if (!hp
->requestUri().isEmpty() && hp
->requestUri()[0] != '/')
2100 return; /* already in good shape */
2102 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2104 if (const char *host
= hp
->getHeaderField("Host")) {
2105 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
+
2107 http
->uri
= (char *)xcalloc(url_sz
, 1);
2108 snprintf(http
->uri
, url_sz
, "%s://%s" SQUIDSBUFPH
,
2109 AnyP::UriScheme(conn
->transferProtocol
.protocol
).c_str(), host
, SQUIDSBUFPRINT(hp
->requestUri()));
2110 debugs(33, 5, "TRANSPARENT HOST REWRITE: " << http
->uri
);
2112 /* Put the local socket IP address as the hostname. */
2113 const int url_sz
= hp
->requestUri().length() + 32 + Config
.appendDomainLen
;
2114 http
->uri
= (char *)xcalloc(url_sz
, 1);
2115 static char ipbuf
[MAX_IPSTRLEN
];
2116 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2117 snprintf(http
->uri
, url_sz
, "%s://%s:%d" SQUIDSBUFPH
,
2118 AnyP::UriScheme(http
->getConn()->transferProtocol
.protocol
).c_str(),
2119 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SQUIDSBUFPRINT(hp
->requestUri()));
2120 debugs(33, 5, "TRANSPARENT REWRITE: " << http
->uri
);
2124 /** Parse an HTTP request
2126 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2127 * to 1 if the request was correctly parsed.
2128 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2129 * \param[in] hp an Http1::RequestParser
2130 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2131 * Pointed-to value will be set to Http::METHOD_NONE in case of
2133 * \param[out] http_ver will be set as a side-effect of the parsing
2134 * \return NULL on incomplete requests,
2135 * a ClientSocketContext structure on success or failure.
2137 ClientSocketContext
*
2138 parseHttpRequest(ConnStateData
*csd
, const Http1::RequestParserPointer
&hp
)
2140 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
2142 const bool parsedOk
= hp
->parse(csd
->in
.buf
);
2144 if (csd
->port
->flags
.isIntercepted() && Config
.accessList
.on_unsupported_protocol
)
2145 csd
->preservedClientData
= csd
->in
.buf
;
2146 // sync the buffers after parsing.
2147 csd
->in
.buf
= hp
->remaining();
2149 if (hp
->needsMoreData()) {
2150 debugs(33, 5, "Incomplete request, waiting for end of request line");
2155 if (hp
->parseStatusCode
== Http::scRequestHeaderFieldsTooLarge
|| hp
->parseStatusCode
== Http::scUriTooLong
)
2156 return csd
->abortRequestParsing("error:request-too-large");
2158 return csd
->abortRequestParsing("error:invalid-request");
2162 /* We know the whole request is in parser now */
2163 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2164 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
2165 hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol() << "\n" <<
2169 /* deny CONNECT via accelerated ports */
2170 if (hp
->method() == Http::METHOD_CONNECT
&& csd
->port
!= NULL
&& csd
->port
->flags
.accelSurrogate
) {
2171 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->transferProtocol
<< " Accelerator port " << csd
->port
->s
.port());
2172 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2173 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2174 return csd
->abortRequestParsing("error:method-not-allowed");
2177 /* draft-ietf-httpbis-http2-16 section 11.6 registers the method PRI as HTTP/2 specific
2178 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
2179 * If seen it signals a broken client or proxy has corrupted the traffic.
2181 if (hp
->method() == Http::METHOD_PRI
&& hp
->messageProtocol() < Http::ProtocolVersion(2,0)) {
2182 debugs(33, DBG_IMPORTANT
, "WARNING: PRI method received on " << csd
->transferProtocol
<< " port " << csd
->port
->s
.port());
2183 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2184 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2185 return csd
->abortRequestParsing("error:method-not-allowed");
2188 if (hp
->method() == Http::METHOD_NONE
) {
2189 debugs(33, DBG_IMPORTANT
, "WARNING: Unsupported method: " << hp
->method() << " " << hp
->requestUri() << " " << hp
->messageProtocol());
2190 hp
->parseStatusCode
= Http::scMethodNotAllowed
;
2191 return csd
->abortRequestParsing("error:unsupported-request-method");
2194 // Process headers after request line
2195 debugs(33, 3, "complete request received. " <<
2196 "prefix_sz = " << hp
->messageHeaderSize() <<
2197 ", request-line-size=" << hp
->firstLineSize() <<
2198 ", mime-header-size=" << hp
->headerBlockSize() <<
2199 ", mime header block:\n" << hp
->mimeHeader() << "\n----------");
2201 /* Ok, all headers are received */
2202 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
2204 http
->req_sz
= hp
->messageHeaderSize();
2205 ClientSocketContext
*result
= new ClientSocketContext(csd
->clientConnection
, http
);
2207 StoreIOBuffer tempBuffer
;
2208 tempBuffer
.data
= result
->reqbuf
;
2209 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2211 ClientStreamData newServer
= new clientReplyContext(http
);
2212 ClientStreamData newClient
= result
;
2213 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2214 clientReplyStatus
, newServer
, clientSocketRecipient
,
2215 clientSocketDetach
, newClient
, tempBuffer
);
2218 // XXX: c_str() does re-allocate but here replaces explicit malloc/free.
2219 // when internalCheck() accepts SBuf removing this will be a net gain for performance.
2220 SBuf
tmp(hp
->requestUri());
2221 const char *url
= tmp
.c_str();
2223 debugs(33,5, HERE
<< "repare absolute URL from " <<
2224 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2225 /* Rewrite the URL in transparent or accelerator mode */
2226 /* NP: there are several cases to traverse here:
2227 * - standard mode (forward proxy)
2228 * - transparent mode (TPROXY)
2229 * - transparent mode with failures
2230 * - intercept mode (NAT)
2231 * - intercept mode with failures
2232 * - accelerator mode (reverse proxy)
2234 * - mixed combos of the above with internal URL
2235 * - remote interception with PROXY protocol
2236 * - remote reverse-proxy with PROXY protocol
2238 if (csd
->transparent()) {
2239 /* intercept or transparent mode, properly working with no failures */
2240 prepareTransparentURL(csd
, http
, hp
);
2242 } else if (internalCheck(url
)) {
2243 /* internal URL mode */
2244 /* prepend our name & port */
2245 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2246 // We just re-wrote the URL. Must replace the Host: header.
2247 // But have not parsed there yet!! flag for local-only handling.
2248 http
->flags
.internal
= true;
2250 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2251 /* accelerator mode */
2252 prepareAcceleratedURL(csd
, http
, hp
);
2256 /* No special rewrites have been applied above, use the
2257 * requested url. may be rewritten later, so make extra room */
2258 int url_sz
= hp
->requestUri().length() + Config
.appendDomainLen
+ 5;
2259 http
->uri
= (char *)xcalloc(url_sz
, 1);
2260 strcpy(http
->uri
, url
);
2263 result
->flags
.parsed_ok
= 1;
2268 ConnStateData::In::maybeMakeSpaceAvailable()
2270 if (buf
.spaceSize() < 2) {
2271 const SBuf::size_type haveCapacity
= buf
.length() + buf
.spaceSize();
2272 if (haveCapacity
>= Config
.maxRequestBufferSize
) {
2273 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2276 if (haveCapacity
== 0) {
2277 // haveCapacity is based on the SBuf visible window of the MemBlob buffer, which may fill up.
2278 // at which point bump the buffer back to default. This allocates a new MemBlob with any un-parsed bytes.
2279 buf
.reserveCapacity(CLIENT_REQ_BUF_SZ
);
2281 const SBuf::size_type wantCapacity
= min(static_cast<SBuf::size_type
>(Config
.maxRequestBufferSize
), haveCapacity
*2);
2282 buf
.reserveCapacity(wantCapacity
);
2284 debugs(33, 2, "growing request buffer: available=" << buf
.spaceSize() << " used=" << buf
.length());
2286 return (buf
.spaceSize() >= 2);
2290 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2292 ClientSocketContext::Pointer
*S
;
2294 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2302 ConnStateData::getConcurrentRequestCount() const
2305 ClientSocketContext::Pointer
*T
;
2307 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2308 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2313 ConnStateData::connFinishedWithConn(int size
)
2316 if (getConcurrentRequestCount() == 0 && in
.buf
.isEmpty()) {
2317 /* no current or pending requests */
2318 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2320 } else if (!Config
.onoff
.half_closed_clients
) {
2321 /* admin doesn't want to support half-closed client sockets */
2322 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2323 notifyAllContexts(0); // no specific error implies abort
2332 ConnStateData::consumeInput(const size_t byteCount
)
2334 assert(byteCount
> 0 && byteCount
<= in
.buf
.length());
2335 in
.buf
.consume(byteCount
);
2336 debugs(33, 5, "in.buf has " << in
.buf
.length() << " unused bytes");
2340 ConnStateData::clientAfterReadingRequests()
2342 // Were we expecting to read more request body from half-closed connection?
2343 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2344 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2345 clientConnection
->close();
2354 ConnStateData::quitAfterError(HttpRequest
*request
)
2356 // From HTTP p.o.v., we do not have to close after every error detected
2357 // at the client-side, but many such errors do require closure and the
2358 // client-side code is bad at handling errors so we play it safe.
2360 request
->flags
.proxyKeepalive
= false;
2361 flags
.readMore
= false;
2362 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2366 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2368 ClientHttpRequest
*http
= context
->http
;
2373 assert(sslServerBump
->entry
);
2374 // Did we create an error entry while processing CONNECT?
2375 if (!sslServerBump
->entry
->isEmpty()) {
2376 quitAfterError(http
->request
);
2378 // Get the saved error entry and send it to the client by replacing the
2379 // ClientHttpRequest store entry with it.
2380 clientStreamNode
*node
= context
->getClientReplyContext();
2381 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2383 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2384 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
2386 // save the original request for logging purposes
2387 if (!context
->http
->al
->request
) {
2388 context
->http
->al
->request
= http
->request
;
2389 HTTPMSGLOCK(context
->http
->al
->request
);
2392 // Get error details from the fake certificate-peeking request.
2393 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2394 context
->pullData();
2398 // In bump-server-first mode, we have not necessarily seen the intended
2399 // server name at certificate-peeking time. Check for domain mismatch now,
2400 // when we can extract the intended name from the bumped HTTP request.
2401 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2402 HttpRequest
*request
= http
->request
;
2403 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2404 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2405 "does not match domainname " << request
->GetHost());
2407 bool allowDomainMismatch
= false;
2408 if (Config
.ssl_client
.cert_error
) {
2409 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2410 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2411 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2412 delete check
.sslErrors
;
2413 check
.sslErrors
= NULL
;
2416 if (!allowDomainMismatch
) {
2417 quitAfterError(request
);
2419 clientStreamNode
*node
= context
->getClientReplyContext();
2420 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2421 assert (repContext
);
2423 // Fill the server IP and hostname for error page generation.
2424 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2425 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2427 // Create an error object and fill it
2428 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2429 err
->src_addr
= clientConnection
->remote
;
2430 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2431 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2433 err
->detail
= errDetail
;
2434 // Save the original request for logging purposes.
2435 if (!context
->http
->al
->request
) {
2436 context
->http
->al
->request
= request
;
2437 HTTPMSGLOCK(context
->http
->al
->request
);
2439 repContext
->setReplyToError(request
->method
, err
);
2440 assert(context
->http
->out
.offset
== 0);
2441 context
->pullData();
2449 #endif // USE_OPENSSL
2452 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
2453 * or false otherwise
2456 clientTunnelOnError(ConnStateData
*conn
, ClientSocketContext
*context
, HttpRequest
*request
, const HttpRequestMethod
& method
, err_type requestError
, Http::StatusCode errStatusCode
, const char *requestErrorBytes
)
2458 if (conn
->port
->flags
.isIntercepted() &&
2459 Config
.accessList
.on_unsupported_protocol
&& conn
->nrequests
<= 1) {
2460 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, request
, NULL
);
2461 checklist
.requestErrorType
= requestError
;
2462 checklist
.src_addr
= conn
->clientConnection
->remote
;
2463 checklist
.my_addr
= conn
->clientConnection
->local
;
2464 checklist
.conn(conn
);
2465 allow_t answer
= checklist
.fastCheck();
2466 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
2467 debugs(33, 3, "Request will be tunneled to server");
2469 context
->removeFromConnectionList(conn
);
2470 Comm::SetSelect(conn
->clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2473 if (conn
->preservedClientData
.length())
2474 preReadData
.append(conn
->preservedClientData
);
2475 static char ip
[MAX_IPSTRLEN
];
2476 conn
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
2477 conn
->in
.buf
.assign("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n").append(preReadData
);
2479 bool ret
= conn
->handleReadData();
2481 ret
= conn
->clientParseRequests();
2484 debugs(33, 2, "Failed to start fake CONNECT request for on_unsupported_protocol: " << conn
->clientConnection
);
2485 conn
->clientConnection
->close();
2489 debugs(33, 3, "Continue with returning the error: " << requestError
);
2494 conn
->quitAfterError(request
);
2495 clientStreamNode
*node
= context
->getClientReplyContext();
2496 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2497 assert (repContext
);
2499 repContext
->setReplyToError(requestError
, errStatusCode
, method
, context
->http
->uri
, conn
->clientConnection
->remote
, NULL
, requestErrorBytes
, NULL
);
2501 assert(context
->http
->out
.offset
== 0);
2502 context
->pullData();
2503 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
2508 clientProcessRequestFinished(ConnStateData
*conn
, const HttpRequest::Pointer
&request
)
2512 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2513 * to here because calling comm_reset_close() causes http to
2514 * be freed before accessing.
2516 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2517 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2518 conn
->flags
.readMore
= false;
2519 comm_reset_close(conn
->clientConnection
);
2524 clientProcessRequest(ConnStateData
*conn
, const Http1::RequestParserPointer
&hp
, ClientSocketContext
*context
)
2526 ClientHttpRequest
*http
= context
->http
;
2527 bool chunked
= false;
2528 bool mustReplyToOptions
= false;
2529 bool unsupportedTe
= false;
2530 bool expectBody
= false;
2532 // We already have the request parsed and checked, so we
2533 // only need to go through the final body/conn setup to doCallouts().
2534 assert(http
->request
);
2535 HttpRequest::Pointer request
= http
->request
;
2537 // temporary hack to avoid splitting this huge function with sensitive code
2538 const bool isFtp
= !hp
;
2540 // Some blobs below are still HTTP-specific, but we would have to rewrite
2541 // this entire function to remove them from the FTP code path. Connection
2542 // setup and body_pipe preparation blobs are needed for FTP.
2544 request
->clientConnectionManager
= conn
;
2546 request
->flags
.accelerated
= http
->flags
.accel
;
2547 request
->flags
.sslBumped
=conn
->switchedToHttps();
2548 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2549 // TODO: decouple http->flags.accel from request->flags.sslBumped
2550 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2551 !conn
->port
->allow_direct
: 0;
2553 if (request
->flags
.sslBumped
) {
2554 if (conn
->getAuth() != NULL
)
2555 request
->auth_user_request
= conn
->getAuth();
2560 * If transparent or interception mode is working clone the transparent and interception flags
2561 * from the port settings to the request.
2563 if (http
->clientConnection
!= NULL
) {
2564 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2565 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2566 static const bool proxyProtocolPort
= (conn
->port
!= NULL
) ? conn
->port
->flags
.proxySurrogate
: false;
2567 if (request
->flags
.interceptTproxy
&& !proxyProtocolPort
) {
2568 if (Config
.accessList
.spoof_client_ip
) {
2569 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2570 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2573 request
->flags
.spoofClientIp
= true;
2575 request
->flags
.spoofClientIp
= false;
2578 if (internalCheck(request
->urlpath
.termedBuf())) {
2579 if (internalHostnameIs(request
->GetHost()) && request
->port
== getMyPort()) {
2580 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2581 ':' << request
->port
);
2582 http
->flags
.internal
= true;
2583 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2584 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2585 ':' << request
->port
<< " (global_internal_static on)");
2586 request
->SetHost(internalHostname());
2587 request
->port
= getMyPort();
2588 http
->flags
.internal
= true;
2590 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2591 ':' << request
->port
<< " (not this proxy)");
2594 request
->flags
.internal
= http
->flags
.internal
;
2595 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2596 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2597 #if FOLLOW_X_FORWARDED_FOR
2598 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2599 // not a details about teh TCP connection itself
2600 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2601 #endif /* FOLLOW_X_FORWARDED_FOR */
2602 request
->my_addr
= conn
->clientConnection
->local
;
2603 request
->myportname
= conn
->port
->name
;
2606 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
2607 // for now Squid only supports HTTP requests
2608 const AnyP::ProtocolVersion
&http_ver
= hp
->messageProtocol();
2609 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
2610 request
->http_ver
.major
= http_ver
.major
;
2611 request
->http_ver
.minor
= http_ver
.minor
;
2614 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2615 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2616 request
->clientConnectionManager
= conn
;
2618 if (request
->header
.chunked()) {
2620 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2621 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2622 // HTTP/1.1 requires chunking to be the last encoding if there is one
2623 unsupportedTe
= te
.size() && te
!= "identity";
2624 } // else implied identity coding
2626 mustReplyToOptions
= (request
->method
== Http::METHOD_OPTIONS
) &&
2627 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2628 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2629 clientStreamNode
*node
= context
->getClientReplyContext();
2630 conn
->quitAfterError(request
.getRaw());
2631 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2632 assert (repContext
);
2633 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2634 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2635 assert(context
->http
->out
.offset
== 0);
2636 context
->pullData();
2637 clientProcessRequestFinished(conn
, request
);
2641 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2642 clientStreamNode
*node
= context
->getClientReplyContext();
2643 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2644 assert (repContext
);
2645 conn
->quitAfterError(request
.getRaw());
2646 repContext
->setReplyToError(ERR_INVALID_REQ
,
2647 Http::scLengthRequired
, request
->method
, NULL
,
2648 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2649 assert(context
->http
->out
.offset
== 0);
2650 context
->pullData();
2651 clientProcessRequestFinished(conn
, request
);
2655 clientSetKeepaliveFlag(http
);
2656 // Let tunneling code be fully responsible for CONNECT requests
2657 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2658 context
->mayUseConnection(true);
2659 conn
->flags
.readMore
= false;
2663 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
)) {
2664 clientProcessRequestFinished(conn
, request
);
2669 /* Do we expect a request-body? */
2670 expectBody
= chunked
|| request
->content_length
> 0;
2671 if (!context
->mayUseConnection() && expectBody
) {
2672 request
->body_pipe
= conn
->expectRequestBody(
2673 chunked
? -1 : request
->content_length
);
2675 /* Is it too large? */
2676 if (!chunked
&& // if chunked, we will check as we accumulate
2677 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2678 clientStreamNode
*node
= context
->getClientReplyContext();
2679 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2680 assert (repContext
);
2681 conn
->quitAfterError(request
.getRaw());
2682 repContext
->setReplyToError(ERR_TOO_BIG
,
2683 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
2684 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2685 assert(context
->http
->out
.offset
== 0);
2686 context
->pullData();
2687 clientProcessRequestFinished(conn
, request
);
2692 // We may stop producing, comm_close, and/or call setReplyToError()
2693 // below, so quit on errors to avoid http->doCallouts()
2694 if (!conn
->handleRequestBodyData()) {
2695 clientProcessRequestFinished(conn
, request
);
2699 if (!request
->body_pipe
->productionEnded()) {
2700 debugs(33, 5, "need more request body");
2701 context
->mayUseConnection(true);
2702 assert(conn
->flags
.readMore
);
2707 http
->calloutContext
= new ClientRequestContext(http
);
2711 clientProcessRequestFinished(conn
, request
);
2715 ConnStateData::pipelinePrefetchMax() const
2717 return Config
.pipeline_max_prefetch
;
2721 * Limit the number of concurrent requests.
2722 * \return true when there are available position(s) in the pipeline queue for another request.
2723 * \return false when the pipeline queue is full or disabled.
2726 ConnStateData::concurrentRequestQueueFilled() const
2728 const int existingRequestCount
= getConcurrentRequestCount();
2730 // default to the configured pipeline size.
2731 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2733 const int internalRequest
= (transparent() && sslBumpMode
== Ssl::bumpSplice
) ? 1 : 0;
2735 const int internalRequest
= 0;
2737 const int concurrentRequestLimit
= pipelinePrefetchMax() + 1 + internalRequest
;
2739 // when queue filled already we cant add more.
2740 if (existingRequestCount
>= concurrentRequestLimit
) {
2741 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2742 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2750 * Perform proxy_protocol_access ACL tests on the client which
2751 * connected to PROXY protocol port to see if we trust the
2752 * sender enough to accept their PROXY header claim.
2755 ConnStateData::proxyProtocolValidateClient()
2757 if (!Config
.accessList
.proxyProtocol
)
2758 return proxyProtocolError("PROXY client not permitted by default ACL");
2760 ACLFilledChecklist
ch(Config
.accessList
.proxyProtocol
, NULL
, clientConnection
->rfc931
);
2761 ch
.src_addr
= clientConnection
->remote
;
2762 ch
.my_addr
= clientConnection
->local
;
2765 if (ch
.fastCheck() != ACCESS_ALLOWED
)
2766 return proxyProtocolError("PROXY client not permitted by ACLs");
2772 * Perform cleanup on PROXY protocol errors.
2773 * If header parsing hits a fatal error terminate the connection,
2774 * otherwise wait for more data.
2777 ConnStateData::proxyProtocolError(const char *msg
)
2780 // This is important to know, but maybe not so much that flooding the log is okay.
2781 #if QUIET_PROXY_PROTOCOL
2782 // display the first of every 32 occurances at level 1, the others at level 2.
2783 static uint8_t hide
= 0;
2784 debugs(33, (hide
++ % 32 == 0 ? DBG_IMPORTANT
: 2), msg
<< " from " << clientConnection
);
2786 debugs(33, DBG_IMPORTANT
, msg
<< " from " << clientConnection
);
2793 /// magic octet prefix for PROXY protocol version 1
2794 static const SBuf
Proxy1p0magic("PROXY ", 6);
2796 /// magic octet prefix for PROXY protocol version 2
2797 static const SBuf
Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
2800 * Test the connection read buffer for PROXY protocol header.
2801 * Version 1 and 2 header currently supported.
2804 ConnStateData::parseProxyProtocolHeader()
2806 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
2808 // detect and parse PROXY/2.0 protocol header
2809 if (in
.buf
.startsWith(Proxy2p0magic
))
2810 return parseProxy2p0();
2812 // detect and parse PROXY/1.0 protocol header
2813 if (in
.buf
.startsWith(Proxy1p0magic
))
2814 return parseProxy1p0();
2816 // detect and terminate other protocols
2817 if (in
.buf
.length() >= Proxy2p0magic
.length()) {
2818 // PROXY/1.0 magic is shorter, so we know that
2819 // the input does not start with any PROXY magic
2820 return proxyProtocolError("PROXY protocol error: invalid header");
2823 // TODO: detect short non-magic prefixes earlier to avoid
2824 // waiting for more data which may never come
2826 // not enough bytes to parse yet.
2830 /// parse the PROXY/1.0 protocol header from the connection read buffer
2832 ConnStateData::parseProxy1p0()
2834 ::Parser::Tokenizer
tok(in
.buf
);
2835 tok
.skip(Proxy1p0magic
);
2837 // skip to first LF (assumes it is part of CRLF)
2838 static const CharacterSet lineContent
= CharacterSet::LF
.complement("non-LF");
2840 if (tok
.prefix(line
, lineContent
, 107-Proxy1p0magic
.length())) {
2841 if (tok
.skip('\n')) {
2842 // found valid header
2843 in
.buf
= tok
.remaining();
2844 needProxyProtocolHeader_
= false;
2845 // reset the tokenizer to work on found line only.
2848 return false; // no LF yet
2850 } else // protocol error only if there are more than 107 bytes prefix header
2851 return proxyProtocolError(in
.buf
.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL
);
2853 static const SBuf
unknown("UNKNOWN"), tcpName("TCP");
2854 if (tok
.skip(tcpName
)) {
2856 // skip TCP/IP version number
2857 static const CharacterSet
tcpVersions("TCP-version","46");
2858 if (!tok
.skipOne(tcpVersions
))
2859 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
2861 // skip SP after protocol version
2863 return proxyProtocolError("PROXY/1.0 error: missing SP");
2866 int64_t porta
, portb
;
2867 static const CharacterSet ipChars
= CharacterSet("IP Address",".:") + CharacterSet::HEXDIG
;
2869 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
2870 // leave the LF until later.
2871 const bool correct
= tok
.prefix(ipa
, ipChars
) && tok
.skip(' ') &&
2872 tok
.prefix(ipb
, ipChars
) && tok
.skip(' ') &&
2873 tok
.int64(porta
) && tok
.skip(' ') &&
2877 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
2879 // parse IP and port strings
2880 Ip::Address originalClient
, originalDest
;
2882 if (!originalClient
.GetHostByName(ipa
.c_str()))
2883 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
2885 if (!originalDest
.GetHostByName(ipb
.c_str()))
2886 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
2888 if (porta
> 0 && porta
<= 0xFFFF) // max uint16_t
2889 originalClient
.port(static_cast<uint16_t>(porta
));
2891 return proxyProtocolError("PROXY/1.0 error: invalid src port");
2893 if (portb
> 0 && portb
<= 0xFFFF) // max uint16_t
2894 originalDest
.port(static_cast<uint16_t>(portb
));
2896 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
2898 // we have original client and destination details now
2899 // replace the client connection values
2900 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection
);
2901 clientConnection
->local
= originalDest
;
2902 clientConnection
->remote
= originalClient
;
2903 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2904 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2905 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection
);
2907 // repeat fetch ensuring the new client FQDN can be logged
2908 if (Config
.onoff
.log_fqdn
)
2909 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
2913 } else if (tok
.skip(unknown
)) {
2914 // found valid but unusable header
2918 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
2923 /// parse the PROXY/2.0 protocol header from the connection read buffer
2925 ConnStateData::parseProxy2p0()
2927 static const SBuf::size_type prefixLen
= Proxy2p0magic
.length();
2928 if (in
.buf
.length() < prefixLen
+ 4)
2929 return false; // need more bytes
2931 if ((in
.buf
[prefixLen
] & 0xF0) != 0x20) // version == 2 is mandatory
2932 return proxyProtocolError("PROXY/2.0 error: invalid version");
2934 const char command
= (in
.buf
[prefixLen
] & 0x0F);
2935 if ((command
& 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2936 return proxyProtocolError("PROXY/2.0 error: invalid command");
2938 const char family
= (in
.buf
[prefixLen
+1] & 0xF0) >>4;
2939 if (family
> 0x3) // values other than 0x0-0x3 are invalid
2940 return proxyProtocolError("PROXY/2.0 error: invalid family");
2942 const char proto
= (in
.buf
[prefixLen
+1] & 0x0F);
2943 if (proto
> 0x2) // values other than 0x0-0x2 are invalid
2944 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
2946 const char *clen
= in
.buf
.rawContent() + prefixLen
+ 2;
2948 memcpy(&len
, clen
, sizeof(len
));
2951 if (in
.buf
.length() < prefixLen
+ 4 + len
)
2952 return false; // need more bytes
2954 in
.buf
.consume(prefixLen
+ 4); // 4 being the extra bytes
2955 const SBuf extra
= in
.buf
.consume(len
);
2956 needProxyProtocolHeader_
= false; // found successfully
2958 // LOCAL connections do nothing with the extras
2959 if (command
== 0x00/* LOCAL*/)
2963 struct { /* for TCP/UDP over IPv4, len = 12 */
2964 struct in_addr src_addr
;
2965 struct in_addr dst_addr
;
2969 struct { /* for TCP/UDP over IPv6, len = 36 */
2970 struct in6_addr src_addr
;
2971 struct in6_addr dst_addr
;
2976 struct { /* for AF_UNIX sockets, len = 216 */
2977 uint8_t src_addr
[108];
2978 uint8_t dst_addr
[108];
2984 memcpy(&ipu
, extra
.rawContent(), sizeof(pax
));
2986 // replace the client connection values
2987 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection
);
2990 clientConnection
->local
= ipu
.ipv4_addr
.dst_addr
;
2991 clientConnection
->local
.port(ntohs(ipu
.ipv4_addr
.dst_port
));
2992 clientConnection
->remote
= ipu
.ipv4_addr
.src_addr
;
2993 clientConnection
->remote
.port(ntohs(ipu
.ipv4_addr
.src_port
));
2994 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
2995 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
2998 clientConnection
->local
= ipu
.ipv6_addr
.dst_addr
;
2999 clientConnection
->local
.port(ntohs(ipu
.ipv6_addr
.dst_port
));
3000 clientConnection
->remote
= ipu
.ipv6_addr
.src_addr
;
3001 clientConnection
->remote
.port(ntohs(ipu
.ipv6_addr
.src_port
));
3002 if ((clientConnection
->flags
& COMM_TRANSPARENT
))
3003 clientConnection
->flags
^= COMM_TRANSPARENT
; // prevent TPROXY spoofing of this new IP.
3005 default: // do nothing
3008 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection
);
3010 // repeat fetch ensuring the new client FQDN can be logged
3011 if (Config
.onoff
.log_fqdn
)
3012 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3018 ConnStateData::receivedFirstByte()
3020 if (receivedFirstByte_
)
3023 receivedFirstByte_
= true;
3024 // Set timeout to Config.Timeout.request
3025 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3026 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3027 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3028 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
3032 * Attempt to parse one or more requests from the input buffer.
3033 * Returns true after completing parsing of at least one request [header]. That
3034 * includes cases where parsing ended with an error (e.g., a huge request).
3037 ConnStateData::clientParseRequests()
3039 bool parsed_req
= false;
3041 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
3043 // Loop while we have read bytes that are not needed for producing the body
3044 // On errors, bodyPipe may become nil, but readMore will be cleared
3045 while (!in
.buf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
3047 /* Don't try to parse if the buffer is empty */
3048 if (in
.buf
.isEmpty())
3051 /* Limit the number of concurrent requests */
3052 if (concurrentRequestQueueFilled())
3055 /*Do not read more requests if persistent connection lifetime exceeded*/
3056 if (Config
.Timeout
.pconnLifetime
&& clientConnection
->lifeTime() > Config
.Timeout
.pconnLifetime
) {
3057 flags
.readMore
= false;
3061 // try to parse the PROXY protocol header magic bytes
3062 if (needProxyProtocolHeader_
&& !parseProxyProtocolHeader())
3065 if (ClientSocketContext
*context
= parseOneRequest()) {
3066 debugs(33, 5, clientConnection
<< ": done parsing a request");
3068 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3069 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
3070 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3072 context
->registerWithConn();
3074 processParsedRequest(context
);
3076 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3078 if (context
->mayUseConnection()) {
3079 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3083 debugs(33, 5, clientConnection
<< ": not enough request data: " <<
3084 in
.buf
.length() << " < " << Config
.maxRequestHeaderSize
);
3085 Must(in
.buf
.length() < Config
.maxRequestHeaderSize
);
3090 /* XXX where to 'finish' the parsing pass? */
3095 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3097 debugs(33,5, io
.conn
);
3101 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
3102 if (io
.flag
== Comm::ERR_CLOSING
) {
3103 debugs(33,5, io
.conn
<< " closing Bailout.");
3107 assert(Comm::IsConnOpen(clientConnection
));
3108 assert(io
.conn
->fd
== clientConnection
->fd
);
3111 * Don't reset the timeout value here. The value should be
3112 * counting Config.Timeout.request and applies to the request
3113 * as a whole, not individual read() calls.
3114 * Plus, it breaks our lame *HalfClosed() detection
3117 in
.maybeMakeSpaceAvailable();
3118 CommIoCbParams
rd(this); // will be expanded with ReadNow results
3120 switch (Comm::ReadNow(rd
, in
.buf
)) {
3121 case Comm::INPROGRESS
:
3122 if (in
.buf
.isEmpty())
3123 debugs(33, 2, io
.conn
<< ": no data to process, " << xstrerr(rd
.xerrno
));
3128 kb_incr(&(statCounter
.client_http
.kbytes_in
), rd
.size
);
3129 if (!receivedFirstByte_
)
3130 receivedFirstByte();
3131 // may comm_close or setReplyToError
3132 if (!handleReadData())
3135 /* Continue to process previously read data */
3138 case Comm::ENDFILE
: // close detected by 0-byte read
3139 debugs(33, 5, io
.conn
<< " closed?");
3141 if (connFinishedWithConn(rd
.size
)) {
3142 clientConnection
->close();
3146 /* It might be half-closed, we can't tell */
3147 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3148 commMarkHalfClosed(io
.conn
->fd
);
3149 fd_note(io
.conn
->fd
, "half-closed");
3151 /* There is one more close check at the end, to detect aborted
3152 * (partial) requests. At this point we can't tell if the request
3156 /* Continue to process previously read data */
3159 // case Comm::COMM_ERROR:
3160 default: // no other flags should ever occur
3161 debugs(33, 2, io
.conn
<< ": got flag " << rd
.flag
<< "; " << xstrerr(rd
.xerrno
));
3162 notifyAllContexts(rd
.xerrno
);
3167 /* Process next request */
3168 if (getConcurrentRequestCount() == 0)
3169 fd_note(io
.fd
, "Reading next request");
3171 if (!clientParseRequests()) {
3175 * If the client here is half closed and we failed
3176 * to parse a request, close the connection.
3177 * The above check with connFinishedWithConn() only
3178 * succeeds _if_ the buffer is empty which it won't
3179 * be if we have an incomplete request.
3180 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3182 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3183 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3184 clientConnection
->close();
3192 clientAfterReadingRequests();
3196 * called when new request data has been read from the socket
3198 * \retval false called comm_close or setReplyToError (the caller should bail)
3199 * \retval true we did not call comm_close or setReplyToError
3202 ConnStateData::handleReadData()
3204 // if we are reading a body, stuff data into the body pipe
3205 if (bodyPipe
!= NULL
)
3206 return handleRequestBodyData();
3211 * called when new request body data has been buffered in in.buf
3212 * may close the connection if we were closing and piped everything out
3214 * \retval false called comm_close or setReplyToError (the caller should bail)
3215 * \retval true we did not call comm_close or setReplyToError
3218 ConnStateData::handleRequestBodyData()
3220 assert(bodyPipe
!= NULL
);
3224 if (in
.bodyParser
) { // chunked encoding
3225 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3226 abortChunkedRequestBody(error
);
3229 } else { // identity encoding
3230 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3231 putSize
= bodyPipe
->putMoreData(in
.buf
.c_str(), in
.buf
.length());
3232 if (!bodyPipe
->mayNeedMoreData()) {
3233 // BodyPipe will clear us automagically when we produced everything
3239 consumeInput(putSize
);
3242 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3244 if (const char *reason
= stoppedSending()) {
3245 /* we've finished reading like good clients,
3246 * now do the close that initiateClose initiated.
3248 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3249 clientConnection
->close();
3257 /// parses available chunked encoded body bytes, checks size, returns errors
3259 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3261 debugs(33, 7, "chunked from " << clientConnection
<< ": " << in
.buf
.length());
3263 try { // the parser will throw on errors
3265 if (in
.buf
.isEmpty()) // nothing to do
3268 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3269 // add one because MemBuf will assert if it cannot 0-terminate
3270 raw
.init(in
.buf
.length(), in
.buf
.length()+1);
3271 raw
.append(in
.buf
.c_str(), in
.buf
.length());
3273 const mb_size_t wasContentSize
= raw
.contentSize();
3274 BodyPipeCheckout
bpc(*bodyPipe
);
3275 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3277 putSize
= wasContentSize
- raw
.contentSize();
3279 // dechunk then check: the size limit applies to _dechunked_ content
3280 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3284 finishDechunkingRequest(true);
3286 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3289 // if chunk parser needs data, then the body pipe must need it too
3290 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3292 // if parser needs more space and we can consume nothing, we will stall
3293 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3294 } catch (...) { // TODO: be more specific
3295 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3296 return ERR_INVALID_REQ
;
3299 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3303 /// quit on errors related to chunked request body handling
3305 ConnStateData::abortChunkedRequestBody(const err_type error
)
3307 finishDechunkingRequest(false);
3309 // XXX: The code below works if we fail during initial request parsing,
3310 // but if we fail when the server connection is used already, the server may send
3311 // us its response too, causing various assertions. How to prevent that?
3312 #if WE_KNOW_HOW_TO_SEND_ERRORS
3313 ClientSocketContext::Pointer context
= getCurrentContext();
3314 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3315 clientStreamNode
*node
= context
->getClientReplyContext();
3316 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3318 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3319 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
3320 repContext
->setReplyToError(error
, scode
,
3321 repContext
->http
->request
->method
,
3322 repContext
->http
->uri
,
3324 repContext
->http
->request
,
3326 context
->pullData();
3328 // close or otherwise we may get stuck as nobody will notice the error?
3329 comm_reset_close(clientConnection
);
3332 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3333 comm_reset_close(clientConnection
);
3335 flags
.readMore
= false;
3339 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3341 // request reader may get stuck waiting for space if nobody consumes body
3342 if (bodyPipe
!= NULL
)
3343 bodyPipe
->enableAutoConsumption();
3348 /** general lifetime handler for HTTP requests */
3350 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3352 if (Config
.accessList
.on_unsupported_protocol
&& !receivedFirstByte_
) {
3354 if (serverBump() && (serverBump()->act
.step1
== Ssl::bumpPeek
|| serverBump()->act
.step1
== Ssl::bumpStare
)) {
3355 if (spliceOnError(ERR_REQUEST_START_TIMEOUT
)) {
3356 receivedFirstByte();
3359 } else if (fd_table
[io
.conn
->fd
].ssl
== NULL
)
3362 const HttpRequestMethod method
;
3363 if (clientTunnelOnError(this, NULL
, NULL
, method
, ERR_REQUEST_START_TIMEOUT
, Http::scNone
, NULL
)) {
3364 // Tunnel established. Set receivedFirstByte to avoid loop.
3365 receivedFirstByte();
3371 * Just close the connection to not confuse browsers
3372 * using persistent connections. Some browsers open
3373 * a connection and then do not use it until much
3374 * later (presumeably because the request triggering
3375 * the open has already been completed on another
3378 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3383 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3385 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3386 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3387 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3388 http
->al
->http
.timedout
= true;
3389 if (Comm::IsConnOpen(io
.conn
))
3393 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3394 AsyncJob("ConnStateData"), // kids overwrite
3397 sslBumpMode(Ssl::bumpEnd
),
3399 needProxyProtocolHeader_(false),
3401 switchedToHttps_(false),
3402 sslServerBump(NULL
),
3403 signAlgorithm(Ssl::algSignTrusted
),
3405 stoppedSending_(NULL
),
3406 stoppedReceiving_(NULL
),
3407 receivedFirstByte_(false)
3409 flags
.readMore
= true; // kids may overwrite
3410 flags
.swanSang
= false;
3412 pinning
.host
= NULL
;
3414 pinning
.pinned
= false;
3415 pinning
.auth
= false;
3416 pinning
.zeroReply
= false;
3417 pinning
.peer
= NULL
;
3419 // store the details required for creating more MasterXaction objects as new requests come in
3420 clientConnection
= xact
->tcpClient
;
3421 port
= xact
->squidPort
;
3422 transferProtocol
= port
->transport
; // default to the *_port protocol= setting. may change later.
3423 log_addr
= xact
->tcpClient
->remote
;
3424 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3428 ConnStateData::start()
3430 BodyProducer::start();
3431 HttpControlMsgSink::start();
3433 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3434 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3435 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3436 int i
= IP_PMTUDISC_DONT
;
3437 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3438 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3440 static bool reported
= false;
3443 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3449 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3450 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3451 comm_add_close_handler(clientConnection
->fd
, call
);
3453 if (Config
.onoff
.log_fqdn
)
3454 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3457 if (Ident::TheConfig
.identLookup
) {
3458 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3459 identChecklist
.src_addr
= clientConnection
->remote
;
3460 identChecklist
.my_addr
= clientConnection
->local
;
3461 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3462 Ident::Start(clientConnection
, clientIdentDone
, this);
3466 clientdbEstablished(clientConnection
->remote
, 1);
3468 needProxyProtocolHeader_
= port
->flags
.proxySurrogate
;
3469 if (needProxyProtocolHeader_
) {
3470 if (!proxyProtocolValidateClient()) // will close the connection on failure
3475 fd_table
[clientConnection
->fd
].clientInfo
= NULL
;
3477 if (Config
.onoff
.client_db
) {
3478 /* it was said several times that client write limiter does not work if client_db is disabled */
3480 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3481 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3483 // TODO: we check early to limit error response bandwith but we
3484 // should recheck when we can honor delay_pool_uses_indirect
3485 // TODO: we should also pass the port details for myportname here.
3486 ch
.src_addr
= clientConnection
->remote
;
3487 ch
.my_addr
= clientConnection
->local
;
3489 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3491 /* pools require explicit 'allow' to assign a client into them */
3492 if (pools
[pool
].access
) {
3493 ch
.accessList
= pools
[pool
].access
;
3494 allow_t answer
= ch
.fastCheck();
3495 if (answer
== ACCESS_ALLOWED
) {
3497 /* request client information from db after we did all checks
3498 this will save hash lookup if client failed checks */
3499 ClientInfo
* cli
= clientdbGetInfo(clientConnection
->remote
);
3502 /* put client info in FDE */
3503 fd_table
[clientConnection
->fd
].clientInfo
= cli
;
3505 /* setup write limiter for this request */
3506 const double burst
= floor(0.5 +
3507 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3508 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3511 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3518 // kids must extend to actually start doing something (e.g., reading)
3521 /** Handle a new connection on an HTTP socket. */
3523 httpAccept(const CommAcceptCbParams
¶ms
)
3525 MasterXaction::Pointer xact
= params
.xaction
;
3526 AnyP::PortCfgPointer s
= xact
->squidPort
;
3528 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3530 if (params
.flag
!= Comm::OK
) {
3531 // Its possible the call was still queued when the client disconnected
3532 debugs(33, 2, s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3536 debugs(33, 4, params
.conn
<< ": accepted");
3537 fd_note(params
.conn
->fd
, "client http connect");
3539 if (s
->tcp_keepalive
.enabled
)
3540 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3542 ++incoming_sockets_accepted
;
3544 // Socket is ready, setup the connection manager to start using it
3545 ConnStateData
*connState
= Http::NewServer(xact
);
3546 AsyncJob::Start(connState
); // usually async-calls readSomeData()
3551 /** Create SSL connection structure and update fd_table */
3553 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3555 if (SSL
*ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
3556 debugs(33, 5, "will negotate SSL on " << conn
);
3566 * \retval 1 on success
3567 * \retval 0 when needs more data
3568 * \retval -1 on error
3571 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
3573 int fd
= conn
->clientConnection
->fd
;
3574 SSL
*ssl
= fd_table
[fd
].ssl
;
3577 if ((ret
= SSL_accept(ssl
)) <= 0) {
3578 int ssl_error
= SSL_get_error(ssl
, ret
);
3580 switch (ssl_error
) {
3582 case SSL_ERROR_WANT_READ
:
3583 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, conn
, 0);
3586 case SSL_ERROR_WANT_WRITE
:
3587 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, conn
, 0);
3590 case SSL_ERROR_SYSCALL
:
3593 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
3597 if (errno
== ECONNRESET
)
3600 debugs(83, hard
? 1 : 2, "Error negotiating SSL connection on FD " <<
3601 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3605 case SSL_ERROR_ZERO_RETURN
:
3606 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3610 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
3611 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3612 " (" << ssl_error
<< "/" << ret
<< ")");
3621 /** negotiate an SSL connection */
3623 clientNegotiateSSL(int fd
, void *data
)
3625 ConnStateData
*conn
= (ConnStateData
*)data
;
3627 SSL
*ssl
= fd_table
[fd
].ssl
;
3630 if ((ret
= Squid_SSL_accept(conn
, clientNegotiateSSL
)) <= 0) {
3631 if (ret
< 0) // An error
3636 if (SSL_session_reused(ssl
)) {
3637 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3638 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3640 if (do_debug(83, 4)) {
3641 /* Write out the SSL session details.. actually the call below, but
3642 * OpenSSL headers do strange typecasts confusing GCC.. */
3643 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3644 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3645 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
);
3647 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3649 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3650 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3651 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3652 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3653 * Because there are two possible usable cast, if you get an error here, try the other
3654 * commented line. */
3656 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3657 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3661 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3664 /* Note: This does not automatically fflush the log file.. */
3667 debugs(83, 2, "clientNegotiateSSL: New session " <<
3668 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3669 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3673 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3674 SSL_get_cipher(ssl
));
3676 client_cert
= SSL_get_peer_certificate(ssl
);
3678 if (client_cert
!= NULL
) {
3679 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3680 " client certificate: subject: " <<
3681 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3683 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3684 " client certificate: issuer: " <<
3685 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3687 X509_free(client_cert
);
3689 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3690 " has no certificate.");
3693 #if defined(TLSEXT_NAMETYPE_host_name)
3694 if (!conn
->serverBump()) {
3695 // when in bumpClientFirst mode, get the server name from SNI
3696 if (const char *server
= SSL_get_servername(ssl
, TLSEXT_NAMETYPE_host_name
))
3697 conn
->resetSslCommonName(server
);
3701 conn
->readSomeData();
3705 * If SSL_CTX is given, starts reading the SSL handshake.
3706 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3709 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
)
3713 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3715 if (!sslContext
|| !(ssl
= httpsCreate(details
, sslContext
)))
3718 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3719 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3720 connState
, ConnStateData::requestTimeout
);
3721 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3723 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3727 * A callback function to use with the ACLFilledChecklist callback.
3728 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3729 * else reverts the connection to tunnel mode.
3732 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3734 ConnStateData
*connState
= (ConnStateData
*) data
;
3736 // if the connection is closed or closing, just return.
3737 if (!connState
->isOpen())
3740 // Require both a match and a positive bump mode to work around exceptional
3741 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3742 if (answer
== ACCESS_ALLOWED
&& (answer
.kind
!= Ssl::bumpNone
&& answer
.kind
!= Ssl::bumpSplice
)) {
3743 debugs(33, 2, "sslBump needed for " << connState
->clientConnection
<< " method " << answer
.kind
);
3744 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3746 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3747 connState
->sslBumpMode
= Ssl::bumpNone
;
3750 // fake a CONNECT request to force connState to tunnel
3751 static char ip
[MAX_IPSTRLEN
];
3752 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3753 // Pre-pend this fake request to the TLS bits already in the buffer
3755 retStr
.append("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n");
3756 connState
->in
.buf
= retStr
.append(connState
->in
.buf
);
3757 bool ret
= connState
->handleReadData();
3759 ret
= connState
->clientParseRequests();
3762 debugs(33, 2, "Failed to start fake CONNECT request for SSL bumped connection: " << connState
->clientConnection
);
3763 connState
->clientConnection
->close();
3767 /** handle a new HTTPS connection */
3769 httpsAccept(const CommAcceptCbParams
¶ms
)
3771 MasterXaction::Pointer xact
= params
.xaction
;
3772 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3774 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3776 if (params
.flag
!= Comm::OK
) {
3777 // Its possible the call was still queued when the client disconnected
3778 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3782 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3783 fd_note(params
.conn
->fd
, "client https connect");
3785 if (s
->tcp_keepalive
.enabled
) {
3786 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3789 ++incoming_sockets_accepted
;
3791 // Socket is ready, setup the connection manager to start using it
3792 ConnStateData
*connState
= Https::NewServer(xact
);
3793 AsyncJob::Start(connState
); // usually async-calls postHttpsAccept()
3797 ConnStateData::postHttpsAccept()
3799 if (port
->flags
.tunnelSslBumping
) {
3800 debugs(33, 5, "accept transparent connection: " << clientConnection
);
3802 if (!Config
.accessList
.ssl_bump
) {
3803 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, this);
3807 // Create a fake HTTP request for ssl_bump ACL check,
3808 // using tproxy/intercept provided destination IP and port.
3809 HttpRequest
*request
= new HttpRequest();
3810 static char ip
[MAX_IPSTRLEN
];
3811 assert(clientConnection
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3812 request
->SetHost(clientConnection
->local
.toStr(ip
, sizeof(ip
)));
3813 request
->port
= clientConnection
->local
.port();
3814 request
->myportname
= port
->name
;
3816 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3817 acl_checklist
->src_addr
= clientConnection
->remote
;
3818 acl_checklist
->my_addr
= port
->s
;
3819 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, this);
3822 SSL_CTX
*sslContext
= port
->staticSslContext
.get();
3823 httpsEstablish(this, sslContext
);
3828 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const Helper::Reply
&reply
)
3830 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3831 state_data
->sslCrtdHandleReply(reply
);
3835 ConnStateData::sslCrtdHandleReply(const Helper::Reply
&reply
)
3837 if (reply
.result
== Helper::BrokenHelper
) {
3838 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3839 } else if (!reply
.other().hasContent()) {
3840 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3842 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3843 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3844 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3846 if (reply
.result
!= Helper::Okay
) {
3847 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3849 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3850 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
3851 doPeekAndSpliceStep();
3852 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
3853 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
3855 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
3857 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3858 getSslContextDone(ctx
, true);
3864 getSslContextDone(NULL
);
3867 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3869 certProperties
.commonName
= sslCommonName_
.isEmpty() ? sslConnectHostOrIp
.termedBuf() : sslCommonName_
.c_str();
3871 // fake certificate adaptation requires bump-server-first mode
3872 if (!sslServerBump
) {
3873 assert(port
->signingCert
.get());
3874 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3875 if (port
->signPkey
.get())
3876 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3877 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3881 // In case of an error while connecting to the secure server, use a fake
3882 // trusted certificate, with no mimicked fields and no adaptation
3883 // algorithms. There is nothing we can mimic so we want to minimize the
3884 // number of warnings the user will have to see to get to the error page.
3885 assert(sslServerBump
->entry
);
3886 if (sslServerBump
->entry
->isEmpty()) {
3887 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3888 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3890 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3891 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3892 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3894 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3895 // If the algorithm already set, then ignore it.
3896 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3897 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3898 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3901 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3902 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3903 const char *param
= ca
->param
;
3905 // For parameterless CN adaptation, use hostname from the
3907 if (ca
->alg
== Ssl::algSetCommonName
) {
3909 param
= sslConnectHostOrIp
.termedBuf();
3910 certProperties
.commonName
= param
;
3911 certProperties
.setCommonName
= true;
3912 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3913 certProperties
.setValidAfter
= true;
3914 else if (ca
->alg
== Ssl::algSetValidBefore
)
3915 certProperties
.setValidBefore
= true;
3917 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3918 alg
<< " param: " << (param
? param
: "-"));
3922 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3923 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3924 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3925 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3929 } else {// if (!sslServerBump->entry->isEmpty())
3930 // Use trusted certificate for a Squid-generated error
3931 // or the user would have to add a security exception
3932 // just to see the error page. We will close the connection
3933 // so that the trust is not extended to non-Squid content.
3934 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3937 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3939 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3940 assert(port
->untrustedSigningCert
.get());
3941 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3942 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3944 assert(port
->signingCert
.get());
3945 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3947 if (port
->signPkey
.get())
3948 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3950 signAlgorithm
= certProperties
.signAlgorithm
;
3952 certProperties
.signHash
= Ssl::DefaultSignHash
;
3956 ConnStateData::getSslContextStart()
3958 assert(areAllContextsForThisConnection());
3960 /* careful: freeAllContexts() above frees request, host, etc. */
3962 if (port
->generateHostCertificates
) {
3963 Ssl::CertificateProperties certProperties
;
3964 buildSslCertGenerationParams(certProperties
);
3965 sslBumpCertKey
= certProperties
.dbKey().c_str();
3966 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3968 // Disable caching for bumpPeekAndSplice mode
3969 if (!(sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
))) {
3970 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3971 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3972 SSL_CTX
* dynCtx
= NULL
;
3973 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3974 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3975 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " found in cache");
3976 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3977 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3978 getSslContextDone(dynCtx
);
3981 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3983 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3986 debugs(33, 5, "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3992 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3993 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3994 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3995 request_message
.composeRequest(certProperties
);
3996 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3997 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3999 } catch (const std::exception
&e
) {
4000 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
4001 "request for " << certProperties
.commonName
<<
4002 " certificate: " << e
.what() << "; will now block to " <<
4003 "generate that certificate.");
4004 // fall through to do blocking in-process generation.
4006 #endif // USE_SSL_CRTD
4008 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
4009 if (sslServerBump
&& (sslServerBump
->act
.step1
== Ssl::bumpPeek
|| sslServerBump
->act
.step1
== Ssl::bumpStare
)) {
4010 doPeekAndSpliceStep();
4011 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4012 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
4013 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
4015 SSL_CTX
*dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
4016 getSslContextDone(dynCtx
, true);
4020 getSslContextDone(NULL
);
4024 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
4026 // Try to add generated ssl context to storage.
4027 if (port
->generateHostCertificates
&& isNew
) {
4029 if (signAlgorithm
== Ssl::algSignTrusted
) {
4030 // Add signing certificate to the certificates chain
4031 X509
*cert
= port
->signingCert
.get();
4032 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
4033 // increase the certificate lock
4034 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
4036 const int ssl_error
= ERR_get_error();
4037 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
4039 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
4041 //else it is self-signed or untrusted do not attrach any certificate
4043 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
4044 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
4046 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
4047 // If it is not in storage delete after using. Else storage deleted it.
4048 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
4051 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
4055 // If generated ssl context = NULL, try to use static ssl context.
4057 if (!port
->staticSslContext
) {
4058 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
4059 clientConnection
->close();
4062 debugs(33, 5, HERE
<< "Using static ssl context.");
4063 sslContext
= port
->staticSslContext
.get();
4067 if (!httpsCreate(clientConnection
, sslContext
))
4070 // bumped intercepted conns should already have Config.Timeout.request set
4071 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
4072 // to make sure the connection does not get stuck on non-SSL clients.
4073 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
4074 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
4075 this, ConnStateData::requestTimeout
);
4076 commSetConnTimeout(clientConnection
, Config
.Timeout
.request
, timeoutCall
);
4078 // Disable the client read handler until CachePeer selection is complete
4079 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4080 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
4081 switchedToHttps_
= true;
4085 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
4087 assert(!switchedToHttps_
);
4089 sslConnectHostOrIp
= request
->GetHost();
4090 resetSslCommonName(request
->GetHost());
4092 // We are going to read new request
4093 flags
.readMore
= true;
4094 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
4096 // keep version major.minor details the same.
4097 // but we are now performing the HTTPS handshake traffic
4098 transferProtocol
.protocol
= AnyP::PROTO_HTTPS
;
4100 // If sslServerBump is set, then we have decided to deny CONNECT
4101 // and now want to switch to SSL to send the error to the client
4102 // without even peeking at the origin server certificate.
4103 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
4104 request
->flags
.sslPeek
= true;
4105 sslServerBump
= new Ssl::ServerBump(request
);
4107 // will call httpsPeeked() with certificate and connection, eventually
4108 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4110 } else if (bumpServerMode
== Ssl::bumpPeek
|| bumpServerMode
== Ssl::bumpStare
) {
4111 request
->flags
.sslPeek
= true;
4112 sslServerBump
= new Ssl::ServerBump(request
, NULL
, bumpServerMode
);
4113 startPeekAndSplice();
4117 // otherwise, use sslConnectHostOrIp
4118 getSslContextStart();
4122 ConnStateData::spliceOnError(const err_type err
)
4124 if (Config
.accessList
.on_unsupported_protocol
) {
4125 assert(serverBump());
4126 ACLFilledChecklist
checklist(Config
.accessList
.on_unsupported_protocol
, serverBump()->request
.getRaw(), NULL
);
4127 checklist
.requestErrorType
= err
;
4128 checklist
.conn(this);
4129 allow_t answer
= checklist
.fastCheck();
4130 if (answer
== ACCESS_ALLOWED
&& answer
.kind
== 1) {
4138 /** negotiate an SSL connection */
4140 clientPeekAndSpliceSSL(int fd
, void *data
)
4142 ConnStateData
*conn
= (ConnStateData
*)data
;
4143 SSL
*ssl
= fd_table
[fd
].ssl
;
4145 debugs(83, 5, "Start peek and splice on FD " << fd
);
4148 if ((ret
= Squid_SSL_accept(conn
, clientPeekAndSpliceSSL
)) < 0)
4149 debugs(83, 2, "SSL_accept failed.");
4151 BIO
*b
= SSL_get_rbio(ssl
);
4153 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4155 const err_type err
= bio
->noSslClient() ? ERR_PROTOCOL_UNKNOWN
: ERR_SECURE_ACCEPT_FAIL
;
4156 if (!conn
->spliceOnError(err
))
4157 conn
->clientConnection
->close();
4161 if (bio
->rBufData().contentSize() > 0)
4162 conn
->receivedFirstByte();
4164 if (bio
->gotHello()) {
4165 if (conn
->serverBump()) {
4166 Ssl::Bio::sslFeatures
const &features
= bio
->getFeatures();
4167 if (!features
.serverName
.isEmpty()) {
4168 conn
->serverBump()->clientSni
= features
.serverName
;
4169 conn
->resetSslCommonName(features
.serverName
.c_str());
4173 debugs(83, 5, "I got hello. Start forwarding the request!!! ");
4174 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4175 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
4176 conn
->startPeekAndSpliceDone();
4181 void ConnStateData::startPeekAndSplice()
4183 // will call httpsPeeked() with certificate and connection, eventually
4184 SSL_CTX
*unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
4185 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
4187 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
4190 // commSetConnTimeout() was called for this request before we switched.
4191 // Fix timeout to request_start_timeout
4192 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
4193 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
4194 TimeoutDialer
, this, ConnStateData::requestTimeout
);
4195 commSetConnTimeout(clientConnection
, Config
.Timeout
.request_start_timeout
, timeoutCall
);
4196 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
4197 // a bumbed "connect" request on non transparent port.
4198 receivedFirstByte_
= false;
4200 // Disable the client read handler until CachePeer selection is complete
4201 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4202 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientPeekAndSpliceSSL
, this, 0);
4203 switchedToHttps_
= true;
4205 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4206 BIO
*b
= SSL_get_rbio(ssl
);
4207 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4211 void httpsSslBumpStep2AccessCheckDone(allow_t answer
, void *data
)
4213 ConnStateData
*connState
= (ConnStateData
*) data
;
4215 // if the connection is closed or closing, just return.
4216 if (!connState
->isOpen())
4219 debugs(33, 5, "Answer: " << answer
<< " kind:" << answer
.kind
);
4220 assert(connState
->serverBump());
4221 Ssl::BumpMode bumpAction
;
4222 if (answer
== ACCESS_ALLOWED
) {
4223 if (answer
.kind
== Ssl::bumpNone
)
4224 bumpAction
= Ssl::bumpSplice
;
4225 else if (answer
.kind
== Ssl::bumpClientFirst
|| answer
.kind
== Ssl::bumpServerFirst
)
4226 bumpAction
= Ssl::bumpBump
;
4228 bumpAction
= (Ssl::BumpMode
)answer
.kind
;
4230 bumpAction
= Ssl::bumpSplice
;
4232 connState
->serverBump()->act
.step2
= bumpAction
;
4233 connState
->sslBumpMode
= bumpAction
;
4235 if (bumpAction
== Ssl::bumpTerminate
) {
4236 comm_close(connState
->clientConnection
->fd
);
4237 } else if (bumpAction
!= Ssl::bumpSplice
) {
4238 connState
->startPeekAndSpliceDone();
4240 connState
->splice();
4244 ConnStateData::splice()
4246 //Normally we can splice here, because we just got client hello message
4247 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4248 BIO
*b
= SSL_get_rbio(ssl
);
4249 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4250 MemBuf
const &rbuf
= bio
->rBufData();
4251 debugs(83,5, "Bio for " << clientConnection
<< " read " << rbuf
.contentSize() << " helo bytes");
4253 fd_table
[clientConnection
->fd
].read_method
= &default_read_method
;
4254 fd_table
[clientConnection
->fd
].write_method
= &default_write_method
;
4256 if (transparent()) {
4257 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
4258 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
4259 transferProtocol
= Http::ProtocolVersion();
4260 // fake a CONNECT request to force connState to tunnel
4261 static char ip
[MAX_IPSTRLEN
];
4262 clientConnection
->local
.toUrl(ip
, sizeof(ip
));
4263 in
.buf
.assign("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n").append(rbuf
.content(), rbuf
.contentSize());
4264 bool ret
= handleReadData();
4266 ret
= clientParseRequests();
4269 debugs(33, 2, "Failed to start fake CONNECT request for ssl spliced connection: " << clientConnection
);
4270 clientConnection
->close();
4273 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
4275 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
4276 transferProtocol
= Http::ProtocolVersion();
4277 // in.buf still has the "CONNECT ..." request data, reset it to SSL hello message
4278 in
.buf
.append(rbuf
.content(), rbuf
.contentSize());
4279 ClientSocketContext::Pointer context
= getCurrentContext();
4280 ClientHttpRequest
*http
= context
->http
;
4281 tunnelStart(http
, &http
->out
.size
, &http
->al
->http
.code
, http
->al
);
4286 ConnStateData::startPeekAndSpliceDone()
4288 // This is the Step2 of the SSL bumping
4289 assert(sslServerBump
);
4290 if (sslServerBump
->step
== Ssl::bumpStep1
) {
4291 sslServerBump
->step
= Ssl::bumpStep2
;
4292 // Run a accessList check to check if want to splice or continue bumping
4294 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, sslServerBump
->request
.getRaw(), NULL
);
4295 //acl_checklist->src_addr = params.conn->remote;
4296 //acl_checklist->my_addr = s->s;
4297 acl_checklist
->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone
, this);
4301 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4305 ConnStateData::doPeekAndSpliceStep()
4307 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4308 BIO
*b
= SSL_get_rbio(ssl
);
4310 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4312 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
4315 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
4316 switchedToHttps_
= true;
4320 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4322 Must(sslServerBump
!= NULL
);
4324 if (Comm::IsConnOpen(serverConnection
)) {
4325 pinConnection(serverConnection
, NULL
, NULL
, false);
4327 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4329 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4331 // copy error detail from bump-server-first request to CONNECT request
4332 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4333 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4336 getSslContextStart();
4339 #endif /* USE_OPENSSL */
4341 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4343 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4345 if (!Comm::IsConnOpen(c
)) {
4346 Must(NHttpSockets
> 0); // we tried to open some
4347 --NHttpSockets
; // there will be fewer sockets than planned
4348 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4350 if (!NHttpSockets
) // we could not open any listen sockets at all
4351 fatalf("Unable to open %s",FdNote(portType
));
4358 /// find any unused HttpSockets[] slot and store fd there or return false
4360 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4363 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4364 if ((found
= HttpSockets
[i
] < 0))
4365 HttpSockets
[i
] = conn
->fd
;
4371 clientHttpConnectionsOpen(void)
4373 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4374 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4375 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4376 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4381 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4382 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4383 s
->flags
.tunnelSslBumping
= false;
4386 if (s
->flags
.tunnelSslBumping
&&
4387 !s
->staticSslContext
&&
4388 !s
->generateHostCertificates
) {
4389 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4390 s
->flags
.tunnelSslBumping
= false;
4392 if (s
->flags
.tunnelSslBumping
) {
4393 // Create ssl_ctx cache for this port.
4394 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4398 // Fill out a Comm::Connection which IPC will open as a listener for us
4399 // then pass back when active so we can start a TcpAcceptor subscription.
4400 s
->listenConn
= new Comm::Connection
;
4401 s
->listenConn
->local
= s
->s
;
4402 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4404 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4405 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4406 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, CommAcceptCbParams(NULL
)));
4407 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4409 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4410 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4411 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4413 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4420 clientHttpsConnectionsOpen(void)
4422 for (AnyP::PortCfgPointer s
= HttpsPortList
; s
!= NULL
; s
= s
->next
) {
4423 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4424 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4425 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4429 if (!s
->staticSslContext
) {
4430 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4431 " due to SSL initialization failure.");
4435 // TODO: merge with similar code in clientHttpConnectionsOpen()
4436 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4437 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4438 s
->flags
.tunnelSslBumping
= false;
4441 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4442 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4443 s
->flags
.tunnelSslBumping
= false;
4446 if (s
->flags
.tunnelSslBumping
) {
4447 // Create ssl_ctx cache for this port.
4448 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4451 // Fill out a Comm::Connection which IPC will open as a listener for us
4452 s
->listenConn
= new Comm::Connection
;
4453 s
->listenConn
->local
= s
->s
;
4454 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4455 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4457 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4458 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4459 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, CommAcceptCbParams(NULL
)));
4460 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4462 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4463 ListeningStartedDialer(&clientListenerConnectionOpened
,
4464 s
, Ipc::fdnHttpsSocket
, sub
));
4465 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4466 HttpSockets
[NHttpSockets
] = -1;
4473 clientStartListeningOn(AnyP::PortCfgPointer
&port
, const RefCount
< CommCbFunPtrCallT
<CommAcceptCbPtrFun
> > &subCall
, const Ipc::FdNoteId fdNote
)
4475 // Fill out a Comm::Connection which IPC will open as a listener for us
4476 port
->listenConn
= new Comm::Connection
;
4477 port
->listenConn
->local
= port
->s
;
4478 port
->listenConn
->flags
=
4480 (port
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4481 (port
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4483 // route new connections to subCall
4484 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4485 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4486 AsyncCall::Pointer listenCall
=
4487 asyncCall(33, 2, "clientListenerConnectionOpened",
4488 ListeningStartedDialer(&clientListenerConnectionOpened
,
4489 port
, fdNote
, sub
));
4490 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, port
->listenConn
, fdNote
, listenCall
);
4492 assert(NHttpSockets
< MAXTCPLISTENPORTS
);
4493 HttpSockets
[NHttpSockets
] = -1;
4497 /// process clientHttpConnectionsOpen result
4499 clientListenerConnectionOpened(AnyP::PortCfgPointer
&s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4503 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4506 Must(Comm::IsConnOpen(s
->listenConn
));
4508 // TCP: setup a job to handle accept() with subscribed handler
4509 AsyncJob::Start(new Comm::TcpAcceptor(s
, FdNote(portTypeNote
), sub
));
4511 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4512 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4513 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4514 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4515 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4516 << FdNote(portTypeNote
) << " connections at "
4519 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4523 clientOpenListenSockets(void)
4525 clientHttpConnectionsOpen();
4527 clientHttpsConnectionsOpen();
4529 Ftp::StartListening();
4531 if (NHttpSockets
< 1)
4532 fatal("No HTTP, HTTPS, or FTP ports configured");
4536 clientConnectionsClose()
4538 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
4539 if (s
->listenConn
!= NULL
) {
4540 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4541 s
->listenConn
->close();
4542 s
->listenConn
= NULL
;
4547 for (AnyP::PortCfgPointer s
= HttpsPortList
; s
!= NULL
; s
= s
->next
) {
4548 if (s
->listenConn
!= NULL
) {
4549 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4550 s
->listenConn
->close();
4551 s
->listenConn
= NULL
;
4556 Ftp::StopListening();
4558 // TODO see if we can drop HttpSockets array entirely */
4559 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4560 HttpSockets
[i
] = -1;
4567 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4569 const char *vary
= request
->vary_headers
;
4570 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4571 #if X_ACCELERATOR_VARY
4574 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4577 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4579 /* Oops... something odd is going on here.. */
4580 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4581 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4582 safe_free(request
->vary_headers
);
4587 /* This is not a varying object */
4591 /* virtual "vary" object found. Calculate the vary key and
4592 * continue the search
4594 vary
= httpMakeVaryMark(request
, entry
->getReply());
4597 request
->vary_headers
= xstrdup(vary
);
4600 /* Ouch.. we cannot handle this kind of variance */
4601 /* XXX This cannot really happen, but just to be complete */
4606 vary
= httpMakeVaryMark(request
, entry
->getReply());
4609 request
->vary_headers
= xstrdup(vary
);
4613 /* Ouch.. we cannot handle this kind of variance */
4614 /* XXX This cannot really happen, but just to be complete */
4616 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4619 /* Oops.. we have already been here and still haven't
4620 * found the requested variant. Bail out
4622 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4623 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4629 ACLFilledChecklist
*
4630 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4632 ConnStateData
* conn
= http
->getConn();
4633 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4634 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4637 * hack for ident ACL. It needs to get full addresses, and a place to store
4638 * the ident result on persistent connections...
4640 /* connection oriented auth also needs these two lines for it's operation. */
4645 ConnStateData::transparent() const
4647 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4651 ConnStateData::reading() const
4653 return reader
!= NULL
;
4657 ConnStateData::stopReading()
4660 Comm::ReadCancel(clientConnection
->fd
, reader
);
4666 ConnStateData::expectRequestBody(int64_t size
)
4668 bodyPipe
= new BodyPipe(this);
4670 bodyPipe
->setBodySize(size
);
4672 startDechunkingRequest();
4677 ConnStateData::mayNeedToReadMoreBody() const
4680 return 0; // request without a body or read/produced all body bytes
4682 if (!bodyPipe
->bodySizeKnown())
4683 return -1; // probably need to read more, but we cannot be sure
4685 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4686 const int64_t haveAvailable
= static_cast<int64_t>(in
.buf
.length());
4688 if (needToProduce
<= haveAvailable
)
4689 return 0; // we have read what we need (but are waiting for pipe space)
4691 return needToProduce
- haveAvailable
;
4695 ConnStateData::stopReceiving(const char *error
)
4697 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4698 "; old sending error: " <<
4699 (stoppedSending() ? stoppedSending_
: "none"));
4701 if (const char *oldError
= stoppedReceiving()) {
4702 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4703 return; // nothing has changed as far as this connection is concerned
4706 stoppedReceiving_
= error
;
4708 if (const char *sendError
= stoppedSending()) {
4709 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4710 clientConnection
->close();
4715 ConnStateData::expectNoForwarding()
4717 if (bodyPipe
!= NULL
) {
4718 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4719 bodyPipe
->expectNoConsumption();
4723 /// initialize dechunking state
4725 ConnStateData::startDechunkingRequest()
4727 Must(bodyPipe
!= NULL
);
4728 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4729 assert(!in
.bodyParser
);
4730 in
.bodyParser
= new ChunkedCodingParser
;
4733 /// put parsed content into input buffer and clean up
4735 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4737 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4739 if (bodyPipe
!= NULL
) {
4740 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4741 BodyPipe::Pointer myPipe
= bodyPipe
;
4742 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4743 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4745 Must(myPipe
->bodySizeKnown());
4746 ClientSocketContext::Pointer context
= getCurrentContext();
4747 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4748 context
->http
->request
->setContentLength(myPipe
->bodySize());
4752 delete in
.bodyParser
;
4753 in
.bodyParser
= NULL
;
4756 ConnStateData::In::In() :
4761 ConnStateData::In::~In()
4763 delete bodyParser
; // TODO: pool
4767 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4770 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4774 ClientSocketContext::Pointer context
= getCurrentContext();
4775 if (context
!= NULL
) {
4776 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4780 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4781 clientConnection
->close();
4784 /// Our close handler called by Comm when the pinned connection is closed
4786 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4788 // FwdState might repin a failed connection sooner than this close
4789 // callback is called for the failed connection.
4790 assert(pinning
.serverConnection
== io
.conn
);
4791 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4792 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4793 unpinConnection(false);
4795 if (sawZeroReply
&& clientConnection
!= NULL
) {
4796 debugs(33, 3, "Closing client connection on pinned zero reply.");
4797 clientConnection
->close();
4803 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
, bool monitor
)
4805 if (!Comm::IsConnOpen(pinning
.serverConnection
) ||
4806 pinning
.serverConnection
->fd
!= pinServer
->fd
)
4807 pinNewConnection(pinServer
, request
, aPeer
, auth
);
4810 startPinnedConnectionMonitoring();
4814 ConnStateData::pinNewConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4816 unpinConnection(true); // closes pinned connection, if any, and resets fields
4818 pinning
.serverConnection
= pinServer
;
4820 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4822 Must(pinning
.serverConnection
!= NULL
);
4824 // when pinning an SSL bumped connection, the request may be NULL
4825 const char *pinnedHost
= "[unknown]";
4827 pinning
.host
= xstrdup(request
->GetHost());
4828 pinning
.port
= request
->port
;
4829 pinnedHost
= pinning
.host
;
4831 pinning
.port
= pinServer
->remote
.port();
4833 pinning
.pinned
= true;
4835 pinning
.peer
= cbdataReference(aPeer
);
4836 pinning
.auth
= auth
;
4837 char stmp
[MAX_IPSTRLEN
];
4838 char desc
[FD_DESC_SZ
];
4839 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4840 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4841 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4842 clientConnection
->fd
);
4843 fd_note(pinning
.serverConnection
->fd
, desc
);
4845 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4846 pinning
.closeHandler
= JobCallback(33, 5,
4847 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4848 // remember the pinned connection so that cb does not unpin a fresher one
4849 typedef CommCloseCbParams Params
;
4850 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4851 params
.conn
= pinning
.serverConnection
;
4852 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4855 /// [re]start monitoring pinned connection for peer closures so that we can
4856 /// propagate them to an _idle_ client pinned to that peer
4858 ConnStateData::startPinnedConnectionMonitoring()
4860 if (pinning
.readHandler
!= NULL
)
4861 return; // already monitoring
4863 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4864 pinning
.readHandler
= JobCallback(33, 3,
4865 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4866 Comm::Read(pinning
.serverConnection
, pinning
.readHandler
);
4870 ConnStateData::stopPinnedConnectionMonitoring()
4872 if (pinning
.readHandler
!= NULL
) {
4873 Comm::ReadCancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4874 pinning
.readHandler
= NULL
;
4878 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4879 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4881 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4883 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4885 if (io
.flag
== Comm::ERR_CLOSING
)
4886 return; // close handler will clean up
4888 // We could use getConcurrentRequestCount(), but this may be faster.
4889 const bool clientIsIdle
= !getCurrentContext();
4891 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4892 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4894 assert(pinning
.serverConnection
== io
.conn
);
4895 pinning
.serverConnection
->close();
4897 // If we are still sending data to the client, do not close now. When we are done sending,
4898 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4899 // However, if we are idle, then we must close to inform the idle client and minimize races.
4900 if (clientIsIdle
&& clientConnection
!= NULL
)
4901 clientConnection
->close();
4904 const Comm::ConnectionPointer
4905 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4907 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4910 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4912 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4914 else if (request
&& pinning
.port
!= request
->port
)
4916 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4918 else if (aPeer
!= pinning
.peer
)
4922 /* The pinning info is not safe, remove any pinning info */
4923 unpinConnection(true);
4926 return pinning
.serverConnection
;
4929 Comm::ConnectionPointer
4930 ConnStateData::borrowPinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4932 debugs(33, 7, pinning
.serverConnection
);
4933 if (validatePinnedConnection(request
, aPeer
) != NULL
)
4934 stopPinnedConnectionMonitoring();
4936 return pinning
.serverConnection
; // closed if validation failed
4940 ConnStateData::unpinConnection(const bool andClose
)
4942 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4945 cbdataReferenceDone(pinning
.peer
);
4947 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4948 if (pinning
.closeHandler
!= NULL
) {
4949 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4950 pinning
.closeHandler
= NULL
;
4953 stopPinnedConnectionMonitoring();
4955 // close the server side socket if requested
4957 pinning
.serverConnection
->close();
4958 pinning
.serverConnection
= NULL
;
4961 safe_free(pinning
.host
);
4963 pinning
.zeroReply
= false;
4965 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4966 * connection has gone away */