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.h"
90 #include "client_side_reply.h"
91 #include "client_side_request.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/context_storage.h"
140 #include "ssl/gadgets.h"
141 #include "ssl/helper.h"
142 #include "ssl/ProxyCerts.h"
143 #include "ssl/ServerBump.h"
144 #include "ssl/support.h"
147 #include "ssl/certificate_db.h"
148 #include "ssl/crtd_message.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
);
196 /* Local functions */
197 static IOCB clientWriteComplete
;
198 static IOCB clientWriteBodyComplete
;
199 static IOACB httpAccept
;
201 static IOACB httpsAccept
;
203 static CTCB clientLifetimeTimeout
;
204 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
205 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, Http::ProtocolVersion
*);
207 static IDCB clientIdentDone
;
209 static CSCB clientSocketRecipient
;
210 static CSD clientSocketDetach
;
211 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
212 static int clientIsContentLengthValid(HttpRequest
* r
);
213 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
215 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
216 static void clientUpdateStatCounters(LogTags logType
);
217 static void clientUpdateHierCounters(HierarchyLogEntry
*);
218 static bool clientPingHasFinished(ping_data
const *aPing
);
219 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
221 static bool connIsUsable(ConnStateData
* conn
);
223 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
224 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
225 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
227 char *skipLeadingSpace(char *aString
);
228 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
231 ClientSocketContext::getTail() const
233 if (http
->client_stream
.tail
)
234 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
240 ClientSocketContext::getClientReplyContext() const
242 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
246 * This routine should be called to grow the inbuf and then
250 ConnStateData::readSomeData()
255 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
257 if (!maybeMakeSpaceAvailable())
260 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
261 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
262 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
266 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
268 ClientSocketContext::Pointer
*tempContextPointer
;
269 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
270 assert(conn
->getCurrentContext() != NULL
);
271 /* Unlink us from the connection request list */
272 tempContextPointer
= & conn
->currentobject
;
274 while (tempContextPointer
->getRaw()) {
275 if (*tempContextPointer
== this)
278 tempContextPointer
= &(*tempContextPointer
)->next
;
281 assert(tempContextPointer
->getRaw() != NULL
);
282 *tempContextPointer
= next
;
286 ClientSocketContext::~ClientSocketContext()
288 clientStreamNode
*node
= getTail();
291 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
294 /* We are *always* the tail - prevent recursive free */
295 assert(this == streamContext
);
301 deRegisterWithConn();
303 httpRequestFree(http
);
305 /* clean up connection links to us */
306 assert(this != next
.getRaw());
310 ClientSocketContext::registerWithConn()
312 assert (!connRegistered_
);
314 assert (http
->getConn() != NULL
);
315 connRegistered_
= true;
316 http
->getConn()->addContextToQueue(this);
320 ClientSocketContext::deRegisterWithConn()
322 assert (connRegistered_
);
323 removeFromConnectionList(http
->getConn());
324 connRegistered_
= false;
328 ClientSocketContext::connIsFinished()
331 assert (http
->getConn() != NULL
);
332 deRegisterWithConn();
333 /* we can't handle any more stream data - detach */
334 clientStreamDetach(getTail(), http
);
337 ClientSocketContext::ClientSocketContext(const Comm::ConnectionPointer
&aConn
, ClientHttpRequest
*aReq
) :
338 clientConnection(aConn
),
343 mayUseConnection_ (false),
344 connRegistered_ (false)
346 assert(http
!= NULL
);
347 memset (reqbuf
, '\0', sizeof (reqbuf
));
350 deferredparams
.node
= NULL
;
351 deferredparams
.rep
= NULL
;
355 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
357 const HttpReply::Pointer
rep(msg
.reply
);
360 // apply selected clientReplyContext::buildReplyHeader() mods
361 // it is not clear what headers are required for control messages
362 rep
->header
.removeHopByHopEntries();
363 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
364 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
366 // remember the callback
367 cbControlMsgSent
= msg
.cbSuccess
;
369 MemBuf
*mb
= rep
->pack();
371 debugs(11, 2, "HTTP Client " << clientConnection
);
372 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
374 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
375 CommIoCbPtrFun(&WroteControlMsg
, this));
376 Comm::Write(clientConnection
, mb
, call
);
381 /// called when we wrote the 1xx response
383 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
385 if (errflag
== COMM_ERR_CLOSING
)
388 if (errflag
== COMM_OK
) {
389 ScheduleCallHere(cbControlMsgSent
);
393 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
394 // no error notification: see HttpControlMsg.h for rationale and
395 // note that some errors are detected elsewhere (e.g., close handler)
397 // close on 1xx errors to be conservative and to simplify the code
398 // (if we do not close, we must notify the source of a failure!)
402 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
404 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
406 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
407 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
412 clientIdentDone(const char *ident
, void *data
)
414 ConnStateData
*conn
= (ConnStateData
*)data
;
415 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
420 clientUpdateStatCounters(LogTags logType
)
422 ++statCounter
.client_http
.requests
;
424 if (logTypeIsATcpHit(logType
))
425 ++statCounter
.client_http
.hits
;
427 if (logType
== LOG_TCP_HIT
)
428 ++statCounter
.client_http
.disk_hits
;
429 else if (logType
== LOG_TCP_MEM_HIT
)
430 ++statCounter
.client_http
.mem_hits
;
434 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
436 statCounter
.client_http
.allSvcTime
.count(svc_time
);
438 * The idea here is not to be complete, but to get service times
439 * for only well-defined types. For example, we don't include
440 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
441 * (we *tried* to validate it, but failed).
446 case LOG_TCP_REFRESH_UNMODIFIED
:
447 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
450 case LOG_TCP_IMS_HIT
:
451 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
456 case LOG_TCP_MEM_HIT
:
458 case LOG_TCP_OFFLINE_HIT
:
459 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
464 case LOG_TCP_CLIENT_REFRESH_MISS
:
465 statCounter
.client_http
.missSvcTime
.count(svc_time
);
469 /* make compiler warnings go away */
475 clientPingHasFinished(ping_data
const *aPing
)
477 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
484 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
488 switch (someEntry
->code
) {
489 #if USE_CACHE_DIGESTS
494 ++ statCounter
.cd
.times_used
;
502 case FIRST_PARENT_MISS
:
504 case CLOSEST_PARENT_MISS
:
505 ++ statCounter
.icp
.times_used
;
506 i
= &someEntry
->ping
;
508 if (clientPingHasFinished(i
))
509 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
512 ++ statCounter
.icp
.query_timeouts
;
519 ++ statCounter
.netdb
.times_used
;
529 ClientHttpRequest::updateCounters()
531 clientUpdateStatCounters(logType
);
533 if (request
->errType
!= ERR_NONE
)
534 ++ statCounter
.client_http
.errors
;
536 clientUpdateStatHistCounters(logType
,
537 tvSubMsec(al
->cache
.start_time
, current_time
));
539 clientUpdateHierCounters(&request
->hier
);
543 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
546 assert(aLogEntry
!= NULL
);
548 if (Config
.onoff
.log_mime_hdrs
) {
552 packerToMemInit(&p
, &mb
);
553 request
->header
.packInto(&p
);
554 //This is the request after adaptation or redirection
555 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
557 // the virgin request is saved to aLogEntry->request
558 if (aLogEntry
->request
) {
561 packerToMemInit(&p
, &mb
);
562 aLogEntry
->request
->header
.packInto(&p
);
563 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
567 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
571 packerToMemInit(&p
, &mb
);
572 ah
->lastMeta
.packInto(&p
);
573 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
582 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
584 aLogEntry
->icap
.processingTime
= ih
->processingTime();
587 aLogEntry
->http
.method
= request
->method
;
588 aLogEntry
->http
.version
= request
->http_ver
;
589 aLogEntry
->hier
= request
->hier
;
590 if (request
->content_length
> 0) // negative when no body or unknown length
591 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
592 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
594 // Adapted request, if any, inherits and then collects all the stats, but
595 // the virgin request gets logged instead; copy the stats to log them.
596 // TODO: avoid losses by keeping these stats in a shared history object?
597 if (aLogEntry
->request
) {
598 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
599 aLogEntry
->request
->errType
= request
->errType
;
600 aLogEntry
->request
->errDetail
= request
->errDetail
;
605 ClientHttpRequest::logRequest()
607 if (!out
.size
&& !logType
)
608 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
610 al
->icp
.opcode
= ICP_INVALID
;
612 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
615 al
->http
.code
= al
->reply
->sline
.status();
616 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
617 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
618 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
619 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
622 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
624 if (loggingEntry() && loggingEntry()->mem_obj
)
625 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
627 al
->http
.clientRequestSz
.header
= req_sz
;
628 al
->http
.clientReplySz
.header
= out
.headers_sz
;
629 // XXX: calculate without payload encoding or headers !!
630 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
632 al
->cache
.highOffset
= out
.offset
;
634 al
->cache
.code
= logType
;
636 al
->cache
.msec
= tvSubMsec(al
->cache
.start_time
, current_time
);
639 prepareLogWithRequestDetails(request
, al
);
641 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
642 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
646 /* This is broken. Fails if the connection has been closed. Needs
647 * to snarf the ssl details some place earlier..
649 if (getConn() != NULL
)
650 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
655 // The al->notes and request->notes must point to the same object.
656 (void)SyncNotes(*al
, *request
);
657 typedef Notes::iterator ACAMLI
;
658 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
659 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
660 NotePairs
¬es
= SyncNotes(*al
, *request
);
661 notes
.add((*i
)->key
.termedBuf(), value
);
662 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
666 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
668 checklist
.reply
= al
->reply
;
669 HTTPMSGLOCK(checklist
.reply
);
673 al
->adapted_request
= request
;
674 HTTPMSGLOCK(al
->adapted_request
);
676 accessLogLog(al
, &checklist
);
678 bool updatePerformanceCounters
= true;
679 if (Config
.accessList
.stats_collection
) {
680 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
682 statsCheck
.reply
= al
->reply
;
683 HTTPMSGLOCK(statsCheck
.reply
);
685 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
688 if (updatePerformanceCounters
) {
692 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
693 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
698 ClientHttpRequest::freeResources()
702 safe_free(redirect
.location
);
703 range_iter
.boundary
.clean();
704 HTTPMSGUNLOCK(request
);
706 if (client_stream
.tail
)
707 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
711 httpRequestFree(void *data
)
713 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
714 assert(http
!= NULL
);
719 ConnStateData::areAllContextsForThisConnection() const
721 assert(this != NULL
);
722 ClientSocketContext::Pointer context
= getCurrentContext();
724 while (context
.getRaw()) {
725 if (context
->http
->getConn() != this)
728 context
= context
->next
;
735 ConnStateData::freeAllContexts()
737 ClientSocketContext::Pointer context
;
739 while ((context
= getCurrentContext()).getRaw() != NULL
) {
740 assert(getCurrentContext() !=
741 getCurrentContext()->next
);
742 context
->connIsFinished();
743 assert (context
!= currentobject
);
747 /// propagates abort event to all contexts
749 ConnStateData::notifyAllContexts(int xerrno
)
751 typedef ClientSocketContext::Pointer CSCP
;
752 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
753 c
->noteIoError(xerrno
);
756 /* This is a handler normally called by comm_close() */
757 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
759 deleteThis("ConnStateData::connStateClosed");
764 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
768 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
774 // clobered with self-pointer
775 // NP: something nasty is going on in Squid, but harmless.
777 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
782 * Connection-auth relies on a single set of credentials being preserved
783 * for all requests on a connection once they have been setup.
784 * There are several things which need to happen to preserve security
785 * when connection-auth credentials change unexpectedly or are unset.
787 * 1) auth helper released from any active state
789 * They can only be reserved by a handshake process which this
790 * connection can now never complete.
791 * This prevents helpers hanging when their connections close.
793 * 2) pinning is expected to be removed and server conn closed
795 * The upstream link is authenticated with the same credentials.
796 * Expecting the same level of consistency we should have received.
797 * This prevents upstream being faced with multiple or missing
798 * credentials after authentication.
799 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
800 * we just trigger that cleanup here via comm_reset_close() or
801 * ConnStateData::stopReceiving()
803 * 3) the connection needs to close.
805 * This prevents attackers injecting requests into a connection,
806 * or gateways wrongly multiplexing users into a single connection.
808 * When credentials are missing closure needs to follow an auth
809 * challenge for best recovery by the client.
811 * When credentials change there is nothing we can do but abort as
812 * fast as possible. Sending TCP RST instead of an HTTP response
813 * is the best-case action.
816 // clobbered with nul-pointer
818 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
819 auth_
->releaseAuthServer();
821 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
822 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
823 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
824 stopReceiving("connection-auth removed");
828 // clobbered with alternative credentials
830 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
831 auth_
->releaseAuthServer();
833 // this is a fatal type of problem.
834 // Close the connection immediately with TCP RST to abort all traffic flow
835 comm_reset_close(clientConnection
);
843 // cleans up before destructor is called
845 ConnStateData::swanSong()
847 debugs(33, 2, HERE
<< clientConnection
);
848 flags
.readMore
= false;
849 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
850 assert(areAllContextsForThisConnection());
855 if (Comm::IsConnOpen(clientConnection
))
856 clientConnection
->close();
859 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
860 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
863 BodyProducer::swanSong();
864 flags
.swanSang
= true;
868 ConnStateData::isOpen() const
870 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
871 Comm::IsConnOpen(clientConnection
) &&
872 !fd_table
[clientConnection
->fd
].closing();
875 ConnStateData::~ConnStateData()
877 assert(this != NULL
);
878 debugs(33, 3, HERE
<< clientConnection
);
881 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
884 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
886 cbdataReferenceDone(port
);
888 if (bodyPipe
!= NULL
)
889 stopProducingFor(bodyPipe
, false);
892 delete sslServerBump
;
897 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
898 * This is the client-side persistent connection flag. We need
899 * to set this relatively early in the request processing
900 * to handle hacks for broken servers and clients.
903 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
905 HttpRequest
*request
= http
->request
;
907 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
908 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
909 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
910 RequestMethodStr(request
->method
));
912 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
913 request
->flags
.proxyKeepalive
= request
->persistent();
917 clientIsContentLengthValid(HttpRequest
* r
)
919 switch (r
->method
.id()) {
921 case Http::METHOD_GET
:
923 case Http::METHOD_HEAD
:
924 /* We do not want to see a request entity on GET/HEAD requests */
925 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
928 /* For other types of requests we don't care */
936 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
938 if (Config
.maxRequestBodySize
&&
939 bodyLength
> Config
.maxRequestBodySize
)
940 return 1; /* too large */
947 connIsUsable(ConnStateData
* conn
)
949 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
957 // careful: the "current" context may be gone if we wrote an early response
958 ClientSocketContext::Pointer
959 ConnStateData::getCurrentContext() const
962 return currentobject
;
966 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
968 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
969 assert(flags
.deferred
== 0);
971 deferredparams
.node
= node
;
972 deferredparams
.rep
= rep
;
973 deferredparams
.queuedBuffer
= receivedData
;
978 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
980 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
987 ClientSocketContext::startOfOutput() const
989 return http
->out
.size
== 0;
993 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
995 /*the size of available range can always fit in a size_t type*/
996 size_t maximum
= (size_t)available
.size();
998 if (!http
->request
->range
)
1001 assert (canPackMoreRanges());
1003 if (http
->range_iter
.debt() == -1)
1006 assert (http
->range_iter
.debt() > 0);
1008 /* TODO this + the last line could be a range intersection calculation */
1009 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
1012 return min(http
->range_iter
.debt(), (int64_t)maximum
);
1016 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
1018 http
->out
.offset
+= bytes
;
1020 if (!http
->request
->range
)
1023 if (http
->range_iter
.debt() != -1) {
1024 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
1025 assert (http
->range_iter
.debt() >= 0);
1028 /* debt() always stops at -1, below that is a bug */
1029 assert (http
->range_iter
.debt() >= -1);
1033 ClientHttpRequest::multipartRangeRequest() const
1035 return request
->multipartRangeRequest();
1039 ClientSocketContext::multipartRangeRequest() const
1041 return http
->multipartRangeRequest();
1045 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1047 assert(rep
== NULL
);
1049 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1050 size_t length
= lengthToSend(bodyData
.range());
1051 noteSentBodyBytes (length
);
1052 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1053 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1054 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1060 if (multipartRangeRequest())
1061 packRange(bodyData
, &mb
);
1063 packChunk(bodyData
, mb
);
1065 if (mb
.contentSize()) {
1067 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1068 CommIoCbPtrFun(clientWriteComplete
, this));
1069 Comm::Write(clientConnection
, &mb
, call
);
1071 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1075 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1076 * if bodyData is empty.
1079 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1081 const uint64_t length
=
1082 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1083 noteSentBodyBytes(length
);
1085 mb
.Printf("%" PRIX64
"\r\n", length
);
1086 mb
.append(bodyData
.data
, length
);
1090 /** put terminating boundary for multiparts */
1092 clientPackTermBound(String boundary
, MemBuf
* mb
)
1094 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1095 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1098 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1100 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1102 HttpHeader
hdr(hoReply
);
1108 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1109 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1110 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1112 /* stuff the header with required entries and pack it */
1114 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1115 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1117 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1119 packerToMemInit(&p
, mb
);
1127 /* append <crlf> (we packed a header, not a reply) */
1132 * extracts a "range" from *buf and appends them to mb, updating
1133 * all offsets and such.
1136 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1138 HttpHdrRangeIter
* i
= &http
->range_iter
;
1139 Range
<int64_t> available (source
.range());
1140 char const *buf
= source
.data
;
1142 while (i
->currentSpec() && available
.size()) {
1143 const size_t copy_sz
= lengthToSend(available
);
1147 * intersection of "have" and "need" ranges must not be empty
1149 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1150 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1153 * put boundary and headers at the beginning of a range in a
1157 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1158 assert(http
->memObject());
1160 http
->memObject()->getReply(), /* original reply */
1161 i
->currentSpec(), /* current range */
1162 i
->boundary
, /* boundary, the same for all */
1169 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1171 noteSentBodyBytes (copy_sz
);
1173 mb
->append(buf
, copy_sz
);
1178 available
.start
+= copy_sz
;
1184 if (!canPackMoreRanges()) {
1185 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1188 /* put terminating boundary for multiparts */
1189 clientPackTermBound(i
->boundary
, mb
);
1194 int64_t nextOffset
= getNextRangeOffset();
1196 assert (nextOffset
>= http
->out
.offset
);
1198 int64_t skip
= nextOffset
- http
->out
.offset
;
1200 /* adjust for not to be transmitted bytes */
1201 http
->out
.offset
= nextOffset
;
1203 if (available
.size() <= (uint64_t)skip
)
1206 available
.start
+= skip
;
1215 /** returns expected content length for multi-range replies
1216 * note: assumes that httpHdrRangeCanonize has already been called
1217 * warning: assumes that HTTP headers for individual ranges at the
1218 * time of the actuall assembly will be exactly the same as
1219 * the headers when clientMRangeCLen() is called */
1221 ClientHttpRequest::mRangeCLen()
1226 assert(memObject());
1229 HttpHdrRange::iterator pos
= request
->range
->begin();
1231 while (pos
!= request
->range
->end()) {
1232 /* account for headers for this range */
1234 clientPackRangeHdr(memObject()->getReply(),
1235 *pos
, range_iter
.boundary
, &mb
);
1238 /* account for range content */
1239 clen
+= (*pos
)->length
;
1241 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1245 /* account for the terminating boundary */
1248 clientPackTermBound(range_iter
.boundary
, &mb
);
1258 * returns true if If-Range specs match reply, false otherwise
1261 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1263 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1264 /* check for parsing falure */
1271 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1272 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1273 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1276 return 0; /* entity has no etag to compare with! */
1278 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1279 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1280 return 0; /* must use strong validator for sub-range requests */
1283 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1286 /* got modification time? */
1287 if (spec
.time
>= 0) {
1288 return http
->storeEntry()->lastmod
<= spec
.time
;
1291 assert(0); /* should not happen */
1296 * generates a "unique" boundary string for multipart responses
1297 * the caller is responsible for cleaning the string */
1299 ClientHttpRequest::rangeBoundaryStr() const
1303 String
b(APP_FULLNAME
);
1305 key
= storeEntry()->getMD5Text();
1306 b
.append(key
, strlen(key
));
1310 /** adds appropriate Range headers if needed */
1312 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1314 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1315 const char *range_err
= NULL
;
1316 HttpRequest
*request
= http
->request
;
1317 assert(request
->range
);
1318 /* check if we still want to do ranges */
1320 int64_t roffLimit
= request
->getRangeOffsetLimit();
1323 range_err
= "no [parse-able] reply";
1324 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1325 range_err
= "wrong status code";
1326 else if (hdr
->has(HDR_CONTENT_RANGE
))
1327 range_err
= "origin server does ranges";
1328 else if (rep
->content_length
< 0)
1329 range_err
= "unknown length";
1330 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1331 range_err
= "INCONSISTENT length"; /* a bug? */
1333 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1336 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1337 range_err
= "If-Range match failed";
1338 else if (!http
->request
->range
->canonize(rep
))
1339 range_err
= "canonization failed";
1340 else if (http
->request
->range
->isComplex())
1341 range_err
= "too complex range header";
1342 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1343 range_err
= "range outside range_offset_limit";
1345 /* get rid of our range specs on error */
1347 /* XXX We do this here because we need canonisation etc. However, this current
1348 * code will lead to incorrect store offset requests - the store will have the
1349 * offset data, but we won't be requesting it.
1350 * So, we can either re-request, or generate an error
1352 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1353 delete http
->request
->range
;
1354 http
->request
->range
= NULL
;
1356 /* XXX: TODO: Review, this unconditional set may be wrong. */
1357 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1358 // web server responded with a valid, but unexpected range.
1359 // will (try-to) forward as-is.
1360 //TODO: we should cope with multirange request/responses
1361 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1362 request
->range
->contains(rep
->content_range
->spec
) :
1364 const int spec_count
= http
->request
->range
->specs
.size();
1365 int64_t actual_clen
= -1;
1367 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1368 spec_count
<< " virgin clen: " << rep
->content_length
);
1369 assert(spec_count
> 0);
1370 /* append appropriate header(s) */
1372 if (spec_count
== 1) {
1373 if (!replyMatchRequest
) {
1374 hdr
->delById(HDR_CONTENT_RANGE
);
1375 hdr
->putContRange(rep
->content_range
);
1376 actual_clen
= rep
->content_length
;
1377 //http->range_iter.pos = rep->content_range->spec.begin();
1378 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1379 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1382 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1384 /* append Content-Range */
1386 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1387 /* No content range, so this was a full object we are
1390 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1393 /* set new Content-Length to the actual number of bytes
1394 * transmitted in the message-body */
1395 actual_clen
= (*pos
)->length
;
1399 /* generate boundary string */
1400 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1401 /* delete old Content-Type, add ours */
1402 hdr
->delById(HDR_CONTENT_TYPE
);
1403 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1404 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1405 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1406 /* Content-Length is not required in multipart responses
1407 * but it is always nice to have one */
1408 actual_clen
= http
->mRangeCLen();
1409 /* http->out needs to start where we want data at */
1410 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1413 /* replace Content-Length header */
1414 assert(actual_clen
>= 0);
1416 hdr
->delById(HDR_CONTENT_LENGTH
);
1418 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1420 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1422 /* And start the range iter off */
1423 http
->range_iter
.updateSpec();
1428 ClientSocketContext::prepareReply(HttpReply
* rep
)
1432 if (http
->request
->range
)
1433 buildRangeHeader(rep
);
1437 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1441 MemBuf
*mb
= rep
->pack();
1443 // dump now, so we dont output any body.
1444 debugs(11, 2, "HTTP Client " << clientConnection
);
1445 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1447 /* Save length of headers for persistent conn checks */
1448 http
->out
.headers_sz
= mb
->contentSize();
1451 headersLog(0, 0, http
->request
->method
, rep
);
1454 if (bodyData
.data
&& bodyData
.length
) {
1455 if (multipartRangeRequest())
1456 packRange(bodyData
, mb
);
1457 else if (http
->request
->flags
.chunkedReply
) {
1458 packChunk(bodyData
, *mb
);
1460 size_t length
= lengthToSend(bodyData
.range());
1461 noteSentBodyBytes (length
);
1463 mb
->append(bodyData
.data
, length
);
1468 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1469 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1470 CommIoCbPtrFun(clientWriteComplete
, this));
1471 Comm::Write(clientConnection
, mb
, call
);
1476 * Write a chunk of data to a client socket. If the reply is present,
1477 * send the reply headers down the wire too, and clean them up when
1480 * The request is one backed by a connection, not an internal request.
1481 * data context is not NULL
1482 * There are no more entries in the stream chain.
1485 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1486 HttpReply
* rep
, StoreIOBuffer receivedData
)
1488 /* Test preconditions */
1489 assert(node
!= NULL
);
1490 PROF_start(clientSocketRecipient
);
1491 /* TODO: handle this rather than asserting
1492 * - it should only ever happen if we cause an abort and
1493 * the callback chain loops back to here, so we can simply return.
1494 * However, that itself shouldn't happen, so it stays as an assert for now.
1496 assert(cbdataReferenceValid(node
));
1497 assert(node
->node
.next
== NULL
);
1498 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1499 assert(context
!= NULL
);
1500 assert(connIsUsable(http
->getConn()));
1502 /* TODO: check offset is what we asked for */
1504 if (context
!= http
->getConn()->getCurrentContext()) {
1505 context
->deferRecipientForLater(node
, rep
, receivedData
);
1506 PROF_stop(clientSocketRecipient
);
1510 // After sending Transfer-Encoding: chunked (at least), always send
1511 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1512 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1513 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1514 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1515 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1516 PROF_stop(clientSocketRecipient
);
1520 if (!context
->startOfOutput())
1521 context
->sendBody(rep
, receivedData
);
1524 http
->al
->reply
= rep
;
1525 HTTPMSGLOCK(http
->al
->reply
);
1526 context
->sendStartOfMessage(rep
, receivedData
);
1529 PROF_stop(clientSocketRecipient
);
1533 * Called when a downstream node is no longer interested in
1534 * our data. As we are a terminal node, this means on aborts
1538 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1540 /* Test preconditions */
1541 assert(node
!= NULL
);
1542 /* TODO: handle this rather than asserting
1543 * - it should only ever happen if we cause an abort and
1544 * the callback chain loops back to here, so we can simply return.
1545 * However, that itself shouldn't happen, so it stays as an assert for now.
1547 assert(cbdataReferenceValid(node
));
1548 /* Set null by ContextFree */
1549 assert(node
->node
.next
== NULL
);
1550 /* this is the assert discussed above */
1551 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1552 /* We are only called when the client socket shutsdown.
1553 * Tell the prev pipeline member we're finished
1555 clientStreamDetach(node
, http
);
1559 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1561 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1562 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1566 ConnStateData::readNextRequest()
1568 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1570 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1572 * Set the timeout BEFORE calling clientReadRequest().
1574 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1575 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1576 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1577 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1580 /** Please don't do anything with the FD past here! */
1584 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1586 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1588 /** If the client stream is waiting on a socket write to occur, then */
1590 if (deferredRequest
->flags
.deferred
) {
1591 /** NO data is allowed to have been sent. */
1592 assert(deferredRequest
->http
->out
.size
== 0);
1594 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1595 deferredRequest
->http
,
1596 deferredRequest
->deferredparams
.rep
,
1597 deferredRequest
->deferredparams
.queuedBuffer
);
1600 /** otherwise, the request is still active in a callbacksomewhere,
1605 /// called when we have successfully finished writing the response
1607 ClientSocketContext::keepaliveNextRequest()
1609 ConnStateData
* conn
= http
->getConn();
1611 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1614 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1615 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1616 conn
->clientConnection
->close();
1621 * We are done with the response, and we are either still receiving request
1622 * body (early response!) or have already stopped receiving anything.
1624 * If we are still receiving, then clientParseRequest() below will fail.
1625 * (XXX: but then we will call readNextRequest() which may succeed and
1626 * execute a smuggled request as we are not done with the current request).
1628 * If we stopped because we got everything, then try the next request.
1630 * If we stopped receiving because of an error, then close now to avoid
1631 * getting stuck and to prevent accidental request smuggling.
1634 if (const char *reason
= conn
->stoppedReceiving()) {
1635 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1636 conn
->clientConnection
->close();
1641 * Attempt to parse a request from the request buffer.
1642 * If we've been fed a pipelined request it may already
1643 * be in our read buffer.
1646 * This needs to fall through - if we're unlucky and parse the _last_ request
1647 * from our read buffer we may never re-register for another client read.
1650 if (conn
->clientParseRequests()) {
1651 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1655 * Either we need to kick-start another read or, if we have
1656 * a half-closed connection, kill it after the last request.
1657 * This saves waiting for half-closed connections to finished being
1658 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1659 * the keepalive "Waiting for next request" state.
1661 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1662 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1663 conn
->clientConnection
->close();
1667 ClientSocketContext::Pointer deferredRequest
;
1670 * At this point we either have a parsed request (which we've
1671 * kicked off the processing for) or not. If we have a deferred
1672 * request (parsed but deferred for pipeling processing reasons)
1673 * then look at processing it. If not, simply kickstart
1677 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1678 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1679 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1680 } else if (conn
->flags
.readMore
) {
1681 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1682 conn
->readNextRequest();
1684 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1685 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1690 clientUpdateSocketStats(LogTags logType
, size_t size
)
1695 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1697 if (logTypeIsATcpHit(logType
))
1698 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1702 * increments iterator "i"
1703 * used by clientPackMoreRanges
1705 \retval true there is still data available to pack more ranges
1709 ClientSocketContext::canPackMoreRanges() const
1711 /** first update iterator "i" if needed */
1713 if (!http
->range_iter
.debt()) {
1714 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1716 if (http
->range_iter
.pos
.incrementable())
1717 ++http
->range_iter
.pos
;
1719 http
->range_iter
.updateSpec();
1722 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1724 /* paranoid sync condition */
1725 /* continue condition: need_more_data */
1726 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1727 return http
->range_iter
.currentSpec() ? true : false;
1731 ClientSocketContext::getNextRangeOffset() const
1733 if (http
->request
->range
) {
1734 /* offset in range specs does not count the prefix of an http msg */
1735 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1736 /* check: reply was parsed and range iterator was initialized */
1737 assert(http
->range_iter
.valid
);
1738 /* filter out data according to range specs */
1739 assert (canPackMoreRanges());
1741 int64_t start
; /* offset of still missing data */
1742 assert(http
->range_iter
.currentSpec());
1743 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1744 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1745 debugs(33, 3, "clientPackMoreRanges: out:"
1746 " start: " << start
<<
1747 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1748 " [" << http
->range_iter
.currentSpec()->offset
<<
1749 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1750 " len: " << http
->range_iter
.currentSpec()->length
<<
1751 " debt: " << http
->range_iter
.debt());
1752 if (http
->range_iter
.currentSpec()->length
!= -1)
1753 assert(http
->out
.offset
<= start
); /* we did not miss it */
1758 } else if (reply
&& reply
->content_range
) {
1759 /* request does not have ranges, but reply does */
1760 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1761 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1763 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1766 return http
->out
.offset
;
1770 ClientSocketContext::pullData()
1772 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1774 /* More data will be coming from the stream. */
1775 StoreIOBuffer readBuffer
;
1776 /* XXX: Next requested byte in the range sequence */
1777 /* XXX: length = getmaximumrangelenfgth */
1778 readBuffer
.offset
= getNextRangeOffset();
1779 readBuffer
.length
= HTTP_REQBUF_SZ
;
1780 readBuffer
.data
= reqbuf
;
1781 /* we may note we have reached the end of the wanted ranges */
1782 clientStreamRead(getTail(), http
, readBuffer
);
1785 /** Adapt stream status to account for Range cases
1788 clientStream_status_t
1789 ClientSocketContext::socketState()
1791 switch (clientStreamStatus(getTail(), http
)) {
1794 /* check for range support ending */
1796 if (http
->request
->range
) {
1797 /* check: reply was parsed and range iterator was initialized */
1798 assert(http
->range_iter
.valid
);
1799 /* filter out data according to range specs */
1801 if (!canPackMoreRanges()) {
1802 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1803 "range sequence on " << clientConnection
);
1804 // we got everything we wanted from the store
1805 return STREAM_COMPLETE
;
1807 } else if (reply
&& reply
->content_range
) {
1808 /* reply has content-range, but Squid is not managing ranges */
1809 const int64_t &bytesSent
= http
->out
.offset
;
1810 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1812 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1813 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1814 reply
->content_range
->spec
.offset
<< ")");
1816 // did we get at least what we expected, based on range specs?
1818 if (bytesSent
== bytesExpected
) // got everything
1819 return STREAM_COMPLETE
;
1821 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1822 return STREAM_UNPLANNED_COMPLETE
;
1827 case STREAM_COMPLETE
:
1828 return STREAM_COMPLETE
;
1830 case STREAM_UNPLANNED_COMPLETE
:
1831 return STREAM_UNPLANNED_COMPLETE
;
1834 return STREAM_FAILED
;
1837 fatal ("unreachable code\n");
1842 * A write has just completed to the client, or we have just realised there is
1843 * no more data to send.
1846 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1848 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1849 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1852 /// remembers the abnormal connection termination for logging purposes
1854 ClientSocketContext::noteIoError(const int xerrno
)
1857 if (xerrno
== ETIMEDOUT
)
1858 http
->al
->http
.timedout
= true;
1859 else // even if xerrno is zero (which means read abort/eof)
1860 http
->al
->http
.aborted
= true;
1865 ClientSocketContext::doClose()
1867 clientConnection
->close();
1870 /// called when we encounter a response-related error
1872 ClientSocketContext::initiateClose(const char *reason
)
1874 http
->getConn()->stopSending(reason
); // closes ASAP
1878 ConnStateData::stopSending(const char *error
)
1880 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1881 "; old receiving error: " <<
1882 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1884 if (const char *oldError
= stoppedSending()) {
1885 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1886 return; // nothing has changed as far as this connection is concerned
1888 stoppedSending_
= error
;
1890 if (!stoppedReceiving()) {
1891 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1892 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1893 " request body bytes with " << in
.notYetUsed
<< " unused");
1894 return; // wait for the request receiver to finish reading
1898 clientConnection
->close();
1902 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1904 const StoreEntry
*entry
= http
->storeEntry();
1905 http
->out
.size
+= size
;
1906 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1907 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1908 (entry
? entry
->objectLen() : 0));
1909 clientUpdateSocketStats(http
->logType
, size
);
1911 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1913 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1916 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1917 initiateClose("failure or true request status");
1918 /* Do we leak here ? */
1922 switch (socketState()) {
1928 case STREAM_COMPLETE
:
1929 debugs(33, 5, conn
<< "Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1930 if (http
->request
->flags
.proxyKeepalive
)
1931 keepaliveNextRequest();
1933 initiateClose("STREAM_COMPLETE NOKEEPALIVE");
1936 case STREAM_UNPLANNED_COMPLETE
:
1937 initiateClose("STREAM_UNPLANNED_COMPLETE");
1941 initiateClose("STREAM_FAILED");
1945 fatal("Hit unreachable code in clientWriteComplete\n");
1949 SQUIDCEXTERN CSR clientGetMoreData
;
1950 SQUIDCEXTERN CSS clientReplyStatus
;
1951 SQUIDCEXTERN CSD clientReplyDetach
;
1953 static ClientSocketContext
*
1954 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1956 ClientHttpRequest
*http
;
1957 ClientSocketContext
*context
;
1958 StoreIOBuffer tempBuffer
;
1959 http
= new ClientHttpRequest(csd
);
1960 http
->req_sz
= csd
->in
.notYetUsed
;
1961 http
->uri
= xstrdup(uri
);
1962 setLogUri (http
, uri
);
1963 context
= new ClientSocketContext(csd
->clientConnection
, http
);
1964 tempBuffer
.data
= context
->reqbuf
;
1965 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1966 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1967 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1968 clientSocketDetach
, context
, tempBuffer
);
1973 skipLeadingSpace(char *aString
)
1975 char *result
= aString
;
1977 while (xisspace(*aString
))
1984 * 'end' defaults to NULL for backwards compatibility
1985 * remove default value if we ever get rid of NULL-terminated
1989 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1992 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1996 for (; end
> uriAndHTTPVersion
; --end
) {
1997 if (*end
== '\n' || *end
== '\r')
2000 if (xisspace(*end
)) {
2001 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2012 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2014 safe_free(http
->log_uri
);
2017 // The uri is already clean just dump it.
2018 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2021 switch (Config
.uri_whitespace
) {
2022 case URI_WHITESPACE_ALLOW
:
2023 flags
|= RFC1738_ESCAPE_NOSPACE
;
2025 case URI_WHITESPACE_ENCODE
:
2026 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2027 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2030 case URI_WHITESPACE_CHOP
: {
2031 flags
|= RFC1738_ESCAPE_NOSPACE
;
2032 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2033 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2034 int pos
= strcspn(http
->log_uri
, w_space
);
2035 http
->log_uri
[pos
] = '\0';
2039 case URI_WHITESPACE_DENY
:
2040 case URI_WHITESPACE_STRIP
:
2043 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2047 if (!xisspace(*t
)) {
2054 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2063 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2065 int vhost
= conn
->port
->vhost
;
2066 int vport
= conn
->port
->vport
;
2068 char ipbuf
[MAX_IPSTRLEN
];
2070 http
->flags
.accel
= true;
2072 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2074 if (strncasecmp(url
, "cache_object://", 15) == 0)
2075 return; /* already in good shape */
2078 if (conn
->port
->vhost
)
2079 return; /* already in good shape */
2081 /* else we need to ignore the host name */
2082 url
= strstr(url
, "//");
2084 #if SHOULD_REJECT_UNKNOWN_URLS
2087 hp
->request_parse_status
= Http::scBadRequest
;
2088 return parseHttpRequestAbort(conn
, "error:invalid-request");
2093 url
= strchr(url
+ 2, '/');
2100 vport
= http
->getConn()->clientConnection
->local
.port();
2102 const bool switchedToHttps
= conn
->switchedToHttps();
2103 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2104 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2105 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2110 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2111 strncpy(thost
, host
, (t
-host
));
2112 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2115 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2118 } // else nothing to alter port-wise.
2119 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2121 http
->uri
= (char *)xcalloc(url_sz
, 1);
2122 const char *protocol
= switchedToHttps
?
2123 "https" : URLScheme(conn
->port
->transport
.protocol
).const_str();
2124 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2125 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2126 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2127 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2128 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2129 strlen(conn
->port
->defaultsite
);
2130 http
->uri
= (char *)xcalloc(url_sz
, 1);
2134 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2136 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2137 URLScheme(conn
->port
->transport
.protocol
).const_str(), conn
->port
->defaultsite
, vportStr
, url
);
2138 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2139 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2140 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2141 /* Put the local socket IP address as the hostname, with whatever vport we found */
2142 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2143 http
->uri
= (char *)xcalloc(url_sz
, 1);
2144 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2145 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2146 URLScheme(conn
->port
->transport
.protocol
).const_str(),
2148 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2153 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2156 char ipbuf
[MAX_IPSTRLEN
];
2159 return; /* already in good shape */
2161 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2163 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2164 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2166 http
->uri
= (char *)xcalloc(url_sz
, 1);
2167 snprintf(http
->uri
, url_sz
, "%s://%s%s", URLScheme(conn
->port
->transport
.protocol
).const_str(), host
, url
);
2168 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2170 /* Put the local socket IP address as the hostname. */
2171 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2172 http
->uri
= (char *)xcalloc(url_sz
, 1);
2173 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2174 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2175 URLScheme(http
->getConn()->port
->transport
.protocol
).const_str(),
2176 ipbuf
, http
->getConn()->clientConnection
->local
.port(), url
);
2177 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2181 /** Parse an HTTP request
2183 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2184 * to 1 if the request was correctly parsed.
2185 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2186 * \param[in] hp an HttpParser
2187 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2188 * Pointed-to value will be set to Http::METHOD_NONE in case of
2190 * \param[out] http_ver will be set as a side-effect of the parsing
2191 * \return NULL on incomplete requests,
2192 * a ClientSocketContext structure on success or failure.
2194 static ClientSocketContext
*
2195 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2197 char *req_hdr
= NULL
;
2200 ClientHttpRequest
*http
;
2201 ClientSocketContext
*result
;
2202 StoreIOBuffer tempBuffer
;
2205 /* pre-set these values to make aborting simpler */
2206 *method_p
= Http::METHOD_NONE
;
2208 /* NP: don't be tempted to move this down or remove again.
2209 * It's the only DDoS protection old-String has against long URL */
2210 if ( hp
->bufsiz
<= 0) {
2211 debugs(33, 5, "Incomplete request, waiting for end of request line");
2213 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2214 debugs(33, 5, "parseHttpRequest: Too large request");
2215 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2216 return parseHttpRequestAbort(csd
, "error:request-too-large");
2219 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2220 r
= HttpParserParseReqLine(hp
);
2223 debugs(33, 5, "Incomplete request, waiting for end of request line");
2228 return parseHttpRequestAbort(csd
, "error:invalid-request");
2231 /* Request line is valid here .. */
2232 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2234 /* This call scans the entire request, not just the headers */
2235 if (hp
->req
.v_maj
> 0) {
2236 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2237 debugs(33, 5, "Incomplete request, waiting for end of headers");
2241 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2242 req_sz
= HttpParserReqSz(hp
);
2245 /* We know the whole request is in hp->buf now */
2247 assert(req_sz
<= (size_t) hp
->bufsiz
);
2249 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2250 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2253 hp
->hdr_end
= req_sz
- 1;
2255 hp
->hdr_start
= hp
->req
.end
+ 1;
2257 /* Enforce max_request_size */
2258 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2259 debugs(33, 5, "parseHttpRequest: Too large request");
2260 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2261 return parseHttpRequestAbort(csd
, "error:request-too-large");
2265 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2267 /* deny CONNECT via accelerated ports */
2268 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2269 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->transport
.protocol
<< " Accelerator port " << csd
->port
->s
.port());
2270 /* XXX need a way to say "this many character length string" */
2271 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2272 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2273 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2276 if (*method_p
== Http::METHOD_NONE
) {
2277 /* XXX need a way to say "this many character length string" */
2278 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2279 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2280 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2284 * Process headers after request line
2285 * TODO: Use httpRequestParse here.
2287 /* XXX this code should be modified to take a const char * later! */
2288 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2290 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2292 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2294 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2296 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2297 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2298 HttpParserReqSz(hp
));
2300 /* Ok, all headers are received */
2301 http
= new ClientHttpRequest(csd
);
2303 http
->req_sz
= HttpParserRequestLen(hp
);
2304 result
= new ClientSocketContext(csd
->clientConnection
, http
);
2305 tempBuffer
.data
= result
->reqbuf
;
2306 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2308 ClientStreamData newServer
= new clientReplyContext(http
);
2309 ClientStreamData newClient
= result
;
2310 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2311 clientReplyStatus
, newServer
, clientSocketRecipient
,
2312 clientSocketDetach
, newClient
, tempBuffer
);
2314 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2318 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2319 * below needs to be modified to not expect a mutable nul-terminated string.
2321 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2323 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2325 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2327 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2329 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2334 debugs(33,5, HERE
<< "repare absolute URL from " <<
2335 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2336 /* Rewrite the URL in transparent or accelerator mode */
2337 /* NP: there are several cases to traverse here:
2338 * - standard mode (forward proxy)
2339 * - transparent mode (TPROXY)
2340 * - transparent mode with failures
2341 * - intercept mode (NAT)
2342 * - intercept mode with failures
2343 * - accelerator mode (reverse proxy)
2345 * - mixed combos of the above with internal URL
2347 if (csd
->transparent()) {
2348 /* intercept or transparent mode, properly working with no failures */
2349 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2351 } else if (internalCheck(url
)) {
2352 /* internal URL mode */
2353 /* prepend our name & port */
2354 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2355 // We just re-wrote the URL. Must replace the Host: header.
2356 // But have not parsed there yet!! flag for local-only handling.
2357 http
->flags
.internal
= true;
2359 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2360 /* accelerator mode */
2361 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2365 /* No special rewrites have been applied above, use the
2366 * requested url. may be rewritten later, so make extra room */
2367 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2368 http
->uri
= (char *)xcalloc(url_sz
, 1);
2369 strcpy(http
->uri
, url
);
2372 debugs(33, 5, "parseHttpRequest: Complete request received");
2374 // XXX: crop this dump at the end of headers. No need for extras
2375 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2376 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2378 result
->flags
.parsed_ok
= 1;
2384 ConnStateData::getAvailableBufferLength() const
2386 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2387 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2388 // huge request_header_max_size may lead to more than INT_MAX unused space
2389 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2394 ConnStateData::maybeMakeSpaceAvailable()
2396 if (getAvailableBufferLength() < 2) {
2398 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2399 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2402 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2403 newSize
=Config
.maxRequestBufferSize
;
2405 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2406 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2412 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2414 ClientSocketContext::Pointer
*S
;
2416 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2424 ConnStateData::getConcurrentRequestCount() const
2427 ClientSocketContext::Pointer
*T
;
2429 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2430 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2435 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2437 if (flag
!= COMM_OK
) {
2438 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2443 if (!ignoreErrno(xerrno
)) {
2444 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2446 } else if (in
.notYetUsed
== 0) {
2447 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2455 ConnStateData::connFinishedWithConn(int size
)
2458 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2459 /* no current or pending requests */
2460 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2462 } else if (!Config
.onoff
.half_closed_clients
) {
2463 /* admin doesn't want to support half-closed client sockets */
2464 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2465 notifyAllContexts(0); // no specific error implies abort
2474 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2476 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2477 conn
->in
.notYetUsed
-= byteCount
;
2478 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2480 * If there is still data that will be used,
2481 * move it to the beginning.
2484 if (conn
->in
.notYetUsed
> 0)
2485 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2488 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2490 ConnStateData::checkHeaderLimits()
2492 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2493 return; // can accumulte more header data
2495 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2496 Config
.maxRequestHeaderSize
<< " bytes)");
2498 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2499 clientStreamNode
*node
= context
->getClientReplyContext();
2500 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2501 assert (repContext
);
2502 repContext
->setReplyToError(ERR_TOO_BIG
,
2503 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2504 clientConnection
->remote
, NULL
, NULL
, NULL
);
2505 context
->registerWithConn();
2506 context
->pullData();
2510 ConnStateData::clientAfterReadingRequests()
2512 // Were we expecting to read more request body from half-closed connection?
2513 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2514 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2515 clientConnection
->close();
2524 ConnStateData::quitAfterError(HttpRequest
*request
)
2526 // From HTTP p.o.v., we do not have to close after every error detected
2527 // at the client-side, but many such errors do require closure and the
2528 // client-side code is bad at handling errors so we play it safe.
2530 request
->flags
.proxyKeepalive
= false;
2531 flags
.readMore
= false;
2532 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2536 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2538 ClientHttpRequest
*http
= context
->http
;
2543 assert(sslServerBump
->entry
);
2544 // Did we create an error entry while processing CONNECT?
2545 if (!sslServerBump
->entry
->isEmpty()) {
2546 quitAfterError(http
->request
);
2548 // Get the saved error entry and send it to the client by replacing the
2549 // ClientHttpRequest store entry with it.
2550 clientStreamNode
*node
= context
->getClientReplyContext();
2551 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2553 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2554 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2556 // save the original request for logging purposes
2557 if (!context
->http
->al
->request
) {
2558 context
->http
->al
->request
= http
->request
;
2559 HTTPMSGLOCK(context
->http
->al
->request
);
2562 // Get error details from the fake certificate-peeking request.
2563 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2564 context
->pullData();
2568 // In bump-server-first mode, we have not necessarily seen the intended
2569 // server name at certificate-peeking time. Check for domain mismatch now,
2570 // when we can extract the intended name from the bumped HTTP request.
2571 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2572 HttpRequest
*request
= http
->request
;
2573 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2574 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2575 "does not match domainname " << request
->GetHost());
2577 bool allowDomainMismatch
= false;
2578 if (Config
.ssl_client
.cert_error
) {
2579 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2580 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2581 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2582 delete check
.sslErrors
;
2583 check
.sslErrors
= NULL
;
2586 if (!allowDomainMismatch
) {
2587 quitAfterError(request
);
2589 clientStreamNode
*node
= context
->getClientReplyContext();
2590 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2591 assert (repContext
);
2593 // Fill the server IP and hostname for error page generation.
2594 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2595 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2597 // Create an error object and fill it
2598 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2599 err
->src_addr
= clientConnection
->remote
;
2600 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2601 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2603 err
->detail
= errDetail
;
2604 // Save the original request for logging purposes.
2605 if (!context
->http
->al
->request
) {
2606 context
->http
->al
->request
= request
;
2607 HTTPMSGLOCK(context
->http
->al
->request
);
2609 repContext
->setReplyToError(request
->method
, err
);
2610 assert(context
->http
->out
.offset
== 0);
2611 context
->pullData();
2622 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2624 ClientHttpRequest
*http
= context
->http
;
2625 HttpRequest::Pointer request
;
2626 bool notedUseOfBuffer
= false;
2627 bool chunked
= false;
2628 bool mustReplyToOptions
= false;
2629 bool unsupportedTe
= false;
2630 bool expectBody
= false;
2632 /* We have an initial client stream in place should it be needed */
2633 /* setup our private context */
2634 context
->registerWithConn();
2636 if (context
->flags
.parsed_ok
== 0) {
2637 clientStreamNode
*node
= context
->getClientReplyContext();
2638 debugs(33, 2, "clientProcessRequest: Invalid Request");
2639 conn
->quitAfterError(NULL
);
2640 // setLogUri should called before repContext->setReplyToError
2641 setLogUri(http
, http
->uri
, true);
2642 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2643 assert (repContext
);
2644 switch (hp
->request_parse_status
) {
2645 case Http::scHeaderTooLarge
:
2646 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2648 case Http::scMethodNotAllowed
:
2649 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2650 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2653 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2654 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2656 assert(context
->http
->out
.offset
== 0);
2657 context
->pullData();
2661 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2662 clientStreamNode
*node
= context
->getClientReplyContext();
2663 debugs(33, 5, "Invalid URL: " << http
->uri
);
2664 conn
->quitAfterError(request
.getRaw());
2665 // setLogUri should called before repContext->setReplyToError
2666 setLogUri(http
, http
->uri
, true);
2667 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2668 assert (repContext
);
2669 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2670 assert(context
->http
->out
.offset
== 0);
2671 context
->pullData();
2675 /* RFC 2616 section 10.5.6 : handle unsupported HTTP major versions cleanly. */
2676 /* We currently only support 0.9, 1.0, 1.1 properly */
2677 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2678 (http_ver
.major
> 1) ) {
2680 clientStreamNode
*node
= context
->getClientReplyContext();
2681 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2682 conn
->quitAfterError(request
.getRaw());
2683 // setLogUri should called before repContext->setReplyToError
2684 setLogUri(http
, http
->uri
, true);
2685 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2686 assert (repContext
);
2687 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2688 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2689 assert(context
->http
->out
.offset
== 0);
2690 context
->pullData();
2694 /* compile headers */
2695 /* we should skip request line! */
2696 /* XXX should actually know the damned buffer size here */
2697 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2698 clientStreamNode
*node
= context
->getClientReplyContext();
2699 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2700 conn
->quitAfterError(request
.getRaw());
2701 // setLogUri should called before repContext->setReplyToError
2702 setLogUri(http
, http
->uri
, true);
2703 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2704 assert (repContext
);
2705 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2706 assert(context
->http
->out
.offset
== 0);
2707 context
->pullData();
2711 request
->clientConnectionManager
= conn
;
2713 request
->flags
.accelerated
= http
->flags
.accel
;
2714 request
->flags
.sslBumped
=conn
->switchedToHttps();
2715 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2716 // TODO: decouple http->flags.accel from request->flags.sslBumped
2717 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2718 !conn
->port
->allow_direct
: 0;
2720 if (request
->flags
.sslBumped
) {
2721 if (conn
->getAuth() != NULL
)
2722 request
->auth_user_request
= conn
->getAuth();
2727 * If transparent or interception mode is working clone the transparent and interception flags
2728 * from the port settings to the request.
2730 if (http
->clientConnection
!= NULL
) {
2731 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2732 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2733 if (request
->flags
.interceptTproxy
) {
2734 if (Config
.accessList
.spoof_client_ip
) {
2735 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2736 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2739 request
->flags
.spoofClientIp
= true;
2741 request
->flags
.spoofClientIp
= false;
2744 if (internalCheck(request
->urlpath
.termedBuf())) {
2745 if (internalHostnameIs(request
->GetHost()) &&
2746 request
->port
== getMyPort()) {
2747 http
->flags
.internal
= true;
2748 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2749 request
->SetHost(internalHostname());
2750 request
->port
= getMyPort();
2751 http
->flags
.internal
= true;
2755 if (http
->flags
.internal
) {
2756 request
->protocol
= AnyP::PROTO_HTTP
;
2757 request
->login
[0] = '\0';
2760 request
->flags
.internal
= http
->flags
.internal
;
2761 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2762 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2763 #if FOLLOW_X_FORWARDED_FOR
2764 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2765 // not a details about teh TCP connection itself
2766 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2767 #endif /* FOLLOW_X_FORWARDED_FOR */
2768 request
->my_addr
= conn
->clientConnection
->local
;
2769 request
->myportname
= conn
->port
->name
;
2770 request
->http_ver
= http_ver
;
2772 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2773 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2774 request
->clientConnectionManager
= conn
;
2776 if (request
->header
.chunked()) {
2778 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2779 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2780 // HTTP/1.1 requires chunking to be the last encoding if there is one
2781 unsupportedTe
= te
.size() && te
!= "identity";
2782 } // else implied identity coding
2784 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2785 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2786 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2787 clientStreamNode
*node
= context
->getClientReplyContext();
2788 conn
->quitAfterError(request
.getRaw());
2789 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2790 assert (repContext
);
2791 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2792 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2793 assert(context
->http
->out
.offset
== 0);
2794 context
->pullData();
2798 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2799 clientStreamNode
*node
= context
->getClientReplyContext();
2800 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2801 assert (repContext
);
2802 conn
->quitAfterError(request
.getRaw());
2803 repContext
->setReplyToError(ERR_INVALID_REQ
,
2804 Http::scLengthRequired
, request
->method
, NULL
,
2805 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2806 assert(context
->http
->out
.offset
== 0);
2807 context
->pullData();
2811 if (request
->header
.has(HDR_EXPECT
)) {
2812 const String expect
= request
->header
.getList(HDR_EXPECT
);
2813 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2814 if (!supportedExpect
) {
2815 clientStreamNode
*node
= context
->getClientReplyContext();
2816 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2817 assert (repContext
);
2818 conn
->quitAfterError(request
.getRaw());
2819 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2820 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2821 assert(context
->http
->out
.offset
== 0);
2822 context
->pullData();
2827 http
->request
= request
.getRaw();
2828 HTTPMSGLOCK(http
->request
);
2829 clientSetKeepaliveFlag(http
);
2831 // Let tunneling code be fully responsible for CONNECT requests
2832 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2833 context
->mayUseConnection(true);
2834 conn
->flags
.readMore
= false;
2838 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2842 /* Do we expect a request-body? */
2843 expectBody
= chunked
|| request
->content_length
> 0;
2844 if (!context
->mayUseConnection() && expectBody
) {
2845 request
->body_pipe
= conn
->expectRequestBody(
2846 chunked
? -1 : request
->content_length
);
2848 // consume header early so that body pipe gets just the body
2849 connNoteUseOfBuffer(conn
, http
->req_sz
);
2850 notedUseOfBuffer
= true;
2852 /* Is it too large? */
2853 if (!chunked
&& // if chunked, we will check as we accumulate
2854 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2855 clientStreamNode
*node
= context
->getClientReplyContext();
2856 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2857 assert (repContext
);
2858 conn
->quitAfterError(request
.getRaw());
2859 repContext
->setReplyToError(ERR_TOO_BIG
,
2860 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2861 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2862 assert(context
->http
->out
.offset
== 0);
2863 context
->pullData();
2867 // We may stop producing, comm_close, and/or call setReplyToError()
2868 // below, so quit on errors to avoid http->doCallouts()
2869 if (!conn
->handleRequestBodyData())
2872 if (!request
->body_pipe
->productionEnded()) {
2873 debugs(33, 5, HERE
<< "need more request body");
2874 context
->mayUseConnection(true);
2875 assert(conn
->flags
.readMore
);
2879 http
->calloutContext
= new ClientRequestContext(http
);
2884 if (!notedUseOfBuffer
)
2885 connNoteUseOfBuffer(conn
, http
->req_sz
);
2889 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2890 * to here because calling comm_reset_close() causes http to
2891 * be freed and the above connNoteUseOfBuffer() would hit an
2892 * assertion, not to mention that we were accessing freed memory.
2894 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2895 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2896 conn
->flags
.readMore
= false;
2897 comm_reset_close(conn
->clientConnection
);
2902 connStripBufferWhitespace (ConnStateData
* conn
)
2904 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2905 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2906 -- conn
->in
.notYetUsed
;
2911 * Limit the number of concurrent requests.
2912 * \return true when there are available position(s) in the pipeline queue for another request.
2913 * \return false when the pipeline queue is full or disabled.
2916 ConnStateData::concurrentRequestQueueFilled() const
2918 const int existingRequestCount
= getConcurrentRequestCount();
2920 // default to the configured pipeline size.
2921 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2922 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2924 // when queue filled already we cant add more.
2925 if (existingRequestCount
>= concurrentRequestLimit
) {
2926 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2927 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2935 * Attempt to parse one or more requests from the input buffer.
2936 * If a request is successfully parsed, even if the next request
2937 * is only partially parsed, it will return TRUE.
2940 ConnStateData::clientParseRequests()
2942 HttpRequestMethod method
;
2943 bool parsed_req
= false;
2945 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2947 // Loop while we have read bytes that are not needed for producing the body
2948 // On errors, bodyPipe may become nil, but readMore will be cleared
2949 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2950 connStripBufferWhitespace(this);
2952 /* Don't try to parse if the buffer is empty */
2953 if (in
.notYetUsed
== 0)
2956 /* Limit the number of concurrent requests */
2957 if (concurrentRequestQueueFilled())
2960 /* Should not be needed anymore */
2961 /* Terminate the string */
2962 in
.buf
[in
.notYetUsed
] = '\0';
2964 /* Begin the parsing */
2965 PROF_start(parseHttpRequest
);
2966 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
2968 /* Process request */
2969 Http::ProtocolVersion http_ver
;
2970 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2971 PROF_stop(parseHttpRequest
);
2973 /* partial or incomplete request */
2975 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2976 // (which becomes context) but checkHeaderLimits cannot?
2977 checkHeaderLimits();
2981 /* status -1 or 1 */
2983 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2984 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2985 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2986 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2988 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2990 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2992 if (context
->mayUseConnection()) {
2993 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2999 /* XXX where to 'finish' the parsing pass? */
3004 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3006 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3010 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
3012 if (io
.flag
== COMM_ERR_CLOSING
) {
3013 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
3017 assert(Comm::IsConnOpen(clientConnection
));
3018 assert(io
.conn
->fd
== clientConnection
->fd
);
3021 * Don't reset the timeout value here. The timeout value will be
3022 * set to Config.Timeout.request by httpAccept() and
3023 * clientWriteComplete(), and should apply to the request as a
3024 * whole, not individual read() calls. Plus, it breaks our
3025 * lame half-close detection
3027 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3028 notifyAllContexts(io
.xerrno
);
3033 if (io
.flag
== COMM_OK
) {
3035 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3037 // may comm_close or setReplyToError
3038 if (!handleReadData(io
.buf
, io
.size
))
3041 } else if (io
.size
== 0) {
3042 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3044 if (connFinishedWithConn(io
.size
)) {
3045 clientConnection
->close();
3049 /* It might be half-closed, we can't tell */
3050 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3052 commMarkHalfClosed(io
.conn
->fd
);
3054 fd_note(io
.conn
->fd
, "half-closed");
3056 /* There is one more close check at the end, to detect aborted
3057 * (partial) requests. At this point we can't tell if the request
3060 /* Continue to process previously read data */
3064 /* Process next request */
3065 if (getConcurrentRequestCount() == 0)
3066 fd_note(io
.fd
, "Reading next request");
3068 if (!clientParseRequests()) {
3072 * If the client here is half closed and we failed
3073 * to parse a request, close the connection.
3074 * The above check with connFinishedWithConn() only
3075 * succeeds _if_ the buffer is empty which it won't
3076 * be if we have an incomplete request.
3077 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3079 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3080 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3081 clientConnection
->close();
3089 clientAfterReadingRequests();
3093 * called when new request data has been read from the socket
3095 * \retval false called comm_close or setReplyToError (the caller should bail)
3096 * \retval true we did not call comm_close or setReplyToError
3099 ConnStateData::handleReadData(char *buf
, size_t size
)
3101 char *current_buf
= in
.addressToReadInto();
3103 if (buf
!= current_buf
)
3104 memmove(current_buf
, buf
, size
);
3106 in
.notYetUsed
+= size
;
3108 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3110 // if we are reading a body, stuff data into the body pipe
3111 if (bodyPipe
!= NULL
)
3112 return handleRequestBodyData();
3117 * called when new request body data has been buffered in in.buf
3118 * may close the connection if we were closing and piped everything out
3120 * \retval false called comm_close or setReplyToError (the caller should bail)
3121 * \retval true we did not call comm_close or setReplyToError
3124 ConnStateData::handleRequestBodyData()
3126 assert(bodyPipe
!= NULL
);
3130 if (in
.bodyParser
) { // chunked encoding
3131 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3132 abortChunkedRequestBody(error
);
3135 } else { // identity encoding
3136 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3137 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3138 if (!bodyPipe
->mayNeedMoreData()) {
3139 // BodyPipe will clear us automagically when we produced everything
3145 connNoteUseOfBuffer(this, putSize
);
3148 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3150 if (const char *reason
= stoppedSending()) {
3151 /* we've finished reading like good clients,
3152 * now do the close that initiateClose initiated.
3154 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3155 clientConnection
->close();
3163 /// parses available chunked encoded body bytes, checks size, returns errors
3165 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3167 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3169 try { // the parser will throw on errors
3171 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3174 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3175 // add one because MemBuf will assert if it cannot 0-terminate
3176 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3177 raw
.append(in
.buf
, in
.notYetUsed
);
3179 const mb_size_t wasContentSize
= raw
.contentSize();
3180 BodyPipeCheckout
bpc(*bodyPipe
);
3181 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3183 putSize
= wasContentSize
- raw
.contentSize();
3185 // dechunk then check: the size limit applies to _dechunked_ content
3186 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3190 finishDechunkingRequest(true);
3192 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3195 // if chunk parser needs data, then the body pipe must need it too
3196 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3198 // if parser needs more space and we can consume nothing, we will stall
3199 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3200 } catch (...) { // TODO: be more specific
3201 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3202 return ERR_INVALID_REQ
;
3205 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3209 /// quit on errors related to chunked request body handling
3211 ConnStateData::abortChunkedRequestBody(const err_type error
)
3213 finishDechunkingRequest(false);
3215 // XXX: The code below works if we fail during initial request parsing,
3216 // but if we fail when the server-side works already, the server may send
3217 // us its response too, causing various assertions. How to prevent that?
3218 #if WE_KNOW_HOW_TO_SEND_ERRORS
3219 ClientSocketContext::Pointer context
= getCurrentContext();
3220 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3221 clientStreamNode
*node
= context
->getClientReplyContext();
3222 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3224 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3225 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3226 repContext
->setReplyToError(error
, scode
,
3227 repContext
->http
->request
->method
,
3228 repContext
->http
->uri
,
3230 repContext
->http
->request
,
3232 context
->pullData();
3234 // close or otherwise we may get stuck as nobody will notice the error?
3235 comm_reset_close(clientConnection
);
3238 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3239 comm_reset_close(clientConnection
);
3241 flags
.readMore
= false;
3245 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3247 if (!handleRequestBodyData())
3250 // too late to read more body
3251 if (!isOpen() || stoppedReceiving())
3258 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3260 // request reader may get stuck waiting for space if nobody consumes body
3261 if (bodyPipe
!= NULL
)
3262 bodyPipe
->enableAutoConsumption();
3264 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3267 /** general lifetime handler for HTTP requests */
3269 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3272 * Just close the connection to not confuse browsers
3273 * using persistent connections. Some browsers open
3274 * a connection and then do not use it until much
3275 * later (presumeably because the request triggering
3276 * the open has already been completed on another
3279 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3284 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3286 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3287 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3288 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3289 http
->al
->http
.timedout
= true;
3290 if (Comm::IsConnOpen(io
.conn
))
3294 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3295 AsyncJob("ConnStateData"),
3297 sslBumpMode(Ssl::bumpEnd
),
3298 switchedToHttps_(false),
3299 sslServerBump(NULL
),
3301 stoppedSending_(NULL
),
3302 stoppedReceiving_(NULL
)
3304 pinning
.host
= NULL
;
3306 pinning
.pinned
= false;
3307 pinning
.auth
= false;
3308 pinning
.zeroReply
= false;
3309 pinning
.peer
= NULL
;
3311 // store the details required for creating more MasterXaction objects as new requests come in
3312 clientConnection
= xact
->tcpClient
;
3313 port
= cbdataReference(xact
->squidPort
.get());
3314 log_addr
= xact
->tcpClient
->remote
;
3315 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3317 in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &in
.allocatedSize
);
3319 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3320 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3321 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3322 int i
= IP_PMTUDISC_DONT
;
3323 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3324 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3326 static bool reported
= false;
3329 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3335 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3336 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3337 comm_add_close_handler(clientConnection
->fd
, call
);
3339 if (Config
.onoff
.log_fqdn
)
3340 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3343 if (Ident::TheConfig
.identLookup
) {
3344 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3345 identChecklist
.src_addr
= xact
->tcpClient
->remote
;
3346 identChecklist
.my_addr
= xact
->tcpClient
->local
;
3347 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3348 Ident::Start(xact
->tcpClient
, clientIdentDone
, this);
3352 clientdbEstablished(clientConnection
->remote
, 1);
3354 flags
.readMore
= true;
3357 /** Handle a new connection on HTTP socket. */
3359 httpAccept(const CommAcceptCbParams
¶ms
)
3361 MasterXaction::Pointer xact
= params
.xaction
;
3362 AnyP::PortCfgPointer s
= xact
->squidPort
;
3365 // it is possible the call or accept() was still queued when the port was reconfigured
3366 debugs(33, 2, "HTTP accept failure: port reconfigured.");
3370 if (params
.flag
!= COMM_OK
) {
3371 // Its possible the call was still queued when the client disconnected
3372 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3376 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3377 fd_note(params
.conn
->fd
, "client http connect");
3379 if (s
->tcp_keepalive
.enabled
) {
3380 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3383 ++ incoming_sockets_accepted
;
3385 // Socket is ready, setup the connection manager to start using it
3386 ConnStateData
*connState
= new ConnStateData(xact
);
3388 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3389 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3390 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3391 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3393 connState
->readSomeData();
3396 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3398 if (Config
.onoff
.client_db
) {
3399 /* it was said several times that client write limiter does not work if client_db is disabled */
3401 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3402 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3404 // TODO: we check early to limit error response bandwith but we
3405 // should recheck when we can honor delay_pool_uses_indirect
3406 // TODO: we should also pass the port details for myportname here.
3407 ch
.src_addr
= params
.conn
->remote
;
3408 ch
.my_addr
= params
.conn
->local
;
3410 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3412 /* pools require explicit 'allow' to assign a client into them */
3413 if (pools
[pool
].access
) {
3414 ch
.accessList
= pools
[pool
].access
;
3415 allow_t answer
= ch
.fastCheck();
3416 if (answer
== ACCESS_ALLOWED
) {
3418 /* request client information from db after we did all checks
3419 this will save hash lookup if client failed checks */
3420 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3423 /* put client info in FDE */
3424 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3426 /* setup write limiter for this request */
3427 const double burst
= floor(0.5 +
3428 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3429 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3432 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3442 /** Create SSL connection structure and update fd_table */
3444 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3446 SSL
*ssl
= SSL_new(sslContext
);
3449 const int ssl_error
= ERR_get_error();
3450 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3455 SSL_set_fd(ssl
, conn
->fd
);
3456 fd_table
[conn
->fd
].ssl
= ssl
;
3457 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3458 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3460 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3461 fd_note(conn
->fd
, "client https start");
3466 /** negotiate an SSL connection */
3468 clientNegotiateSSL(int fd
, void *data
)
3470 ConnStateData
*conn
= (ConnStateData
*)data
;
3472 SSL
*ssl
= fd_table
[fd
].ssl
;
3475 if ((ret
= SSL_accept(ssl
)) <= 0) {
3476 int ssl_error
= SSL_get_error(ssl
, ret
);
3478 switch (ssl_error
) {
3480 case SSL_ERROR_WANT_READ
:
3481 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3484 case SSL_ERROR_WANT_WRITE
:
3485 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3488 case SSL_ERROR_SYSCALL
:
3491 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3497 if (errno
== ECONNRESET
)
3500 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3501 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3508 case SSL_ERROR_ZERO_RETURN
:
3509 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3514 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3515 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3516 " (" << ssl_error
<< "/" << ret
<< ")");
3524 if (SSL_session_reused(ssl
)) {
3525 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3526 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3528 if (do_debug(83, 4)) {
3529 /* Write out the SSL session details.. actually the call below, but
3530 * OpenSSL headers do strange typecasts confusing GCC.. */
3531 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3532 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3533 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
);
3535 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3537 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3538 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3539 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3540 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3541 * Because there are two possible usable cast, if you get an error here, try the other
3542 * commented line. */
3544 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3545 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3549 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3552 /* Note: This does not automatically fflush the log file.. */
3555 debugs(83, 2, "clientNegotiateSSL: New session " <<
3556 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3557 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3561 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3562 SSL_get_cipher(ssl
));
3564 client_cert
= SSL_get_peer_certificate(ssl
);
3566 if (client_cert
!= NULL
) {
3567 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3568 " client certificate: subject: " <<
3569 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3571 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3572 " client certificate: issuer: " <<
3573 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3575 X509_free(client_cert
);
3577 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3578 " has no certificate.");
3581 conn
->readSomeData();
3585 * If SSL_CTX is given, starts reading the SSL handshake.
3586 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3589 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3593 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3595 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3598 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3599 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3600 connState
, ConnStateData::requestTimeout
);
3601 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3604 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3606 char buf
[MAX_IPSTRLEN
];
3607 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3608 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3609 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3610 fakeRequest
->port
= details
->local
.port();
3611 fakeRequest
->clientConnectionManager
= connState
;
3612 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3613 #if FOLLOW_X_FORWARDED_FOR
3614 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3616 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3617 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3618 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3619 fakeRequest
->myportname
= connState
->port
->name
;
3620 if (fakeRequest
->flags
.interceptTproxy
) {
3621 if (Config
.accessList
.spoof_client_ip
) {
3622 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3623 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3625 fakeRequest
->flags
.spoofClientIp
= true;
3627 fakeRequest
->flags
.spoofClientIp
= false;
3628 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3629 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3634 * A callback function to use with the ACLFilledChecklist callback.
3635 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3636 * else reverts the connection to tunnel mode.
3639 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3641 ConnStateData
*connState
= (ConnStateData
*) data
;
3643 // if the connection is closed or closing, just return.
3644 if (!connState
->isOpen())
3647 // Require both a match and a positive bump mode to work around exceptional
3648 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3649 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3650 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3651 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3652 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3654 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3655 connState
->sslBumpMode
= Ssl::bumpNone
;
3657 // fake a CONNECT request to force connState to tunnel
3658 static char ip
[MAX_IPSTRLEN
];
3659 static char reqStr
[MAX_IPSTRLEN
+ 80];
3660 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3661 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, ip
);
3662 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3664 ret
= connState
->clientParseRequests();
3667 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3668 connState
->clientConnection
->close();
3673 /** handle a new HTTPS connection */
3675 httpsAccept(const CommAcceptCbParams
¶ms
)
3677 MasterXaction::Pointer xact
= params
.xaction
;
3678 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3681 // it is possible the call or accept() was still queued when the port was reconfigured
3682 debugs(33, 2, "HTTPS accept failure: port reconfigured.");
3686 if (params
.flag
!= COMM_OK
) {
3687 // Its possible the call was still queued when the client disconnected
3688 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3692 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3693 fd_note(params
.conn
->fd
, "client https connect");
3695 if (s
->tcp_keepalive
.enabled
) {
3696 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3699 ++incoming_sockets_accepted
;
3701 // Socket is ready, setup the connection manager to start using it
3702 ConnStateData
*connState
= new ConnStateData(xact
);
3704 if (s
->flags
.tunnelSslBumping
) {
3705 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3707 if (!Config
.accessList
.ssl_bump
) {
3708 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3712 // Create a fake HTTP request for ssl_bump ACL check,
3713 // using tproxy/intercept provided destination IP and port.
3714 HttpRequest
*request
= new HttpRequest();
3715 static char ip
[MAX_IPSTRLEN
];
3716 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3717 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3718 request
->port
= params
.conn
->local
.port();
3719 request
->myportname
= s
->name
;
3721 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3722 acl_checklist
->src_addr
= params
.conn
->remote
;
3723 acl_checklist
->my_addr
= s
->s
;
3724 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3727 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3728 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3733 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3735 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3736 state_data
->sslCrtdHandleReply(reply
);
3740 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3742 if (reply
.result
== HelperReply::BrokenHelper
) {
3743 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3744 } else if (!reply
.other().hasContent()) {
3745 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3747 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3748 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3749 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3751 if (reply
.result
!= HelperReply::Okay
) {
3752 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3754 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3755 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3756 getSslContextDone(ctx
, true);
3761 getSslContextDone(NULL
);
3764 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3766 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3768 // fake certificate adaptation requires bump-server-first mode
3769 if (!sslServerBump
) {
3770 assert(port
->signingCert
.get());
3771 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3772 if (port
->signPkey
.get())
3773 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3774 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3778 // In case of an error while connecting to the secure server, use a fake
3779 // trusted certificate, with no mimicked fields and no adaptation
3780 // algorithms. There is nothing we can mimic so we want to minimize the
3781 // number of warnings the user will have to see to get to the error page.
3782 assert(sslServerBump
->entry
);
3783 if (sslServerBump
->entry
->isEmpty()) {
3784 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3785 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3787 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3788 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3789 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3791 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3792 // If the algorithm already set, then ignore it.
3793 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3794 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3795 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3798 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3799 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3800 const char *param
= ca
->param
;
3802 // For parameterless CN adaptation, use hostname from the
3804 if (ca
->alg
== Ssl::algSetCommonName
) {
3806 param
= sslConnectHostOrIp
.termedBuf();
3807 certProperties
.commonName
= param
;
3808 certProperties
.setCommonName
= true;
3809 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3810 certProperties
.setValidAfter
= true;
3811 else if (ca
->alg
== Ssl::algSetValidBefore
)
3812 certProperties
.setValidBefore
= true;
3814 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3815 alg
<< " param: " << (param
? param
: "-"));
3819 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3820 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3821 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3822 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3826 } else {// if (!sslServerBump->entry->isEmpty())
3827 // Use trusted certificate for a Squid-generated error
3828 // or the user would have to add a security exception
3829 // just to see the error page. We will close the connection
3830 // so that the trust is not extended to non-Squid content.
3831 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3834 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3836 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3837 assert(port
->untrustedSigningCert
.get());
3838 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3839 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3841 assert(port
->signingCert
.get());
3842 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3844 if (port
->signPkey
.get())
3845 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3847 signAlgorithm
= certProperties
.signAlgorithm
;
3851 ConnStateData::getSslContextStart()
3853 assert(areAllContextsForThisConnection());
3855 /* careful: freeAllContexts() above frees request, host, etc. */
3857 if (port
->generateHostCertificates
) {
3858 Ssl::CertificateProperties certProperties
;
3859 buildSslCertGenerationParams(certProperties
);
3860 sslBumpCertKey
= certProperties
.dbKey().c_str();
3861 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3863 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3864 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3865 SSL_CTX
* dynCtx
= NULL
;
3866 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
.get(sslBumpCertKey
.termedBuf());
3867 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3868 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3869 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3870 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3871 getSslContextDone(dynCtx
);
3874 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3875 ssl_ctx_cache
.del(sslBumpCertKey
.termedBuf());
3878 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3883 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3884 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3885 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3886 request_message
.composeRequest(certProperties
);
3887 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3888 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3890 } catch (const std::exception
&e
) {
3891 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3892 "request for " << certProperties
.commonName
<<
3893 " certificate: " << e
.what() << "; will now block to " <<
3894 "generate that certificate.");
3895 // fall through to do blocking in-process generation.
3897 #endif // USE_SSL_CRTD
3899 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3900 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3901 getSslContextDone(dynCtx
, true);
3904 getSslContextDone(NULL
);
3908 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3910 // Try to add generated ssl context to storage.
3911 if (port
->generateHostCertificates
&& isNew
) {
3913 if (signAlgorithm
== Ssl::algSignTrusted
) {
3914 // Add signing certificate to the certificates chain
3915 X509
*cert
= port
->signingCert
.get();
3916 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3917 // increase the certificate lock
3918 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3920 const int ssl_error
= ERR_get_error();
3921 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3923 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3925 //else it is self-signed or untrusted do not attrach any certificate
3927 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3928 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3930 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3931 // If it is not in storage delete after using. Else storage deleted it.
3932 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3935 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3939 // If generated ssl context = NULL, try to use static ssl context.
3941 if (!port
->staticSslContext
) {
3942 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3943 clientConnection
->close();
3946 debugs(33, 5, HERE
<< "Using static ssl context.");
3947 sslContext
= port
->staticSslContext
.get();
3951 if (!httpsCreate(clientConnection
, sslContext
))
3954 // commSetConnTimeout() was called for this request before we switched.
3956 // Disable the client read handler until CachePeer selection is complete
3957 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3958 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3959 switchedToHttps_
= true;
3963 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3965 assert(!switchedToHttps_
);
3967 sslConnectHostOrIp
= request
->GetHost();
3968 sslCommonName
= request
->GetHost();
3970 // We are going to read new request
3971 flags
.readMore
= true;
3972 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3974 // If sslServerBump is set, then we have decided to deny CONNECT
3975 // and now want to switch to SSL to send the error to the client
3976 // without even peeking at the origin server certificate.
3977 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3978 request
->flags
.sslPeek
= true;
3979 sslServerBump
= new Ssl::ServerBump(request
);
3981 // will call httpsPeeked() with certificate and connection, eventually
3982 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3986 // otherwise, use sslConnectHostOrIp
3987 getSslContextStart();
3991 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3993 Must(sslServerBump
!= NULL
);
3995 if (Comm::IsConnOpen(serverConnection
)) {
3996 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3998 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3999 assert(serverCert
.get() != NULL
);
4000 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4001 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4002 " bumped: " << *serverConnection
);
4004 pinConnection(serverConnection
, NULL
, NULL
, false);
4006 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4008 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4009 Ip::Address intendedDest
;
4010 intendedDest
= sslConnectHostOrIp
.termedBuf();
4011 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4013 // Squid serves its own error page and closes, so we want
4014 // a CN that causes no additional browser errors. Possible
4015 // only when bumping CONNECT with a user-typed address.
4016 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4017 sslCommonName
= sslConnectHostOrIp
;
4018 else if (sslServerBump
->serverCert
.get())
4019 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4021 // copy error detail from bump-server-first request to CONNECT request
4022 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4023 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4026 getSslContextStart();
4029 #endif /* USE_SSL */
4031 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4033 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4035 if (!Comm::IsConnOpen(c
)) {
4036 Must(NHttpSockets
> 0); // we tried to open some
4037 --NHttpSockets
; // there will be fewer sockets than planned
4038 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4040 if (!NHttpSockets
) // we could not open any listen sockets at all
4041 fatalf("Unable to open %s",FdNote(portType
));
4048 /// find any unused HttpSockets[] slot and store fd there or return false
4050 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4053 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4054 if ((found
= HttpSockets
[i
] < 0))
4055 HttpSockets
[i
] = conn
->fd
;
4061 clientHttpConnectionsOpen(void)
4063 AnyP::PortCfg
*s
= NULL
;
4065 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4066 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4067 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4068 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4073 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4074 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << URLScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4075 s
->flags
.tunnelSslBumping
= false;
4078 if (s
->flags
.tunnelSslBumping
&&
4079 !s
->staticSslContext
&&
4080 !s
->generateHostCertificates
) {
4081 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4082 s
->flags
.tunnelSslBumping
= false;
4084 if (s
->flags
.tunnelSslBumping
) {
4085 // Create ssl_ctx cache for this port.
4086 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4090 // Fill out a Comm::Connection which IPC will open as a listener for us
4091 // then pass back when active so we can start a TcpAcceptor subscription.
4092 s
->listenConn
= new Comm::Connection
;
4093 s
->listenConn
->local
= s
->s
;
4094 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4096 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4097 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4098 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4099 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4101 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4102 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4103 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4105 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4112 clientHttpsConnectionsOpen(void)
4116 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4117 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4118 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4119 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4123 if (!s
->staticSslContext
) {
4124 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4125 " due to SSL initialization failure.");
4129 // TODO: merge with similar code in clientHttpConnectionsOpen()
4130 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4131 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << URLScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4132 s
->flags
.tunnelSslBumping
= false;
4135 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4136 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4137 s
->flags
.tunnelSslBumping
= false;
4140 if (s
->flags
.tunnelSslBumping
) {
4141 // Create ssl_ctx cache for this port.
4142 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4145 // Fill out a Comm::Connection which IPC will open as a listener for us
4146 s
->listenConn
= new Comm::Connection
;
4147 s
->listenConn
->local
= s
->s
;
4148 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4149 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4151 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4152 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4153 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4154 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4156 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4157 ListeningStartedDialer(&clientListenerConnectionOpened
,
4158 s
, Ipc::fdnHttpsSocket
, sub
));
4159 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4160 HttpSockets
[NHttpSockets
] = -1;
4166 /// process clientHttpConnectionsOpen result
4168 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4170 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4174 Must(Comm::IsConnOpen(s
->listenConn
));
4176 // TCP: setup a job to handle accept() with subscribed handler
4177 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4179 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4180 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4181 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4182 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4183 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4184 << FdNote(portTypeNote
) << " connections at "
4187 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4191 clientOpenListenSockets(void)
4193 clientHttpConnectionsOpen();
4195 clientHttpsConnectionsOpen();
4198 if (NHttpSockets
< 1)
4199 fatal("No HTTP or HTTPS ports configured");
4203 clientHttpConnectionsClose(void)
4205 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4206 if (s
->listenConn
!= NULL
) {
4207 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4208 s
->listenConn
->close();
4209 s
->listenConn
= NULL
;
4214 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4215 if (s
->listenConn
!= NULL
) {
4216 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4217 s
->listenConn
->close();
4218 s
->listenConn
= NULL
;
4223 // TODO see if we can drop HttpSockets array entirely */
4224 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4225 HttpSockets
[i
] = -1;
4232 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4234 const char *vary
= request
->vary_headers
;
4235 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4236 #if X_ACCELERATOR_VARY
4239 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4242 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4244 /* Oops... something odd is going on here.. */
4245 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4246 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4247 safe_free(request
->vary_headers
);
4252 /* This is not a varying object */
4256 /* virtual "vary" object found. Calculate the vary key and
4257 * continue the search
4259 vary
= httpMakeVaryMark(request
, entry
->getReply());
4262 request
->vary_headers
= xstrdup(vary
);
4265 /* Ouch.. we cannot handle this kind of variance */
4266 /* XXX This cannot really happen, but just to be complete */
4271 vary
= httpMakeVaryMark(request
, entry
->getReply());
4274 request
->vary_headers
= xstrdup(vary
);
4278 /* Ouch.. we cannot handle this kind of variance */
4279 /* XXX This cannot really happen, but just to be complete */
4281 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4284 /* Oops.. we have already been here and still haven't
4285 * found the requested variant. Bail out
4287 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4288 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4294 ACLFilledChecklist
*
4295 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4297 ConnStateData
* conn
= http
->getConn();
4298 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4299 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4302 * hack for ident ACL. It needs to get full addresses, and a place to store
4303 * the ident result on persistent connections...
4305 /* connection oriented auth also needs these two lines for it's operation. */
4309 CBDATA_CLASS_INIT(ConnStateData
);
4312 ConnStateData::transparent() const
4314 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4318 ConnStateData::reading() const
4320 return reader
!= NULL
;
4324 ConnStateData::stopReading()
4327 comm_read_cancel(clientConnection
->fd
, reader
);
4333 ConnStateData::expectRequestBody(int64_t size
)
4335 bodyPipe
= new BodyPipe(this);
4337 bodyPipe
->setBodySize(size
);
4339 startDechunkingRequest();
4344 ConnStateData::mayNeedToReadMoreBody() const
4347 return 0; // request without a body or read/produced all body bytes
4349 if (!bodyPipe
->bodySizeKnown())
4350 return -1; // probably need to read more, but we cannot be sure
4352 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4353 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4355 if (needToProduce
<= haveAvailable
)
4356 return 0; // we have read what we need (but are waiting for pipe space)
4358 return needToProduce
- haveAvailable
;
4362 ConnStateData::stopReceiving(const char *error
)
4364 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4365 "; old sending error: " <<
4366 (stoppedSending() ? stoppedSending_
: "none"));
4368 if (const char *oldError
= stoppedReceiving()) {
4369 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4370 return; // nothing has changed as far as this connection is concerned
4373 stoppedReceiving_
= error
;
4375 if (const char *sendError
= stoppedSending()) {
4376 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4377 clientConnection
->close();
4382 ConnStateData::expectNoForwarding()
4384 if (bodyPipe
!= NULL
) {
4385 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4386 bodyPipe
->expectNoConsumption();
4390 /// initialize dechunking state
4392 ConnStateData::startDechunkingRequest()
4394 Must(bodyPipe
!= NULL
);
4395 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4396 assert(!in
.bodyParser
);
4397 in
.bodyParser
= new ChunkedCodingParser
;
4400 /// put parsed content into input buffer and clean up
4402 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4404 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4406 if (bodyPipe
!= NULL
) {
4407 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4408 BodyPipe::Pointer myPipe
= bodyPipe
;
4409 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4410 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4412 Must(myPipe
->bodySizeKnown());
4413 ClientSocketContext::Pointer context
= getCurrentContext();
4414 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4415 context
->http
->request
->setContentLength(myPipe
->bodySize());
4419 delete in
.bodyParser
;
4420 in
.bodyParser
= NULL
;
4424 ConnStateData::In::addressToReadInto() const
4426 return buf
+ notYetUsed
;
4429 ConnStateData::In::In() : bodyParser(NULL
),
4430 buf (NULL
), notYetUsed (0), allocatedSize (0)
4433 ConnStateData::In::~In()
4436 memFreeBuf(allocatedSize
, buf
);
4437 delete bodyParser
; // TODO: pool
4441 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4444 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4448 ClientSocketContext::Pointer context
= getCurrentContext();
4449 if (context
!= NULL
) {
4450 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4454 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4455 clientConnection
->close();
4458 /// Our close handler called by Comm when the pinned connection is closed
4460 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4462 // FwdState might repin a failed connection sooner than this close
4463 // callback is called for the failed connection.
4464 assert(pinning
.serverConnection
== io
.conn
);
4465 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4466 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4468 if (sawZeroReply
&& clientConnection
!= NULL
) {
4469 debugs(33, 3, "Closing client connection on pinned zero reply.");
4470 clientConnection
->close();
4475 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4477 char desc
[FD_DESC_SZ
];
4479 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4480 if (pinning
.serverConnection
->fd
== pinServer
->fd
) {
4481 startPinnedConnectionMonitoring();
4486 unpinConnection(); // closes pinned connection, if any, and resets fields
4488 pinning
.serverConnection
= pinServer
;
4490 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4492 // when pinning an SSL bumped connection, the request may be NULL
4493 const char *pinnedHost
= "[unknown]";
4495 pinning
.host
= xstrdup(request
->GetHost());
4496 pinning
.port
= request
->port
;
4497 pinnedHost
= pinning
.host
;
4499 pinning
.port
= pinServer
->remote
.port();
4501 pinning
.pinned
= true;
4503 pinning
.peer
= cbdataReference(aPeer
);
4504 pinning
.auth
= auth
;
4505 char stmp
[MAX_IPSTRLEN
];
4506 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4507 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4508 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4509 clientConnection
->fd
);
4510 fd_note(pinning
.serverConnection
->fd
, desc
);
4512 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4513 pinning
.closeHandler
= JobCallback(33, 5,
4514 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4515 // remember the pinned connection so that cb does not unpin a fresher one
4516 typedef CommCloseCbParams Params
;
4517 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4518 params
.conn
= pinning
.serverConnection
;
4519 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4521 startPinnedConnectionMonitoring();
4524 /// Assign a read handler to an idle pinned connection so that we can detect connection closures.
4526 ConnStateData::startPinnedConnectionMonitoring()
4528 if (pinning
.readHandler
!= NULL
)
4529 return; // already monitoring
4531 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4532 pinning
.readHandler
= JobCallback(33, 3,
4533 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4534 static char unusedBuf
[8];
4535 comm_read(pinning
.serverConnection
, unusedBuf
, sizeof(unusedBuf
), pinning
.readHandler
);
4539 ConnStateData::stopPinnedConnectionMonitoring()
4541 if (pinning
.readHandler
!= NULL
) {
4542 comm_read_cancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4543 pinning
.readHandler
= NULL
;
4547 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4548 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4550 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4552 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4554 if (io
.flag
== COMM_ERR_CLOSING
)
4555 return; // close handler will clean up
4557 // We could use getConcurrentRequestCount(), but this may be faster.
4558 const bool clientIsIdle
= !getCurrentContext();
4560 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4561 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4563 assert(pinning
.serverConnection
== io
.conn
);
4564 pinning
.serverConnection
->close();
4566 // If we are still sending data to the client, do not close now. When we are done sending,
4567 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4568 // However, if we are idle, then we must close to inform the idle client and minimize races.
4569 if (clientIsIdle
&& clientConnection
!= NULL
)
4570 clientConnection
->close();
4573 const Comm::ConnectionPointer
4574 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4576 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4579 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4581 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4583 else if (request
&& pinning
.port
!= request
->port
)
4585 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4587 else if (aPeer
!= pinning
.peer
)
4591 /* The pinning info is not safe, remove any pinning info */
4595 return pinning
.serverConnection
;
4599 ConnStateData::unpinConnection()
4601 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4604 cbdataReferenceDone(pinning
.peer
);
4606 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4607 if (pinning
.closeHandler
!= NULL
) {
4608 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4609 pinning
.closeHandler
= NULL
;
4611 /// also close the server side socket, we should not use it for any future requests...
4612 // TODO: do not close if called from our close handler?
4613 pinning
.serverConnection
->close();
4616 safe_free(pinning
.host
);
4618 pinning
.zeroReply
= false;
4620 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4621 * connection has gone away */