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
.count
;
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 clientStream_status_t
1786 ClientSocketContext::socketState()
1788 switch (clientStreamStatus(getTail(), http
)) {
1791 /* check for range support ending */
1793 if (http
->request
->range
) {
1794 /* check: reply was parsed and range iterator was initialized */
1795 assert(http
->range_iter
.valid
);
1796 /* filter out data according to range specs */
1798 if (!canPackMoreRanges()) {
1799 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1800 "range sequence on " << clientConnection
);
1802 if (http
->request
->flags
.proxyKeepalive
)
1803 return STREAM_COMPLETE
;
1805 return STREAM_UNPLANNED_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 if (http
->request
->flags
.proxyKeepalive
)
1820 return STREAM_COMPLETE
;
1822 return STREAM_UNPLANNED_COMPLETE
;
1825 // The logic below is not clear: If we got more than we
1826 // expected why would persistency matter? Should not this
1827 // always be an error?
1828 if (bytesSent
> bytesExpected
) { // got extra
1829 if (http
->request
->flags
.proxyKeepalive
)
1830 return STREAM_COMPLETE
;
1832 return STREAM_UNPLANNED_COMPLETE
;
1835 // did not get enough yet, expecting more
1840 case STREAM_COMPLETE
:
1841 return STREAM_COMPLETE
;
1843 case STREAM_UNPLANNED_COMPLETE
:
1844 return STREAM_UNPLANNED_COMPLETE
;
1847 return STREAM_FAILED
;
1850 fatal ("unreachable code\n");
1855 * A write has just completed to the client, or we have just realised there is
1856 * no more data to send.
1859 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1861 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1862 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1865 /// remembers the abnormal connection termination for logging purposes
1867 ClientSocketContext::noteIoError(const int xerrno
)
1870 if (xerrno
== ETIMEDOUT
)
1871 http
->al
->http
.timedout
= true;
1872 else // even if xerrno is zero (which means read abort/eof)
1873 http
->al
->http
.aborted
= true;
1878 ClientSocketContext::doClose()
1880 clientConnection
->close();
1883 /// called when we encounter a response-related error
1885 ClientSocketContext::initiateClose(const char *reason
)
1887 http
->getConn()->stopSending(reason
); // closes ASAP
1891 ConnStateData::stopSending(const char *error
)
1893 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1894 "; old receiving error: " <<
1895 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1897 if (const char *oldError
= stoppedSending()) {
1898 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1899 return; // nothing has changed as far as this connection is concerned
1901 stoppedSending_
= error
;
1903 if (!stoppedReceiving()) {
1904 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1905 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1906 " request body bytes with " << in
.notYetUsed
<< " unused");
1907 return; // wait for the request receiver to finish reading
1911 clientConnection
->close();
1915 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1917 const StoreEntry
*entry
= http
->storeEntry();
1918 http
->out
.size
+= size
;
1919 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1920 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1921 (entry
? entry
->objectLen() : 0));
1922 clientUpdateSocketStats(http
->logType
, size
);
1924 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1926 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1929 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1930 initiateClose("failure or true request status");
1931 /* Do we leak here ? */
1935 switch (socketState()) {
1941 case STREAM_COMPLETE
:
1942 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1943 keepaliveNextRequest();
1946 case STREAM_UNPLANNED_COMPLETE
:
1947 initiateClose("STREAM_UNPLANNED_COMPLETE");
1951 initiateClose("STREAM_FAILED");
1955 fatal("Hit unreachable code in clientWriteComplete\n");
1959 SQUIDCEXTERN CSR clientGetMoreData
;
1960 SQUIDCEXTERN CSS clientReplyStatus
;
1961 SQUIDCEXTERN CSD clientReplyDetach
;
1963 static ClientSocketContext
*
1964 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1966 ClientHttpRequest
*http
;
1967 ClientSocketContext
*context
;
1968 StoreIOBuffer tempBuffer
;
1969 http
= new ClientHttpRequest(csd
);
1970 http
->req_sz
= csd
->in
.notYetUsed
;
1971 http
->uri
= xstrdup(uri
);
1972 setLogUri (http
, uri
);
1973 context
= new ClientSocketContext(csd
->clientConnection
, http
);
1974 tempBuffer
.data
= context
->reqbuf
;
1975 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1976 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1977 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1978 clientSocketDetach
, context
, tempBuffer
);
1983 skipLeadingSpace(char *aString
)
1985 char *result
= aString
;
1987 while (xisspace(*aString
))
1994 * 'end' defaults to NULL for backwards compatibility
1995 * remove default value if we ever get rid of NULL-terminated
1999 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
2002 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
2006 for (; end
> uriAndHTTPVersion
; --end
) {
2007 if (*end
== '\n' || *end
== '\r')
2010 if (xisspace(*end
)) {
2011 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2022 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2024 safe_free(http
->log_uri
);
2027 // The uri is already clean just dump it.
2028 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2031 switch (Config
.uri_whitespace
) {
2032 case URI_WHITESPACE_ALLOW
:
2033 flags
|= RFC1738_ESCAPE_NOSPACE
;
2035 case URI_WHITESPACE_ENCODE
:
2036 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2037 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2040 case URI_WHITESPACE_CHOP
: {
2041 flags
|= RFC1738_ESCAPE_NOSPACE
;
2042 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2043 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2044 int pos
= strcspn(http
->log_uri
, w_space
);
2045 http
->log_uri
[pos
] = '\0';
2049 case URI_WHITESPACE_DENY
:
2050 case URI_WHITESPACE_STRIP
:
2053 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2057 if (!xisspace(*t
)) {
2064 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2073 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2075 int vhost
= conn
->port
->vhost
;
2076 int vport
= conn
->port
->vport
;
2078 char ipbuf
[MAX_IPSTRLEN
];
2080 http
->flags
.accel
= true;
2082 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2084 if (strncasecmp(url
, "cache_object://", 15) == 0)
2085 return; /* already in good shape */
2088 if (conn
->port
->vhost
)
2089 return; /* already in good shape */
2091 /* else we need to ignore the host name */
2092 url
= strstr(url
, "//");
2094 #if SHOULD_REJECT_UNKNOWN_URLS
2097 hp
->request_parse_status
= Http::scBadRequest
;
2098 return parseHttpRequestAbort(conn
, "error:invalid-request");
2103 url
= strchr(url
+ 2, '/');
2110 vport
= http
->getConn()->clientConnection
->local
.port();
2112 const bool switchedToHttps
= conn
->switchedToHttps();
2113 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2114 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2115 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2120 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2121 strncpy(thost
, host
, (t
-host
));
2122 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2125 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2128 } // else nothing to alter port-wise.
2129 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2131 http
->uri
= (char *)xcalloc(url_sz
, 1);
2132 const char *protocol
= switchedToHttps
?
2133 "https" : URLScheme(conn
->port
->transport
.protocol
).const_str();
2134 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2135 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2136 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2137 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2138 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2139 strlen(conn
->port
->defaultsite
);
2140 http
->uri
= (char *)xcalloc(url_sz
, 1);
2144 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2146 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2147 URLScheme(conn
->port
->transport
.protocol
).const_str(), conn
->port
->defaultsite
, vportStr
, url
);
2148 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2149 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2150 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2151 /* Put the local socket IP address as the hostname, with whatever vport we found */
2152 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2153 http
->uri
= (char *)xcalloc(url_sz
, 1);
2154 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2155 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2156 URLScheme(conn
->port
->transport
.protocol
).const_str(),
2158 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2163 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2166 char ipbuf
[MAX_IPSTRLEN
];
2169 return; /* already in good shape */
2171 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2173 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2174 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2176 http
->uri
= (char *)xcalloc(url_sz
, 1);
2177 snprintf(http
->uri
, url_sz
, "%s://%s%s", URLScheme(conn
->port
->transport
.protocol
).const_str(), host
, url
);
2178 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2180 /* Put the local socket IP address as the hostname. */
2181 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2182 http
->uri
= (char *)xcalloc(url_sz
, 1);
2183 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2184 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2185 URLScheme(http
->getConn()->port
->transport
.protocol
).const_str(),
2186 ipbuf
, http
->getConn()->clientConnection
->local
.port(), url
);
2187 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2191 /** Parse an HTTP request
2193 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2194 * to 1 if the request was correctly parsed.
2195 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2196 * \param[in] hp an HttpParser
2197 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2198 * Pointed-to value will be set to Http::METHOD_NONE in case of
2200 * \param[out] http_ver will be set as a side-effect of the parsing
2201 * \return NULL on incomplete requests,
2202 * a ClientSocketContext structure on success or failure.
2204 static ClientSocketContext
*
2205 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2207 char *req_hdr
= NULL
;
2210 ClientHttpRequest
*http
;
2211 ClientSocketContext
*result
;
2212 StoreIOBuffer tempBuffer
;
2215 /* pre-set these values to make aborting simpler */
2216 *method_p
= Http::METHOD_NONE
;
2218 /* NP: don't be tempted to move this down or remove again.
2219 * It's the only DDoS protection old-String has against long URL */
2220 if ( hp
->bufsiz
<= 0) {
2221 debugs(33, 5, "Incomplete request, waiting for end of request line");
2223 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2224 debugs(33, 5, "parseHttpRequest: Too large request");
2225 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2226 return parseHttpRequestAbort(csd
, "error:request-too-large");
2229 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2230 r
= HttpParserParseReqLine(hp
);
2233 debugs(33, 5, "Incomplete request, waiting for end of request line");
2238 return parseHttpRequestAbort(csd
, "error:invalid-request");
2241 /* Request line is valid here .. */
2242 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2244 /* This call scans the entire request, not just the headers */
2245 if (hp
->req
.v_maj
> 0) {
2246 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2247 debugs(33, 5, "Incomplete request, waiting for end of headers");
2251 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2252 req_sz
= HttpParserReqSz(hp
);
2255 /* We know the whole request is in hp->buf now */
2257 assert(req_sz
<= (size_t) hp
->bufsiz
);
2259 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2260 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2263 hp
->hdr_end
= req_sz
- 1;
2265 hp
->hdr_start
= hp
->req
.end
+ 1;
2267 /* Enforce max_request_size */
2268 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2269 debugs(33, 5, "parseHttpRequest: Too large request");
2270 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2271 return parseHttpRequestAbort(csd
, "error:request-too-large");
2275 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2277 /* deny CONNECT via accelerated ports */
2278 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2279 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->transport
.protocol
<< " Accelerator port " << csd
->port
->s
.port());
2280 /* XXX need a way to say "this many character length string" */
2281 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2282 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2283 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2286 if (*method_p
== Http::METHOD_NONE
) {
2287 /* XXX need a way to say "this many character length string" */
2288 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2289 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2290 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2294 * Process headers after request line
2295 * TODO: Use httpRequestParse here.
2297 /* XXX this code should be modified to take a const char * later! */
2298 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2300 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2302 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2304 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2306 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2307 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2308 HttpParserReqSz(hp
));
2310 /* Ok, all headers are received */
2311 http
= new ClientHttpRequest(csd
);
2313 http
->req_sz
= HttpParserRequestLen(hp
);
2314 result
= new ClientSocketContext(csd
->clientConnection
, http
);
2315 tempBuffer
.data
= result
->reqbuf
;
2316 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2318 ClientStreamData newServer
= new clientReplyContext(http
);
2319 ClientStreamData newClient
= result
;
2320 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2321 clientReplyStatus
, newServer
, clientSocketRecipient
,
2322 clientSocketDetach
, newClient
, tempBuffer
);
2324 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2328 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2329 * below needs to be modified to not expect a mutable nul-terminated string.
2331 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2333 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2335 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2337 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2339 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2344 debugs(33,5, HERE
<< "repare absolute URL from " <<
2345 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2346 /* Rewrite the URL in transparent or accelerator mode */
2347 /* NP: there are several cases to traverse here:
2348 * - standard mode (forward proxy)
2349 * - transparent mode (TPROXY)
2350 * - transparent mode with failures
2351 * - intercept mode (NAT)
2352 * - intercept mode with failures
2353 * - accelerator mode (reverse proxy)
2355 * - mixed combos of the above with internal URL
2357 if (csd
->transparent()) {
2358 /* intercept or transparent mode, properly working with no failures */
2359 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2361 } else if (internalCheck(url
)) {
2362 /* internal URL mode */
2363 /* prepend our name & port */
2364 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2365 // We just re-wrote the URL. Must replace the Host: header.
2366 // But have not parsed there yet!! flag for local-only handling.
2367 http
->flags
.internal
= true;
2369 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2370 /* accelerator mode */
2371 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2375 /* No special rewrites have been applied above, use the
2376 * requested url. may be rewritten later, so make extra room */
2377 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2378 http
->uri
= (char *)xcalloc(url_sz
, 1);
2379 strcpy(http
->uri
, url
);
2382 debugs(33, 5, "parseHttpRequest: Complete request received");
2384 // XXX: crop this dump at the end of headers. No need for extras
2385 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2386 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2388 result
->flags
.parsed_ok
= 1;
2394 ConnStateData::getAvailableBufferLength() const
2396 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2397 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2398 // huge request_header_max_size may lead to more than INT_MAX unused space
2399 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2404 ConnStateData::maybeMakeSpaceAvailable()
2406 if (getAvailableBufferLength() < 2) {
2408 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2409 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2412 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2413 newSize
=Config
.maxRequestBufferSize
;
2415 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2416 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2422 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2424 ClientSocketContext::Pointer
*S
;
2426 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2434 ConnStateData::getConcurrentRequestCount() const
2437 ClientSocketContext::Pointer
*T
;
2439 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2440 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2445 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2447 if (flag
!= COMM_OK
) {
2448 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2453 if (!ignoreErrno(xerrno
)) {
2454 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2456 } else if (in
.notYetUsed
== 0) {
2457 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2465 ConnStateData::connFinishedWithConn(int size
)
2468 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2469 /* no current or pending requests */
2470 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2472 } else if (!Config
.onoff
.half_closed_clients
) {
2473 /* admin doesn't want to support half-closed client sockets */
2474 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2475 notifyAllContexts(0); // no specific error implies abort
2484 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2486 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2487 conn
->in
.notYetUsed
-= byteCount
;
2488 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2490 * If there is still data that will be used,
2491 * move it to the beginning.
2494 if (conn
->in
.notYetUsed
> 0)
2495 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2498 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2500 ConnStateData::checkHeaderLimits()
2502 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2503 return; // can accumulte more header data
2505 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2506 Config
.maxRequestHeaderSize
<< " bytes)");
2508 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2509 clientStreamNode
*node
= context
->getClientReplyContext();
2510 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2511 assert (repContext
);
2512 repContext
->setReplyToError(ERR_TOO_BIG
,
2513 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2514 clientConnection
->remote
, NULL
, NULL
, NULL
);
2515 context
->registerWithConn();
2516 context
->pullData();
2520 ConnStateData::clientAfterReadingRequests()
2522 // Were we expecting to read more request body from half-closed connection?
2523 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2524 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2525 clientConnection
->close();
2534 ConnStateData::quitAfterError(HttpRequest
*request
)
2536 // From HTTP p.o.v., we do not have to close after every error detected
2537 // at the client-side, but many such errors do require closure and the
2538 // client-side code is bad at handling errors so we play it safe.
2540 request
->flags
.proxyKeepalive
= false;
2541 flags
.readMore
= false;
2542 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2546 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2548 ClientHttpRequest
*http
= context
->http
;
2553 assert(sslServerBump
->entry
);
2554 // Did we create an error entry while processing CONNECT?
2555 if (!sslServerBump
->entry
->isEmpty()) {
2556 quitAfterError(http
->request
);
2558 // Get the saved error entry and send it to the client by replacing the
2559 // ClientHttpRequest store entry with it.
2560 clientStreamNode
*node
= context
->getClientReplyContext();
2561 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2563 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2564 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2566 // save the original request for logging purposes
2567 if (!context
->http
->al
->request
) {
2568 context
->http
->al
->request
= http
->request
;
2569 HTTPMSGLOCK(context
->http
->al
->request
);
2572 // Get error details from the fake certificate-peeking request.
2573 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2574 context
->pullData();
2578 // In bump-server-first mode, we have not necessarily seen the intended
2579 // server name at certificate-peeking time. Check for domain mismatch now,
2580 // when we can extract the intended name from the bumped HTTP request.
2581 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2582 HttpRequest
*request
= http
->request
;
2583 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2584 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2585 "does not match domainname " << request
->GetHost());
2587 bool allowDomainMismatch
= false;
2588 if (Config
.ssl_client
.cert_error
) {
2589 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2590 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2591 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2592 delete check
.sslErrors
;
2593 check
.sslErrors
= NULL
;
2596 if (!allowDomainMismatch
) {
2597 quitAfterError(request
);
2599 clientStreamNode
*node
= context
->getClientReplyContext();
2600 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2601 assert (repContext
);
2603 // Fill the server IP and hostname for error page generation.
2604 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2605 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2607 // Create an error object and fill it
2608 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2609 err
->src_addr
= clientConnection
->remote
;
2610 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2611 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2613 err
->detail
= errDetail
;
2614 // Save the original request for logging purposes.
2615 if (!context
->http
->al
->request
) {
2616 context
->http
->al
->request
= request
;
2617 HTTPMSGLOCK(context
->http
->al
->request
);
2619 repContext
->setReplyToError(request
->method
, err
);
2620 assert(context
->http
->out
.offset
== 0);
2621 context
->pullData();
2632 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2634 ClientHttpRequest
*http
= context
->http
;
2635 HttpRequest::Pointer request
;
2636 bool notedUseOfBuffer
= false;
2637 bool chunked
= false;
2638 bool mustReplyToOptions
= false;
2639 bool unsupportedTe
= false;
2640 bool expectBody
= false;
2642 /* We have an initial client stream in place should it be needed */
2643 /* setup our private context */
2644 context
->registerWithConn();
2646 if (context
->flags
.parsed_ok
== 0) {
2647 clientStreamNode
*node
= context
->getClientReplyContext();
2648 debugs(33, 2, "clientProcessRequest: Invalid Request");
2649 conn
->quitAfterError(NULL
);
2650 // setLogUri should called before repContext->setReplyToError
2651 setLogUri(http
, http
->uri
, true);
2652 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2653 assert (repContext
);
2654 switch (hp
->request_parse_status
) {
2655 case Http::scHeaderTooLarge
:
2656 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2658 case Http::scMethodNotAllowed
:
2659 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2660 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2663 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2664 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2666 assert(context
->http
->out
.offset
== 0);
2667 context
->pullData();
2671 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2672 clientStreamNode
*node
= context
->getClientReplyContext();
2673 debugs(33, 5, "Invalid URL: " << http
->uri
);
2674 conn
->quitAfterError(request
.getRaw());
2675 // setLogUri should called before repContext->setReplyToError
2676 setLogUri(http
, http
->uri
, true);
2677 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2678 assert (repContext
);
2679 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2680 assert(context
->http
->out
.offset
== 0);
2681 context
->pullData();
2685 /* RFC 2616 section 10.5.6 : handle unsupported HTTP major versions cleanly. */
2686 /* We currently only support 0.9, 1.0, 1.1 properly */
2687 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2688 (http_ver
.major
> 1) ) {
2690 clientStreamNode
*node
= context
->getClientReplyContext();
2691 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2692 conn
->quitAfterError(request
.getRaw());
2693 // setLogUri should called before repContext->setReplyToError
2694 setLogUri(http
, http
->uri
, true);
2695 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2696 assert (repContext
);
2697 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2698 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2699 assert(context
->http
->out
.offset
== 0);
2700 context
->pullData();
2704 /* compile headers */
2705 /* we should skip request line! */
2706 /* XXX should actually know the damned buffer size here */
2707 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2708 clientStreamNode
*node
= context
->getClientReplyContext();
2709 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2710 conn
->quitAfterError(request
.getRaw());
2711 // setLogUri should called before repContext->setReplyToError
2712 setLogUri(http
, http
->uri
, true);
2713 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2714 assert (repContext
);
2715 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2716 assert(context
->http
->out
.offset
== 0);
2717 context
->pullData();
2721 request
->clientConnectionManager
= conn
;
2723 request
->flags
.accelerated
= http
->flags
.accel
;
2724 request
->flags
.sslBumped
=conn
->switchedToHttps();
2725 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2726 // TODO: decouple http->flags.accel from request->flags.sslBumped
2727 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2728 !conn
->port
->allow_direct
: 0;
2730 if (request
->flags
.sslBumped
) {
2731 if (conn
->getAuth() != NULL
)
2732 request
->auth_user_request
= conn
->getAuth();
2737 * If transparent or interception mode is working clone the transparent and interception flags
2738 * from the port settings to the request.
2740 if (http
->clientConnection
!= NULL
) {
2741 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2742 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2743 if (request
->flags
.interceptTproxy
) {
2744 if (Config
.accessList
.spoof_client_ip
) {
2745 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2746 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2749 request
->flags
.spoofClientIp
= true;
2751 request
->flags
.spoofClientIp
= false;
2754 if (internalCheck(request
->urlpath
.termedBuf())) {
2755 if (internalHostnameIs(request
->GetHost()) &&
2756 request
->port
== getMyPort()) {
2757 http
->flags
.internal
= true;
2758 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2759 request
->SetHost(internalHostname());
2760 request
->port
= getMyPort();
2761 http
->flags
.internal
= true;
2765 if (http
->flags
.internal
) {
2766 request
->protocol
= AnyP::PROTO_HTTP
;
2767 request
->login
[0] = '\0';
2770 request
->flags
.internal
= http
->flags
.internal
;
2771 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2772 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2773 #if FOLLOW_X_FORWARDED_FOR
2774 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2775 // not a details about teh TCP connection itself
2776 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2777 #endif /* FOLLOW_X_FORWARDED_FOR */
2778 request
->my_addr
= conn
->clientConnection
->local
;
2779 request
->myportname
= conn
->port
->name
;
2780 request
->http_ver
= http_ver
;
2782 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2783 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2784 request
->clientConnectionManager
= conn
;
2786 if (request
->header
.chunked()) {
2788 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2789 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2790 // HTTP/1.1 requires chunking to be the last encoding if there is one
2791 unsupportedTe
= te
.size() && te
!= "identity";
2792 } // else implied identity coding
2794 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2795 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2796 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2797 clientStreamNode
*node
= context
->getClientReplyContext();
2798 conn
->quitAfterError(request
.getRaw());
2799 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2800 assert (repContext
);
2801 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2802 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2803 assert(context
->http
->out
.offset
== 0);
2804 context
->pullData();
2808 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2809 clientStreamNode
*node
= context
->getClientReplyContext();
2810 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2811 assert (repContext
);
2812 conn
->quitAfterError(request
.getRaw());
2813 repContext
->setReplyToError(ERR_INVALID_REQ
,
2814 Http::scLengthRequired
, request
->method
, NULL
,
2815 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2816 assert(context
->http
->out
.offset
== 0);
2817 context
->pullData();
2821 if (request
->header
.has(HDR_EXPECT
)) {
2822 const String expect
= request
->header
.getList(HDR_EXPECT
);
2823 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2824 if (!supportedExpect
) {
2825 clientStreamNode
*node
= context
->getClientReplyContext();
2826 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2827 assert (repContext
);
2828 conn
->quitAfterError(request
.getRaw());
2829 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2830 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2831 assert(context
->http
->out
.offset
== 0);
2832 context
->pullData();
2837 http
->request
= request
.getRaw();
2838 HTTPMSGLOCK(http
->request
);
2839 clientSetKeepaliveFlag(http
);
2841 // Let tunneling code be fully responsible for CONNECT requests
2842 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2843 context
->mayUseConnection(true);
2844 conn
->flags
.readMore
= false;
2848 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2852 /* Do we expect a request-body? */
2853 expectBody
= chunked
|| request
->content_length
> 0;
2854 if (!context
->mayUseConnection() && expectBody
) {
2855 request
->body_pipe
= conn
->expectRequestBody(
2856 chunked
? -1 : request
->content_length
);
2858 // consume header early so that body pipe gets just the body
2859 connNoteUseOfBuffer(conn
, http
->req_sz
);
2860 notedUseOfBuffer
= true;
2862 /* Is it too large? */
2863 if (!chunked
&& // if chunked, we will check as we accumulate
2864 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2865 clientStreamNode
*node
= context
->getClientReplyContext();
2866 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2867 assert (repContext
);
2868 conn
->quitAfterError(request
.getRaw());
2869 repContext
->setReplyToError(ERR_TOO_BIG
,
2870 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2871 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2872 assert(context
->http
->out
.offset
== 0);
2873 context
->pullData();
2877 // We may stop producing, comm_close, and/or call setReplyToError()
2878 // below, so quit on errors to avoid http->doCallouts()
2879 if (!conn
->handleRequestBodyData())
2882 if (!request
->body_pipe
->productionEnded()) {
2883 debugs(33, 5, HERE
<< "need more request body");
2884 context
->mayUseConnection(true);
2885 assert(conn
->flags
.readMore
);
2889 http
->calloutContext
= new ClientRequestContext(http
);
2894 if (!notedUseOfBuffer
)
2895 connNoteUseOfBuffer(conn
, http
->req_sz
);
2899 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2900 * to here because calling comm_reset_close() causes http to
2901 * be freed and the above connNoteUseOfBuffer() would hit an
2902 * assertion, not to mention that we were accessing freed memory.
2904 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2905 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2906 conn
->flags
.readMore
= false;
2907 comm_reset_close(conn
->clientConnection
);
2912 connStripBufferWhitespace (ConnStateData
* conn
)
2914 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2915 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2916 -- conn
->in
.notYetUsed
;
2921 * Limit the number of concurrent requests.
2922 * \return true when there are available position(s) in the pipeline queue for another request.
2923 * \return false when the pipeline queue is full or disabled.
2926 ConnStateData::concurrentRequestQueueFilled() const
2928 const int existingRequestCount
= getConcurrentRequestCount();
2930 // default to the configured pipeline size.
2931 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2932 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2934 // when queue filled already we cant add more.
2935 if (existingRequestCount
>= concurrentRequestLimit
) {
2936 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2937 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2945 * Attempt to parse one or more requests from the input buffer.
2946 * If a request is successfully parsed, even if the next request
2947 * is only partially parsed, it will return TRUE.
2950 ConnStateData::clientParseRequests()
2952 HttpRequestMethod method
;
2953 bool parsed_req
= false;
2955 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2957 // Loop while we have read bytes that are not needed for producing the body
2958 // On errors, bodyPipe may become nil, but readMore will be cleared
2959 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2960 connStripBufferWhitespace(this);
2962 /* Don't try to parse if the buffer is empty */
2963 if (in
.notYetUsed
== 0)
2966 /* Limit the number of concurrent requests */
2967 if (concurrentRequestQueueFilled())
2970 /* Should not be needed anymore */
2971 /* Terminate the string */
2972 in
.buf
[in
.notYetUsed
] = '\0';
2974 /* Begin the parsing */
2975 PROF_start(parseHttpRequest
);
2976 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
2978 /* Process request */
2979 Http::ProtocolVersion http_ver
;
2980 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2981 PROF_stop(parseHttpRequest
);
2983 /* partial or incomplete request */
2985 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2986 // (which becomes context) but checkHeaderLimits cannot?
2987 checkHeaderLimits();
2991 /* status -1 or 1 */
2993 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2994 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2995 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2996 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2998 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
3000 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3002 if (context
->mayUseConnection()) {
3003 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3009 /* XXX where to 'finish' the parsing pass? */
3014 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3016 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3020 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
3022 if (io
.flag
== COMM_ERR_CLOSING
) {
3023 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
3027 assert(Comm::IsConnOpen(clientConnection
));
3028 assert(io
.conn
->fd
== clientConnection
->fd
);
3031 * Don't reset the timeout value here. The timeout value will be
3032 * set to Config.Timeout.request by httpAccept() and
3033 * clientWriteComplete(), and should apply to the request as a
3034 * whole, not individual read() calls. Plus, it breaks our
3035 * lame half-close detection
3037 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3038 notifyAllContexts(io
.xerrno
);
3043 if (io
.flag
== COMM_OK
) {
3045 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3047 // may comm_close or setReplyToError
3048 if (!handleReadData(io
.buf
, io
.size
))
3051 } else if (io
.size
== 0) {
3052 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3054 if (connFinishedWithConn(io
.size
)) {
3055 clientConnection
->close();
3059 /* It might be half-closed, we can't tell */
3060 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3062 commMarkHalfClosed(io
.conn
->fd
);
3064 fd_note(io
.conn
->fd
, "half-closed");
3066 /* There is one more close check at the end, to detect aborted
3067 * (partial) requests. At this point we can't tell if the request
3070 /* Continue to process previously read data */
3074 /* Process next request */
3075 if (getConcurrentRequestCount() == 0)
3076 fd_note(io
.fd
, "Reading next request");
3078 if (!clientParseRequests()) {
3082 * If the client here is half closed and we failed
3083 * to parse a request, close the connection.
3084 * The above check with connFinishedWithConn() only
3085 * succeeds _if_ the buffer is empty which it won't
3086 * be if we have an incomplete request.
3087 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3089 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3090 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3091 clientConnection
->close();
3099 clientAfterReadingRequests();
3103 * called when new request data has been read from the socket
3105 * \retval false called comm_close or setReplyToError (the caller should bail)
3106 * \retval true we did not call comm_close or setReplyToError
3109 ConnStateData::handleReadData(char *buf
, size_t size
)
3111 char *current_buf
= in
.addressToReadInto();
3113 if (buf
!= current_buf
)
3114 memmove(current_buf
, buf
, size
);
3116 in
.notYetUsed
+= size
;
3118 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3120 // if we are reading a body, stuff data into the body pipe
3121 if (bodyPipe
!= NULL
)
3122 return handleRequestBodyData();
3127 * called when new request body data has been buffered in in.buf
3128 * may close the connection if we were closing and piped everything out
3130 * \retval false called comm_close or setReplyToError (the caller should bail)
3131 * \retval true we did not call comm_close or setReplyToError
3134 ConnStateData::handleRequestBodyData()
3136 assert(bodyPipe
!= NULL
);
3140 if (in
.bodyParser
) { // chunked encoding
3141 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3142 abortChunkedRequestBody(error
);
3145 } else { // identity encoding
3146 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3147 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3148 if (!bodyPipe
->mayNeedMoreData()) {
3149 // BodyPipe will clear us automagically when we produced everything
3155 connNoteUseOfBuffer(this, putSize
);
3158 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3160 if (const char *reason
= stoppedSending()) {
3161 /* we've finished reading like good clients,
3162 * now do the close that initiateClose initiated.
3164 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3165 clientConnection
->close();
3173 /// parses available chunked encoded body bytes, checks size, returns errors
3175 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3177 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3179 try { // the parser will throw on errors
3181 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3184 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3185 // add one because MemBuf will assert if it cannot 0-terminate
3186 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3187 raw
.append(in
.buf
, in
.notYetUsed
);
3189 const mb_size_t wasContentSize
= raw
.contentSize();
3190 BodyPipeCheckout
bpc(*bodyPipe
);
3191 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3193 putSize
= wasContentSize
- raw
.contentSize();
3195 // dechunk then check: the size limit applies to _dechunked_ content
3196 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3200 finishDechunkingRequest(true);
3202 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3205 // if chunk parser needs data, then the body pipe must need it too
3206 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3208 // if parser needs more space and we can consume nothing, we will stall
3209 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3210 } catch (...) { // TODO: be more specific
3211 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3212 return ERR_INVALID_REQ
;
3215 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3219 /// quit on errors related to chunked request body handling
3221 ConnStateData::abortChunkedRequestBody(const err_type error
)
3223 finishDechunkingRequest(false);
3225 // XXX: The code below works if we fail during initial request parsing,
3226 // but if we fail when the server-side works already, the server may send
3227 // us its response too, causing various assertions. How to prevent that?
3228 #if WE_KNOW_HOW_TO_SEND_ERRORS
3229 ClientSocketContext::Pointer context
= getCurrentContext();
3230 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3231 clientStreamNode
*node
= context
->getClientReplyContext();
3232 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3234 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3235 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3236 repContext
->setReplyToError(error
, scode
,
3237 repContext
->http
->request
->method
,
3238 repContext
->http
->uri
,
3240 repContext
->http
->request
,
3242 context
->pullData();
3244 // close or otherwise we may get stuck as nobody will notice the error?
3245 comm_reset_close(clientConnection
);
3248 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3249 comm_reset_close(clientConnection
);
3251 flags
.readMore
= false;
3255 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3257 if (!handleRequestBodyData())
3260 // too late to read more body
3261 if (!isOpen() || stoppedReceiving())
3268 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3270 // request reader may get stuck waiting for space if nobody consumes body
3271 if (bodyPipe
!= NULL
)
3272 bodyPipe
->enableAutoConsumption();
3274 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3277 /** general lifetime handler for HTTP requests */
3279 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3282 * Just close the connection to not confuse browsers
3283 * using persistent connections. Some browsers open
3284 * a connection and then do not use it until much
3285 * later (presumeably because the request triggering
3286 * the open has already been completed on another
3289 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3294 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3296 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3297 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3298 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3299 http
->al
->http
.timedout
= true;
3300 if (Comm::IsConnOpen(io
.conn
))
3304 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3305 AsyncJob("ConnStateData"),
3307 sslBumpMode(Ssl::bumpEnd
),
3308 switchedToHttps_(false),
3309 sslServerBump(NULL
),
3311 stoppedSending_(NULL
),
3312 stoppedReceiving_(NULL
)
3314 pinning
.host
= NULL
;
3316 pinning
.pinned
= false;
3317 pinning
.auth
= false;
3318 pinning
.zeroReply
= false;
3319 pinning
.peer
= NULL
;
3321 // store the details required for creating more MasterXaction objects as new requests come in
3322 clientConnection
= xact
->tcpClient
;
3323 port
= cbdataReference(xact
->squidPort
.get());
3324 log_addr
= xact
->tcpClient
->remote
;
3325 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3327 in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &in
.allocatedSize
);
3329 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3330 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3331 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3332 int i
= IP_PMTUDISC_DONT
;
3333 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3334 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3336 static bool reported
= false;
3339 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3345 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3346 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3347 comm_add_close_handler(clientConnection
->fd
, call
);
3349 if (Config
.onoff
.log_fqdn
)
3350 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3353 if (Ident::TheConfig
.identLookup
) {
3354 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3355 identChecklist
.src_addr
= xact
->tcpClient
->remote
;
3356 identChecklist
.my_addr
= xact
->tcpClient
->local
;
3357 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3358 Ident::Start(xact
->tcpClient
, clientIdentDone
, this);
3362 clientdbEstablished(clientConnection
->remote
, 1);
3364 flags
.readMore
= true;
3367 /** Handle a new connection on HTTP socket. */
3369 httpAccept(const CommAcceptCbParams
¶ms
)
3371 MasterXaction::Pointer xact
= params
.xaction
;
3372 AnyP::PortCfgPointer s
= xact
->squidPort
;
3375 // it is possible the call or accept() was still queued when the port was reconfigured
3376 debugs(33, 2, "HTTP accept failure: port reconfigured.");
3380 if (params
.flag
!= COMM_OK
) {
3381 // Its possible the call was still queued when the client disconnected
3382 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3386 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3387 fd_note(params
.conn
->fd
, "client http connect");
3389 if (s
->tcp_keepalive
.enabled
) {
3390 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3393 ++ incoming_sockets_accepted
;
3395 // Socket is ready, setup the connection manager to start using it
3396 ConnStateData
*connState
= new ConnStateData(xact
);
3398 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3399 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3400 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3401 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3403 connState
->readSomeData();
3406 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3408 if (Config
.onoff
.client_db
) {
3409 /* it was said several times that client write limiter does not work if client_db is disabled */
3411 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3412 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3414 // TODO: we check early to limit error response bandwith but we
3415 // should recheck when we can honor delay_pool_uses_indirect
3416 // TODO: we should also pass the port details for myportname here.
3417 ch
.src_addr
= params
.conn
->remote
;
3418 ch
.my_addr
= params
.conn
->local
;
3420 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3422 /* pools require explicit 'allow' to assign a client into them */
3423 if (pools
[pool
].access
) {
3424 ch
.accessList
= pools
[pool
].access
;
3425 allow_t answer
= ch
.fastCheck();
3426 if (answer
== ACCESS_ALLOWED
) {
3428 /* request client information from db after we did all checks
3429 this will save hash lookup if client failed checks */
3430 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3433 /* put client info in FDE */
3434 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3436 /* setup write limiter for this request */
3437 const double burst
= floor(0.5 +
3438 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3439 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3442 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3452 /** Create SSL connection structure and update fd_table */
3454 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3456 SSL
*ssl
= SSL_new(sslContext
);
3459 const int ssl_error
= ERR_get_error();
3460 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3465 SSL_set_fd(ssl
, conn
->fd
);
3466 fd_table
[conn
->fd
].ssl
= ssl
;
3467 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3468 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3470 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3471 fd_note(conn
->fd
, "client https start");
3476 /** negotiate an SSL connection */
3478 clientNegotiateSSL(int fd
, void *data
)
3480 ConnStateData
*conn
= (ConnStateData
*)data
;
3482 SSL
*ssl
= fd_table
[fd
].ssl
;
3485 if ((ret
= SSL_accept(ssl
)) <= 0) {
3486 int ssl_error
= SSL_get_error(ssl
, ret
);
3488 switch (ssl_error
) {
3490 case SSL_ERROR_WANT_READ
:
3491 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3494 case SSL_ERROR_WANT_WRITE
:
3495 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3498 case SSL_ERROR_SYSCALL
:
3501 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3507 if (errno
== ECONNRESET
)
3510 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3511 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3518 case SSL_ERROR_ZERO_RETURN
:
3519 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3524 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3525 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3526 " (" << ssl_error
<< "/" << ret
<< ")");
3534 if (SSL_session_reused(ssl
)) {
3535 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3536 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3538 if (do_debug(83, 4)) {
3539 /* Write out the SSL session details.. actually the call below, but
3540 * OpenSSL headers do strange typecasts confusing GCC.. */
3541 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3542 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3543 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
);
3545 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3547 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3548 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3549 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3550 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3551 * Because there are two possible usable cast, if you get an error here, try the other
3552 * commented line. */
3554 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3555 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3559 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3562 /* Note: This does not automatically fflush the log file.. */
3565 debugs(83, 2, "clientNegotiateSSL: New session " <<
3566 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3567 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3571 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3572 SSL_get_cipher(ssl
));
3574 client_cert
= SSL_get_peer_certificate(ssl
);
3576 if (client_cert
!= NULL
) {
3577 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3578 " client certificate: subject: " <<
3579 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3581 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3582 " client certificate: issuer: " <<
3583 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3585 X509_free(client_cert
);
3587 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3588 " has no certificate.");
3591 conn
->readSomeData();
3595 * If SSL_CTX is given, starts reading the SSL handshake.
3596 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3599 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3603 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3605 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3608 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3609 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3610 connState
, ConnStateData::requestTimeout
);
3611 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3614 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3616 char buf
[MAX_IPSTRLEN
];
3617 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3618 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3619 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3620 fakeRequest
->port
= details
->local
.port();
3621 fakeRequest
->clientConnectionManager
= connState
;
3622 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3623 #if FOLLOW_X_FORWARDED_FOR
3624 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3626 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3627 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3628 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3629 fakeRequest
->myportname
= connState
->port
->name
;
3630 if (fakeRequest
->flags
.interceptTproxy
) {
3631 if (Config
.accessList
.spoof_client_ip
) {
3632 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3633 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3635 fakeRequest
->flags
.spoofClientIp
= true;
3637 fakeRequest
->flags
.spoofClientIp
= false;
3638 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3639 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3644 * A callback function to use with the ACLFilledChecklist callback.
3645 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3646 * else reverts the connection to tunnel mode.
3649 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3651 ConnStateData
*connState
= (ConnStateData
*) data
;
3653 // if the connection is closed or closing, just return.
3654 if (!connState
->isOpen())
3657 // Require both a match and a positive bump mode to work around exceptional
3658 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3659 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3660 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3661 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3662 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3664 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3665 connState
->sslBumpMode
= Ssl::bumpNone
;
3667 // fake a CONNECT request to force connState to tunnel
3668 static char ip
[MAX_IPSTRLEN
];
3669 static char reqStr
[MAX_IPSTRLEN
+ 80];
3670 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3671 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, ip
);
3672 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3674 ret
= connState
->clientParseRequests();
3677 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3678 connState
->clientConnection
->close();
3683 /** handle a new HTTPS connection */
3685 httpsAccept(const CommAcceptCbParams
¶ms
)
3687 MasterXaction::Pointer xact
= params
.xaction
;
3688 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3691 // it is possible the call or accept() was still queued when the port was reconfigured
3692 debugs(33, 2, "HTTPS accept failure: port reconfigured.");
3696 if (params
.flag
!= COMM_OK
) {
3697 // Its possible the call was still queued when the client disconnected
3698 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3702 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3703 fd_note(params
.conn
->fd
, "client https connect");
3705 if (s
->tcp_keepalive
.enabled
) {
3706 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3709 ++incoming_sockets_accepted
;
3711 // Socket is ready, setup the connection manager to start using it
3712 ConnStateData
*connState
= new ConnStateData(xact
);
3714 if (s
->flags
.tunnelSslBumping
) {
3715 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3717 if (!Config
.accessList
.ssl_bump
) {
3718 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3722 // Create a fake HTTP request for ssl_bump ACL check,
3723 // using tproxy/intercept provided destination IP and port.
3724 HttpRequest
*request
= new HttpRequest();
3725 static char ip
[MAX_IPSTRLEN
];
3726 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3727 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3728 request
->port
= params
.conn
->local
.port();
3729 request
->myportname
= s
->name
;
3731 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3732 acl_checklist
->src_addr
= params
.conn
->remote
;
3733 acl_checklist
->my_addr
= s
->s
;
3734 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3737 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3738 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3743 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3745 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3746 state_data
->sslCrtdHandleReply(reply
);
3750 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3752 if (reply
.result
== HelperReply::BrokenHelper
) {
3753 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3754 } else if (!reply
.other().hasContent()) {
3755 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3757 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3758 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3759 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3761 if (reply
.result
!= HelperReply::Okay
) {
3762 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3764 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3765 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3766 getSslContextDone(ctx
, true);
3771 getSslContextDone(NULL
);
3774 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3776 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3778 // fake certificate adaptation requires bump-server-first mode
3779 if (!sslServerBump
) {
3780 assert(port
->signingCert
.get());
3781 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3782 if (port
->signPkey
.get())
3783 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3784 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3788 // In case of an error while connecting to the secure server, use a fake
3789 // trusted certificate, with no mimicked fields and no adaptation
3790 // algorithms. There is nothing we can mimic so we want to minimize the
3791 // number of warnings the user will have to see to get to the error page.
3792 assert(sslServerBump
->entry
);
3793 if (sslServerBump
->entry
->isEmpty()) {
3794 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3795 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3797 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3798 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3799 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3801 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3802 // If the algorithm already set, then ignore it.
3803 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3804 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3805 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3808 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3809 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3810 const char *param
= ca
->param
;
3812 // For parameterless CN adaptation, use hostname from the
3814 if (ca
->alg
== Ssl::algSetCommonName
) {
3816 param
= sslConnectHostOrIp
.termedBuf();
3817 certProperties
.commonName
= param
;
3818 certProperties
.setCommonName
= true;
3819 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3820 certProperties
.setValidAfter
= true;
3821 else if (ca
->alg
== Ssl::algSetValidBefore
)
3822 certProperties
.setValidBefore
= true;
3824 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3825 alg
<< " param: " << (param
? param
: "-"));
3829 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3830 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3831 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3832 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3836 } else {// if (!sslServerBump->entry->isEmpty())
3837 // Use trusted certificate for a Squid-generated error
3838 // or the user would have to add a security exception
3839 // just to see the error page. We will close the connection
3840 // so that the trust is not extended to non-Squid content.
3841 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3844 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3846 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3847 assert(port
->untrustedSigningCert
.get());
3848 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3849 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3851 assert(port
->signingCert
.get());
3852 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3854 if (port
->signPkey
.get())
3855 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3857 signAlgorithm
= certProperties
.signAlgorithm
;
3861 ConnStateData::getSslContextStart()
3863 assert(areAllContextsForThisConnection());
3865 /* careful: freeAllContexts() above frees request, host, etc. */
3867 if (port
->generateHostCertificates
) {
3868 Ssl::CertificateProperties certProperties
;
3869 buildSslCertGenerationParams(certProperties
);
3870 sslBumpCertKey
= certProperties
.dbKey().c_str();
3871 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3873 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3874 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3875 SSL_CTX
* dynCtx
= NULL
;
3876 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
.get(sslBumpCertKey
.termedBuf());
3877 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3878 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3879 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3880 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3881 getSslContextDone(dynCtx
);
3884 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3885 ssl_ctx_cache
.del(sslBumpCertKey
.termedBuf());
3888 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3893 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3894 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3895 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3896 request_message
.composeRequest(certProperties
);
3897 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3898 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3900 } catch (const std::exception
&e
) {
3901 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3902 "request for " << certProperties
.commonName
<<
3903 " certificate: " << e
.what() << "; will now block to " <<
3904 "generate that certificate.");
3905 // fall through to do blocking in-process generation.
3907 #endif // USE_SSL_CRTD
3909 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3910 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3911 getSslContextDone(dynCtx
, true);
3914 getSslContextDone(NULL
);
3918 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3920 // Try to add generated ssl context to storage.
3921 if (port
->generateHostCertificates
&& isNew
) {
3923 if (signAlgorithm
== Ssl::algSignTrusted
) {
3924 // Add signing certificate to the certificates chain
3925 X509
*cert
= port
->signingCert
.get();
3926 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3927 // increase the certificate lock
3928 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3930 const int ssl_error
= ERR_get_error();
3931 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3933 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3935 //else it is self-signed or untrusted do not attrach any certificate
3937 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3938 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3940 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3941 // If it is not in storage delete after using. Else storage deleted it.
3942 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3945 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3949 // If generated ssl context = NULL, try to use static ssl context.
3951 if (!port
->staticSslContext
) {
3952 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3953 clientConnection
->close();
3956 debugs(33, 5, HERE
<< "Using static ssl context.");
3957 sslContext
= port
->staticSslContext
.get();
3961 if (!httpsCreate(clientConnection
, sslContext
))
3964 // commSetConnTimeout() was called for this request before we switched.
3966 // Disable the client read handler until CachePeer selection is complete
3967 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3968 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3969 switchedToHttps_
= true;
3973 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3975 assert(!switchedToHttps_
);
3977 sslConnectHostOrIp
= request
->GetHost();
3978 sslCommonName
= request
->GetHost();
3980 // We are going to read new request
3981 flags
.readMore
= true;
3982 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3984 // If sslServerBump is set, then we have decided to deny CONNECT
3985 // and now want to switch to SSL to send the error to the client
3986 // without even peeking at the origin server certificate.
3987 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3988 request
->flags
.sslPeek
= true;
3989 sslServerBump
= new Ssl::ServerBump(request
);
3991 // will call httpsPeeked() with certificate and connection, eventually
3992 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3996 // otherwise, use sslConnectHostOrIp
3997 getSslContextStart();
4001 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4003 Must(sslServerBump
!= NULL
);
4005 if (Comm::IsConnOpen(serverConnection
)) {
4006 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
4008 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
4009 assert(serverCert
.get() != NULL
);
4010 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4011 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4012 " bumped: " << *serverConnection
);
4014 pinConnection(serverConnection
, NULL
, NULL
, false);
4016 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4018 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4019 Ip::Address intendedDest
;
4020 intendedDest
= sslConnectHostOrIp
.termedBuf();
4021 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4023 // Squid serves its own error page and closes, so we want
4024 // a CN that causes no additional browser errors. Possible
4025 // only when bumping CONNECT with a user-typed address.
4026 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4027 sslCommonName
= sslConnectHostOrIp
;
4028 else if (sslServerBump
->serverCert
.get())
4029 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4031 // copy error detail from bump-server-first request to CONNECT request
4032 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4033 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4036 getSslContextStart();
4039 #endif /* USE_SSL */
4041 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4043 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4045 if (!Comm::IsConnOpen(c
)) {
4046 Must(NHttpSockets
> 0); // we tried to open some
4047 --NHttpSockets
; // there will be fewer sockets than planned
4048 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4050 if (!NHttpSockets
) // we could not open any listen sockets at all
4051 fatalf("Unable to open %s",FdNote(portType
));
4058 /// find any unused HttpSockets[] slot and store fd there or return false
4060 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4063 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4064 if ((found
= HttpSockets
[i
] < 0))
4065 HttpSockets
[i
] = conn
->fd
;
4071 clientHttpConnectionsOpen(void)
4073 AnyP::PortCfg
*s
= NULL
;
4075 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4076 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4077 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4078 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4083 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4084 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << URLScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4085 s
->flags
.tunnelSslBumping
= false;
4088 if (s
->flags
.tunnelSslBumping
&&
4089 !s
->staticSslContext
&&
4090 !s
->generateHostCertificates
) {
4091 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4092 s
->flags
.tunnelSslBumping
= false;
4094 if (s
->flags
.tunnelSslBumping
) {
4095 // Create ssl_ctx cache for this port.
4096 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4100 // Fill out a Comm::Connection which IPC will open as a listener for us
4101 // then pass back when active so we can start a TcpAcceptor subscription.
4102 s
->listenConn
= new Comm::Connection
;
4103 s
->listenConn
->local
= s
->s
;
4104 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4106 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4107 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4108 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4109 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4111 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4112 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4113 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4115 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4122 clientHttpsConnectionsOpen(void)
4126 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4127 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4128 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4129 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4133 if (!s
->staticSslContext
) {
4134 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4135 " due to SSL initialization failure.");
4139 // TODO: merge with similar code in clientHttpConnectionsOpen()
4140 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4141 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << URLScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4142 s
->flags
.tunnelSslBumping
= false;
4145 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4146 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4147 s
->flags
.tunnelSslBumping
= false;
4150 if (s
->flags
.tunnelSslBumping
) {
4151 // Create ssl_ctx cache for this port.
4152 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4155 // Fill out a Comm::Connection which IPC will open as a listener for us
4156 s
->listenConn
= new Comm::Connection
;
4157 s
->listenConn
->local
= s
->s
;
4158 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4159 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4161 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4162 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4163 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4164 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4166 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4167 ListeningStartedDialer(&clientListenerConnectionOpened
,
4168 s
, Ipc::fdnHttpsSocket
, sub
));
4169 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4170 HttpSockets
[NHttpSockets
] = -1;
4176 /// process clientHttpConnectionsOpen result
4178 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4180 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4184 Must(Comm::IsConnOpen(s
->listenConn
));
4186 // TCP: setup a job to handle accept() with subscribed handler
4187 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4189 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4190 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4191 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4192 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4193 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4194 << FdNote(portTypeNote
) << " connections at "
4197 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4201 clientOpenListenSockets(void)
4203 clientHttpConnectionsOpen();
4205 clientHttpsConnectionsOpen();
4208 if (NHttpSockets
< 1)
4209 fatal("No HTTP or HTTPS ports configured");
4213 clientHttpConnectionsClose(void)
4215 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4216 if (s
->listenConn
!= NULL
) {
4217 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4218 s
->listenConn
->close();
4219 s
->listenConn
= NULL
;
4224 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4225 if (s
->listenConn
!= NULL
) {
4226 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4227 s
->listenConn
->close();
4228 s
->listenConn
= NULL
;
4233 // TODO see if we can drop HttpSockets array entirely */
4234 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4235 HttpSockets
[i
] = -1;
4242 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4244 const char *vary
= request
->vary_headers
;
4245 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4246 #if X_ACCELERATOR_VARY
4249 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4252 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4254 /* Oops... something odd is going on here.. */
4255 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4256 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4257 safe_free(request
->vary_headers
);
4262 /* This is not a varying object */
4266 /* virtual "vary" object found. Calculate the vary key and
4267 * continue the search
4269 vary
= httpMakeVaryMark(request
, entry
->getReply());
4272 request
->vary_headers
= xstrdup(vary
);
4275 /* Ouch.. we cannot handle this kind of variance */
4276 /* XXX This cannot really happen, but just to be complete */
4281 vary
= httpMakeVaryMark(request
, entry
->getReply());
4284 request
->vary_headers
= xstrdup(vary
);
4288 /* Ouch.. we cannot handle this kind of variance */
4289 /* XXX This cannot really happen, but just to be complete */
4291 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4294 /* Oops.. we have already been here and still haven't
4295 * found the requested variant. Bail out
4297 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4298 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4304 ACLFilledChecklist
*
4305 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4307 ConnStateData
* conn
= http
->getConn();
4308 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4309 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4312 * hack for ident ACL. It needs to get full addresses, and a place to store
4313 * the ident result on persistent connections...
4315 /* connection oriented auth also needs these two lines for it's operation. */
4319 CBDATA_CLASS_INIT(ConnStateData
);
4322 ConnStateData::transparent() const
4324 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4328 ConnStateData::reading() const
4330 return reader
!= NULL
;
4334 ConnStateData::stopReading()
4337 comm_read_cancel(clientConnection
->fd
, reader
);
4343 ConnStateData::expectRequestBody(int64_t size
)
4345 bodyPipe
= new BodyPipe(this);
4347 bodyPipe
->setBodySize(size
);
4349 startDechunkingRequest();
4354 ConnStateData::mayNeedToReadMoreBody() const
4357 return 0; // request without a body or read/produced all body bytes
4359 if (!bodyPipe
->bodySizeKnown())
4360 return -1; // probably need to read more, but we cannot be sure
4362 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4363 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4365 if (needToProduce
<= haveAvailable
)
4366 return 0; // we have read what we need (but are waiting for pipe space)
4368 return needToProduce
- haveAvailable
;
4372 ConnStateData::stopReceiving(const char *error
)
4374 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4375 "; old sending error: " <<
4376 (stoppedSending() ? stoppedSending_
: "none"));
4378 if (const char *oldError
= stoppedReceiving()) {
4379 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4380 return; // nothing has changed as far as this connection is concerned
4383 stoppedReceiving_
= error
;
4385 if (const char *sendError
= stoppedSending()) {
4386 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4387 clientConnection
->close();
4392 ConnStateData::expectNoForwarding()
4394 if (bodyPipe
!= NULL
) {
4395 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4396 bodyPipe
->expectNoConsumption();
4400 /// initialize dechunking state
4402 ConnStateData::startDechunkingRequest()
4404 Must(bodyPipe
!= NULL
);
4405 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4406 assert(!in
.bodyParser
);
4407 in
.bodyParser
= new ChunkedCodingParser
;
4410 /// put parsed content into input buffer and clean up
4412 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4414 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4416 if (bodyPipe
!= NULL
) {
4417 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4418 BodyPipe::Pointer myPipe
= bodyPipe
;
4419 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4420 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4422 Must(myPipe
->bodySizeKnown());
4423 ClientSocketContext::Pointer context
= getCurrentContext();
4424 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4425 context
->http
->request
->setContentLength(myPipe
->bodySize());
4429 delete in
.bodyParser
;
4430 in
.bodyParser
= NULL
;
4434 ConnStateData::In::addressToReadInto() const
4436 return buf
+ notYetUsed
;
4439 ConnStateData::In::In() : bodyParser(NULL
),
4440 buf (NULL
), notYetUsed (0), allocatedSize (0)
4443 ConnStateData::In::~In()
4446 memFreeBuf(allocatedSize
, buf
);
4447 delete bodyParser
; // TODO: pool
4451 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4454 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4458 ClientSocketContext::Pointer context
= getCurrentContext();
4459 if (context
!= NULL
) {
4460 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4464 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4465 clientConnection
->close();
4468 /// Our close handler called by Comm when the pinned connection is closed
4470 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4472 // FwdState might repin a failed connection sooner than this close
4473 // callback is called for the failed connection.
4474 assert(pinning
.serverConnection
== io
.conn
);
4475 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4476 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4478 if (sawZeroReply
&& clientConnection
!= NULL
) {
4479 debugs(33, 3, "Closing client connection on pinned zero reply.");
4480 clientConnection
->close();
4485 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4487 char desc
[FD_DESC_SZ
];
4489 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4490 if (pinning
.serverConnection
->fd
== pinServer
->fd
) {
4491 startPinnedConnectionMonitoring();
4496 unpinConnection(); // closes pinned connection, if any, and resets fields
4498 pinning
.serverConnection
= pinServer
;
4500 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4502 // when pinning an SSL bumped connection, the request may be NULL
4503 const char *pinnedHost
= "[unknown]";
4505 pinning
.host
= xstrdup(request
->GetHost());
4506 pinning
.port
= request
->port
;
4507 pinnedHost
= pinning
.host
;
4509 pinning
.port
= pinServer
->remote
.port();
4511 pinning
.pinned
= true;
4513 pinning
.peer
= cbdataReference(aPeer
);
4514 pinning
.auth
= auth
;
4515 char stmp
[MAX_IPSTRLEN
];
4516 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4517 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4518 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4519 clientConnection
->fd
);
4520 fd_note(pinning
.serverConnection
->fd
, desc
);
4522 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4523 pinning
.closeHandler
= JobCallback(33, 5,
4524 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4525 // remember the pinned connection so that cb does not unpin a fresher one
4526 typedef CommCloseCbParams Params
;
4527 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4528 params
.conn
= pinning
.serverConnection
;
4529 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4531 startPinnedConnectionMonitoring();
4534 /// Assign a read handler to an idle pinned connection so that we can detect connection closures.
4536 ConnStateData::startPinnedConnectionMonitoring()
4538 if (pinning
.readHandler
!= NULL
)
4539 return; // already monitoring
4541 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4542 pinning
.readHandler
= JobCallback(33, 3,
4543 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4544 static char unusedBuf
[8];
4545 comm_read(pinning
.serverConnection
, unusedBuf
, sizeof(unusedBuf
), pinning
.readHandler
);
4549 ConnStateData::stopPinnedConnectionMonitoring()
4551 if (pinning
.readHandler
!= NULL
) {
4552 comm_read_cancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4553 pinning
.readHandler
= NULL
;
4557 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4558 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4560 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4562 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4564 if (io
.flag
== COMM_ERR_CLOSING
)
4565 return; // close handler will clean up
4567 // We could use getConcurrentRequestCount(), but this may be faster.
4568 const bool clientIsIdle
= !getCurrentContext();
4570 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4571 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4573 assert(pinning
.serverConnection
== io
.conn
);
4574 pinning
.serverConnection
->close();
4576 // If we are still sending data to the client, do not close now. When we are done sending,
4577 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4578 // However, if we are idle, then we must close to inform the idle client and minimize races.
4579 if (clientIsIdle
&& clientConnection
!= NULL
)
4580 clientConnection
->close();
4583 const Comm::ConnectionPointer
4584 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4586 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4589 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4591 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4593 else if (request
&& pinning
.port
!= request
->port
)
4595 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4597 else if (aPeer
!= pinning
.peer
)
4601 /* The pinning info is not safe, remove any pinning info */
4605 return pinning
.serverConnection
;
4609 ConnStateData::unpinConnection()
4611 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4614 cbdataReferenceDone(pinning
.peer
);
4616 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4617 if (pinning
.closeHandler
!= NULL
) {
4618 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4619 pinning
.closeHandler
= NULL
;
4621 /// also close the server side socket, we should not use it for any future requests...
4622 // TODO: do not close if called from our close handler?
4623 pinning
.serverConnection
->close();
4626 safe_free(pinning
.host
);
4628 pinning
.zeroReply
= false;
4630 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4631 * connection has gone away */