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"
156 #define comm_close comm_lingering_close
159 /// dials clientListenerConnectionOpened call
160 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
163 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
164 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
165 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
167 virtual void print(std::ostream
&os
) const {
169 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
172 virtual bool canDial(AsyncCall
&) const { return true; }
173 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
179 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
180 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
181 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
184 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
186 /* our socket-related context */
188 CBDATA_CLASS_INIT(ClientSocketContext
);
190 /* Local functions */
191 static IOCB clientWriteComplete
;
192 static IOCB clientWriteBodyComplete
;
193 static IOACB httpAccept
;
195 static IOACB httpsAccept
;
197 static CTCB clientLifetimeTimeout
;
198 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
199 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, Http::ProtocolVersion
*);
201 static IDCB clientIdentDone
;
203 static CSCB clientSocketRecipient
;
204 static CSD clientSocketDetach
;
205 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
206 static int clientIsContentLengthValid(HttpRequest
* r
);
207 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
209 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
210 static void clientUpdateStatCounters(LogTags logType
);
211 static void clientUpdateHierCounters(HierarchyLogEntry
*);
212 static bool clientPingHasFinished(ping_data
const *aPing
);
213 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
215 static bool connIsUsable(ConnStateData
* conn
);
217 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
218 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
219 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
221 char *skipLeadingSpace(char *aString
);
222 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
225 ClientSocketContext::getTail() const
227 if (http
->client_stream
.tail
)
228 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
234 ClientSocketContext::getClientReplyContext() const
236 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
240 * This routine should be called to grow the inbuf and then
244 ConnStateData::readSomeData()
249 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
251 if (!maybeMakeSpaceAvailable())
254 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
255 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
256 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
260 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
262 ClientSocketContext::Pointer
*tempContextPointer
;
263 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
264 assert(conn
->getCurrentContext() != NULL
);
265 /* Unlink us from the connection request list */
266 tempContextPointer
= & conn
->currentobject
;
268 while (tempContextPointer
->getRaw()) {
269 if (*tempContextPointer
== this)
272 tempContextPointer
= &(*tempContextPointer
)->next
;
275 assert(tempContextPointer
->getRaw() != NULL
);
276 *tempContextPointer
= next
;
280 ClientSocketContext::~ClientSocketContext()
282 clientStreamNode
*node
= getTail();
285 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
288 /* We are *always* the tail - prevent recursive free */
289 assert(this == streamContext
);
295 deRegisterWithConn();
297 httpRequestFree(http
);
299 /* clean up connection links to us */
300 assert(this != next
.getRaw());
304 ClientSocketContext::registerWithConn()
306 assert (!connRegistered_
);
308 assert (http
->getConn() != NULL
);
309 connRegistered_
= true;
310 http
->getConn()->addContextToQueue(this);
314 ClientSocketContext::deRegisterWithConn()
316 assert (connRegistered_
);
317 removeFromConnectionList(http
->getConn());
318 connRegistered_
= false;
322 ClientSocketContext::connIsFinished()
325 assert (http
->getConn() != NULL
);
326 deRegisterWithConn();
327 /* we can't handle any more stream data - detach */
328 clientStreamDetach(getTail(), http
);
331 ClientSocketContext::ClientSocketContext(const Comm::ConnectionPointer
&aConn
, ClientHttpRequest
*aReq
) :
332 clientConnection(aConn
),
337 mayUseConnection_ (false),
338 connRegistered_ (false)
340 assert(http
!= NULL
);
341 memset (reqbuf
, '\0', sizeof (reqbuf
));
344 deferredparams
.node
= NULL
;
345 deferredparams
.rep
= NULL
;
349 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
351 const HttpReply::Pointer
rep(msg
.reply
);
354 // apply selected clientReplyContext::buildReplyHeader() mods
355 // it is not clear what headers are required for control messages
356 rep
->header
.removeHopByHopEntries();
357 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
358 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
360 // remember the callback
361 cbControlMsgSent
= msg
.cbSuccess
;
363 MemBuf
*mb
= rep
->pack();
365 debugs(11, 2, "HTTP Client " << clientConnection
);
366 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
368 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
369 CommIoCbPtrFun(&WroteControlMsg
, this));
370 Comm::Write(clientConnection
, mb
, call
);
375 /// called when we wrote the 1xx response
377 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
379 if (errflag
== COMM_ERR_CLOSING
)
382 if (errflag
== COMM_OK
) {
383 ScheduleCallHere(cbControlMsgSent
);
387 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
388 // no error notification: see HttpControlMsg.h for rationale and
389 // note that some errors are detected elsewhere (e.g., close handler)
391 // close on 1xx errors to be conservative and to simplify the code
392 // (if we do not close, we must notify the source of a failure!)
396 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
398 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
400 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
401 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
406 clientIdentDone(const char *ident
, void *data
)
408 ConnStateData
*conn
= (ConnStateData
*)data
;
409 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
414 clientUpdateStatCounters(LogTags logType
)
416 ++statCounter
.client_http
.requests
;
418 if (logTypeIsATcpHit(logType
))
419 ++statCounter
.client_http
.hits
;
421 if (logType
== LOG_TCP_HIT
)
422 ++statCounter
.client_http
.disk_hits
;
423 else if (logType
== LOG_TCP_MEM_HIT
)
424 ++statCounter
.client_http
.mem_hits
;
428 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
430 statCounter
.client_http
.allSvcTime
.count(svc_time
);
432 * The idea here is not to be complete, but to get service times
433 * for only well-defined types. For example, we don't include
434 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
435 * (we *tried* to validate it, but failed).
440 case LOG_TCP_REFRESH_UNMODIFIED
:
441 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
444 case LOG_TCP_IMS_HIT
:
445 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
450 case LOG_TCP_MEM_HIT
:
452 case LOG_TCP_OFFLINE_HIT
:
453 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
458 case LOG_TCP_CLIENT_REFRESH_MISS
:
459 statCounter
.client_http
.missSvcTime
.count(svc_time
);
463 /* make compiler warnings go away */
469 clientPingHasFinished(ping_data
const *aPing
)
471 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
478 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
482 switch (someEntry
->code
) {
483 #if USE_CACHE_DIGESTS
488 ++ statCounter
.cd
.times_used
;
496 case FIRST_PARENT_MISS
:
498 case CLOSEST_PARENT_MISS
:
499 ++ statCounter
.icp
.times_used
;
500 i
= &someEntry
->ping
;
502 if (clientPingHasFinished(i
))
503 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
506 ++ statCounter
.icp
.query_timeouts
;
513 ++ statCounter
.netdb
.times_used
;
523 ClientHttpRequest::updateCounters()
525 clientUpdateStatCounters(logType
);
527 if (request
->errType
!= ERR_NONE
)
528 ++ statCounter
.client_http
.errors
;
530 clientUpdateStatHistCounters(logType
,
531 tvSubMsec(al
->cache
.start_time
, current_time
));
533 clientUpdateHierCounters(&request
->hier
);
537 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
540 assert(aLogEntry
!= NULL
);
542 if (Config
.onoff
.log_mime_hdrs
) {
546 packerToMemInit(&p
, &mb
);
547 request
->header
.packInto(&p
);
548 //This is the request after adaptation or redirection
549 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
551 // the virgin request is saved to aLogEntry->request
552 if (aLogEntry
->request
) {
555 packerToMemInit(&p
, &mb
);
556 aLogEntry
->request
->header
.packInto(&p
);
557 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
561 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
565 packerToMemInit(&p
, &mb
);
566 ah
->lastMeta
.packInto(&p
);
567 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
576 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
578 aLogEntry
->icap
.processingTime
= ih
->processingTime();
581 aLogEntry
->http
.method
= request
->method
;
582 aLogEntry
->http
.version
= request
->http_ver
;
583 aLogEntry
->hier
= request
->hier
;
584 if (request
->content_length
> 0) // negative when no body or unknown length
585 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
586 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
588 // Adapted request, if any, inherits and then collects all the stats, but
589 // the virgin request gets logged instead; copy the stats to log them.
590 // TODO: avoid losses by keeping these stats in a shared history object?
591 if (aLogEntry
->request
) {
592 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
593 aLogEntry
->request
->errType
= request
->errType
;
594 aLogEntry
->request
->errDetail
= request
->errDetail
;
599 ClientHttpRequest::logRequest()
601 if (!out
.size
&& !logType
)
602 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
604 al
->icp
.opcode
= ICP_INVALID
;
606 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
609 al
->http
.code
= al
->reply
->sline
.status();
610 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
611 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
612 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
613 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
616 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
618 if (loggingEntry() && loggingEntry()->mem_obj
)
619 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
621 al
->http
.clientRequestSz
.header
= req_sz
;
622 al
->http
.clientReplySz
.header
= out
.headers_sz
;
623 // XXX: calculate without payload encoding or headers !!
624 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
626 al
->cache
.highOffset
= out
.offset
;
628 al
->cache
.code
= logType
;
630 al
->cache
.msec
= tvSubMsec(al
->cache
.start_time
, current_time
);
633 prepareLogWithRequestDetails(request
, al
);
635 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
636 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
640 /* This is broken. Fails if the connection has been closed. Needs
641 * to snarf the ssl details some place earlier..
643 if (getConn() != NULL
)
644 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
649 // The al->notes and request->notes must point to the same object.
650 (void)SyncNotes(*al
, *request
);
651 typedef Notes::iterator ACAMLI
;
652 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
653 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
654 NotePairs
¬es
= SyncNotes(*al
, *request
);
655 notes
.add((*i
)->key
.termedBuf(), value
);
656 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
660 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
662 checklist
.reply
= al
->reply
;
663 HTTPMSGLOCK(checklist
.reply
);
667 al
->adapted_request
= request
;
668 HTTPMSGLOCK(al
->adapted_request
);
670 accessLogLog(al
, &checklist
);
672 bool updatePerformanceCounters
= true;
673 if (Config
.accessList
.stats_collection
) {
674 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
676 statsCheck
.reply
= al
->reply
;
677 HTTPMSGLOCK(statsCheck
.reply
);
679 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
682 if (updatePerformanceCounters
) {
686 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
687 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
692 ClientHttpRequest::freeResources()
696 safe_free(redirect
.location
);
697 range_iter
.boundary
.clean();
698 HTTPMSGUNLOCK(request
);
700 if (client_stream
.tail
)
701 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
705 httpRequestFree(void *data
)
707 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
708 assert(http
!= NULL
);
713 ConnStateData::areAllContextsForThisConnection() const
715 assert(this != NULL
);
716 ClientSocketContext::Pointer context
= getCurrentContext();
718 while (context
.getRaw()) {
719 if (context
->http
->getConn() != this)
722 context
= context
->next
;
729 ConnStateData::freeAllContexts()
731 ClientSocketContext::Pointer context
;
733 while ((context
= getCurrentContext()).getRaw() != NULL
) {
734 assert(getCurrentContext() !=
735 getCurrentContext()->next
);
736 context
->connIsFinished();
737 assert (context
!= currentobject
);
741 /// propagates abort event to all contexts
743 ConnStateData::notifyAllContexts(int xerrno
)
745 typedef ClientSocketContext::Pointer CSCP
;
746 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
747 c
->noteIoError(xerrno
);
750 /* This is a handler normally called by comm_close() */
751 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
753 deleteThis("ConnStateData::connStateClosed");
758 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
762 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
768 // clobered with self-pointer
769 // NP: something nasty is going on in Squid, but harmless.
771 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
776 * Connection-auth relies on a single set of credentials being preserved
777 * for all requests on a connection once they have been setup.
778 * There are several things which need to happen to preserve security
779 * when connection-auth credentials change unexpectedly or are unset.
781 * 1) auth helper released from any active state
783 * They can only be reserved by a handshake process which this
784 * connection can now never complete.
785 * This prevents helpers hanging when their connections close.
787 * 2) pinning is expected to be removed and server conn closed
789 * The upstream link is authenticated with the same credentials.
790 * Expecting the same level of consistency we should have received.
791 * This prevents upstream being faced with multiple or missing
792 * credentials after authentication.
793 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
794 * we just trigger that cleanup here via comm_reset_close() or
795 * ConnStateData::stopReceiving()
797 * 3) the connection needs to close.
799 * This prevents attackers injecting requests into a connection,
800 * or gateways wrongly multiplexing users into a single connection.
802 * When credentials are missing closure needs to follow an auth
803 * challenge for best recovery by the client.
805 * When credentials change there is nothing we can do but abort as
806 * fast as possible. Sending TCP RST instead of an HTTP response
807 * is the best-case action.
810 // clobbered with nul-pointer
812 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
813 auth_
->releaseAuthServer();
815 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
816 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
817 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
818 stopReceiving("connection-auth removed");
822 // clobbered with alternative credentials
824 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
825 auth_
->releaseAuthServer();
827 // this is a fatal type of problem.
828 // Close the connection immediately with TCP RST to abort all traffic flow
829 comm_reset_close(clientConnection
);
837 // cleans up before destructor is called
839 ConnStateData::swanSong()
841 debugs(33, 2, HERE
<< clientConnection
);
842 flags
.readMore
= false;
843 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
844 assert(areAllContextsForThisConnection());
849 if (Comm::IsConnOpen(clientConnection
))
850 clientConnection
->close();
853 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
854 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
857 BodyProducer::swanSong();
858 flags
.swanSang
= true;
862 ConnStateData::isOpen() const
864 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
865 Comm::IsConnOpen(clientConnection
) &&
866 !fd_table
[clientConnection
->fd
].closing();
869 ConnStateData::~ConnStateData()
871 assert(this != NULL
);
872 debugs(33, 3, HERE
<< clientConnection
);
875 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
878 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
880 cbdataReferenceDone(port
);
882 if (bodyPipe
!= NULL
)
883 stopProducingFor(bodyPipe
, false);
886 delete sslServerBump
;
891 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
892 * This is the client-side persistent connection flag. We need
893 * to set this relatively early in the request processing
894 * to handle hacks for broken servers and clients.
897 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
899 HttpRequest
*request
= http
->request
;
901 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
902 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
903 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
904 RequestMethodStr(request
->method
));
906 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
907 request
->flags
.proxyKeepalive
= request
->persistent();
911 clientIsContentLengthValid(HttpRequest
* r
)
913 switch (r
->method
.id()) {
915 case Http::METHOD_GET
:
917 case Http::METHOD_HEAD
:
918 /* We do not want to see a request entity on GET/HEAD requests */
919 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
922 /* For other types of requests we don't care */
930 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
932 if (Config
.maxRequestBodySize
&&
933 bodyLength
> Config
.maxRequestBodySize
)
934 return 1; /* too large */
941 connIsUsable(ConnStateData
* conn
)
943 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
951 // careful: the "current" context may be gone if we wrote an early response
952 ClientSocketContext::Pointer
953 ConnStateData::getCurrentContext() const
956 return currentobject
;
960 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
962 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
963 assert(flags
.deferred
== 0);
965 deferredparams
.node
= node
;
966 deferredparams
.rep
= rep
;
967 deferredparams
.queuedBuffer
= receivedData
;
972 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
974 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
981 ClientSocketContext::startOfOutput() const
983 return http
->out
.size
== 0;
987 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
989 /*the size of available range can always fit in a size_t type*/
990 size_t maximum
= (size_t)available
.size();
992 if (!http
->request
->range
)
995 assert (canPackMoreRanges());
997 if (http
->range_iter
.debt() == -1)
1000 assert (http
->range_iter
.debt() > 0);
1002 /* TODO this + the last line could be a range intersection calculation */
1003 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
1006 return min(http
->range_iter
.debt(), (int64_t)maximum
);
1010 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
1012 http
->out
.offset
+= bytes
;
1014 if (!http
->request
->range
)
1017 if (http
->range_iter
.debt() != -1) {
1018 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
1019 assert (http
->range_iter
.debt() >= 0);
1022 /* debt() always stops at -1, below that is a bug */
1023 assert (http
->range_iter
.debt() >= -1);
1027 ClientHttpRequest::multipartRangeRequest() const
1029 return request
->multipartRangeRequest();
1033 ClientSocketContext::multipartRangeRequest() const
1035 return http
->multipartRangeRequest();
1039 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1041 assert(rep
== NULL
);
1043 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1044 size_t length
= lengthToSend(bodyData
.range());
1045 noteSentBodyBytes (length
);
1046 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1047 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1048 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1054 if (multipartRangeRequest())
1055 packRange(bodyData
, &mb
);
1057 packChunk(bodyData
, mb
);
1059 if (mb
.contentSize()) {
1061 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1062 CommIoCbPtrFun(clientWriteComplete
, this));
1063 Comm::Write(clientConnection
, &mb
, call
);
1065 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1069 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1070 * if bodyData is empty.
1073 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1075 const uint64_t length
=
1076 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1077 noteSentBodyBytes(length
);
1079 mb
.Printf("%" PRIX64
"\r\n", length
);
1080 mb
.append(bodyData
.data
, length
);
1084 /** put terminating boundary for multiparts */
1086 clientPackTermBound(String boundary
, MemBuf
* mb
)
1088 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1089 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1092 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1094 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1096 HttpHeader
hdr(hoReply
);
1102 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1103 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1104 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1106 /* stuff the header with required entries and pack it */
1108 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1109 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1111 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1113 packerToMemInit(&p
, mb
);
1121 /* append <crlf> (we packed a header, not a reply) */
1126 * extracts a "range" from *buf and appends them to mb, updating
1127 * all offsets and such.
1130 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1132 HttpHdrRangeIter
* i
= &http
->range_iter
;
1133 Range
<int64_t> available (source
.range());
1134 char const *buf
= source
.data
;
1136 while (i
->currentSpec() && available
.size()) {
1137 const size_t copy_sz
= lengthToSend(available
);
1141 * intersection of "have" and "need" ranges must not be empty
1143 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1144 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1147 * put boundary and headers at the beginning of a range in a
1151 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1152 assert(http
->memObject());
1154 http
->memObject()->getReply(), /* original reply */
1155 i
->currentSpec(), /* current range */
1156 i
->boundary
, /* boundary, the same for all */
1163 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1165 noteSentBodyBytes (copy_sz
);
1167 mb
->append(buf
, copy_sz
);
1172 available
.start
+= copy_sz
;
1178 if (!canPackMoreRanges()) {
1179 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1182 /* put terminating boundary for multiparts */
1183 clientPackTermBound(i
->boundary
, mb
);
1188 int64_t nextOffset
= getNextRangeOffset();
1190 assert (nextOffset
>= http
->out
.offset
);
1192 int64_t skip
= nextOffset
- http
->out
.offset
;
1194 /* adjust for not to be transmitted bytes */
1195 http
->out
.offset
= nextOffset
;
1197 if (available
.size() <= (uint64_t)skip
)
1200 available
.start
+= skip
;
1209 /** returns expected content length for multi-range replies
1210 * note: assumes that httpHdrRangeCanonize has already been called
1211 * warning: assumes that HTTP headers for individual ranges at the
1212 * time of the actuall assembly will be exactly the same as
1213 * the headers when clientMRangeCLen() is called */
1215 ClientHttpRequest::mRangeCLen()
1220 assert(memObject());
1223 HttpHdrRange::iterator pos
= request
->range
->begin();
1225 while (pos
!= request
->range
->end()) {
1226 /* account for headers for this range */
1228 clientPackRangeHdr(memObject()->getReply(),
1229 *pos
, range_iter
.boundary
, &mb
);
1232 /* account for range content */
1233 clen
+= (*pos
)->length
;
1235 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1239 /* account for the terminating boundary */
1242 clientPackTermBound(range_iter
.boundary
, &mb
);
1252 * returns true if If-Range specs match reply, false otherwise
1255 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1257 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1258 /* check for parsing falure */
1265 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1266 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1267 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1270 return 0; /* entity has no etag to compare with! */
1272 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1273 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1274 return 0; /* must use strong validator for sub-range requests */
1277 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1280 /* got modification time? */
1281 if (spec
.time
>= 0) {
1282 return http
->storeEntry()->lastmod
<= spec
.time
;
1285 assert(0); /* should not happen */
1290 * generates a "unique" boundary string for multipart responses
1291 * the caller is responsible for cleaning the string */
1293 ClientHttpRequest::rangeBoundaryStr() const
1297 String
b(APP_FULLNAME
);
1299 key
= storeEntry()->getMD5Text();
1300 b
.append(key
, strlen(key
));
1304 /** adds appropriate Range headers if needed */
1306 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1308 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1309 const char *range_err
= NULL
;
1310 HttpRequest
*request
= http
->request
;
1311 assert(request
->range
);
1312 /* check if we still want to do ranges */
1314 int64_t roffLimit
= request
->getRangeOffsetLimit();
1317 range_err
= "no [parse-able] reply";
1318 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1319 range_err
= "wrong status code";
1320 else if (hdr
->has(HDR_CONTENT_RANGE
))
1321 range_err
= "origin server does ranges";
1322 else if (rep
->content_length
< 0)
1323 range_err
= "unknown length";
1324 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1325 range_err
= "INCONSISTENT length"; /* a bug? */
1327 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1330 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1331 range_err
= "If-Range match failed";
1332 else if (!http
->request
->range
->canonize(rep
))
1333 range_err
= "canonization failed";
1334 else if (http
->request
->range
->isComplex())
1335 range_err
= "too complex range header";
1336 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1337 range_err
= "range outside range_offset_limit";
1339 /* get rid of our range specs on error */
1341 /* XXX We do this here because we need canonisation etc. However, this current
1342 * code will lead to incorrect store offset requests - the store will have the
1343 * offset data, but we won't be requesting it.
1344 * So, we can either re-request, or generate an error
1346 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1347 delete http
->request
->range
;
1348 http
->request
->range
= NULL
;
1350 /* XXX: TODO: Review, this unconditional set may be wrong. */
1351 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1352 // web server responded with a valid, but unexpected range.
1353 // will (try-to) forward as-is.
1354 //TODO: we should cope with multirange request/responses
1355 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1356 request
->range
->contains(rep
->content_range
->spec
) :
1358 const int spec_count
= http
->request
->range
->specs
.size();
1359 int64_t actual_clen
= -1;
1361 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1362 spec_count
<< " virgin clen: " << rep
->content_length
);
1363 assert(spec_count
> 0);
1364 /* append appropriate header(s) */
1366 if (spec_count
== 1) {
1367 if (!replyMatchRequest
) {
1368 hdr
->delById(HDR_CONTENT_RANGE
);
1369 hdr
->putContRange(rep
->content_range
);
1370 actual_clen
= rep
->content_length
;
1371 //http->range_iter.pos = rep->content_range->spec.begin();
1372 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1373 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1376 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1378 /* append Content-Range */
1380 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1381 /* No content range, so this was a full object we are
1384 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1387 /* set new Content-Length to the actual number of bytes
1388 * transmitted in the message-body */
1389 actual_clen
= (*pos
)->length
;
1393 /* generate boundary string */
1394 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1395 /* delete old Content-Type, add ours */
1396 hdr
->delById(HDR_CONTENT_TYPE
);
1397 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1398 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1399 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1400 /* Content-Length is not required in multipart responses
1401 * but it is always nice to have one */
1402 actual_clen
= http
->mRangeCLen();
1403 /* http->out needs to start where we want data at */
1404 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1407 /* replace Content-Length header */
1408 assert(actual_clen
>= 0);
1410 hdr
->delById(HDR_CONTENT_LENGTH
);
1412 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1414 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1416 /* And start the range iter off */
1417 http
->range_iter
.updateSpec();
1422 ClientSocketContext::prepareReply(HttpReply
* rep
)
1426 if (http
->request
->range
)
1427 buildRangeHeader(rep
);
1431 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1435 MemBuf
*mb
= rep
->pack();
1437 // dump now, so we dont output any body.
1438 debugs(11, 2, "HTTP Client " << clientConnection
);
1439 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1441 /* Save length of headers for persistent conn checks */
1442 http
->out
.headers_sz
= mb
->contentSize();
1445 headersLog(0, 0, http
->request
->method
, rep
);
1448 if (bodyData
.data
&& bodyData
.length
) {
1449 if (multipartRangeRequest())
1450 packRange(bodyData
, mb
);
1451 else if (http
->request
->flags
.chunkedReply
) {
1452 packChunk(bodyData
, *mb
);
1454 size_t length
= lengthToSend(bodyData
.range());
1455 noteSentBodyBytes (length
);
1457 mb
->append(bodyData
.data
, length
);
1462 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1463 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1464 CommIoCbPtrFun(clientWriteComplete
, this));
1465 Comm::Write(clientConnection
, mb
, call
);
1470 * Write a chunk of data to a client socket. If the reply is present,
1471 * send the reply headers down the wire too, and clean them up when
1474 * The request is one backed by a connection, not an internal request.
1475 * data context is not NULL
1476 * There are no more entries in the stream chain.
1479 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1480 HttpReply
* rep
, StoreIOBuffer receivedData
)
1482 /* Test preconditions */
1483 assert(node
!= NULL
);
1484 PROF_start(clientSocketRecipient
);
1485 /* TODO: handle this rather than asserting
1486 * - it should only ever happen if we cause an abort and
1487 * the callback chain loops back to here, so we can simply return.
1488 * However, that itself shouldn't happen, so it stays as an assert for now.
1490 assert(cbdataReferenceValid(node
));
1491 assert(node
->node
.next
== NULL
);
1492 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1493 assert(context
!= NULL
);
1494 assert(connIsUsable(http
->getConn()));
1496 /* TODO: check offset is what we asked for */
1498 if (context
!= http
->getConn()->getCurrentContext()) {
1499 context
->deferRecipientForLater(node
, rep
, receivedData
);
1500 PROF_stop(clientSocketRecipient
);
1504 // After sending Transfer-Encoding: chunked (at least), always send
1505 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1506 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1507 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1508 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1509 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1510 PROF_stop(clientSocketRecipient
);
1514 if (!context
->startOfOutput())
1515 context
->sendBody(rep
, receivedData
);
1518 http
->al
->reply
= rep
;
1519 HTTPMSGLOCK(http
->al
->reply
);
1520 context
->sendStartOfMessage(rep
, receivedData
);
1523 PROF_stop(clientSocketRecipient
);
1527 * Called when a downstream node is no longer interested in
1528 * our data. As we are a terminal node, this means on aborts
1532 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1534 /* Test preconditions */
1535 assert(node
!= NULL
);
1536 /* TODO: handle this rather than asserting
1537 * - it should only ever happen if we cause an abort and
1538 * the callback chain loops back to here, so we can simply return.
1539 * However, that itself shouldn't happen, so it stays as an assert for now.
1541 assert(cbdataReferenceValid(node
));
1542 /* Set null by ContextFree */
1543 assert(node
->node
.next
== NULL
);
1544 /* this is the assert discussed above */
1545 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1546 /* We are only called when the client socket shutsdown.
1547 * Tell the prev pipeline member we're finished
1549 clientStreamDetach(node
, http
);
1553 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1555 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1556 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1560 ConnStateData::readNextRequest()
1562 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1564 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1566 * Set the timeout BEFORE calling clientReadRequest().
1568 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1569 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1570 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1571 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1574 /** Please don't do anything with the FD past here! */
1578 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1580 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1582 /** If the client stream is waiting on a socket write to occur, then */
1584 if (deferredRequest
->flags
.deferred
) {
1585 /** NO data is allowed to have been sent. */
1586 assert(deferredRequest
->http
->out
.size
== 0);
1588 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1589 deferredRequest
->http
,
1590 deferredRequest
->deferredparams
.rep
,
1591 deferredRequest
->deferredparams
.queuedBuffer
);
1594 /** otherwise, the request is still active in a callbacksomewhere,
1599 /// called when we have successfully finished writing the response
1601 ClientSocketContext::keepaliveNextRequest()
1603 ConnStateData
* conn
= http
->getConn();
1605 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1608 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1609 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1610 conn
->clientConnection
->close();
1615 * We are done with the response, and we are either still receiving request
1616 * body (early response!) or have already stopped receiving anything.
1618 * If we are still receiving, then clientParseRequest() below will fail.
1619 * (XXX: but then we will call readNextRequest() which may succeed and
1620 * execute a smuggled request as we are not done with the current request).
1622 * If we stopped because we got everything, then try the next request.
1624 * If we stopped receiving because of an error, then close now to avoid
1625 * getting stuck and to prevent accidental request smuggling.
1628 if (const char *reason
= conn
->stoppedReceiving()) {
1629 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1630 conn
->clientConnection
->close();
1635 * Attempt to parse a request from the request buffer.
1636 * If we've been fed a pipelined request it may already
1637 * be in our read buffer.
1640 * This needs to fall through - if we're unlucky and parse the _last_ request
1641 * from our read buffer we may never re-register for another client read.
1644 if (conn
->clientParseRequests()) {
1645 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1649 * Either we need to kick-start another read or, if we have
1650 * a half-closed connection, kill it after the last request.
1651 * This saves waiting for half-closed connections to finished being
1652 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1653 * the keepalive "Waiting for next request" state.
1655 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1656 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1657 conn
->clientConnection
->close();
1661 ClientSocketContext::Pointer deferredRequest
;
1664 * At this point we either have a parsed request (which we've
1665 * kicked off the processing for) or not. If we have a deferred
1666 * request (parsed but deferred for pipeling processing reasons)
1667 * then look at processing it. If not, simply kickstart
1671 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1672 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1673 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1674 } else if (conn
->flags
.readMore
) {
1675 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1676 conn
->readNextRequest();
1678 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1679 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1684 clientUpdateSocketStats(LogTags logType
, size_t size
)
1689 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1691 if (logTypeIsATcpHit(logType
))
1692 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1696 * increments iterator "i"
1697 * used by clientPackMoreRanges
1699 \retval true there is still data available to pack more ranges
1703 ClientSocketContext::canPackMoreRanges() const
1705 /** first update iterator "i" if needed */
1707 if (!http
->range_iter
.debt()) {
1708 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1710 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1711 ++http
->range_iter
.pos
;
1713 http
->range_iter
.updateSpec();
1716 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1718 /* paranoid sync condition */
1719 /* continue condition: need_more_data */
1720 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1721 return http
->range_iter
.currentSpec() ? true : false;
1725 ClientSocketContext::getNextRangeOffset() const
1727 if (http
->request
->range
) {
1728 /* offset in range specs does not count the prefix of an http msg */
1729 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1730 /* check: reply was parsed and range iterator was initialized */
1731 assert(http
->range_iter
.valid
);
1732 /* filter out data according to range specs */
1733 assert (canPackMoreRanges());
1735 int64_t start
; /* offset of still missing data */
1736 assert(http
->range_iter
.currentSpec());
1737 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1738 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1739 debugs(33, 3, "clientPackMoreRanges: out:"
1740 " start: " << start
<<
1741 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1742 " [" << http
->range_iter
.currentSpec()->offset
<<
1743 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1744 " len: " << http
->range_iter
.currentSpec()->length
<<
1745 " debt: " << http
->range_iter
.debt());
1746 if (http
->range_iter
.currentSpec()->length
!= -1)
1747 assert(http
->out
.offset
<= start
); /* we did not miss it */
1752 } else if (reply
&& reply
->content_range
) {
1753 /* request does not have ranges, but reply does */
1754 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1755 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1757 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1760 return http
->out
.offset
;
1764 ClientSocketContext::pullData()
1766 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1768 /* More data will be coming from the stream. */
1769 StoreIOBuffer readBuffer
;
1770 /* XXX: Next requested byte in the range sequence */
1771 /* XXX: length = getmaximumrangelenfgth */
1772 readBuffer
.offset
= getNextRangeOffset();
1773 readBuffer
.length
= HTTP_REQBUF_SZ
;
1774 readBuffer
.data
= reqbuf
;
1775 /* we may note we have reached the end of the wanted ranges */
1776 clientStreamRead(getTail(), http
, readBuffer
);
1779 /** Adapt stream status to account for Range cases
1782 clientStream_status_t
1783 ClientSocketContext::socketState()
1785 switch (clientStreamStatus(getTail(), http
)) {
1788 /* check for range support ending */
1790 if (http
->request
->range
) {
1791 /* check: reply was parsed and range iterator was initialized */
1792 assert(http
->range_iter
.valid
);
1793 /* filter out data according to range specs */
1795 if (!canPackMoreRanges()) {
1796 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1797 "range sequence on " << clientConnection
);
1798 // we got everything we wanted from the store
1799 return STREAM_COMPLETE
;
1801 } else if (reply
&& reply
->content_range
) {
1802 /* reply has content-range, but Squid is not managing ranges */
1803 const int64_t &bytesSent
= http
->out
.offset
;
1804 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1806 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1807 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1808 reply
->content_range
->spec
.offset
<< ")");
1810 // did we get at least what we expected, based on range specs?
1812 if (bytesSent
== bytesExpected
) // got everything
1813 return STREAM_COMPLETE
;
1815 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1816 return STREAM_UNPLANNED_COMPLETE
;
1821 case STREAM_COMPLETE
:
1822 return STREAM_COMPLETE
;
1824 case STREAM_UNPLANNED_COMPLETE
:
1825 return STREAM_UNPLANNED_COMPLETE
;
1828 return STREAM_FAILED
;
1831 fatal ("unreachable code\n");
1836 * A write has just completed to the client, or we have just realised there is
1837 * no more data to send.
1840 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1842 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1843 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1846 /// remembers the abnormal connection termination for logging purposes
1848 ClientSocketContext::noteIoError(const int xerrno
)
1851 if (xerrno
== ETIMEDOUT
)
1852 http
->al
->http
.timedout
= true;
1853 else // even if xerrno is zero (which means read abort/eof)
1854 http
->al
->http
.aborted
= true;
1859 ClientSocketContext::doClose()
1861 clientConnection
->close();
1864 /// called when we encounter a response-related error
1866 ClientSocketContext::initiateClose(const char *reason
)
1868 http
->getConn()->stopSending(reason
); // closes ASAP
1872 ConnStateData::stopSending(const char *error
)
1874 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1875 "; old receiving error: " <<
1876 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1878 if (const char *oldError
= stoppedSending()) {
1879 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1880 return; // nothing has changed as far as this connection is concerned
1882 stoppedSending_
= error
;
1884 if (!stoppedReceiving()) {
1885 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1886 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1887 " request body bytes with " << in
.notYetUsed
<< " unused");
1888 return; // wait for the request receiver to finish reading
1892 clientConnection
->close();
1896 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1898 const StoreEntry
*entry
= http
->storeEntry();
1899 http
->out
.size
+= size
;
1900 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1901 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1902 (entry
? entry
->objectLen() : 0));
1903 clientUpdateSocketStats(http
->logType
, size
);
1905 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1907 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1910 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1911 initiateClose("failure or true request status");
1912 /* Do we leak here ? */
1916 switch (socketState()) {
1922 case STREAM_COMPLETE
:
1923 debugs(33, 5, conn
<< "Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1924 if (http
->request
->flags
.proxyKeepalive
)
1925 keepaliveNextRequest();
1927 initiateClose("STREAM_COMPLETE NOKEEPALIVE");
1930 case STREAM_UNPLANNED_COMPLETE
:
1931 initiateClose("STREAM_UNPLANNED_COMPLETE");
1935 initiateClose("STREAM_FAILED");
1939 fatal("Hit unreachable code in clientWriteComplete\n");
1943 SQUIDCEXTERN CSR clientGetMoreData
;
1944 SQUIDCEXTERN CSS clientReplyStatus
;
1945 SQUIDCEXTERN CSD clientReplyDetach
;
1947 static ClientSocketContext
*
1948 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1950 ClientHttpRequest
*http
;
1951 ClientSocketContext
*context
;
1952 StoreIOBuffer tempBuffer
;
1953 http
= new ClientHttpRequest(csd
);
1954 http
->req_sz
= csd
->in
.notYetUsed
;
1955 http
->uri
= xstrdup(uri
);
1956 setLogUri (http
, uri
);
1957 context
= new ClientSocketContext(csd
->clientConnection
, http
);
1958 tempBuffer
.data
= context
->reqbuf
;
1959 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1960 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1961 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1962 clientSocketDetach
, context
, tempBuffer
);
1967 skipLeadingSpace(char *aString
)
1969 char *result
= aString
;
1971 while (xisspace(*aString
))
1978 * 'end' defaults to NULL for backwards compatibility
1979 * remove default value if we ever get rid of NULL-terminated
1983 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1986 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1990 for (; end
> uriAndHTTPVersion
; --end
) {
1991 if (*end
== '\n' || *end
== '\r')
1994 if (xisspace(*end
)) {
1995 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2006 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2008 safe_free(http
->log_uri
);
2011 // The uri is already clean just dump it.
2012 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2015 switch (Config
.uri_whitespace
) {
2016 case URI_WHITESPACE_ALLOW
:
2017 flags
|= RFC1738_ESCAPE_NOSPACE
;
2019 case URI_WHITESPACE_ENCODE
:
2020 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2021 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2024 case URI_WHITESPACE_CHOP
: {
2025 flags
|= RFC1738_ESCAPE_NOSPACE
;
2026 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2027 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2028 int pos
= strcspn(http
->log_uri
, w_space
);
2029 http
->log_uri
[pos
] = '\0';
2033 case URI_WHITESPACE_DENY
:
2034 case URI_WHITESPACE_STRIP
:
2037 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2041 if (!xisspace(*t
)) {
2048 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2057 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2059 int vhost
= conn
->port
->vhost
;
2060 int vport
= conn
->port
->vport
;
2062 char ipbuf
[MAX_IPSTRLEN
];
2064 http
->flags
.accel
= true;
2066 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2068 if (strncasecmp(url
, "cache_object://", 15) == 0)
2069 return; /* already in good shape */
2072 if (conn
->port
->vhost
)
2073 return; /* already in good shape */
2075 /* else we need to ignore the host name */
2076 url
= strstr(url
, "//");
2078 #if SHOULD_REJECT_UNKNOWN_URLS
2081 hp
->request_parse_status
= Http::scBadRequest
;
2082 return parseHttpRequestAbort(conn
, "error:invalid-request");
2087 url
= strchr(url
+ 2, '/');
2094 vport
= http
->getConn()->clientConnection
->local
.port();
2096 const bool switchedToHttps
= conn
->switchedToHttps();
2097 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2098 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2099 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2104 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2105 strncpy(thost
, host
, (t
-host
));
2106 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2109 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2112 } // else nothing to alter port-wise.
2113 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2115 http
->uri
= (char *)xcalloc(url_sz
, 1);
2116 const char *protocol
= switchedToHttps
?
2117 "https" : AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str();
2118 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2119 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2120 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2121 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2122 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2123 strlen(conn
->port
->defaultsite
);
2124 http
->uri
= (char *)xcalloc(url_sz
, 1);
2128 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2130 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2131 AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, url
);
2132 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2133 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2134 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2135 /* Put the local socket IP address as the hostname, with whatever vport we found */
2136 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2137 http
->uri
= (char *)xcalloc(url_sz
, 1);
2138 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2139 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2140 AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(),
2142 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2147 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2150 char ipbuf
[MAX_IPSTRLEN
];
2153 return; /* already in good shape */
2155 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2157 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2158 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2160 http
->uri
= (char *)xcalloc(url_sz
, 1);
2161 snprintf(http
->uri
, url_sz
, "%s://%s%s", AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(), host
, url
);
2162 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2164 /* Put the local socket IP address as the hostname. */
2165 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2166 http
->uri
= (char *)xcalloc(url_sz
, 1);
2167 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2168 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2169 AnyP::UriScheme(http
->getConn()->port
->transport
.protocol
).c_str(),
2170 ipbuf
, http
->getConn()->clientConnection
->local
.port(), url
);
2171 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2175 /** Parse an HTTP request
2177 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2178 * to 1 if the request was correctly parsed.
2179 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2180 * \param[in] hp an HttpParser
2181 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2182 * Pointed-to value will be set to Http::METHOD_NONE in case of
2184 * \param[out] http_ver will be set as a side-effect of the parsing
2185 * \return NULL on incomplete requests,
2186 * a ClientSocketContext structure on success or failure.
2188 static ClientSocketContext
*
2189 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2191 char *req_hdr
= NULL
;
2194 ClientHttpRequest
*http
;
2195 ClientSocketContext
*result
;
2196 StoreIOBuffer tempBuffer
;
2199 /* pre-set these values to make aborting simpler */
2200 *method_p
= Http::METHOD_NONE
;
2202 /* NP: don't be tempted to move this down or remove again.
2203 * It's the only DDoS protection old-String has against long URL */
2204 if ( hp
->bufsiz
<= 0) {
2205 debugs(33, 5, "Incomplete request, waiting for end of request line");
2207 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2208 debugs(33, 5, "parseHttpRequest: Too large request");
2209 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2210 return parseHttpRequestAbort(csd
, "error:request-too-large");
2213 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2214 r
= HttpParserParseReqLine(hp
);
2217 debugs(33, 5, "Incomplete request, waiting for end of request line");
2222 return parseHttpRequestAbort(csd
, "error:invalid-request");
2225 /* Request line is valid here .. */
2226 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2228 /* This call scans the entire request, not just the headers */
2229 if (hp
->req
.v_maj
> 0) {
2230 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2231 debugs(33, 5, "Incomplete request, waiting for end of headers");
2235 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2236 req_sz
= HttpParserReqSz(hp
);
2239 /* We know the whole request is in hp->buf now */
2241 assert(req_sz
<= (size_t) hp
->bufsiz
);
2243 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2244 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2247 hp
->hdr_end
= req_sz
- 1;
2249 hp
->hdr_start
= hp
->req
.end
+ 1;
2251 /* Enforce max_request_size */
2252 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2253 debugs(33, 5, "parseHttpRequest: Too large request");
2254 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2255 return parseHttpRequestAbort(csd
, "error:request-too-large");
2259 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2261 /* deny CONNECT via accelerated ports */
2262 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2263 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->transport
.protocol
<< " Accelerator port " << csd
->port
->s
.port());
2264 /* XXX need a way to say "this many character length string" */
2265 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2266 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2267 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2270 if (*method_p
== Http::METHOD_NONE
) {
2271 /* XXX need a way to say "this many character length string" */
2272 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2273 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2274 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2278 * Process headers after request line
2279 * TODO: Use httpRequestParse here.
2281 /* XXX this code should be modified to take a const char * later! */
2282 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2284 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2286 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2288 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2290 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2291 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2292 HttpParserReqSz(hp
));
2294 /* Ok, all headers are received */
2295 http
= new ClientHttpRequest(csd
);
2297 http
->req_sz
= HttpParserRequestLen(hp
);
2298 result
= new ClientSocketContext(csd
->clientConnection
, http
);
2299 tempBuffer
.data
= result
->reqbuf
;
2300 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2302 ClientStreamData newServer
= new clientReplyContext(http
);
2303 ClientStreamData newClient
= result
;
2304 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2305 clientReplyStatus
, newServer
, clientSocketRecipient
,
2306 clientSocketDetach
, newClient
, tempBuffer
);
2308 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2312 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2313 * below needs to be modified to not expect a mutable nul-terminated string.
2315 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2317 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2319 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2321 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2323 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2328 debugs(33,5, HERE
<< "repare absolute URL from " <<
2329 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2330 /* Rewrite the URL in transparent or accelerator mode */
2331 /* NP: there are several cases to traverse here:
2332 * - standard mode (forward proxy)
2333 * - transparent mode (TPROXY)
2334 * - transparent mode with failures
2335 * - intercept mode (NAT)
2336 * - intercept mode with failures
2337 * - accelerator mode (reverse proxy)
2339 * - mixed combos of the above with internal URL
2341 if (csd
->transparent()) {
2342 /* intercept or transparent mode, properly working with no failures */
2343 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2345 } else if (internalCheck(url
)) {
2346 /* internal URL mode */
2347 /* prepend our name & port */
2348 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2349 // We just re-wrote the URL. Must replace the Host: header.
2350 // But have not parsed there yet!! flag for local-only handling.
2351 http
->flags
.internal
= true;
2353 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2354 /* accelerator mode */
2355 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2359 /* No special rewrites have been applied above, use the
2360 * requested url. may be rewritten later, so make extra room */
2361 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2362 http
->uri
= (char *)xcalloc(url_sz
, 1);
2363 strcpy(http
->uri
, url
);
2366 debugs(33, 5, "parseHttpRequest: Complete request received");
2368 // XXX: crop this dump at the end of headers. No need for extras
2369 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2370 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2372 result
->flags
.parsed_ok
= 1;
2378 ConnStateData::getAvailableBufferLength() const
2380 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2381 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2382 // huge request_header_max_size may lead to more than INT_MAX unused space
2383 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2388 ConnStateData::maybeMakeSpaceAvailable()
2390 if (getAvailableBufferLength() < 2) {
2392 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2393 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2396 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2397 newSize
=Config
.maxRequestBufferSize
;
2399 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2400 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2406 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2408 ClientSocketContext::Pointer
*S
;
2410 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2418 ConnStateData::getConcurrentRequestCount() const
2421 ClientSocketContext::Pointer
*T
;
2423 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2424 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2429 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2431 if (flag
!= COMM_OK
) {
2432 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2437 if (!ignoreErrno(xerrno
)) {
2438 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2440 } else if (in
.notYetUsed
== 0) {
2441 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2449 ConnStateData::connFinishedWithConn(int size
)
2452 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2453 /* no current or pending requests */
2454 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2456 } else if (!Config
.onoff
.half_closed_clients
) {
2457 /* admin doesn't want to support half-closed client sockets */
2458 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2459 notifyAllContexts(0); // no specific error implies abort
2468 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2470 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2471 conn
->in
.notYetUsed
-= byteCount
;
2472 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2474 * If there is still data that will be used,
2475 * move it to the beginning.
2478 if (conn
->in
.notYetUsed
> 0)
2479 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2482 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2484 ConnStateData::checkHeaderLimits()
2486 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2487 return; // can accumulte more header data
2489 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2490 Config
.maxRequestHeaderSize
<< " bytes)");
2492 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2493 clientStreamNode
*node
= context
->getClientReplyContext();
2494 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2495 assert (repContext
);
2496 repContext
->setReplyToError(ERR_TOO_BIG
,
2497 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2498 clientConnection
->remote
, NULL
, NULL
, NULL
);
2499 context
->registerWithConn();
2500 context
->pullData();
2504 ConnStateData::clientAfterReadingRequests()
2506 // Were we expecting to read more request body from half-closed connection?
2507 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2508 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2509 clientConnection
->close();
2518 ConnStateData::quitAfterError(HttpRequest
*request
)
2520 // From HTTP p.o.v., we do not have to close after every error detected
2521 // at the client-side, but many such errors do require closure and the
2522 // client-side code is bad at handling errors so we play it safe.
2524 request
->flags
.proxyKeepalive
= false;
2525 flags
.readMore
= false;
2526 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2530 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2532 ClientHttpRequest
*http
= context
->http
;
2537 assert(sslServerBump
->entry
);
2538 // Did we create an error entry while processing CONNECT?
2539 if (!sslServerBump
->entry
->isEmpty()) {
2540 quitAfterError(http
->request
);
2542 // Get the saved error entry and send it to the client by replacing the
2543 // ClientHttpRequest store entry with it.
2544 clientStreamNode
*node
= context
->getClientReplyContext();
2545 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2547 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2548 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2550 // save the original request for logging purposes
2551 if (!context
->http
->al
->request
) {
2552 context
->http
->al
->request
= http
->request
;
2553 HTTPMSGLOCK(context
->http
->al
->request
);
2556 // Get error details from the fake certificate-peeking request.
2557 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2558 context
->pullData();
2562 // In bump-server-first mode, we have not necessarily seen the intended
2563 // server name at certificate-peeking time. Check for domain mismatch now,
2564 // when we can extract the intended name from the bumped HTTP request.
2565 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2566 HttpRequest
*request
= http
->request
;
2567 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2568 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2569 "does not match domainname " << request
->GetHost());
2571 bool allowDomainMismatch
= false;
2572 if (Config
.ssl_client
.cert_error
) {
2573 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2574 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2575 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2576 delete check
.sslErrors
;
2577 check
.sslErrors
= NULL
;
2580 if (!allowDomainMismatch
) {
2581 quitAfterError(request
);
2583 clientStreamNode
*node
= context
->getClientReplyContext();
2584 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2585 assert (repContext
);
2587 // Fill the server IP and hostname for error page generation.
2588 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2589 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2591 // Create an error object and fill it
2592 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2593 err
->src_addr
= clientConnection
->remote
;
2594 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2595 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2597 err
->detail
= errDetail
;
2598 // Save the original request for logging purposes.
2599 if (!context
->http
->al
->request
) {
2600 context
->http
->al
->request
= request
;
2601 HTTPMSGLOCK(context
->http
->al
->request
);
2603 repContext
->setReplyToError(request
->method
, err
);
2604 assert(context
->http
->out
.offset
== 0);
2605 context
->pullData();
2616 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2618 ClientHttpRequest
*http
= context
->http
;
2619 HttpRequest::Pointer request
;
2620 bool notedUseOfBuffer
= false;
2621 bool chunked
= false;
2622 bool mustReplyToOptions
= false;
2623 bool unsupportedTe
= false;
2624 bool expectBody
= false;
2626 /* We have an initial client stream in place should it be needed */
2627 /* setup our private context */
2628 context
->registerWithConn();
2630 if (context
->flags
.parsed_ok
== 0) {
2631 clientStreamNode
*node
= context
->getClientReplyContext();
2632 debugs(33, 2, "clientProcessRequest: Invalid Request");
2633 conn
->quitAfterError(NULL
);
2634 // setLogUri should called before repContext->setReplyToError
2635 setLogUri(http
, http
->uri
, true);
2636 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2637 assert (repContext
);
2638 switch (hp
->request_parse_status
) {
2639 case Http::scHeaderTooLarge
:
2640 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2642 case Http::scMethodNotAllowed
:
2643 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2644 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2647 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2648 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2650 assert(context
->http
->out
.offset
== 0);
2651 context
->pullData();
2655 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2656 clientStreamNode
*node
= context
->getClientReplyContext();
2657 debugs(33, 5, "Invalid URL: " << http
->uri
);
2658 conn
->quitAfterError(request
.getRaw());
2659 // setLogUri should called before repContext->setReplyToError
2660 setLogUri(http
, http
->uri
, true);
2661 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2662 assert (repContext
);
2663 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2664 assert(context
->http
->out
.offset
== 0);
2665 context
->pullData();
2669 /* RFC 2616 section 10.5.6 : handle unsupported HTTP major versions cleanly. */
2670 /* We currently only support 0.9, 1.0, 1.1 properly */
2671 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2672 (http_ver
.major
> 1) ) {
2674 clientStreamNode
*node
= context
->getClientReplyContext();
2675 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2676 conn
->quitAfterError(request
.getRaw());
2677 // setLogUri should called before repContext->setReplyToError
2678 setLogUri(http
, http
->uri
, true);
2679 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2680 assert (repContext
);
2681 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2682 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2683 assert(context
->http
->out
.offset
== 0);
2684 context
->pullData();
2688 /* compile headers */
2689 /* we should skip request line! */
2690 /* XXX should actually know the damned buffer size here */
2691 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2692 clientStreamNode
*node
= context
->getClientReplyContext();
2693 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2694 conn
->quitAfterError(request
.getRaw());
2695 // setLogUri should called before repContext->setReplyToError
2696 setLogUri(http
, http
->uri
, true);
2697 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2698 assert (repContext
);
2699 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2700 assert(context
->http
->out
.offset
== 0);
2701 context
->pullData();
2705 request
->clientConnectionManager
= conn
;
2707 request
->flags
.accelerated
= http
->flags
.accel
;
2708 request
->flags
.sslBumped
=conn
->switchedToHttps();
2709 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2710 // TODO: decouple http->flags.accel from request->flags.sslBumped
2711 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2712 !conn
->port
->allow_direct
: 0;
2714 if (request
->flags
.sslBumped
) {
2715 if (conn
->getAuth() != NULL
)
2716 request
->auth_user_request
= conn
->getAuth();
2721 * If transparent or interception mode is working clone the transparent and interception flags
2722 * from the port settings to the request.
2724 if (http
->clientConnection
!= NULL
) {
2725 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2726 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2727 if (request
->flags
.interceptTproxy
) {
2728 if (Config
.accessList
.spoof_client_ip
) {
2729 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2730 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2733 request
->flags
.spoofClientIp
= true;
2735 request
->flags
.spoofClientIp
= false;
2738 if (internalCheck(request
->urlpath
.termedBuf())) {
2739 if (internalHostnameIs(request
->GetHost()) &&
2740 request
->port
== getMyPort()) {
2741 http
->flags
.internal
= true;
2742 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2743 request
->SetHost(internalHostname());
2744 request
->port
= getMyPort();
2745 http
->flags
.internal
= true;
2749 if (http
->flags
.internal
) {
2750 request
->protocol
= AnyP::PROTO_HTTP
;
2751 request
->login
[0] = '\0';
2754 request
->flags
.internal
= http
->flags
.internal
;
2755 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2756 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2757 #if FOLLOW_X_FORWARDED_FOR
2758 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2759 // not a details about teh TCP connection itself
2760 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2761 #endif /* FOLLOW_X_FORWARDED_FOR */
2762 request
->my_addr
= conn
->clientConnection
->local
;
2763 request
->myportname
= conn
->port
->name
;
2764 request
->http_ver
= http_ver
;
2766 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2767 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2768 request
->clientConnectionManager
= conn
;
2770 if (request
->header
.chunked()) {
2772 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2773 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2774 // HTTP/1.1 requires chunking to be the last encoding if there is one
2775 unsupportedTe
= te
.size() && te
!= "identity";
2776 } // else implied identity coding
2778 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2779 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2780 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2781 clientStreamNode
*node
= context
->getClientReplyContext();
2782 conn
->quitAfterError(request
.getRaw());
2783 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2784 assert (repContext
);
2785 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2786 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2787 assert(context
->http
->out
.offset
== 0);
2788 context
->pullData();
2792 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2793 clientStreamNode
*node
= context
->getClientReplyContext();
2794 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2795 assert (repContext
);
2796 conn
->quitAfterError(request
.getRaw());
2797 repContext
->setReplyToError(ERR_INVALID_REQ
,
2798 Http::scLengthRequired
, request
->method
, NULL
,
2799 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2800 assert(context
->http
->out
.offset
== 0);
2801 context
->pullData();
2805 if (request
->header
.has(HDR_EXPECT
)) {
2806 const String expect
= request
->header
.getList(HDR_EXPECT
);
2807 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2808 if (!supportedExpect
) {
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
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2814 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2815 assert(context
->http
->out
.offset
== 0);
2816 context
->pullData();
2821 http
->request
= request
.getRaw();
2822 HTTPMSGLOCK(http
->request
);
2823 clientSetKeepaliveFlag(http
);
2825 // Let tunneling code be fully responsible for CONNECT requests
2826 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2827 context
->mayUseConnection(true);
2828 conn
->flags
.readMore
= false;
2832 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2836 /* Do we expect a request-body? */
2837 expectBody
= chunked
|| request
->content_length
> 0;
2838 if (!context
->mayUseConnection() && expectBody
) {
2839 request
->body_pipe
= conn
->expectRequestBody(
2840 chunked
? -1 : request
->content_length
);
2842 // consume header early so that body pipe gets just the body
2843 connNoteUseOfBuffer(conn
, http
->req_sz
);
2844 notedUseOfBuffer
= true;
2846 /* Is it too large? */
2847 if (!chunked
&& // if chunked, we will check as we accumulate
2848 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2849 clientStreamNode
*node
= context
->getClientReplyContext();
2850 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2851 assert (repContext
);
2852 conn
->quitAfterError(request
.getRaw());
2853 repContext
->setReplyToError(ERR_TOO_BIG
,
2854 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2855 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2856 assert(context
->http
->out
.offset
== 0);
2857 context
->pullData();
2861 // We may stop producing, comm_close, and/or call setReplyToError()
2862 // below, so quit on errors to avoid http->doCallouts()
2863 if (!conn
->handleRequestBodyData())
2866 if (!request
->body_pipe
->productionEnded()) {
2867 debugs(33, 5, HERE
<< "need more request body");
2868 context
->mayUseConnection(true);
2869 assert(conn
->flags
.readMore
);
2873 http
->calloutContext
= new ClientRequestContext(http
);
2878 if (!notedUseOfBuffer
)
2879 connNoteUseOfBuffer(conn
, http
->req_sz
);
2883 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2884 * to here because calling comm_reset_close() causes http to
2885 * be freed and the above connNoteUseOfBuffer() would hit an
2886 * assertion, not to mention that we were accessing freed memory.
2888 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2889 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2890 conn
->flags
.readMore
= false;
2891 comm_reset_close(conn
->clientConnection
);
2896 connStripBufferWhitespace (ConnStateData
* conn
)
2898 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2899 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2900 -- conn
->in
.notYetUsed
;
2905 * Limit the number of concurrent requests.
2906 * \return true when there are available position(s) in the pipeline queue for another request.
2907 * \return false when the pipeline queue is full or disabled.
2910 ConnStateData::concurrentRequestQueueFilled() const
2912 const int existingRequestCount
= getConcurrentRequestCount();
2914 // default to the configured pipeline size.
2915 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2916 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2918 // when queue filled already we cant add more.
2919 if (existingRequestCount
>= concurrentRequestLimit
) {
2920 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2921 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2929 * Attempt to parse one or more requests from the input buffer.
2930 * If a request is successfully parsed, even if the next request
2931 * is only partially parsed, it will return TRUE.
2934 ConnStateData::clientParseRequests()
2936 HttpRequestMethod method
;
2937 bool parsed_req
= false;
2939 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2941 // Loop while we have read bytes that are not needed for producing the body
2942 // On errors, bodyPipe may become nil, but readMore will be cleared
2943 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2944 connStripBufferWhitespace(this);
2946 /* Don't try to parse if the buffer is empty */
2947 if (in
.notYetUsed
== 0)
2950 /* Limit the number of concurrent requests */
2951 if (concurrentRequestQueueFilled())
2954 /* Should not be needed anymore */
2955 /* Terminate the string */
2956 in
.buf
[in
.notYetUsed
] = '\0';
2958 /* Begin the parsing */
2959 PROF_start(parseHttpRequest
);
2960 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
2962 /* Process request */
2963 Http::ProtocolVersion http_ver
;
2964 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2965 PROF_stop(parseHttpRequest
);
2967 /* partial or incomplete request */
2969 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2970 // (which becomes context) but checkHeaderLimits cannot?
2971 checkHeaderLimits();
2975 /* status -1 or 1 */
2977 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2978 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2979 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2980 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2982 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2984 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2986 if (context
->mayUseConnection()) {
2987 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2993 /* XXX where to 'finish' the parsing pass? */
2998 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3000 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3004 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
3006 if (io
.flag
== COMM_ERR_CLOSING
) {
3007 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
3011 assert(Comm::IsConnOpen(clientConnection
));
3012 assert(io
.conn
->fd
== clientConnection
->fd
);
3015 * Don't reset the timeout value here. The timeout value will be
3016 * set to Config.Timeout.request by httpAccept() and
3017 * clientWriteComplete(), and should apply to the request as a
3018 * whole, not individual read() calls. Plus, it breaks our
3019 * lame half-close detection
3021 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3022 notifyAllContexts(io
.xerrno
);
3027 if (io
.flag
== COMM_OK
) {
3029 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3031 // may comm_close or setReplyToError
3032 if (!handleReadData(io
.buf
, io
.size
))
3035 } else if (io
.size
== 0) {
3036 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3038 if (connFinishedWithConn(io
.size
)) {
3039 clientConnection
->close();
3043 /* It might be half-closed, we can't tell */
3044 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3046 commMarkHalfClosed(io
.conn
->fd
);
3048 fd_note(io
.conn
->fd
, "half-closed");
3050 /* There is one more close check at the end, to detect aborted
3051 * (partial) requests. At this point we can't tell if the request
3054 /* Continue to process previously read data */
3058 /* Process next request */
3059 if (getConcurrentRequestCount() == 0)
3060 fd_note(io
.fd
, "Reading next request");
3062 if (!clientParseRequests()) {
3066 * If the client here is half closed and we failed
3067 * to parse a request, close the connection.
3068 * The above check with connFinishedWithConn() only
3069 * succeeds _if_ the buffer is empty which it won't
3070 * be if we have an incomplete request.
3071 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3073 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3074 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3075 clientConnection
->close();
3083 clientAfterReadingRequests();
3087 * called when new request data has been read from the socket
3089 * \retval false called comm_close or setReplyToError (the caller should bail)
3090 * \retval true we did not call comm_close or setReplyToError
3093 ConnStateData::handleReadData(char *buf
, size_t size
)
3095 char *current_buf
= in
.addressToReadInto();
3097 if (buf
!= current_buf
)
3098 memmove(current_buf
, buf
, size
);
3100 in
.notYetUsed
+= size
;
3102 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3104 // if we are reading a body, stuff data into the body pipe
3105 if (bodyPipe
!= NULL
)
3106 return handleRequestBodyData();
3111 * called when new request body data has been buffered in in.buf
3112 * may close the connection if we were closing and piped everything out
3114 * \retval false called comm_close or setReplyToError (the caller should bail)
3115 * \retval true we did not call comm_close or setReplyToError
3118 ConnStateData::handleRequestBodyData()
3120 assert(bodyPipe
!= NULL
);
3124 if (in
.bodyParser
) { // chunked encoding
3125 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3126 abortChunkedRequestBody(error
);
3129 } else { // identity encoding
3130 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3131 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3132 if (!bodyPipe
->mayNeedMoreData()) {
3133 // BodyPipe will clear us automagically when we produced everything
3139 connNoteUseOfBuffer(this, putSize
);
3142 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3144 if (const char *reason
= stoppedSending()) {
3145 /* we've finished reading like good clients,
3146 * now do the close that initiateClose initiated.
3148 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3149 clientConnection
->close();
3157 /// parses available chunked encoded body bytes, checks size, returns errors
3159 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3161 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3163 try { // the parser will throw on errors
3165 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3168 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3169 // add one because MemBuf will assert if it cannot 0-terminate
3170 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3171 raw
.append(in
.buf
, in
.notYetUsed
);
3173 const mb_size_t wasContentSize
= raw
.contentSize();
3174 BodyPipeCheckout
bpc(*bodyPipe
);
3175 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3177 putSize
= wasContentSize
- raw
.contentSize();
3179 // dechunk then check: the size limit applies to _dechunked_ content
3180 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3184 finishDechunkingRequest(true);
3186 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3189 // if chunk parser needs data, then the body pipe must need it too
3190 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3192 // if parser needs more space and we can consume nothing, we will stall
3193 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3194 } catch (...) { // TODO: be more specific
3195 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3196 return ERR_INVALID_REQ
;
3199 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3203 /// quit on errors related to chunked request body handling
3205 ConnStateData::abortChunkedRequestBody(const err_type error
)
3207 finishDechunkingRequest(false);
3209 // XXX: The code below works if we fail during initial request parsing,
3210 // but if we fail when the server-side works already, the server may send
3211 // us its response too, causing various assertions. How to prevent that?
3212 #if WE_KNOW_HOW_TO_SEND_ERRORS
3213 ClientSocketContext::Pointer context
= getCurrentContext();
3214 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3215 clientStreamNode
*node
= context
->getClientReplyContext();
3216 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3218 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3219 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3220 repContext
->setReplyToError(error
, scode
,
3221 repContext
->http
->request
->method
,
3222 repContext
->http
->uri
,
3224 repContext
->http
->request
,
3226 context
->pullData();
3228 // close or otherwise we may get stuck as nobody will notice the error?
3229 comm_reset_close(clientConnection
);
3232 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3233 comm_reset_close(clientConnection
);
3235 flags
.readMore
= false;
3239 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3241 if (!handleRequestBodyData())
3244 // too late to read more body
3245 if (!isOpen() || stoppedReceiving())
3252 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3254 // request reader may get stuck waiting for space if nobody consumes body
3255 if (bodyPipe
!= NULL
)
3256 bodyPipe
->enableAutoConsumption();
3258 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3261 /** general lifetime handler for HTTP requests */
3263 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3266 * Just close the connection to not confuse browsers
3267 * using persistent connections. Some browsers open
3268 * a connection and then do not use it until much
3269 * later (presumeably because the request triggering
3270 * the open has already been completed on another
3273 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3278 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3280 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3281 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3282 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3283 http
->al
->http
.timedout
= true;
3284 if (Comm::IsConnOpen(io
.conn
))
3288 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3289 AsyncJob("ConnStateData"),
3291 sslBumpMode(Ssl::bumpEnd
),
3292 switchedToHttps_(false),
3293 sslServerBump(NULL
),
3295 stoppedSending_(NULL
),
3296 stoppedReceiving_(NULL
)
3298 pinning
.host
= NULL
;
3300 pinning
.pinned
= false;
3301 pinning
.auth
= false;
3302 pinning
.zeroReply
= false;
3303 pinning
.peer
= NULL
;
3305 // store the details required for creating more MasterXaction objects as new requests come in
3306 clientConnection
= xact
->tcpClient
;
3307 port
= cbdataReference(xact
->squidPort
.get());
3308 log_addr
= xact
->tcpClient
->remote
;
3309 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3311 in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &in
.allocatedSize
);
3313 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3314 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3315 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3316 int i
= IP_PMTUDISC_DONT
;
3317 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3318 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3320 static bool reported
= false;
3323 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3329 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3330 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3331 comm_add_close_handler(clientConnection
->fd
, call
);
3333 if (Config
.onoff
.log_fqdn
)
3334 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3337 if (Ident::TheConfig
.identLookup
) {
3338 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3339 identChecklist
.src_addr
= xact
->tcpClient
->remote
;
3340 identChecklist
.my_addr
= xact
->tcpClient
->local
;
3341 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3342 Ident::Start(xact
->tcpClient
, clientIdentDone
, this);
3346 clientdbEstablished(clientConnection
->remote
, 1);
3348 flags
.readMore
= true;
3351 /** Handle a new connection on HTTP socket. */
3353 httpAccept(const CommAcceptCbParams
¶ms
)
3355 MasterXaction::Pointer xact
= params
.xaction
;
3356 AnyP::PortCfgPointer s
= xact
->squidPort
;
3359 // it is possible the call or accept() was still queued when the port was reconfigured
3360 debugs(33, 2, "HTTP accept failure: port reconfigured.");
3364 if (params
.flag
!= COMM_OK
) {
3365 // Its possible the call was still queued when the client disconnected
3366 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3370 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3371 fd_note(params
.conn
->fd
, "client http connect");
3373 if (s
->tcp_keepalive
.enabled
) {
3374 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3377 ++ incoming_sockets_accepted
;
3379 // Socket is ready, setup the connection manager to start using it
3380 ConnStateData
*connState
= new ConnStateData(xact
);
3382 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3383 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3384 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3385 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3387 connState
->readSomeData();
3390 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3392 if (Config
.onoff
.client_db
) {
3393 /* it was said several times that client write limiter does not work if client_db is disabled */
3395 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3396 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3398 // TODO: we check early to limit error response bandwith but we
3399 // should recheck when we can honor delay_pool_uses_indirect
3400 // TODO: we should also pass the port details for myportname here.
3401 ch
.src_addr
= params
.conn
->remote
;
3402 ch
.my_addr
= params
.conn
->local
;
3404 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3406 /* pools require explicit 'allow' to assign a client into them */
3407 if (pools
[pool
].access
) {
3408 ch
.accessList
= pools
[pool
].access
;
3409 allow_t answer
= ch
.fastCheck();
3410 if (answer
== ACCESS_ALLOWED
) {
3412 /* request client information from db after we did all checks
3413 this will save hash lookup if client failed checks */
3414 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3417 /* put client info in FDE */
3418 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3420 /* setup write limiter for this request */
3421 const double burst
= floor(0.5 +
3422 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3423 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3426 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3436 /** Create SSL connection structure and update fd_table */
3438 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3440 SSL
*ssl
= SSL_new(sslContext
);
3443 const int ssl_error
= ERR_get_error();
3444 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3449 SSL_set_fd(ssl
, conn
->fd
);
3450 fd_table
[conn
->fd
].ssl
= ssl
;
3451 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3452 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3454 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3455 fd_note(conn
->fd
, "client https start");
3460 /** negotiate an SSL connection */
3462 clientNegotiateSSL(int fd
, void *data
)
3464 ConnStateData
*conn
= (ConnStateData
*)data
;
3466 SSL
*ssl
= fd_table
[fd
].ssl
;
3469 if ((ret
= SSL_accept(ssl
)) <= 0) {
3470 int ssl_error
= SSL_get_error(ssl
, ret
);
3472 switch (ssl_error
) {
3474 case SSL_ERROR_WANT_READ
:
3475 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3478 case SSL_ERROR_WANT_WRITE
:
3479 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3482 case SSL_ERROR_SYSCALL
:
3485 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3491 if (errno
== ECONNRESET
)
3494 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3495 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3502 case SSL_ERROR_ZERO_RETURN
:
3503 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3508 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3509 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3510 " (" << ssl_error
<< "/" << ret
<< ")");
3518 if (SSL_session_reused(ssl
)) {
3519 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3520 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3522 if (do_debug(83, 4)) {
3523 /* Write out the SSL session details.. actually the call below, but
3524 * OpenSSL headers do strange typecasts confusing GCC.. */
3525 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3526 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3527 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
);
3529 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3531 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3532 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3533 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3534 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3535 * Because there are two possible usable cast, if you get an error here, try the other
3536 * commented line. */
3538 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3539 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3543 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3546 /* Note: This does not automatically fflush the log file.. */
3549 debugs(83, 2, "clientNegotiateSSL: New session " <<
3550 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3551 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3555 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3556 SSL_get_cipher(ssl
));
3558 client_cert
= SSL_get_peer_certificate(ssl
);
3560 if (client_cert
!= NULL
) {
3561 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3562 " client certificate: subject: " <<
3563 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3565 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3566 " client certificate: issuer: " <<
3567 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3569 X509_free(client_cert
);
3571 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3572 " has no certificate.");
3575 conn
->readSomeData();
3579 * If SSL_CTX is given, starts reading the SSL handshake.
3580 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3583 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3587 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3589 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3592 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3593 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3594 connState
, ConnStateData::requestTimeout
);
3595 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3598 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3600 char buf
[MAX_IPSTRLEN
];
3601 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3602 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3603 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3604 fakeRequest
->port
= details
->local
.port();
3605 fakeRequest
->clientConnectionManager
= connState
;
3606 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3607 #if FOLLOW_X_FORWARDED_FOR
3608 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3610 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3611 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3612 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3613 fakeRequest
->myportname
= connState
->port
->name
;
3614 if (fakeRequest
->flags
.interceptTproxy
) {
3615 if (Config
.accessList
.spoof_client_ip
) {
3616 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3617 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3619 fakeRequest
->flags
.spoofClientIp
= true;
3621 fakeRequest
->flags
.spoofClientIp
= false;
3622 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3623 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3628 * A callback function to use with the ACLFilledChecklist callback.
3629 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3630 * else reverts the connection to tunnel mode.
3633 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3635 ConnStateData
*connState
= (ConnStateData
*) data
;
3637 // if the connection is closed or closing, just return.
3638 if (!connState
->isOpen())
3641 // Require both a match and a positive bump mode to work around exceptional
3642 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3643 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3644 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3645 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3646 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3648 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3649 connState
->sslBumpMode
= Ssl::bumpNone
;
3651 // fake a CONNECT request to force connState to tunnel
3652 static char ip
[MAX_IPSTRLEN
];
3653 static char reqStr
[MAX_IPSTRLEN
+ 80];
3654 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3655 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, ip
);
3656 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3658 ret
= connState
->clientParseRequests();
3661 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3662 connState
->clientConnection
->close();
3667 /** handle a new HTTPS connection */
3669 httpsAccept(const CommAcceptCbParams
¶ms
)
3671 MasterXaction::Pointer xact
= params
.xaction
;
3672 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3675 // it is possible the call or accept() was still queued when the port was reconfigured
3676 debugs(33, 2, "HTTPS accept failure: port reconfigured.");
3680 if (params
.flag
!= COMM_OK
) {
3681 // Its possible the call was still queued when the client disconnected
3682 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3686 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3687 fd_note(params
.conn
->fd
, "client https connect");
3689 if (s
->tcp_keepalive
.enabled
) {
3690 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3693 ++incoming_sockets_accepted
;
3695 // Socket is ready, setup the connection manager to start using it
3696 ConnStateData
*connState
= new ConnStateData(xact
);
3698 if (s
->flags
.tunnelSslBumping
) {
3699 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3701 if (!Config
.accessList
.ssl_bump
) {
3702 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3706 // Create a fake HTTP request for ssl_bump ACL check,
3707 // using tproxy/intercept provided destination IP and port.
3708 HttpRequest
*request
= new HttpRequest();
3709 static char ip
[MAX_IPSTRLEN
];
3710 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3711 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3712 request
->port
= params
.conn
->local
.port();
3713 request
->myportname
= s
->name
;
3715 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3716 acl_checklist
->src_addr
= params
.conn
->remote
;
3717 acl_checklist
->my_addr
= s
->s
;
3718 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3721 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3722 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3727 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3729 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3730 state_data
->sslCrtdHandleReply(reply
);
3734 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3736 if (reply
.result
== HelperReply::BrokenHelper
) {
3737 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3738 } else if (!reply
.other().hasContent()) {
3739 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3741 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3742 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3743 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3745 if (reply
.result
!= HelperReply::Okay
) {
3746 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3748 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3749 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3750 getSslContextDone(ctx
, true);
3755 getSslContextDone(NULL
);
3758 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3760 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3762 // fake certificate adaptation requires bump-server-first mode
3763 if (!sslServerBump
) {
3764 assert(port
->signingCert
.get());
3765 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3766 if (port
->signPkey
.get())
3767 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3768 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3772 // In case of an error while connecting to the secure server, use a fake
3773 // trusted certificate, with no mimicked fields and no adaptation
3774 // algorithms. There is nothing we can mimic so we want to minimize the
3775 // number of warnings the user will have to see to get to the error page.
3776 assert(sslServerBump
->entry
);
3777 if (sslServerBump
->entry
->isEmpty()) {
3778 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3779 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3781 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3782 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3783 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3785 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3786 // If the algorithm already set, then ignore it.
3787 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3788 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3789 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3792 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3793 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3794 const char *param
= ca
->param
;
3796 // For parameterless CN adaptation, use hostname from the
3798 if (ca
->alg
== Ssl::algSetCommonName
) {
3800 param
= sslConnectHostOrIp
.termedBuf();
3801 certProperties
.commonName
= param
;
3802 certProperties
.setCommonName
= true;
3803 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3804 certProperties
.setValidAfter
= true;
3805 else if (ca
->alg
== Ssl::algSetValidBefore
)
3806 certProperties
.setValidBefore
= true;
3808 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3809 alg
<< " param: " << (param
? param
: "-"));
3813 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3814 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3815 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3816 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3820 } else {// if (!sslServerBump->entry->isEmpty())
3821 // Use trusted certificate for a Squid-generated error
3822 // or the user would have to add a security exception
3823 // just to see the error page. We will close the connection
3824 // so that the trust is not extended to non-Squid content.
3825 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3828 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3830 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3831 assert(port
->untrustedSigningCert
.get());
3832 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3833 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3835 assert(port
->signingCert
.get());
3836 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3838 if (port
->signPkey
.get())
3839 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3841 signAlgorithm
= certProperties
.signAlgorithm
;
3845 ConnStateData::getSslContextStart()
3847 assert(areAllContextsForThisConnection());
3849 /* careful: freeAllContexts() above frees request, host, etc. */
3851 if (port
->generateHostCertificates
) {
3852 Ssl::CertificateProperties certProperties
;
3853 buildSslCertGenerationParams(certProperties
);
3854 sslBumpCertKey
= certProperties
.dbKey().c_str();
3855 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3857 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3858 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3859 SSL_CTX
* dynCtx
= NULL
;
3860 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3861 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3862 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3863 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3864 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3865 getSslContextDone(dynCtx
);
3868 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3870 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3873 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3878 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3879 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3880 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3881 request_message
.composeRequest(certProperties
);
3882 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3883 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3885 } catch (const std::exception
&e
) {
3886 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3887 "request for " << certProperties
.commonName
<<
3888 " certificate: " << e
.what() << "; will now block to " <<
3889 "generate that certificate.");
3890 // fall through to do blocking in-process generation.
3892 #endif // USE_SSL_CRTD
3894 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3895 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3896 getSslContextDone(dynCtx
, true);
3899 getSslContextDone(NULL
);
3903 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3905 // Try to add generated ssl context to storage.
3906 if (port
->generateHostCertificates
&& isNew
) {
3908 if (signAlgorithm
== Ssl::algSignTrusted
) {
3909 // Add signing certificate to the certificates chain
3910 X509
*cert
= port
->signingCert
.get();
3911 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3912 // increase the certificate lock
3913 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3915 const int ssl_error
= ERR_get_error();
3916 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3918 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3920 //else it is self-signed or untrusted do not attrach any certificate
3922 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3923 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3925 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3926 // If it is not in storage delete after using. Else storage deleted it.
3927 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3930 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3934 // If generated ssl context = NULL, try to use static ssl context.
3936 if (!port
->staticSslContext
) {
3937 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3938 clientConnection
->close();
3941 debugs(33, 5, HERE
<< "Using static ssl context.");
3942 sslContext
= port
->staticSslContext
.get();
3946 if (!httpsCreate(clientConnection
, sslContext
))
3949 // commSetConnTimeout() was called for this request before we switched.
3951 // Disable the client read handler until CachePeer selection is complete
3952 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3953 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3954 switchedToHttps_
= true;
3958 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3960 assert(!switchedToHttps_
);
3962 sslConnectHostOrIp
= request
->GetHost();
3963 sslCommonName
= request
->GetHost();
3965 // We are going to read new request
3966 flags
.readMore
= true;
3967 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3969 // If sslServerBump is set, then we have decided to deny CONNECT
3970 // and now want to switch to SSL to send the error to the client
3971 // without even peeking at the origin server certificate.
3972 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3973 request
->flags
.sslPeek
= true;
3974 sslServerBump
= new Ssl::ServerBump(request
);
3976 // will call httpsPeeked() with certificate and connection, eventually
3977 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3981 // otherwise, use sslConnectHostOrIp
3982 getSslContextStart();
3986 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3988 Must(sslServerBump
!= NULL
);
3990 if (Comm::IsConnOpen(serverConnection
)) {
3991 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3993 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3994 assert(serverCert
.get() != NULL
);
3995 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
3996 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
3997 " bumped: " << *serverConnection
);
3999 pinConnection(serverConnection
, NULL
, NULL
, false);
4001 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4003 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4004 Ip::Address intendedDest
;
4005 intendedDest
= sslConnectHostOrIp
.termedBuf();
4006 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4008 // Squid serves its own error page and closes, so we want
4009 // a CN that causes no additional browser errors. Possible
4010 // only when bumping CONNECT with a user-typed address.
4011 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4012 sslCommonName
= sslConnectHostOrIp
;
4013 else if (sslServerBump
->serverCert
.get())
4014 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4016 // copy error detail from bump-server-first request to CONNECT request
4017 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4018 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4021 getSslContextStart();
4024 #endif /* USE_SSL */
4026 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4028 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4030 if (!Comm::IsConnOpen(c
)) {
4031 Must(NHttpSockets
> 0); // we tried to open some
4032 --NHttpSockets
; // there will be fewer sockets than planned
4033 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4035 if (!NHttpSockets
) // we could not open any listen sockets at all
4036 fatalf("Unable to open %s",FdNote(portType
));
4043 /// find any unused HttpSockets[] slot and store fd there or return false
4045 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4048 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4049 if ((found
= HttpSockets
[i
] < 0))
4050 HttpSockets
[i
] = conn
->fd
;
4056 clientHttpConnectionsOpen(void)
4058 AnyP::PortCfg
*s
= NULL
;
4060 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4061 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4062 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4063 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4068 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4069 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4070 s
->flags
.tunnelSslBumping
= false;
4073 if (s
->flags
.tunnelSslBumping
&&
4074 !s
->staticSslContext
&&
4075 !s
->generateHostCertificates
) {
4076 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4077 s
->flags
.tunnelSslBumping
= false;
4079 if (s
->flags
.tunnelSslBumping
) {
4080 // Create ssl_ctx cache for this port.
4081 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4085 // Fill out a Comm::Connection which IPC will open as a listener for us
4086 // then pass back when active so we can start a TcpAcceptor subscription.
4087 s
->listenConn
= new Comm::Connection
;
4088 s
->listenConn
->local
= s
->s
;
4089 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4091 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4092 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4093 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4094 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4096 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4097 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4098 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4100 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4107 clientHttpsConnectionsOpen(void)
4111 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4112 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4113 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4114 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4118 if (!s
->staticSslContext
) {
4119 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4120 " due to SSL initialization failure.");
4124 // TODO: merge with similar code in clientHttpConnectionsOpen()
4125 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4126 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4127 s
->flags
.tunnelSslBumping
= false;
4130 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4131 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4132 s
->flags
.tunnelSslBumping
= false;
4135 if (s
->flags
.tunnelSslBumping
) {
4136 // Create ssl_ctx cache for this port.
4137 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4140 // Fill out a Comm::Connection which IPC will open as a listener for us
4141 s
->listenConn
= new Comm::Connection
;
4142 s
->listenConn
->local
= s
->s
;
4143 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4144 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4146 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4147 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4148 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4149 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4151 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4152 ListeningStartedDialer(&clientListenerConnectionOpened
,
4153 s
, Ipc::fdnHttpsSocket
, sub
));
4154 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4155 HttpSockets
[NHttpSockets
] = -1;
4161 /// process clientHttpConnectionsOpen result
4163 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4165 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4169 Must(Comm::IsConnOpen(s
->listenConn
));
4171 // TCP: setup a job to handle accept() with subscribed handler
4172 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4174 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4175 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4176 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4177 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4178 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4179 << FdNote(portTypeNote
) << " connections at "
4182 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4186 clientOpenListenSockets(void)
4188 clientHttpConnectionsOpen();
4190 clientHttpsConnectionsOpen();
4193 if (NHttpSockets
< 1)
4194 fatal("No HTTP or HTTPS ports configured");
4198 clientHttpConnectionsClose(void)
4200 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4201 if (s
->listenConn
!= NULL
) {
4202 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4203 s
->listenConn
->close();
4204 s
->listenConn
= NULL
;
4209 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4210 if (s
->listenConn
!= NULL
) {
4211 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4212 s
->listenConn
->close();
4213 s
->listenConn
= NULL
;
4218 // TODO see if we can drop HttpSockets array entirely */
4219 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4220 HttpSockets
[i
] = -1;
4227 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4229 const char *vary
= request
->vary_headers
;
4230 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4231 #if X_ACCELERATOR_VARY
4234 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4237 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4239 /* Oops... something odd is going on here.. */
4240 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4241 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4242 safe_free(request
->vary_headers
);
4247 /* This is not a varying object */
4251 /* virtual "vary" object found. Calculate the vary key and
4252 * continue the search
4254 vary
= httpMakeVaryMark(request
, entry
->getReply());
4257 request
->vary_headers
= xstrdup(vary
);
4260 /* Ouch.. we cannot handle this kind of variance */
4261 /* XXX This cannot really happen, but just to be complete */
4266 vary
= httpMakeVaryMark(request
, entry
->getReply());
4269 request
->vary_headers
= xstrdup(vary
);
4273 /* Ouch.. we cannot handle this kind of variance */
4274 /* XXX This cannot really happen, but just to be complete */
4276 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4279 /* Oops.. we have already been here and still haven't
4280 * found the requested variant. Bail out
4282 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4283 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4289 ACLFilledChecklist
*
4290 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4292 ConnStateData
* conn
= http
->getConn();
4293 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4294 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4297 * hack for ident ACL. It needs to get full addresses, and a place to store
4298 * the ident result on persistent connections...
4300 /* connection oriented auth also needs these two lines for it's operation. */
4304 CBDATA_CLASS_INIT(ConnStateData
);
4307 ConnStateData::transparent() const
4309 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4313 ConnStateData::reading() const
4315 return reader
!= NULL
;
4319 ConnStateData::stopReading()
4322 comm_read_cancel(clientConnection
->fd
, reader
);
4328 ConnStateData::expectRequestBody(int64_t size
)
4330 bodyPipe
= new BodyPipe(this);
4332 bodyPipe
->setBodySize(size
);
4334 startDechunkingRequest();
4339 ConnStateData::mayNeedToReadMoreBody() const
4342 return 0; // request without a body or read/produced all body bytes
4344 if (!bodyPipe
->bodySizeKnown())
4345 return -1; // probably need to read more, but we cannot be sure
4347 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4348 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4350 if (needToProduce
<= haveAvailable
)
4351 return 0; // we have read what we need (but are waiting for pipe space)
4353 return needToProduce
- haveAvailable
;
4357 ConnStateData::stopReceiving(const char *error
)
4359 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4360 "; old sending error: " <<
4361 (stoppedSending() ? stoppedSending_
: "none"));
4363 if (const char *oldError
= stoppedReceiving()) {
4364 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4365 return; // nothing has changed as far as this connection is concerned
4368 stoppedReceiving_
= error
;
4370 if (const char *sendError
= stoppedSending()) {
4371 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4372 clientConnection
->close();
4377 ConnStateData::expectNoForwarding()
4379 if (bodyPipe
!= NULL
) {
4380 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4381 bodyPipe
->expectNoConsumption();
4385 /// initialize dechunking state
4387 ConnStateData::startDechunkingRequest()
4389 Must(bodyPipe
!= NULL
);
4390 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4391 assert(!in
.bodyParser
);
4392 in
.bodyParser
= new ChunkedCodingParser
;
4395 /// put parsed content into input buffer and clean up
4397 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4399 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4401 if (bodyPipe
!= NULL
) {
4402 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4403 BodyPipe::Pointer myPipe
= bodyPipe
;
4404 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4405 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4407 Must(myPipe
->bodySizeKnown());
4408 ClientSocketContext::Pointer context
= getCurrentContext();
4409 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4410 context
->http
->request
->setContentLength(myPipe
->bodySize());
4414 delete in
.bodyParser
;
4415 in
.bodyParser
= NULL
;
4419 ConnStateData::In::addressToReadInto() const
4421 return buf
+ notYetUsed
;
4424 ConnStateData::In::In() : bodyParser(NULL
),
4425 buf (NULL
), notYetUsed (0), allocatedSize (0)
4428 ConnStateData::In::~In()
4431 memFreeBuf(allocatedSize
, buf
);
4432 delete bodyParser
; // TODO: pool
4436 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4439 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4443 ClientSocketContext::Pointer context
= getCurrentContext();
4444 if (context
!= NULL
) {
4445 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4449 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4450 clientConnection
->close();
4453 /// Our close handler called by Comm when the pinned connection is closed
4455 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4457 // FwdState might repin a failed connection sooner than this close
4458 // callback is called for the failed connection.
4459 assert(pinning
.serverConnection
== io
.conn
);
4460 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4461 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4463 if (sawZeroReply
&& clientConnection
!= NULL
) {
4464 debugs(33, 3, "Closing client connection on pinned zero reply.");
4465 clientConnection
->close();
4470 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4472 char desc
[FD_DESC_SZ
];
4474 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4475 if (pinning
.serverConnection
->fd
== pinServer
->fd
) {
4476 startPinnedConnectionMonitoring();
4481 unpinConnection(); // closes pinned connection, if any, and resets fields
4483 pinning
.serverConnection
= pinServer
;
4485 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4487 // when pinning an SSL bumped connection, the request may be NULL
4488 const char *pinnedHost
= "[unknown]";
4490 pinning
.host
= xstrdup(request
->GetHost());
4491 pinning
.port
= request
->port
;
4492 pinnedHost
= pinning
.host
;
4494 pinning
.port
= pinServer
->remote
.port();
4496 pinning
.pinned
= true;
4498 pinning
.peer
= cbdataReference(aPeer
);
4499 pinning
.auth
= auth
;
4500 char stmp
[MAX_IPSTRLEN
];
4501 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4502 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4503 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4504 clientConnection
->fd
);
4505 fd_note(pinning
.serverConnection
->fd
, desc
);
4507 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4508 pinning
.closeHandler
= JobCallback(33, 5,
4509 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4510 // remember the pinned connection so that cb does not unpin a fresher one
4511 typedef CommCloseCbParams Params
;
4512 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4513 params
.conn
= pinning
.serverConnection
;
4514 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4516 startPinnedConnectionMonitoring();
4519 /// Assign a read handler to an idle pinned connection so that we can detect connection closures.
4521 ConnStateData::startPinnedConnectionMonitoring()
4523 if (pinning
.readHandler
!= NULL
)
4524 return; // already monitoring
4526 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4527 pinning
.readHandler
= JobCallback(33, 3,
4528 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4529 static char unusedBuf
[8];
4530 comm_read(pinning
.serverConnection
, unusedBuf
, sizeof(unusedBuf
), pinning
.readHandler
);
4534 ConnStateData::stopPinnedConnectionMonitoring()
4536 if (pinning
.readHandler
!= NULL
) {
4537 comm_read_cancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4538 pinning
.readHandler
= NULL
;
4542 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4543 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4545 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4547 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4549 if (io
.flag
== COMM_ERR_CLOSING
)
4550 return; // close handler will clean up
4552 // We could use getConcurrentRequestCount(), but this may be faster.
4553 const bool clientIsIdle
= !getCurrentContext();
4555 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4556 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4558 assert(pinning
.serverConnection
== io
.conn
);
4559 pinning
.serverConnection
->close();
4561 // If we are still sending data to the client, do not close now. When we are done sending,
4562 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4563 // However, if we are idle, then we must close to inform the idle client and minimize races.
4564 if (clientIsIdle
&& clientConnection
!= NULL
)
4565 clientConnection
->close();
4568 const Comm::ConnectionPointer
4569 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4571 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4574 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4576 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4578 else if (request
&& pinning
.port
!= request
->port
)
4580 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4582 else if (aPeer
!= pinning
.peer
)
4586 /* The pinning info is not safe, remove any pinning info */
4590 return pinning
.serverConnection
;
4594 ConnStateData::unpinConnection()
4596 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4599 cbdataReferenceDone(pinning
.peer
);
4601 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4602 if (pinning
.closeHandler
!= NULL
) {
4603 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4604 pinning
.closeHandler
= NULL
;
4606 /// also close the server side socket, we should not use it for any future requests...
4607 // TODO: do not close if called from our close handler?
4608 pinning
.serverConnection
->close();
4611 safe_free(pinning
.host
);
4613 pinning
.zeroReply
= false;
4615 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4616 * connection has gone away */