2 * DEBUG: section 33 Client-side Routines
3 * AUTHOR: Duane Wessels
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 \defgroup ClientSide Client-Side Logics
35 \section cserrors Errors and client side
37 \par Problem the first:
38 * the store entry is no longer authoritative on the
39 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
40 * of client_side_reply.c.
41 * Problem the second: resources are wasted if we delay in cleaning up.
42 * Problem the third we can't depend on a connection close to clean up.
44 \par Nice thing the first:
45 * Any step in the stream can callback with data
46 * representing an error.
47 * Nice thing the second: once you stop requesting reads from upstream,
48 * upstream can be stopped too.
51 * Error has a callback mechanism to hand over a membuf
52 * with the error content. The failing node pushes that back as the
53 * reply. Can this be generalised to reduce duplicate efforts?
54 * A: Possibly. For now, only one location uses this.
55 * How to deal with pre-stream errors?
56 * Tell client_side_reply that we *want* an error page before any
57 * stream calls occur. Then we simply read as normal.
60 \section pconn_logic Persistent connection logic:
63 * requests (httpClientRequest structs) get added to the connection
64 * list, with the current one being chr
67 * The request is *immediately* kicked off, and data flows through
68 * to clientSocketRecipient.
71 * If the data that arrives at clientSocketRecipient is not for the current
72 * request, clientSocketRecipient simply returns, without requesting more
73 * data, or sending it.
76 * ClientKeepAliveNextRequest will then detect the presence of data in
77 * the next ClientHttpRequest, and will send it, restablishing the
82 #include "acl/FilledChecklist.h"
83 #include "anyp/PortCfg.h"
84 #include "base/Subscription.h"
85 #include "base/TextException.h"
86 #include "CachePeer.h"
87 #include "ChunkedCodingParser.h"
88 #include "client_db.h"
89 #include "client_side_reply.h"
90 #include "client_side_request.h"
91 #include "client_side.h"
92 #include "ClientRequestContext.h"
93 #include "clientStream.h"
95 #include "comm/Connection.h"
96 #include "comm/Loops.h"
97 #include "comm/TcpAcceptor.h"
98 #include "comm/Write.h"
99 #include "CommCalls.h"
100 #include "errorpage.h"
103 #include "fqdncache.h"
104 #include "FwdState.h"
107 #include "HttpHdrContRange.h"
108 #include "HttpHeaderTools.h"
109 #include "HttpReply.h"
110 #include "HttpRequest.h"
111 #include "ident/Config.h"
112 #include "ident/Ident.h"
113 #include "internal.h"
114 #include "ipc/FdNotes.h"
115 #include "ipc/StartListening.h"
116 #include "log/access_log.h"
119 #include "MemObject.h"
120 #include "mime_header.h"
121 #include "profiler/Profiler.h"
123 #include "SquidConfig.h"
124 #include "SquidTime.h"
125 #include "StatCounters.h"
126 #include "StatHist.h"
128 #include "TimeOrTag.h"
133 #include "auth/UserRequest.h"
136 #include "ClientInfo.h"
139 #include "ssl/ProxyCerts.h"
140 #include "ssl/context_storage.h"
141 #include "ssl/helper.h"
142 #include "ssl/ServerBump.h"
143 #include "ssl/support.h"
144 #include "ssl/gadgets.h"
147 #include "ssl/crtd_message.h"
148 #include "ssl/certificate_db.h"
162 #define comm_close comm_lingering_close
165 /// dials clientListenerConnectionOpened call
166 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
169 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
170 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
171 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
173 virtual void print(std::ostream
&os
) const {
175 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
178 virtual bool canDial(AsyncCall
&) const { return true; }
179 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
185 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
186 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
187 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
190 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
192 /* our socket-related context */
194 CBDATA_CLASS_INIT(ClientSocketContext
);
197 ClientSocketContext::operator new (size_t byteCount
)
199 /* derived classes with different sizes must implement their own new */
200 assert (byteCount
== sizeof (ClientSocketContext
));
201 CBDATA_INIT_TYPE(ClientSocketContext
);
202 return cbdataAlloc(ClientSocketContext
);
206 ClientSocketContext::operator delete (void *address
)
208 cbdataFree (address
);
211 /* Local functions */
212 /* ClientSocketContext */
213 static ClientSocketContext
*ClientSocketContextNew(const Comm::ConnectionPointer
&clientConn
, ClientHttpRequest
*);
215 static IOCB clientWriteComplete
;
216 static IOCB clientWriteBodyComplete
;
217 static IOACB httpAccept
;
219 static IOACB httpsAccept
;
221 static CTCB clientLifetimeTimeout
;
222 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
223 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, Http::ProtocolVersion
*);
225 static IDCB clientIdentDone
;
227 static CSCB clientSocketRecipient
;
228 static CSD clientSocketDetach
;
229 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
230 static int clientIsContentLengthValid(HttpRequest
* r
);
231 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
233 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
234 static void clientUpdateStatCounters(LogTags logType
);
235 static void clientUpdateHierCounters(HierarchyLogEntry
*);
236 static bool clientPingHasFinished(ping_data
const *aPing
);
237 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
239 static bool connIsUsable(ConnStateData
* conn
);
241 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
242 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
243 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
245 char *skipLeadingSpace(char *aString
);
246 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
248 static ConnStateData
*connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
);
251 ClientSocketContext::getTail() const
253 if (http
->client_stream
.tail
)
254 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
260 ClientSocketContext::getClientReplyContext() const
262 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
266 * This routine should be called to grow the inbuf and then
270 ConnStateData::readSomeData()
275 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
277 if (!maybeMakeSpaceAvailable())
280 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
281 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
282 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
286 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
288 ClientSocketContext::Pointer
*tempContextPointer
;
289 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
290 assert(conn
->getCurrentContext() != NULL
);
291 /* Unlink us from the connection request list */
292 tempContextPointer
= & conn
->currentobject
;
294 while (tempContextPointer
->getRaw()) {
295 if (*tempContextPointer
== this)
298 tempContextPointer
= &(*tempContextPointer
)->next
;
301 assert(tempContextPointer
->getRaw() != NULL
);
302 *tempContextPointer
= next
;
306 ClientSocketContext::~ClientSocketContext()
308 clientStreamNode
*node
= getTail();
311 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
314 /* We are *always* the tail - prevent recursive free */
315 assert(this == streamContext
);
321 deRegisterWithConn();
323 httpRequestFree(http
);
325 /* clean up connection links to us */
326 assert(this != next
.getRaw());
330 ClientSocketContext::registerWithConn()
332 assert (!connRegistered_
);
334 assert (http
->getConn() != NULL
);
335 connRegistered_
= true;
336 http
->getConn()->addContextToQueue(this);
340 ClientSocketContext::deRegisterWithConn()
342 assert (connRegistered_
);
343 removeFromConnectionList(http
->getConn());
344 connRegistered_
= false;
348 ClientSocketContext::connIsFinished()
351 assert (http
->getConn() != NULL
);
352 deRegisterWithConn();
353 /* we can't handle any more stream data - detach */
354 clientStreamDetach(getTail(), http
);
357 ClientSocketContext::ClientSocketContext() : http(NULL
), reply(NULL
), next(NULL
),
359 mayUseConnection_ (false),
360 connRegistered_ (false)
362 memset (reqbuf
, '\0', sizeof (reqbuf
));
365 deferredparams
.node
= NULL
;
366 deferredparams
.rep
= NULL
;
369 ClientSocketContext
*
370 ClientSocketContextNew(const Comm::ConnectionPointer
&client
, ClientHttpRequest
* http
)
372 ClientSocketContext
*newContext
;
373 assert(http
!= NULL
);
374 newContext
= new ClientSocketContext
;
375 newContext
->http
= http
;
376 newContext
->clientConnection
= client
;
381 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
383 const HttpReply::Pointer
rep(msg
.reply
);
386 // apply selected clientReplyContext::buildReplyHeader() mods
387 // it is not clear what headers are required for control messages
388 rep
->header
.removeHopByHopEntries();
389 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
390 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
392 // remember the callback
393 cbControlMsgSent
= msg
.cbSuccess
;
395 MemBuf
*mb
= rep
->pack();
397 debugs(11, 2, "HTTP Client " << clientConnection
);
398 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
400 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
401 CommIoCbPtrFun(&WroteControlMsg
, this));
402 Comm::Write(clientConnection
, mb
, call
);
407 /// called when we wrote the 1xx response
409 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
411 if (errflag
== COMM_ERR_CLOSING
)
414 if (errflag
== COMM_OK
) {
415 ScheduleCallHere(cbControlMsgSent
);
419 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
420 // no error notification: see HttpControlMsg.h for rationale and
421 // note that some errors are detected elsewhere (e.g., close handler)
423 // close on 1xx errors to be conservative and to simplify the code
424 // (if we do not close, we must notify the source of a failure!)
428 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
430 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
432 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
433 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
438 clientIdentDone(const char *ident
, void *data
)
440 ConnStateData
*conn
= (ConnStateData
*)data
;
441 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
446 clientUpdateStatCounters(LogTags logType
)
448 ++statCounter
.client_http
.requests
;
450 if (logTypeIsATcpHit(logType
))
451 ++statCounter
.client_http
.hits
;
453 if (logType
== LOG_TCP_HIT
)
454 ++statCounter
.client_http
.disk_hits
;
455 else if (logType
== LOG_TCP_MEM_HIT
)
456 ++statCounter
.client_http
.mem_hits
;
460 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
462 statCounter
.client_http
.allSvcTime
.count(svc_time
);
464 * The idea here is not to be complete, but to get service times
465 * for only well-defined types. For example, we don't include
466 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
467 * (we *tried* to validate it, but failed).
472 case LOG_TCP_REFRESH_UNMODIFIED
:
473 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
476 case LOG_TCP_IMS_HIT
:
477 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
482 case LOG_TCP_MEM_HIT
:
484 case LOG_TCP_OFFLINE_HIT
:
485 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
490 case LOG_TCP_CLIENT_REFRESH_MISS
:
491 statCounter
.client_http
.missSvcTime
.count(svc_time
);
495 /* make compiler warnings go away */
501 clientPingHasFinished(ping_data
const *aPing
)
503 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
510 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
514 switch (someEntry
->code
) {
515 #if USE_CACHE_DIGESTS
520 ++ statCounter
.cd
.times_used
;
528 case FIRST_PARENT_MISS
:
530 case CLOSEST_PARENT_MISS
:
531 ++ statCounter
.icp
.times_used
;
532 i
= &someEntry
->ping
;
534 if (clientPingHasFinished(i
))
535 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
538 ++ statCounter
.icp
.query_timeouts
;
545 ++ statCounter
.netdb
.times_used
;
555 ClientHttpRequest::updateCounters()
557 clientUpdateStatCounters(logType
);
559 if (request
->errType
!= ERR_NONE
)
560 ++ statCounter
.client_http
.errors
;
562 clientUpdateStatHistCounters(logType
,
563 tvSubMsec(start_time
, current_time
));
565 clientUpdateHierCounters(&request
->hier
);
569 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
572 assert(aLogEntry
!= NULL
);
574 if (Config
.onoff
.log_mime_hdrs
) {
578 packerToMemInit(&p
, &mb
);
579 request
->header
.packInto(&p
);
580 //This is the request after adaptation or redirection
581 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
583 // the virgin request is saved to aLogEntry->request
584 if (aLogEntry
->request
) {
587 packerToMemInit(&p
, &mb
);
588 aLogEntry
->request
->header
.packInto(&p
);
589 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
593 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
597 packerToMemInit(&p
, &mb
);
598 ah
->lastMeta
.packInto(&p
);
599 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
608 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
610 aLogEntry
->icap
.processingTime
= ih
->processingTime();
613 aLogEntry
->http
.method
= request
->method
;
614 aLogEntry
->http
.version
= request
->http_ver
;
615 aLogEntry
->hier
= request
->hier
;
616 if (request
->content_length
> 0) // negative when no body or unknown length
617 aLogEntry
->cache
.requestSize
+= request
->content_length
;
618 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
620 // Adapted request, if any, inherits and then collects all the stats, but
621 // the virgin request gets logged instead; copy the stats to log them.
622 // TODO: avoid losses by keeping these stats in a shared history object?
623 if (aLogEntry
->request
) {
624 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
625 aLogEntry
->request
->errType
= request
->errType
;
626 aLogEntry
->request
->errDetail
= request
->errDetail
;
631 ClientHttpRequest::logRequest()
633 if (!out
.size
&& !logType
)
634 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
636 al
->icp
.opcode
= ICP_INVALID
;
638 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
641 al
->http
.code
= al
->reply
->sline
.status();
642 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
643 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
644 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
645 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
648 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
650 if (loggingEntry() && loggingEntry()->mem_obj
)
651 al
->cache
.objectSize
= loggingEntry()->contentLen();
653 al
->cache
.caddr
.setNoAddr();
655 if (getConn() != NULL
) {
656 al
->cache
.caddr
= getConn()->log_addr
;
657 al
->cache
.port
= cbdataReference(getConn()->port
);
660 al
->cache
.requestSize
= req_sz
;
661 al
->cache
.requestHeadersSize
= req_sz
;
663 al
->cache
.replySize
= out
.size
;
664 al
->cache
.replyHeadersSize
= out
.headers_sz
;
666 al
->cache
.highOffset
= out
.offset
;
668 al
->cache
.code
= logType
;
670 al
->cache
.msec
= tvSubMsec(start_time
, current_time
);
673 prepareLogWithRequestDetails(request
, al
);
675 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
676 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
680 /* This is broken. Fails if the connection has been closed. Needs
681 * to snarf the ssl details some place earlier..
683 if (getConn() != NULL
)
684 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
689 // The al->notes and request->notes must point to the same object.
690 // Enable the following assertion to check for possible bugs.
691 // assert(request->notes == al->notes);
692 typedef Notes::iterator ACAMLI
;
693 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
694 if (const char *value
= (*i
)->match(request
, al
->reply
)) {
695 NotePairs
¬es
= SyncNotes(*al
, *request
);
696 notes
.add((*i
)->key
.termedBuf(), value
);
697 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
701 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
703 checklist
.reply
= al
->reply
;
704 HTTPMSGLOCK(checklist
.reply
);
708 al
->adapted_request
= request
;
709 HTTPMSGLOCK(al
->adapted_request
);
711 accessLogLog(al
, &checklist
);
713 bool updatePerformanceCounters
= true;
714 if (Config
.accessList
.stats_collection
) {
715 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
717 statsCheck
.reply
= al
->reply
;
718 HTTPMSGLOCK(statsCheck
.reply
);
720 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
723 if (updatePerformanceCounters
) {
727 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
728 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
733 ClientHttpRequest::freeResources()
737 safe_free(redirect
.location
);
738 range_iter
.boundary
.clean();
739 HTTPMSGUNLOCK(request
);
741 if (client_stream
.tail
)
742 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
746 httpRequestFree(void *data
)
748 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
749 assert(http
!= NULL
);
754 ConnStateData::areAllContextsForThisConnection() const
756 assert(this != NULL
);
757 ClientSocketContext::Pointer context
= getCurrentContext();
759 while (context
.getRaw()) {
760 if (context
->http
->getConn() != this)
763 context
= context
->next
;
770 ConnStateData::freeAllContexts()
772 ClientSocketContext::Pointer context
;
774 while ((context
= getCurrentContext()).getRaw() != NULL
) {
775 assert(getCurrentContext() !=
776 getCurrentContext()->next
);
777 context
->connIsFinished();
778 assert (context
!= currentobject
);
782 /// propagates abort event to all contexts
784 ConnStateData::notifyAllContexts(int xerrno
)
786 typedef ClientSocketContext::Pointer CSCP
;
787 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
788 c
->noteIoError(xerrno
);
791 /* This is a handler normally called by comm_close() */
792 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
794 deleteThis("ConnStateData::connStateClosed");
799 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
803 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
809 // clobered with self-pointer
810 // NP: something nasty is going on in Squid, but harmless.
812 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
817 * Connection-auth relies on a single set of credentials being preserved
818 * for all requests on a connection once they have been setup.
819 * There are several things which need to happen to preserve security
820 * when connection-auth credentials change unexpectedly or are unset.
822 * 1) auth helper released from any active state
824 * They can only be reserved by a handshake process which this
825 * connection can now never complete.
826 * This prevents helpers hanging when their connections close.
828 * 2) pinning is expected to be removed and server conn closed
830 * The upstream link is authenticated with the same credentials.
831 * Expecting the same level of consistency we should have received.
832 * This prevents upstream being faced with multiple or missing
833 * credentials after authentication.
834 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
835 * we just trigger that cleanup here via comm_reset_close() or
836 * ConnStateData::stopReceiving()
838 * 3) the connection needs to close.
840 * This prevents attackers injecting requests into a connection,
841 * or gateways wrongly multiplexing users into a single connection.
843 * When credentials are missing closure needs to follow an auth
844 * challenge for best recovery by the client.
846 * When credentials change there is nothing we can do but abort as
847 * fast as possible. Sending TCP RST instead of an HTTP response
848 * is the best-case action.
851 // clobbered with nul-pointer
853 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
854 auth_
->releaseAuthServer();
856 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
857 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
858 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
859 stopReceiving("connection-auth removed");
863 // clobbered with alternative credentials
865 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
866 auth_
->releaseAuthServer();
868 // this is a fatal type of problem.
869 // Close the connection immediately with TCP RST to abort all traffic flow
870 comm_reset_close(clientConnection
);
878 // cleans up before destructor is called
880 ConnStateData::swanSong()
882 debugs(33, 2, HERE
<< clientConnection
);
883 flags
.readMore
= false;
884 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
885 assert(areAllContextsForThisConnection());
890 if (Comm::IsConnOpen(clientConnection
))
891 clientConnection
->close();
892 clientConnection
= NULL
;
895 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
896 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
899 BodyProducer::swanSong();
900 flags
.swanSang
= true;
904 ConnStateData::isOpen() const
906 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
907 Comm::IsConnOpen(clientConnection
) &&
908 !fd_table
[clientConnection
->fd
].closing();
911 ConnStateData::~ConnStateData()
913 assert(this != NULL
);
914 debugs(33, 3, HERE
<< clientConnection
);
917 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
920 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
922 cbdataReferenceDone(port
);
924 if (bodyPipe
!= NULL
)
925 stopProducingFor(bodyPipe
, false);
928 delete sslServerBump
;
933 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
934 * This is the client-side persistent connection flag. We need
935 * to set this relatively early in the request processing
936 * to handle hacks for broken servers and clients.
939 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
941 HttpRequest
*request
= http
->request
;
943 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
944 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
945 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
946 RequestMethodStr(request
->method
));
948 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
949 request
->flags
.proxyKeepalive
= request
->persistent();
953 clientIsContentLengthValid(HttpRequest
* r
)
955 switch (r
->method
.id()) {
957 case Http::METHOD_GET
:
959 case Http::METHOD_HEAD
:
960 /* We do not want to see a request entity on GET/HEAD requests */
961 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
964 /* For other types of requests we don't care */
972 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
974 if (Config
.maxRequestBodySize
&&
975 bodyLength
> Config
.maxRequestBodySize
)
976 return 1; /* too large */
983 connIsUsable(ConnStateData
* conn
)
985 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
993 // careful: the "current" context may be gone if we wrote an early response
994 ClientSocketContext::Pointer
995 ConnStateData::getCurrentContext() const
998 return currentobject
;
1002 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
1004 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
1005 assert(flags
.deferred
== 0);
1007 deferredparams
.node
= node
;
1008 deferredparams
.rep
= rep
;
1009 deferredparams
.queuedBuffer
= receivedData
;
1014 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
1016 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
1023 ClientSocketContext::startOfOutput() const
1025 return http
->out
.size
== 0;
1029 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
1031 /*the size of available range can always fit in a size_t type*/
1032 size_t maximum
= (size_t)available
.size();
1034 if (!http
->request
->range
)
1037 assert (canPackMoreRanges());
1039 if (http
->range_iter
.debt() == -1)
1042 assert (http
->range_iter
.debt() > 0);
1044 /* TODO this + the last line could be a range intersection calculation */
1045 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
1048 return min(http
->range_iter
.debt(), (int64_t)maximum
);
1052 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
1054 http
->out
.offset
+= bytes
;
1056 if (!http
->request
->range
)
1059 if (http
->range_iter
.debt() != -1) {
1060 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
1061 assert (http
->range_iter
.debt() >= 0);
1064 /* debt() always stops at -1, below that is a bug */
1065 assert (http
->range_iter
.debt() >= -1);
1069 ClientHttpRequest::multipartRangeRequest() const
1071 return request
->multipartRangeRequest();
1075 ClientSocketContext::multipartRangeRequest() const
1077 return http
->multipartRangeRequest();
1081 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1083 assert(rep
== NULL
);
1085 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1086 size_t length
= lengthToSend(bodyData
.range());
1087 noteSentBodyBytes (length
);
1088 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1089 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1090 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1096 if (multipartRangeRequest())
1097 packRange(bodyData
, &mb
);
1099 packChunk(bodyData
, mb
);
1101 if (mb
.contentSize()) {
1103 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1104 CommIoCbPtrFun(clientWriteComplete
, this));
1105 Comm::Write(clientConnection
, &mb
, call
);
1107 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1111 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1112 * if bodyData is empty.
1115 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1117 const uint64_t length
=
1118 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1119 noteSentBodyBytes(length
);
1121 mb
.Printf("%" PRIX64
"\r\n", length
);
1122 mb
.append(bodyData
.data
, length
);
1126 /** put terminating boundary for multiparts */
1128 clientPackTermBound(String boundary
, MemBuf
* mb
)
1130 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1131 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1134 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1136 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1138 HttpHeader
hdr(hoReply
);
1144 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1145 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1146 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1148 /* stuff the header with required entries and pack it */
1150 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1151 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1153 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1155 packerToMemInit(&p
, mb
);
1163 /* append <crlf> (we packed a header, not a reply) */
1168 * extracts a "range" from *buf and appends them to mb, updating
1169 * all offsets and such.
1172 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1174 HttpHdrRangeIter
* i
= &http
->range_iter
;
1175 Range
<int64_t> available (source
.range());
1176 char const *buf
= source
.data
;
1178 while (i
->currentSpec() && available
.size()) {
1179 const size_t copy_sz
= lengthToSend(available
);
1183 * intersection of "have" and "need" ranges must not be empty
1185 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1186 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1189 * put boundary and headers at the beginning of a range in a
1193 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1194 assert(http
->memObject());
1196 http
->memObject()->getReply(), /* original reply */
1197 i
->currentSpec(), /* current range */
1198 i
->boundary
, /* boundary, the same for all */
1205 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1207 noteSentBodyBytes (copy_sz
);
1209 mb
->append(buf
, copy_sz
);
1214 available
.start
+= copy_sz
;
1220 if (!canPackMoreRanges()) {
1221 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1224 /* put terminating boundary for multiparts */
1225 clientPackTermBound(i
->boundary
, mb
);
1230 int64_t nextOffset
= getNextRangeOffset();
1232 assert (nextOffset
>= http
->out
.offset
);
1234 int64_t skip
= nextOffset
- http
->out
.offset
;
1236 /* adjust for not to be transmitted bytes */
1237 http
->out
.offset
= nextOffset
;
1239 if (available
.size() <= (uint64_t)skip
)
1242 available
.start
+= skip
;
1251 /** returns expected content length for multi-range replies
1252 * note: assumes that httpHdrRangeCanonize has already been called
1253 * warning: assumes that HTTP headers for individual ranges at the
1254 * time of the actuall assembly will be exactly the same as
1255 * the headers when clientMRangeCLen() is called */
1257 ClientHttpRequest::mRangeCLen()
1262 assert(memObject());
1265 HttpHdrRange::iterator pos
= request
->range
->begin();
1267 while (pos
!= request
->range
->end()) {
1268 /* account for headers for this range */
1270 clientPackRangeHdr(memObject()->getReply(),
1271 *pos
, range_iter
.boundary
, &mb
);
1274 /* account for range content */
1275 clen
+= (*pos
)->length
;
1277 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1281 /* account for the terminating boundary */
1284 clientPackTermBound(range_iter
.boundary
, &mb
);
1294 * returns true if If-Range specs match reply, false otherwise
1297 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1299 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1300 /* check for parsing falure */
1307 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1308 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1309 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1312 return 0; /* entity has no etag to compare with! */
1314 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1315 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1316 return 0; /* must use strong validator for sub-range requests */
1319 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1322 /* got modification time? */
1323 if (spec
.time
>= 0) {
1324 return http
->storeEntry()->lastmod
<= spec
.time
;
1327 assert(0); /* should not happen */
1332 * generates a "unique" boundary string for multipart responses
1333 * the caller is responsible for cleaning the string */
1335 ClientHttpRequest::rangeBoundaryStr() const
1339 String
b(APP_FULLNAME
);
1341 key
= storeEntry()->getMD5Text();
1342 b
.append(key
, strlen(key
));
1346 /** adds appropriate Range headers if needed */
1348 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1350 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1351 const char *range_err
= NULL
;
1352 HttpRequest
*request
= http
->request
;
1353 assert(request
->range
);
1354 /* check if we still want to do ranges */
1356 int64_t roffLimit
= request
->getRangeOffsetLimit();
1359 range_err
= "no [parse-able] reply";
1360 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1361 range_err
= "wrong status code";
1362 else if (hdr
->has(HDR_CONTENT_RANGE
))
1363 range_err
= "origin server does ranges";
1364 else if (rep
->content_length
< 0)
1365 range_err
= "unknown length";
1366 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1367 range_err
= "INCONSISTENT length"; /* a bug? */
1369 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1372 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1373 range_err
= "If-Range match failed";
1374 else if (!http
->request
->range
->canonize(rep
))
1375 range_err
= "canonization failed";
1376 else if (http
->request
->range
->isComplex())
1377 range_err
= "too complex range header";
1378 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1379 range_err
= "range outside range_offset_limit";
1381 /* get rid of our range specs on error */
1383 /* XXX We do this here because we need canonisation etc. However, this current
1384 * code will lead to incorrect store offset requests - the store will have the
1385 * offset data, but we won't be requesting it.
1386 * So, we can either re-request, or generate an error
1388 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1389 delete http
->request
->range
;
1390 http
->request
->range
= NULL
;
1392 /* XXX: TODO: Review, this unconditional set may be wrong. */
1393 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1394 // web server responded with a valid, but unexpected range.
1395 // will (try-to) forward as-is.
1396 //TODO: we should cope with multirange request/responses
1397 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1398 request
->range
->contains(rep
->content_range
->spec
) :
1400 const int spec_count
= http
->request
->range
->specs
.count
;
1401 int64_t actual_clen
= -1;
1403 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1404 spec_count
<< " virgin clen: " << rep
->content_length
);
1405 assert(spec_count
> 0);
1406 /* append appropriate header(s) */
1408 if (spec_count
== 1) {
1409 if (!replyMatchRequest
) {
1410 hdr
->delById(HDR_CONTENT_RANGE
);
1411 hdr
->putContRange(rep
->content_range
);
1412 actual_clen
= rep
->content_length
;
1413 //http->range_iter.pos = rep->content_range->spec.begin();
1414 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1415 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1418 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1420 /* append Content-Range */
1422 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1423 /* No content range, so this was a full object we are
1426 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1429 /* set new Content-Length to the actual number of bytes
1430 * transmitted in the message-body */
1431 actual_clen
= (*pos
)->length
;
1435 /* generate boundary string */
1436 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1437 /* delete old Content-Type, add ours */
1438 hdr
->delById(HDR_CONTENT_TYPE
);
1439 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1440 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1441 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1442 /* Content-Length is not required in multipart responses
1443 * but it is always nice to have one */
1444 actual_clen
= http
->mRangeCLen();
1445 /* http->out needs to start where we want data at */
1446 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1449 /* replace Content-Length header */
1450 assert(actual_clen
>= 0);
1452 hdr
->delById(HDR_CONTENT_LENGTH
);
1454 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1456 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1458 /* And start the range iter off */
1459 http
->range_iter
.updateSpec();
1464 ClientSocketContext::prepareReply(HttpReply
* rep
)
1468 if (http
->request
->range
)
1469 buildRangeHeader(rep
);
1473 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1477 MemBuf
*mb
= rep
->pack();
1479 // dump now, so we dont output any body.
1480 debugs(11, 2, "HTTP Client " << clientConnection
);
1481 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1483 /* Save length of headers for persistent conn checks */
1484 http
->out
.headers_sz
= mb
->contentSize();
1487 headersLog(0, 0, http
->request
->method
, rep
);
1490 if (bodyData
.data
&& bodyData
.length
) {
1491 if (multipartRangeRequest())
1492 packRange(bodyData
, mb
);
1493 else if (http
->request
->flags
.chunkedReply
) {
1494 packChunk(bodyData
, *mb
);
1496 size_t length
= lengthToSend(bodyData
.range());
1497 noteSentBodyBytes (length
);
1499 mb
->append(bodyData
.data
, length
);
1504 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1505 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1506 CommIoCbPtrFun(clientWriteComplete
, this));
1507 Comm::Write(clientConnection
, mb
, call
);
1512 * Write a chunk of data to a client socket. If the reply is present,
1513 * send the reply headers down the wire too, and clean them up when
1516 * The request is one backed by a connection, not an internal request.
1517 * data context is not NULL
1518 * There are no more entries in the stream chain.
1521 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1522 HttpReply
* rep
, StoreIOBuffer receivedData
)
1524 /* Test preconditions */
1525 assert(node
!= NULL
);
1526 PROF_start(clientSocketRecipient
);
1527 /* TODO: handle this rather than asserting
1528 * - it should only ever happen if we cause an abort and
1529 * the callback chain loops back to here, so we can simply return.
1530 * However, that itself shouldn't happen, so it stays as an assert for now.
1532 assert(cbdataReferenceValid(node
));
1533 assert(node
->node
.next
== NULL
);
1534 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1535 assert(context
!= NULL
);
1536 assert(connIsUsable(http
->getConn()));
1538 /* TODO: check offset is what we asked for */
1540 if (context
!= http
->getConn()->getCurrentContext()) {
1541 context
->deferRecipientForLater(node
, rep
, receivedData
);
1542 PROF_stop(clientSocketRecipient
);
1546 // After sending Transfer-Encoding: chunked (at least), always send
1547 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1548 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1549 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1550 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1551 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1552 PROF_stop(clientSocketRecipient
);
1556 if (!context
->startOfOutput())
1557 context
->sendBody(rep
, receivedData
);
1560 http
->al
->reply
= rep
;
1561 HTTPMSGLOCK(http
->al
->reply
);
1562 context
->sendStartOfMessage(rep
, receivedData
);
1565 PROF_stop(clientSocketRecipient
);
1569 * Called when a downstream node is no longer interested in
1570 * our data. As we are a terminal node, this means on aborts
1574 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1576 /* Test preconditions */
1577 assert(node
!= NULL
);
1578 /* TODO: handle this rather than asserting
1579 * - it should only ever happen if we cause an abort and
1580 * the callback chain loops back to here, so we can simply return.
1581 * However, that itself shouldn't happen, so it stays as an assert for now.
1583 assert(cbdataReferenceValid(node
));
1584 /* Set null by ContextFree */
1585 assert(node
->node
.next
== NULL
);
1586 /* this is the assert discussed above */
1587 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1588 /* We are only called when the client socket shutsdown.
1589 * Tell the prev pipeline member we're finished
1591 clientStreamDetach(node
, http
);
1595 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1597 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1598 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1602 ConnStateData::readNextRequest()
1604 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1606 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1608 * Set the timeout BEFORE calling clientReadRequest().
1610 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1611 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1612 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1613 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1616 /** Please don't do anything with the FD past here! */
1620 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1622 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1624 /** If the client stream is waiting on a socket write to occur, then */
1626 if (deferredRequest
->flags
.deferred
) {
1627 /** NO data is allowed to have been sent. */
1628 assert(deferredRequest
->http
->out
.size
== 0);
1630 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1631 deferredRequest
->http
,
1632 deferredRequest
->deferredparams
.rep
,
1633 deferredRequest
->deferredparams
.queuedBuffer
);
1636 /** otherwise, the request is still active in a callbacksomewhere,
1641 /// called when we have successfully finished writing the response
1643 ClientSocketContext::keepaliveNextRequest()
1645 ConnStateData
* conn
= http
->getConn();
1647 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1650 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1651 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1652 conn
->clientConnection
->close();
1657 * We are done with the response, and we are either still receiving request
1658 * body (early response!) or have already stopped receiving anything.
1660 * If we are still receiving, then clientParseRequest() below will fail.
1661 * (XXX: but then we will call readNextRequest() which may succeed and
1662 * execute a smuggled request as we are not done with the current request).
1664 * If we stopped because we got everything, then try the next request.
1666 * If we stopped receiving because of an error, then close now to avoid
1667 * getting stuck and to prevent accidental request smuggling.
1670 if (const char *reason
= conn
->stoppedReceiving()) {
1671 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1672 conn
->clientConnection
->close();
1677 * Attempt to parse a request from the request buffer.
1678 * If we've been fed a pipelined request it may already
1679 * be in our read buffer.
1682 * This needs to fall through - if we're unlucky and parse the _last_ request
1683 * from our read buffer we may never re-register for another client read.
1686 if (conn
->clientParseRequests()) {
1687 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1691 * Either we need to kick-start another read or, if we have
1692 * a half-closed connection, kill it after the last request.
1693 * This saves waiting for half-closed connections to finished being
1694 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1695 * the keepalive "Waiting for next request" state.
1697 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1698 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1699 conn
->clientConnection
->close();
1703 ClientSocketContext::Pointer deferredRequest
;
1706 * At this point we either have a parsed request (which we've
1707 * kicked off the processing for) or not. If we have a deferred
1708 * request (parsed but deferred for pipeling processing reasons)
1709 * then look at processing it. If not, simply kickstart
1713 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1714 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1715 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1716 } else if (conn
->flags
.readMore
) {
1717 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1718 conn
->readNextRequest();
1720 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1721 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1726 clientUpdateSocketStats(LogTags logType
, size_t size
)
1731 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1733 if (logTypeIsATcpHit(logType
))
1734 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1738 * increments iterator "i"
1739 * used by clientPackMoreRanges
1741 \retval true there is still data available to pack more ranges
1745 ClientSocketContext::canPackMoreRanges() const
1747 /** first update iterator "i" if needed */
1749 if (!http
->range_iter
.debt()) {
1750 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1752 if (http
->range_iter
.pos
.incrementable())
1753 ++http
->range_iter
.pos
;
1755 http
->range_iter
.updateSpec();
1758 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1760 /* paranoid sync condition */
1761 /* continue condition: need_more_data */
1762 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1763 return http
->range_iter
.currentSpec() ? true : false;
1767 ClientSocketContext::getNextRangeOffset() const
1769 if (http
->request
->range
) {
1770 /* offset in range specs does not count the prefix of an http msg */
1771 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1772 /* check: reply was parsed and range iterator was initialized */
1773 assert(http
->range_iter
.valid
);
1774 /* filter out data according to range specs */
1775 assert (canPackMoreRanges());
1777 int64_t start
; /* offset of still missing data */
1778 assert(http
->range_iter
.currentSpec());
1779 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1780 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1781 debugs(33, 3, "clientPackMoreRanges: out:"
1782 " start: " << start
<<
1783 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1784 " [" << http
->range_iter
.currentSpec()->offset
<<
1785 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1786 " len: " << http
->range_iter
.currentSpec()->length
<<
1787 " debt: " << http
->range_iter
.debt());
1788 if (http
->range_iter
.currentSpec()->length
!= -1)
1789 assert(http
->out
.offset
<= start
); /* we did not miss it */
1794 } else if (reply
&& reply
->content_range
) {
1795 /* request does not have ranges, but reply does */
1796 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1797 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1799 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1802 return http
->out
.offset
;
1806 ClientSocketContext::pullData()
1808 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1810 /* More data will be coming from the stream. */
1811 StoreIOBuffer readBuffer
;
1812 /* XXX: Next requested byte in the range sequence */
1813 /* XXX: length = getmaximumrangelenfgth */
1814 readBuffer
.offset
= getNextRangeOffset();
1815 readBuffer
.length
= HTTP_REQBUF_SZ
;
1816 readBuffer
.data
= reqbuf
;
1817 /* we may note we have reached the end of the wanted ranges */
1818 clientStreamRead(getTail(), http
, readBuffer
);
1821 clientStream_status_t
1822 ClientSocketContext::socketState()
1824 switch (clientStreamStatus(getTail(), http
)) {
1827 /* check for range support ending */
1829 if (http
->request
->range
) {
1830 /* check: reply was parsed and range iterator was initialized */
1831 assert(http
->range_iter
.valid
);
1832 /* filter out data according to range specs */
1834 if (!canPackMoreRanges()) {
1835 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1836 "range sequence on " << clientConnection
);
1838 if (http
->request
->flags
.proxyKeepalive
)
1839 return STREAM_COMPLETE
;
1841 return STREAM_UNPLANNED_COMPLETE
;
1843 } else if (reply
&& reply
->content_range
) {
1844 /* reply has content-range, but Squid is not managing ranges */
1845 const int64_t &bytesSent
= http
->out
.offset
;
1846 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1848 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1849 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1850 reply
->content_range
->spec
.offset
<< ")");
1852 // did we get at least what we expected, based on range specs?
1854 if (bytesSent
== bytesExpected
) { // got everything
1855 if (http
->request
->flags
.proxyKeepalive
)
1856 return STREAM_COMPLETE
;
1858 return STREAM_UNPLANNED_COMPLETE
;
1861 // The logic below is not clear: If we got more than we
1862 // expected why would persistency matter? Should not this
1863 // always be an error?
1864 if (bytesSent
> bytesExpected
) { // got extra
1865 if (http
->request
->flags
.proxyKeepalive
)
1866 return STREAM_COMPLETE
;
1868 return STREAM_UNPLANNED_COMPLETE
;
1871 // did not get enough yet, expecting more
1876 case STREAM_COMPLETE
:
1877 return STREAM_COMPLETE
;
1879 case STREAM_UNPLANNED_COMPLETE
:
1880 return STREAM_UNPLANNED_COMPLETE
;
1883 return STREAM_FAILED
;
1886 fatal ("unreachable code\n");
1891 * A write has just completed to the client, or we have just realised there is
1892 * no more data to send.
1895 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1897 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1898 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1901 /// remembers the abnormal connection termination for logging purposes
1903 ClientSocketContext::noteIoError(const int xerrno
)
1906 if (xerrno
== ETIMEDOUT
)
1907 http
->al
->http
.timedout
= true;
1908 else // even if xerrno is zero (which means read abort/eof)
1909 http
->al
->http
.aborted
= true;
1914 ClientSocketContext::doClose()
1916 clientConnection
->close();
1919 /// called when we encounter a response-related error
1921 ClientSocketContext::initiateClose(const char *reason
)
1923 http
->getConn()->stopSending(reason
); // closes ASAP
1927 ConnStateData::stopSending(const char *error
)
1929 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1930 "; old receiving error: " <<
1931 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1933 if (const char *oldError
= stoppedSending()) {
1934 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1935 return; // nothing has changed as far as this connection is concerned
1937 stoppedSending_
= error
;
1939 if (!stoppedReceiving()) {
1940 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1941 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1942 " request body bytes with " << in
.notYetUsed
<< " unused");
1943 return; // wait for the request receiver to finish reading
1947 clientConnection
->close();
1951 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1953 const StoreEntry
*entry
= http
->storeEntry();
1954 http
->out
.size
+= size
;
1955 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1956 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1957 (entry
? entry
->objectLen() : 0));
1958 clientUpdateSocketStats(http
->logType
, size
);
1960 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1962 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1965 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1966 initiateClose("failure or true request status");
1967 /* Do we leak here ? */
1971 switch (socketState()) {
1977 case STREAM_COMPLETE
:
1978 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1979 keepaliveNextRequest();
1982 case STREAM_UNPLANNED_COMPLETE
:
1983 initiateClose("STREAM_UNPLANNED_COMPLETE");
1987 initiateClose("STREAM_FAILED");
1991 fatal("Hit unreachable code in clientWriteComplete\n");
1995 SQUIDCEXTERN CSR clientGetMoreData
;
1996 SQUIDCEXTERN CSS clientReplyStatus
;
1997 SQUIDCEXTERN CSD clientReplyDetach
;
1999 static ClientSocketContext
*
2000 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
2002 ClientHttpRequest
*http
;
2003 ClientSocketContext
*context
;
2004 StoreIOBuffer tempBuffer
;
2005 http
= new ClientHttpRequest(csd
);
2006 http
->req_sz
= csd
->in
.notYetUsed
;
2007 http
->uri
= xstrdup(uri
);
2008 setLogUri (http
, uri
);
2009 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
2010 tempBuffer
.data
= context
->reqbuf
;
2011 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2012 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2013 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
2014 clientSocketDetach
, context
, tempBuffer
);
2019 skipLeadingSpace(char *aString
)
2021 char *result
= aString
;
2023 while (xisspace(*aString
))
2030 * 'end' defaults to NULL for backwards compatibility
2031 * remove default value if we ever get rid of NULL-terminated
2035 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
2038 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
2042 for (; end
> uriAndHTTPVersion
; --end
) {
2043 if (*end
== '\n' || *end
== '\r')
2046 if (xisspace(*end
)) {
2047 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2058 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2060 safe_free(http
->log_uri
);
2063 // The uri is already clean just dump it.
2064 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2067 switch (Config
.uri_whitespace
) {
2068 case URI_WHITESPACE_ALLOW
:
2069 flags
|= RFC1738_ESCAPE_NOSPACE
;
2071 case URI_WHITESPACE_ENCODE
:
2072 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2073 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2076 case URI_WHITESPACE_CHOP
: {
2077 flags
|= RFC1738_ESCAPE_NOSPACE
;
2078 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2079 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2080 int pos
= strcspn(http
->log_uri
, w_space
);
2081 http
->log_uri
[pos
] = '\0';
2085 case URI_WHITESPACE_DENY
:
2086 case URI_WHITESPACE_STRIP
:
2089 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2093 if (!xisspace(*t
)) {
2100 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2109 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2111 int vhost
= conn
->port
->vhost
;
2112 int vport
= conn
->port
->vport
;
2114 char ipbuf
[MAX_IPSTRLEN
];
2116 http
->flags
.accel
= true;
2118 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2120 if (strncasecmp(url
, "cache_object://", 15) == 0)
2121 return; /* already in good shape */
2124 if (conn
->port
->vhost
)
2125 return; /* already in good shape */
2127 /* else we need to ignore the host name */
2128 url
= strstr(url
, "//");
2130 #if SHOULD_REJECT_UNKNOWN_URLS
2133 hp
->request_parse_status
= Http::scBadRequest
;
2134 return parseHttpRequestAbort(conn
, "error:invalid-request");
2139 url
= strchr(url
+ 2, '/');
2146 vport
= http
->getConn()->clientConnection
->local
.port();
2148 const bool switchedToHttps
= conn
->switchedToHttps();
2149 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2150 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2151 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2156 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2157 strncpy(thost
, host
, (t
-host
));
2158 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2161 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2164 } // else nothing to alter port-wise.
2165 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2167 http
->uri
= (char *)xcalloc(url_sz
, 1);
2168 const char *protocol
= switchedToHttps
?
2169 "https" : conn
->port
->protocol
;
2170 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2171 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2172 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2173 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2174 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2175 strlen(conn
->port
->defaultsite
);
2176 http
->uri
= (char *)xcalloc(url_sz
, 1);
2180 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2182 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2183 conn
->port
->protocol
, conn
->port
->defaultsite
, vportStr
, url
);
2184 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2185 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2186 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2187 /* Put the local socket IP address as the hostname, with whatever vport we found */
2188 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2189 http
->uri
= (char *)xcalloc(url_sz
, 1);
2190 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2191 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2192 http
->getConn()->port
->protocol
,
2194 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2199 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2202 char ipbuf
[MAX_IPSTRLEN
];
2205 return; /* already in good shape */
2207 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2209 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2210 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2212 http
->uri
= (char *)xcalloc(url_sz
, 1);
2213 snprintf(http
->uri
, url_sz
, "%s://%s%s", conn
->port
->protocol
, host
, url
);
2214 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2216 /* Put the local socket IP address as the hostname. */
2217 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2218 http
->uri
= (char *)xcalloc(url_sz
, 1);
2219 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2220 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2221 http
->getConn()->port
->protocol
,
2222 ipbuf
, http
->getConn()->clientConnection
->local
.port(), url
);
2223 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2227 /** Parse an HTTP request
2229 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2230 * to 1 if the request was correctly parsed.
2231 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2232 * \param[in] hp an HttpParser
2233 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2234 * Pointed-to value will be set to Http::METHOD_NONE in case of
2236 * \param[out] http_ver will be set as a side-effect of the parsing
2237 * \return NULL on incomplete requests,
2238 * a ClientSocketContext structure on success or failure.
2240 static ClientSocketContext
*
2241 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2243 char *req_hdr
= NULL
;
2246 ClientHttpRequest
*http
;
2247 ClientSocketContext
*result
;
2248 StoreIOBuffer tempBuffer
;
2251 /* pre-set these values to make aborting simpler */
2252 *method_p
= Http::METHOD_NONE
;
2254 /* NP: don't be tempted to move this down or remove again.
2255 * It's the only DDoS protection old-String has against long URL */
2256 if ( hp
->bufsiz
<= 0) {
2257 debugs(33, 5, "Incomplete request, waiting for end of request line");
2259 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2260 debugs(33, 5, "parseHttpRequest: Too large request");
2261 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2262 return parseHttpRequestAbort(csd
, "error:request-too-large");
2265 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2266 r
= HttpParserParseReqLine(hp
);
2269 debugs(33, 5, "Incomplete request, waiting for end of request line");
2274 return parseHttpRequestAbort(csd
, "error:invalid-request");
2277 /* Request line is valid here .. */
2278 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2280 /* This call scans the entire request, not just the headers */
2281 if (hp
->req
.v_maj
> 0) {
2282 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2283 debugs(33, 5, "Incomplete request, waiting for end of headers");
2287 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2288 req_sz
= HttpParserReqSz(hp
);
2291 /* We know the whole request is in hp->buf now */
2293 assert(req_sz
<= (size_t) hp
->bufsiz
);
2295 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2296 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2299 hp
->hdr_end
= req_sz
- 1;
2301 hp
->hdr_start
= hp
->req
.end
+ 1;
2303 /* Enforce max_request_size */
2304 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2305 debugs(33, 5, "parseHttpRequest: Too large request");
2306 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2307 return parseHttpRequestAbort(csd
, "error:request-too-large");
2311 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2313 /* deny CONNECT via accelerated ports */
2314 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2315 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->protocol
<< " Accelerator port " << csd
->port
->s
.port() );
2316 /* XXX need a way to say "this many character length string" */
2317 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2318 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2319 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2322 if (*method_p
== Http::METHOD_NONE
) {
2323 /* XXX need a way to say "this many character length string" */
2324 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2325 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2326 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2330 * Process headers after request line
2331 * TODO: Use httpRequestParse here.
2333 /* XXX this code should be modified to take a const char * later! */
2334 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2336 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2338 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2340 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2342 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2343 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2344 HttpParserReqSz(hp
));
2346 /* Ok, all headers are received */
2347 http
= new ClientHttpRequest(csd
);
2349 http
->req_sz
= HttpParserRequestLen(hp
);
2350 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2351 tempBuffer
.data
= result
->reqbuf
;
2352 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2354 ClientStreamData newServer
= new clientReplyContext(http
);
2355 ClientStreamData newClient
= result
;
2356 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2357 clientReplyStatus
, newServer
, clientSocketRecipient
,
2358 clientSocketDetach
, newClient
, tempBuffer
);
2360 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2364 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2365 * below needs to be modified to not expect a mutable nul-terminated string.
2367 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2369 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2371 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2373 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2375 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2380 debugs(33,5, HERE
<< "repare absolute URL from " <<
2381 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2382 /* Rewrite the URL in transparent or accelerator mode */
2383 /* NP: there are several cases to traverse here:
2384 * - standard mode (forward proxy)
2385 * - transparent mode (TPROXY)
2386 * - transparent mode with failures
2387 * - intercept mode (NAT)
2388 * - intercept mode with failures
2389 * - accelerator mode (reverse proxy)
2391 * - mixed combos of the above with internal URL
2393 if (csd
->transparent()) {
2394 /* intercept or transparent mode, properly working with no failures */
2395 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2397 } else if (internalCheck(url
)) {
2398 /* internal URL mode */
2399 /* prepend our name & port */
2400 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2401 // We just re-wrote the URL. Must replace the Host: header.
2402 // But have not parsed there yet!! flag for local-only handling.
2403 http
->flags
.internal
= true;
2405 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2406 /* accelerator mode */
2407 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2411 /* No special rewrites have been applied above, use the
2412 * requested url. may be rewritten later, so make extra room */
2413 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2414 http
->uri
= (char *)xcalloc(url_sz
, 1);
2415 strcpy(http
->uri
, url
);
2418 debugs(33, 5, "parseHttpRequest: Complete request received");
2420 // XXX: crop this dump at the end of headers. No need for extras
2421 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2422 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2424 result
->flags
.parsed_ok
= 1;
2430 ConnStateData::getAvailableBufferLength() const
2432 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2433 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2434 // huge request_header_max_size may lead to more than INT_MAX unused space
2435 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2440 ConnStateData::maybeMakeSpaceAvailable()
2442 if (getAvailableBufferLength() < 2) {
2444 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2445 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2448 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2449 newSize
=Config
.maxRequestBufferSize
;
2451 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2452 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2458 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2460 ClientSocketContext::Pointer
*S
;
2462 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2470 ConnStateData::getConcurrentRequestCount() const
2473 ClientSocketContext::Pointer
*T
;
2475 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2476 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2481 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2483 if (flag
!= COMM_OK
) {
2484 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2489 if (!ignoreErrno(xerrno
)) {
2490 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2492 } else if (in
.notYetUsed
== 0) {
2493 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2501 ConnStateData::connFinishedWithConn(int size
)
2504 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2505 /* no current or pending requests */
2506 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2508 } else if (!Config
.onoff
.half_closed_clients
) {
2509 /* admin doesn't want to support half-closed client sockets */
2510 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2511 notifyAllContexts(0); // no specific error implies abort
2520 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2522 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2523 conn
->in
.notYetUsed
-= byteCount
;
2524 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2526 * If there is still data that will be used,
2527 * move it to the beginning.
2530 if (conn
->in
.notYetUsed
> 0)
2531 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2534 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2536 ConnStateData::checkHeaderLimits()
2538 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2539 return; // can accumulte more header data
2541 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2542 Config
.maxRequestHeaderSize
<< " bytes)");
2544 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2545 clientStreamNode
*node
= context
->getClientReplyContext();
2546 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2547 assert (repContext
);
2548 repContext
->setReplyToError(ERR_TOO_BIG
,
2549 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2550 clientConnection
->remote
, NULL
, NULL
, NULL
);
2551 context
->registerWithConn();
2552 context
->pullData();
2556 ConnStateData::clientAfterReadingRequests()
2558 // Were we expecting to read more request body from half-closed connection?
2559 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2560 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2561 clientConnection
->close();
2570 ConnStateData::quitAfterError(HttpRequest
*request
)
2572 // From HTTP p.o.v., we do not have to close after every error detected
2573 // at the client-side, but many such errors do require closure and the
2574 // client-side code is bad at handling errors so we play it safe.
2576 request
->flags
.proxyKeepalive
= false;
2577 flags
.readMore
= false;
2578 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2582 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2584 ClientHttpRequest
*http
= context
->http
;
2589 assert(sslServerBump
->entry
);
2590 // Did we create an error entry while processing CONNECT?
2591 if (!sslServerBump
->entry
->isEmpty()) {
2592 quitAfterError(http
->request
);
2594 // Get the saved error entry and send it to the client by replacing the
2595 // ClientHttpRequest store entry with it.
2596 clientStreamNode
*node
= context
->getClientReplyContext();
2597 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2599 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2600 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2602 // save the original request for logging purposes
2603 if (!context
->http
->al
->request
) {
2604 context
->http
->al
->request
= http
->request
;
2605 HTTPMSGLOCK(context
->http
->al
->request
);
2608 // Get error details from the fake certificate-peeking request.
2609 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2610 context
->pullData();
2614 // In bump-server-first mode, we have not necessarily seen the intended
2615 // server name at certificate-peeking time. Check for domain mismatch now,
2616 // when we can extract the intended name from the bumped HTTP request.
2617 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2618 HttpRequest
*request
= http
->request
;
2619 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2620 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2621 "does not match domainname " << request
->GetHost());
2623 bool allowDomainMismatch
= false;
2624 if (Config
.ssl_client
.cert_error
) {
2625 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2626 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2627 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2628 delete check
.sslErrors
;
2629 check
.sslErrors
= NULL
;
2632 if (!allowDomainMismatch
) {
2633 quitAfterError(request
);
2635 clientStreamNode
*node
= context
->getClientReplyContext();
2636 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2637 assert (repContext
);
2639 // Fill the server IP and hostname for error page generation.
2640 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2641 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2643 // Create an error object and fill it
2644 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2645 err
->src_addr
= clientConnection
->remote
;
2646 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2647 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2649 err
->detail
= errDetail
;
2650 // Save the original request for logging purposes.
2651 if (!context
->http
->al
->request
) {
2652 context
->http
->al
->request
= request
;
2653 HTTPMSGLOCK(context
->http
->al
->request
);
2655 repContext
->setReplyToError(request
->method
, err
);
2656 assert(context
->http
->out
.offset
== 0);
2657 context
->pullData();
2668 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2670 ClientHttpRequest
*http
= context
->http
;
2671 HttpRequest::Pointer request
;
2672 bool notedUseOfBuffer
= false;
2673 bool chunked
= false;
2674 bool mustReplyToOptions
= false;
2675 bool unsupportedTe
= false;
2676 bool expectBody
= false;
2678 /* We have an initial client stream in place should it be needed */
2679 /* setup our private context */
2680 context
->registerWithConn();
2682 if (context
->flags
.parsed_ok
== 0) {
2683 clientStreamNode
*node
= context
->getClientReplyContext();
2684 debugs(33, 2, "clientProcessRequest: Invalid Request");
2685 conn
->quitAfterError(NULL
);
2686 // setLogUri should called before repContext->setReplyToError
2687 setLogUri(http
, http
->uri
, true);
2688 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2689 assert (repContext
);
2690 switch (hp
->request_parse_status
) {
2691 case Http::scHeaderTooLarge
:
2692 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2694 case Http::scMethodNotAllowed
:
2695 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2696 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2699 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2700 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2702 assert(context
->http
->out
.offset
== 0);
2703 context
->pullData();
2707 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2708 clientStreamNode
*node
= context
->getClientReplyContext();
2709 debugs(33, 5, "Invalid URL: " << http
->uri
);
2710 conn
->quitAfterError(request
.getRaw());
2711 // setLogUri should called before repContext->setReplyToError
2712 setLogUri(http
, http
->uri
, true);
2713 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2714 assert (repContext
);
2715 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2716 assert(context
->http
->out
.offset
== 0);
2717 context
->pullData();
2721 /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */
2722 /* We currently only accept 0.9, 1.0, 1.1 */
2723 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2724 (http_ver
.major
== 1 && http_ver
.minor
> 1 ) ||
2725 (http_ver
.major
> 1) ) {
2727 clientStreamNode
*node
= context
->getClientReplyContext();
2728 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2729 conn
->quitAfterError(request
.getRaw());
2730 // setLogUri should called before repContext->setReplyToError
2731 setLogUri(http
, http
->uri
, true);
2732 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2733 assert (repContext
);
2734 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2735 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2736 assert(context
->http
->out
.offset
== 0);
2737 context
->pullData();
2741 /* compile headers */
2742 /* we should skip request line! */
2743 /* XXX should actually know the damned buffer size here */
2744 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2745 clientStreamNode
*node
= context
->getClientReplyContext();
2746 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2747 conn
->quitAfterError(request
.getRaw());
2748 // setLogUri should called before repContext->setReplyToError
2749 setLogUri(http
, http
->uri
, true);
2750 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2751 assert (repContext
);
2752 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2753 assert(context
->http
->out
.offset
== 0);
2754 context
->pullData();
2758 request
->clientConnectionManager
= conn
;
2760 request
->flags
.accelerated
= http
->flags
.accel
;
2761 request
->flags
.sslBumped
=conn
->switchedToHttps();
2762 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2763 // TODO: decouple http->flags.accel from request->flags.sslBumped
2764 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2765 !conn
->port
->allow_direct
: 0;
2767 if (request
->flags
.sslBumped
) {
2768 if (conn
->getAuth() != NULL
)
2769 request
->auth_user_request
= conn
->getAuth();
2774 * If transparent or interception mode is working clone the transparent and interception flags
2775 * from the port settings to the request.
2777 if (http
->clientConnection
!= NULL
) {
2778 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2779 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2780 if (request
->flags
.interceptTproxy
) {
2781 if (Config
.accessList
.spoof_client_ip
) {
2782 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2783 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2786 request
->flags
.spoofClientIp
= true;
2788 request
->flags
.spoofClientIp
= false;
2791 if (internalCheck(request
->urlpath
.termedBuf())) {
2792 if (internalHostnameIs(request
->GetHost()) &&
2793 request
->port
== getMyPort()) {
2794 http
->flags
.internal
= true;
2795 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2796 request
->SetHost(internalHostname());
2797 request
->port
= getMyPort();
2798 http
->flags
.internal
= true;
2802 if (http
->flags
.internal
) {
2803 request
->protocol
= AnyP::PROTO_HTTP
;
2804 request
->login
[0] = '\0';
2807 request
->flags
.internal
= http
->flags
.internal
;
2808 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2809 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2810 #if FOLLOW_X_FORWARDED_FOR
2811 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2812 // not a details about teh TCP connection itself
2813 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2814 #endif /* FOLLOW_X_FORWARDED_FOR */
2815 request
->my_addr
= conn
->clientConnection
->local
;
2816 request
->myportname
= conn
->port
->name
;
2817 request
->http_ver
= http_ver
;
2819 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2820 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2821 request
->clientConnectionManager
= conn
;
2823 if (request
->header
.chunked()) {
2825 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2826 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2827 // HTTP/1.1 requires chunking to be the last encoding if there is one
2828 unsupportedTe
= te
.size() && te
!= "identity";
2829 } // else implied identity coding
2831 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2832 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2833 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2834 clientStreamNode
*node
= context
->getClientReplyContext();
2835 conn
->quitAfterError(request
.getRaw());
2836 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2837 assert (repContext
);
2838 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2839 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2840 assert(context
->http
->out
.offset
== 0);
2841 context
->pullData();
2845 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2846 clientStreamNode
*node
= context
->getClientReplyContext();
2847 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2848 assert (repContext
);
2849 conn
->quitAfterError(request
.getRaw());
2850 repContext
->setReplyToError(ERR_INVALID_REQ
,
2851 Http::scLengthRequired
, request
->method
, NULL
,
2852 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2853 assert(context
->http
->out
.offset
== 0);
2854 context
->pullData();
2858 if (request
->header
.has(HDR_EXPECT
)) {
2859 const String expect
= request
->header
.getList(HDR_EXPECT
);
2860 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2861 if (!supportedExpect
) {
2862 clientStreamNode
*node
= context
->getClientReplyContext();
2863 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2864 assert (repContext
);
2865 conn
->quitAfterError(request
.getRaw());
2866 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2867 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2868 assert(context
->http
->out
.offset
== 0);
2869 context
->pullData();
2874 http
->request
= request
.getRaw();
2875 HTTPMSGLOCK(http
->request
);
2876 clientSetKeepaliveFlag(http
);
2878 // Let tunneling code be fully responsible for CONNECT requests
2879 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2880 context
->mayUseConnection(true);
2881 conn
->flags
.readMore
= false;
2885 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2889 /* Do we expect a request-body? */
2890 expectBody
= chunked
|| request
->content_length
> 0;
2891 if (!context
->mayUseConnection() && expectBody
) {
2892 request
->body_pipe
= conn
->expectRequestBody(
2893 chunked
? -1 : request
->content_length
);
2895 // consume header early so that body pipe gets just the body
2896 connNoteUseOfBuffer(conn
, http
->req_sz
);
2897 notedUseOfBuffer
= true;
2899 /* Is it too large? */
2900 if (!chunked
&& // if chunked, we will check as we accumulate
2901 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2902 clientStreamNode
*node
= context
->getClientReplyContext();
2903 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2904 assert (repContext
);
2905 conn
->quitAfterError(request
.getRaw());
2906 repContext
->setReplyToError(ERR_TOO_BIG
,
2907 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2908 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2909 assert(context
->http
->out
.offset
== 0);
2910 context
->pullData();
2914 // We may stop producing, comm_close, and/or call setReplyToError()
2915 // below, so quit on errors to avoid http->doCallouts()
2916 if (!conn
->handleRequestBodyData())
2919 if (!request
->body_pipe
->productionEnded()) {
2920 debugs(33, 5, HERE
<< "need more request body");
2921 context
->mayUseConnection(true);
2922 assert(conn
->flags
.readMore
);
2926 http
->calloutContext
= new ClientRequestContext(http
);
2931 if (!notedUseOfBuffer
)
2932 connNoteUseOfBuffer(conn
, http
->req_sz
);
2936 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2937 * to here because calling comm_reset_close() causes http to
2938 * be freed and the above connNoteUseOfBuffer() would hit an
2939 * assertion, not to mention that we were accessing freed memory.
2941 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2942 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2943 conn
->flags
.readMore
= false;
2944 comm_reset_close(conn
->clientConnection
);
2949 connStripBufferWhitespace (ConnStateData
* conn
)
2951 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2952 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2953 -- conn
->in
.notYetUsed
;
2958 * Limit the number of concurrent requests.
2959 * \return true when there are available position(s) in the pipeline queue for another request.
2960 * \return false when the pipeline queue is full or disabled.
2963 ConnStateData::concurrentRequestQueueFilled() const
2965 const int existingRequestCount
= getConcurrentRequestCount();
2967 // default to the configured pipeline size.
2968 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2969 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2971 // when queue filled already we cant add more.
2972 if (existingRequestCount
>= concurrentRequestLimit
) {
2973 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2974 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2982 * Attempt to parse one or more requests from the input buffer.
2983 * If a request is successfully parsed, even if the next request
2984 * is only partially parsed, it will return TRUE.
2987 ConnStateData::clientParseRequests()
2989 HttpRequestMethod method
;
2990 bool parsed_req
= false;
2992 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2994 // Loop while we have read bytes that are not needed for producing the body
2995 // On errors, bodyPipe may become nil, but readMore will be cleared
2996 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2997 connStripBufferWhitespace(this);
2999 /* Don't try to parse if the buffer is empty */
3000 if (in
.notYetUsed
== 0)
3003 /* Limit the number of concurrent requests */
3004 if (concurrentRequestQueueFilled())
3007 /* Should not be needed anymore */
3008 /* Terminate the string */
3009 in
.buf
[in
.notYetUsed
] = '\0';
3011 /* Begin the parsing */
3012 PROF_start(parseHttpRequest
);
3013 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
3015 /* Process request */
3016 Http::ProtocolVersion http_ver
;
3017 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
3018 PROF_stop(parseHttpRequest
);
3020 /* partial or incomplete request */
3022 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
3023 // (which becomes context) but checkHeaderLimits cannot?
3024 checkHeaderLimits();
3028 /* status -1 or 1 */
3030 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
3031 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3032 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
3033 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3035 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
3037 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3039 if (context
->mayUseConnection()) {
3040 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3046 /* XXX where to 'finish' the parsing pass? */
3051 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3053 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3057 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
3059 if (io
.flag
== COMM_ERR_CLOSING
) {
3060 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
3064 assert(Comm::IsConnOpen(clientConnection
));
3065 assert(io
.conn
->fd
== clientConnection
->fd
);
3068 * Don't reset the timeout value here. The timeout value will be
3069 * set to Config.Timeout.request by httpAccept() and
3070 * clientWriteComplete(), and should apply to the request as a
3071 * whole, not individual read() calls. Plus, it breaks our
3072 * lame half-close detection
3074 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3075 notifyAllContexts(io
.xerrno
);
3080 if (io
.flag
== COMM_OK
) {
3082 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3084 // may comm_close or setReplyToError
3085 if (!handleReadData(io
.buf
, io
.size
))
3088 } else if (io
.size
== 0) {
3089 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3091 if (connFinishedWithConn(io
.size
)) {
3092 clientConnection
->close();
3096 /* It might be half-closed, we can't tell */
3097 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3099 commMarkHalfClosed(io
.conn
->fd
);
3101 fd_note(io
.conn
->fd
, "half-closed");
3103 /* There is one more close check at the end, to detect aborted
3104 * (partial) requests. At this point we can't tell if the request
3107 /* Continue to process previously read data */
3111 /* Process next request */
3112 if (getConcurrentRequestCount() == 0)
3113 fd_note(io
.fd
, "Reading next request");
3115 if (!clientParseRequests()) {
3119 * If the client here is half closed and we failed
3120 * to parse a request, close the connection.
3121 * The above check with connFinishedWithConn() only
3122 * succeeds _if_ the buffer is empty which it won't
3123 * be if we have an incomplete request.
3124 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3126 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3127 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3128 clientConnection
->close();
3136 clientAfterReadingRequests();
3140 * called when new request data has been read from the socket
3142 * \retval false called comm_close or setReplyToError (the caller should bail)
3143 * \retval true we did not call comm_close or setReplyToError
3146 ConnStateData::handleReadData(char *buf
, size_t size
)
3148 char *current_buf
= in
.addressToReadInto();
3150 if (buf
!= current_buf
)
3151 memmove(current_buf
, buf
, size
);
3153 in
.notYetUsed
+= size
;
3155 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3157 // if we are reading a body, stuff data into the body pipe
3158 if (bodyPipe
!= NULL
)
3159 return handleRequestBodyData();
3164 * called when new request body data has been buffered in in.buf
3165 * may close the connection if we were closing and piped everything out
3167 * \retval false called comm_close or setReplyToError (the caller should bail)
3168 * \retval true we did not call comm_close or setReplyToError
3171 ConnStateData::handleRequestBodyData()
3173 assert(bodyPipe
!= NULL
);
3177 if (in
.bodyParser
) { // chunked encoding
3178 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3179 abortChunkedRequestBody(error
);
3182 } else { // identity encoding
3183 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3184 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3185 if (!bodyPipe
->mayNeedMoreData()) {
3186 // BodyPipe will clear us automagically when we produced everything
3192 connNoteUseOfBuffer(this, putSize
);
3195 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3197 if (const char *reason
= stoppedSending()) {
3198 /* we've finished reading like good clients,
3199 * now do the close that initiateClose initiated.
3201 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3202 clientConnection
->close();
3210 /// parses available chunked encoded body bytes, checks size, returns errors
3212 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3214 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3216 try { // the parser will throw on errors
3218 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3221 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3222 // add one because MemBuf will assert if it cannot 0-terminate
3223 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3224 raw
.append(in
.buf
, in
.notYetUsed
);
3226 const mb_size_t wasContentSize
= raw
.contentSize();
3227 BodyPipeCheckout
bpc(*bodyPipe
);
3228 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3230 putSize
= wasContentSize
- raw
.contentSize();
3232 // dechunk then check: the size limit applies to _dechunked_ content
3233 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3237 finishDechunkingRequest(true);
3239 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3242 // if chunk parser needs data, then the body pipe must need it too
3243 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3245 // if parser needs more space and we can consume nothing, we will stall
3246 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3247 } catch (...) { // TODO: be more specific
3248 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3249 return ERR_INVALID_REQ
;
3252 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3256 /// quit on errors related to chunked request body handling
3258 ConnStateData::abortChunkedRequestBody(const err_type error
)
3260 finishDechunkingRequest(false);
3262 // XXX: The code below works if we fail during initial request parsing,
3263 // but if we fail when the server-side works already, the server may send
3264 // us its response too, causing various assertions. How to prevent that?
3265 #if WE_KNOW_HOW_TO_SEND_ERRORS
3266 ClientSocketContext::Pointer context
= getCurrentContext();
3267 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3268 clientStreamNode
*node
= context
->getClientReplyContext();
3269 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3271 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3272 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3273 repContext
->setReplyToError(error
, scode
,
3274 repContext
->http
->request
->method
,
3275 repContext
->http
->uri
,
3277 repContext
->http
->request
,
3279 context
->pullData();
3281 // close or otherwise we may get stuck as nobody will notice the error?
3282 comm_reset_close(clientConnection
);
3285 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3286 comm_reset_close(clientConnection
);
3288 flags
.readMore
= false;
3292 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3294 if (!handleRequestBodyData())
3297 // too late to read more body
3298 if (!isOpen() || stoppedReceiving())
3305 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3307 // request reader may get stuck waiting for space if nobody consumes body
3308 if (bodyPipe
!= NULL
)
3309 bodyPipe
->enableAutoConsumption();
3311 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3314 /** general lifetime handler for HTTP requests */
3316 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3319 * Just close the connection to not confuse browsers
3320 * using persistent connections. Some browsers open
3321 * a connection and then do not use it until much
3322 * later (presumeably because the request triggering
3323 * the open has already been completed on another
3326 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3331 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3333 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3334 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3335 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3336 http
->al
->http
.timedout
= true;
3337 if (Comm::IsConnOpen(io
.conn
))
3342 connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
)
3344 ConnStateData
*result
= new ConnStateData
;
3346 result
->clientConnection
= client
;
3347 result
->log_addr
= client
->remote
;
3348 result
->log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3349 result
->in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &result
->in
.allocatedSize
);
3350 result
->port
= cbdataReference(port
);
3352 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3353 (result
->transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3354 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3355 int i
= IP_PMTUDISC_DONT
;
3356 if (setsockopt(client
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3357 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << client
<< " : " << xstrerror());
3359 static bool reported
= false;
3362 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3368 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3369 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, result
, ConnStateData::connStateClosed
);
3370 comm_add_close_handler(client
->fd
, call
);
3372 if (Config
.onoff
.log_fqdn
)
3373 fqdncache_gethostbyaddr(client
->remote
, FQDN_LOOKUP_IF_MISS
);
3376 if (Ident::TheConfig
.identLookup
) {
3377 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3378 identChecklist
.src_addr
= client
->remote
;
3379 identChecklist
.my_addr
= client
->local
;
3380 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3381 Ident::Start(client
, clientIdentDone
, result
);
3385 clientdbEstablished(client
->remote
, 1);
3387 result
->flags
.readMore
= true;
3391 /** Handle a new connection on HTTP socket. */
3393 httpAccept(const CommAcceptCbParams
¶ms
)
3395 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3397 if (params
.flag
!= COMM_OK
) {
3398 // Its possible the call was still queued when the client disconnected
3399 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3403 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3404 fd_note(params
.conn
->fd
, "client http connect");
3406 if (s
->tcp_keepalive
.enabled
) {
3407 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3410 ++ incoming_sockets_accepted
;
3412 // Socket is ready, setup the connection manager to start using it
3413 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3415 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3416 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3417 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3418 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3420 connState
->readSomeData();
3423 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3425 if (Config
.onoff
.client_db
) {
3426 /* it was said several times that client write limiter does not work if client_db is disabled */
3428 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3429 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3431 // TODO: we check early to limit error response bandwith but we
3432 // should recheck when we can honor delay_pool_uses_indirect
3433 // TODO: we should also pass the port details for myportname here.
3434 ch
.src_addr
= params
.conn
->remote
;
3435 ch
.my_addr
= params
.conn
->local
;
3437 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3439 /* pools require explicit 'allow' to assign a client into them */
3440 if (pools
[pool
].access
) {
3441 ch
.accessList
= pools
[pool
].access
;
3442 allow_t answer
= ch
.fastCheck();
3443 if (answer
== ACCESS_ALLOWED
) {
3445 /* request client information from db after we did all checks
3446 this will save hash lookup if client failed checks */
3447 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3450 /* put client info in FDE */
3451 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3453 /* setup write limiter for this request */
3454 const double burst
= floor(0.5 +
3455 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3456 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3459 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3469 /** Create SSL connection structure and update fd_table */
3471 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3473 SSL
*ssl
= SSL_new(sslContext
);
3476 const int ssl_error
= ERR_get_error();
3477 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3482 SSL_set_fd(ssl
, conn
->fd
);
3483 fd_table
[conn
->fd
].ssl
= ssl
;
3484 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3485 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3487 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3488 fd_note(conn
->fd
, "client https start");
3493 /** negotiate an SSL connection */
3495 clientNegotiateSSL(int fd
, void *data
)
3497 ConnStateData
*conn
= (ConnStateData
*)data
;
3499 SSL
*ssl
= fd_table
[fd
].ssl
;
3502 if ((ret
= SSL_accept(ssl
)) <= 0) {
3503 int ssl_error
= SSL_get_error(ssl
, ret
);
3505 switch (ssl_error
) {
3507 case SSL_ERROR_WANT_READ
:
3508 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3511 case SSL_ERROR_WANT_WRITE
:
3512 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3515 case SSL_ERROR_SYSCALL
:
3518 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3524 if (errno
== ECONNRESET
)
3527 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3528 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3535 case SSL_ERROR_ZERO_RETURN
:
3536 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3541 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3542 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3543 " (" << ssl_error
<< "/" << ret
<< ")");
3551 if (SSL_session_reused(ssl
)) {
3552 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3553 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3555 if (do_debug(83, 4)) {
3556 /* Write out the SSL session details.. actually the call below, but
3557 * OpenSSL headers do strange typecasts confusing GCC.. */
3558 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3559 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3560 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
);
3562 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3564 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3565 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3566 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3567 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3568 * Because there are two possible usable cast, if you get an error here, try the other
3569 * commented line. */
3571 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3572 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3576 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3579 /* Note: This does not automatically fflush the log file.. */
3582 debugs(83, 2, "clientNegotiateSSL: New session " <<
3583 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3584 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3588 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3589 SSL_get_cipher(ssl
));
3591 client_cert
= SSL_get_peer_certificate(ssl
);
3593 if (client_cert
!= NULL
) {
3594 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3595 " client certificate: subject: " <<
3596 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3598 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3599 " client certificate: issuer: " <<
3600 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3602 X509_free(client_cert
);
3604 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3605 " has no certificate.");
3608 conn
->readSomeData();
3612 * If SSL_CTX is given, starts reading the SSL handshake.
3613 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3616 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3620 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3622 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3625 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3626 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3627 connState
, ConnStateData::requestTimeout
);
3628 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3631 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3633 char buf
[MAX_IPSTRLEN
];
3634 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3635 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3636 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3637 fakeRequest
->port
= details
->local
.port();
3638 fakeRequest
->clientConnectionManager
= connState
;
3639 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3640 #if FOLLOW_X_FORWARDED_FOR
3641 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3643 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3644 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3645 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3646 fakeRequest
->myportname
= connState
->port
->name
;
3647 if (fakeRequest
->flags
.interceptTproxy
) {
3648 if (Config
.accessList
.spoof_client_ip
) {
3649 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3650 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3652 fakeRequest
->flags
.spoofClientIp
= true;
3654 fakeRequest
->flags
.spoofClientIp
= false;
3655 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3656 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3661 * A callback function to use with the ACLFilledChecklist callback.
3662 * In the case of ACCES_ALLOWED answer initializes a bumped SSL connection,
3663 * else reverts the connection to tunnel mode.
3666 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3668 ConnStateData
*connState
= (ConnStateData
*) data
;
3670 // if the connection is closed or closing, just return.
3671 if (!connState
->isOpen())
3674 // Require both a match and a positive bump mode to work around exceptional
3675 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3676 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3677 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3678 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3679 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3681 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3682 connState
->sslBumpMode
= Ssl::bumpNone
;
3684 // fake a CONNECT request to force connState to tunnel
3685 static char ip
[MAX_IPSTRLEN
];
3686 static char reqStr
[MAX_IPSTRLEN
+ 80];
3687 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3688 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, ip
);
3689 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3691 ret
= connState
->clientParseRequests();
3694 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3695 connState
->clientConnection
->close();
3700 /** handle a new HTTPS connection */
3702 httpsAccept(const CommAcceptCbParams
¶ms
)
3704 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3706 if (params
.flag
!= COMM_OK
) {
3707 // Its possible the call was still queued when the client disconnected
3708 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3712 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3713 fd_note(params
.conn
->fd
, "client https connect");
3715 if (s
->tcp_keepalive
.enabled
) {
3716 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3719 ++incoming_sockets_accepted
;
3721 // Socket is ready, setup the connection manager to start using it
3722 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3724 if (s
->flags
.tunnelSslBumping
) {
3725 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3727 if (!Config
.accessList
.ssl_bump
) {
3728 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3732 // Create a fake HTTP request for ssl_bump ACL check,
3733 // using tproxy/intercept provided destination IP and port.
3734 HttpRequest
*request
= new HttpRequest();
3735 static char ip
[MAX_IPSTRLEN
];
3736 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3737 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3738 request
->port
= params
.conn
->local
.port();
3739 request
->myportname
= s
->name
;
3741 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3742 acl_checklist
->src_addr
= params
.conn
->remote
;
3743 acl_checklist
->my_addr
= s
->s
;
3744 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3747 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3748 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3753 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3755 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3756 state_data
->sslCrtdHandleReply(reply
);
3760 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3762 if (reply
.result
== HelperReply::BrokenHelper
) {
3763 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3764 } else if (!reply
.other().hasContent()) {
3765 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3767 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3768 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3769 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3771 if (reply
.result
!= HelperReply::Okay
) {
3772 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3774 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3775 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3776 getSslContextDone(ctx
, true);
3781 getSslContextDone(NULL
);
3784 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3786 certProperties
.commonName
= sslCommonName
.defined() ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3788 // fake certificate adaptation requires bump-server-first mode
3789 if (!sslServerBump
) {
3790 assert(port
->signingCert
.get());
3791 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3792 if (port
->signPkey
.get())
3793 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3794 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3798 // In case of an error while connecting to the secure server, use a fake
3799 // trusted certificate, with no mimicked fields and no adaptation
3800 // algorithms. There is nothing we can mimic so we want to minimize the
3801 // number of warnings the user will have to see to get to the error page.
3802 assert(sslServerBump
->entry
);
3803 if (sslServerBump
->entry
->isEmpty()) {
3804 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3805 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3807 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3808 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3809 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3811 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3812 // If the algorithm already set, then ignore it.
3813 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3814 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3815 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3818 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3819 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3820 const char *param
= ca
->param
;
3822 // For parameterless CN adaptation, use hostname from the
3824 if (ca
->alg
== Ssl::algSetCommonName
) {
3826 param
= sslConnectHostOrIp
.termedBuf();
3827 certProperties
.commonName
= param
;
3828 certProperties
.setCommonName
= true;
3829 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3830 certProperties
.setValidAfter
= true;
3831 else if (ca
->alg
== Ssl::algSetValidBefore
)
3832 certProperties
.setValidBefore
= true;
3834 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3835 alg
<< " param: " << (param
? param
: "-"));
3839 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3840 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3841 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3842 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3846 } else {// if (!sslServerBump->entry->isEmpty())
3847 // Use trusted certificate for a Squid-generated error
3848 // or the user would have to add a security exception
3849 // just to see the error page. We will close the connection
3850 // so that the trust is not extended to non-Squid content.
3851 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3854 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3856 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3857 assert(port
->untrustedSigningCert
.get());
3858 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3859 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3861 assert(port
->signingCert
.get());
3862 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3864 if (port
->signPkey
.get())
3865 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3867 signAlgorithm
= certProperties
.signAlgorithm
;
3871 ConnStateData::getSslContextStart()
3873 assert(areAllContextsForThisConnection());
3875 /* careful: freeAllContexts() above frees request, host, etc. */
3877 if (port
->generateHostCertificates
) {
3878 Ssl::CertificateProperties certProperties
;
3879 buildSslCertGenerationParams(certProperties
);
3880 sslBumpCertKey
= certProperties
.dbKey().c_str();
3881 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3883 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3884 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3885 SSL_CTX
* dynCtx
= NULL
;
3886 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
.get(sslBumpCertKey
.termedBuf());
3887 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3888 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3889 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3890 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3891 getSslContextDone(dynCtx
);
3894 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3895 ssl_ctx_cache
.del(sslBumpCertKey
.termedBuf());
3898 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3903 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3904 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3905 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3906 request_message
.composeRequest(certProperties
);
3907 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3908 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3910 } catch (const std::exception
&e
) {
3911 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3912 "request for " << certProperties
.commonName
<<
3913 " certificate: " << e
.what() << "; will now block to " <<
3914 "generate that certificate.");
3915 // fall through to do blocking in-process generation.
3917 #endif // USE_SSL_CRTD
3919 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3920 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3921 getSslContextDone(dynCtx
, true);
3924 getSslContextDone(NULL
);
3928 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3930 // Try to add generated ssl context to storage.
3931 if (port
->generateHostCertificates
&& isNew
) {
3933 if (signAlgorithm
== Ssl::algSignTrusted
)
3934 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3935 //else it is self-signed or untrusted do not attrach any certificate
3937 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3938 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3940 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3941 // If it is not in storage delete after using. Else storage deleted it.
3942 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3945 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3949 // If generated ssl context = NULL, try to use static ssl context.
3951 if (!port
->staticSslContext
) {
3952 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3953 clientConnection
->close();
3956 debugs(33, 5, HERE
<< "Using static ssl context.");
3957 sslContext
= port
->staticSslContext
.get();
3961 if (!httpsCreate(clientConnection
, sslContext
))
3964 // commSetConnTimeout() was called for this request before we switched.
3966 // Disable the client read handler until CachePeer selection is complete
3967 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3968 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3969 switchedToHttps_
= true;
3973 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3975 assert(!switchedToHttps_
);
3977 sslConnectHostOrIp
= request
->GetHost();
3978 sslCommonName
= request
->GetHost();
3980 // We are going to read new request
3981 flags
.readMore
= true;
3982 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3984 // If sslServerBump is set, then we have decided to deny CONNECT
3985 // and now want to switch to SSL to send the error to the client
3986 // without even peeking at the origin server certificate.
3987 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3988 request
->flags
.sslPeek
= true;
3989 sslServerBump
= new Ssl::ServerBump(request
);
3991 // will call httpsPeeked() with certificate and connection, eventually
3992 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3996 // otherwise, use sslConnectHostOrIp
3997 getSslContextStart();
4001 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4003 Must(sslServerBump
!= NULL
);
4005 if (Comm::IsConnOpen(serverConnection
)) {
4006 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
4008 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
4009 assert(serverCert
.get() != NULL
);
4010 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4011 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4012 " bumped: " << *serverConnection
);
4014 pinConnection(serverConnection
, NULL
, NULL
, false);
4016 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4018 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4019 Ip::Address intendedDest
;
4020 intendedDest
= sslConnectHostOrIp
.termedBuf();
4021 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4023 // Squid serves its own error page and closes, so we want
4024 // a CN that causes no additional browser errors. Possible
4025 // only when bumping CONNECT with a user-typed address.
4026 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4027 sslCommonName
= sslConnectHostOrIp
;
4028 else if (sslServerBump
->serverCert
.get())
4029 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4031 // copy error detail from bump-server-first request to CONNECT request
4032 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4033 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4036 getSslContextStart();
4039 #endif /* USE_SSL */
4041 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4043 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4045 if (!Comm::IsConnOpen(c
)) {
4046 Must(NHttpSockets
> 0); // we tried to open some
4047 --NHttpSockets
; // there will be fewer sockets than planned
4048 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4050 if (!NHttpSockets
) // we could not open any listen sockets at all
4051 fatalf("Unable to open %s",FdNote(portType
));
4058 /// find any unused HttpSockets[] slot and store fd there or return false
4060 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4063 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4064 if ((found
= HttpSockets
[i
] < 0))
4065 HttpSockets
[i
] = conn
->fd
;
4071 clientHttpConnectionsOpen(void)
4073 AnyP::PortCfg
*s
= NULL
;
4075 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4076 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4077 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4078 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4083 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4084 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4085 s
->flags
.tunnelSslBumping
= false;
4088 if (s
->flags
.tunnelSslBumping
&&
4089 !s
->staticSslContext
&&
4090 !s
->generateHostCertificates
) {
4091 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4092 s
->flags
.tunnelSslBumping
= false;
4094 if (s
->flags
.tunnelSslBumping
) {
4095 // Create ssl_ctx cache for this port.
4096 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4100 // Fill out a Comm::Connection which IPC will open as a listener for us
4101 // then pass back when active so we can start a TcpAcceptor subscription.
4102 s
->listenConn
= new Comm::Connection
;
4103 s
->listenConn
->local
= s
->s
;
4104 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4106 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4107 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4108 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4109 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4111 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4112 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4113 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4115 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4122 clientHttpsConnectionsOpen(void)
4126 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4127 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4128 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4129 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4133 if (!s
->staticSslContext
) {
4134 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4135 " due to SSL initialization failure.");
4139 // TODO: merge with similar code in clientHttpConnectionsOpen()
4140 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4141 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4142 s
->flags
.tunnelSslBumping
= false;
4145 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4146 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4147 s
->flags
.tunnelSslBumping
= false;
4150 if (s
->flags
.tunnelSslBumping
) {
4151 // Create ssl_ctx cache for this port.
4152 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4155 // Fill out a Comm::Connection which IPC will open as a listener for us
4156 s
->listenConn
= new Comm::Connection
;
4157 s
->listenConn
->local
= s
->s
;
4158 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4159 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4161 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4162 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4163 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4164 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4166 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4167 ListeningStartedDialer(&clientListenerConnectionOpened
,
4168 s
, Ipc::fdnHttpsSocket
, sub
));
4169 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4170 HttpSockets
[NHttpSockets
] = -1;
4176 /// process clientHttpConnectionsOpen result
4178 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4180 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4184 Must(Comm::IsConnOpen(s
->listenConn
));
4186 // TCP: setup a job to handle accept() with subscribed handler
4187 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4189 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4190 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4191 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4192 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4193 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4194 << FdNote(portTypeNote
) << " connections at "
4197 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4201 clientOpenListenSockets(void)
4203 clientHttpConnectionsOpen();
4205 clientHttpsConnectionsOpen();
4208 if (NHttpSockets
< 1)
4209 fatal("No HTTP or HTTPS ports configured");
4213 clientHttpConnectionsClose(void)
4215 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4216 if (s
->listenConn
!= NULL
) {
4217 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4218 s
->listenConn
->close();
4219 s
->listenConn
= NULL
;
4224 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4225 if (s
->listenConn
!= NULL
) {
4226 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4227 s
->listenConn
->close();
4228 s
->listenConn
= NULL
;
4233 // TODO see if we can drop HttpSockets array entirely */
4234 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4235 HttpSockets
[i
] = -1;
4242 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4244 const char *vary
= request
->vary_headers
;
4245 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4246 #if X_ACCELERATOR_VARY
4249 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4252 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4254 /* Oops... something odd is going on here.. */
4255 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4256 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4257 safe_free(request
->vary_headers
);
4262 /* This is not a varying object */
4266 /* virtual "vary" object found. Calculate the vary key and
4267 * continue the search
4269 vary
= httpMakeVaryMark(request
, entry
->getReply());
4272 request
->vary_headers
= xstrdup(vary
);
4275 /* Ouch.. we cannot handle this kind of variance */
4276 /* XXX This cannot really happen, but just to be complete */
4281 vary
= httpMakeVaryMark(request
, entry
->getReply());
4284 request
->vary_headers
= xstrdup(vary
);
4288 /* Ouch.. we cannot handle this kind of variance */
4289 /* XXX This cannot really happen, but just to be complete */
4291 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4294 /* Oops.. we have already been here and still haven't
4295 * found the requested variant. Bail out
4297 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4298 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4304 ACLFilledChecklist
*
4305 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4307 ConnStateData
* conn
= http
->getConn();
4308 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4309 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4312 * hack for ident ACL. It needs to get full addresses, and a place to store
4313 * the ident result on persistent connections...
4315 /* connection oriented auth also needs these two lines for it's operation. */
4319 CBDATA_CLASS_INIT(ConnStateData
);
4321 ConnStateData::ConnStateData() :
4322 AsyncJob("ConnStateData"),
4324 sslBumpMode(Ssl::bumpEnd
),
4325 switchedToHttps_(false),
4326 sslServerBump(NULL
),
4328 stoppedSending_(NULL
),
4329 stoppedReceiving_(NULL
)
4331 pinning
.host
= NULL
;
4333 pinning
.pinned
= false;
4334 pinning
.auth
= false;
4335 pinning
.zeroReply
= false;
4336 pinning
.peer
= NULL
;
4340 ConnStateData::transparent() const
4342 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4346 ConnStateData::reading() const
4348 return reader
!= NULL
;
4352 ConnStateData::stopReading()
4355 comm_read_cancel(clientConnection
->fd
, reader
);
4361 ConnStateData::expectRequestBody(int64_t size
)
4363 bodyPipe
= new BodyPipe(this);
4365 bodyPipe
->setBodySize(size
);
4367 startDechunkingRequest();
4372 ConnStateData::mayNeedToReadMoreBody() const
4375 return 0; // request without a body or read/produced all body bytes
4377 if (!bodyPipe
->bodySizeKnown())
4378 return -1; // probably need to read more, but we cannot be sure
4380 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4381 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4383 if (needToProduce
<= haveAvailable
)
4384 return 0; // we have read what we need (but are waiting for pipe space)
4386 return needToProduce
- haveAvailable
;
4390 ConnStateData::stopReceiving(const char *error
)
4392 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4393 "; old sending error: " <<
4394 (stoppedSending() ? stoppedSending_
: "none"));
4396 if (const char *oldError
= stoppedReceiving()) {
4397 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4398 return; // nothing has changed as far as this connection is concerned
4401 stoppedReceiving_
= error
;
4403 if (const char *sendError
= stoppedSending()) {
4404 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4405 clientConnection
->close();
4410 ConnStateData::expectNoForwarding()
4412 if (bodyPipe
!= NULL
) {
4413 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4414 bodyPipe
->expectNoConsumption();
4418 /// initialize dechunking state
4420 ConnStateData::startDechunkingRequest()
4422 Must(bodyPipe
!= NULL
);
4423 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4424 assert(!in
.bodyParser
);
4425 in
.bodyParser
= new ChunkedCodingParser
;
4428 /// put parsed content into input buffer and clean up
4430 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4432 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4434 if (bodyPipe
!= NULL
) {
4435 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4436 BodyPipe::Pointer myPipe
= bodyPipe
;
4437 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4438 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4440 Must(myPipe
->bodySizeKnown());
4441 ClientSocketContext::Pointer context
= getCurrentContext();
4442 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4443 context
->http
->request
->setContentLength(myPipe
->bodySize());
4447 delete in
.bodyParser
;
4448 in
.bodyParser
= NULL
;
4452 ConnStateData::In::addressToReadInto() const
4454 return buf
+ notYetUsed
;
4457 ConnStateData::In::In() : bodyParser(NULL
),
4458 buf (NULL
), notYetUsed (0), allocatedSize (0)
4461 ConnStateData::In::~In()
4464 memFreeBuf(allocatedSize
, buf
);
4465 delete bodyParser
; // TODO: pool
4469 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4472 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4476 ClientSocketContext::Pointer context
= getCurrentContext();
4477 if (context
!= NULL
) {
4478 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4482 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4483 clientConnection
->close();
4486 /// Our close handler called by Comm when the pinned connection is closed
4488 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4490 // FwdState might repin a failed connection sooner than this close
4491 // callback is called for the failed connection.
4492 assert(pinning
.serverConnection
== io
.conn
);
4493 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4494 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4497 debugs(33, 3, "Closing client connection on pinned zero reply.");
4498 clientConnection
->close();
4503 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4505 char desc
[FD_DESC_SZ
];
4507 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4508 if (pinning
.serverConnection
->fd
== pinServer
->fd
)
4512 unpinConnection(); // closes pinned connection, if any, and resets fields
4514 pinning
.serverConnection
= pinServer
;
4516 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4518 // when pinning an SSL bumped connection, the request may be NULL
4519 const char *pinnedHost
= "[unknown]";
4521 pinning
.host
= xstrdup(request
->GetHost());
4522 pinning
.port
= request
->port
;
4523 pinnedHost
= pinning
.host
;
4525 pinning
.port
= pinServer
->remote
.port();
4527 pinning
.pinned
= true;
4529 pinning
.peer
= cbdataReference(aPeer
);
4530 pinning
.auth
= auth
;
4531 char stmp
[MAX_IPSTRLEN
];
4532 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4533 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4534 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4535 clientConnection
->fd
);
4536 fd_note(pinning
.serverConnection
->fd
, desc
);
4538 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4539 pinning
.closeHandler
= JobCallback(33, 5,
4540 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4541 // remember the pinned connection so that cb does not unpin a fresher one
4542 typedef CommCloseCbParams Params
;
4543 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4544 params
.conn
= pinning
.serverConnection
;
4545 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4548 const Comm::ConnectionPointer
4549 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4551 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4554 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4556 if (pinning
.auth
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0) {
4559 if (request
&& pinning
.port
!= request
->port
) {
4562 if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
)) {
4565 if (aPeer
!= pinning
.peer
) {
4570 /* The pinning info is not safe, remove any pinning info */
4574 return pinning
.serverConnection
;
4578 ConnStateData::unpinConnection()
4580 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4583 cbdataReferenceDone(pinning
.peer
);
4585 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4586 if (pinning
.closeHandler
!= NULL
) {
4587 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4588 pinning
.closeHandler
= NULL
;
4590 /// also close the server side socket, we should not use it for any future requests...
4591 // TODO: do not close if called from our close handler?
4592 pinning
.serverConnection
->close();
4595 safe_free(pinning
.host
);
4597 pinning
.zeroReply
= false;
4599 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4600 * connection has gone away */