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 (!in
.maybeMakeSpaceAvailable())
254 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
255 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
256 comm_read(clientConnection
, in
.buf
, 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 readSomeData().
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
.buf
.length() << " 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
.buf
.length();
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::In::maybeMakeSpaceAvailable()
2380 if (buf
.spaceSize() < 2) {
2381 const SBuf::size_type haveCapacity
= buf
.length() + buf
.spaceSize();
2382 if (haveCapacity
>= Config
.maxRequestBufferSize
) {
2383 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2386 const SBuf::size_type wantCapacity
= min(Config
.maxRequestBufferSize
, haveCapacity
*2);
2387 buf
.reserveCapacity(wantCapacity
);
2388 debugs(33, 2, "growing request buffer: available=" << buf
.spaceSize() << " used=" << buf
.length());
2390 return (buf
.spaceSize() >= 2);
2394 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2396 ClientSocketContext::Pointer
*S
;
2398 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2406 ConnStateData::getConcurrentRequestCount() const
2409 ClientSocketContext::Pointer
*T
;
2411 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2412 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2417 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2419 if (flag
!= COMM_OK
) {
2420 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2425 if (!ignoreErrno(xerrno
)) {
2426 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2428 } else if (in
.buf
.isEmpty()) {
2429 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2437 ConnStateData::connFinishedWithConn(int size
)
2440 if (getConcurrentRequestCount() == 0 && in
.buf
.isEmpty()) {
2441 /* no current or pending requests */
2442 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2444 } else if (!Config
.onoff
.half_closed_clients
) {
2445 /* admin doesn't want to support half-closed client sockets */
2446 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2447 notifyAllContexts(0); // no specific error implies abort
2456 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2458 assert(byteCount
> 0 && byteCount
<= conn
->in
.buf
.length());
2459 conn
->in
.buf
.consume(byteCount
);
2460 debugs(33, 5, "conn->in.buf has " << conn
->in
.buf
.length() << " bytes unused.");
2463 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2465 ConnStateData::checkHeaderLimits()
2467 if (in
.buf
.length() < Config
.maxRequestHeaderSize
)
2468 return; // can accumulte more header data
2470 debugs(33, 3, "Request header is too large (" << in
.buf
.length() << " > " <<
2471 Config
.maxRequestHeaderSize
<< " bytes)");
2473 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2474 clientStreamNode
*node
= context
->getClientReplyContext();
2475 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2476 assert (repContext
);
2477 repContext
->setReplyToError(ERR_TOO_BIG
,
2478 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2479 clientConnection
->remote
, NULL
, NULL
, NULL
);
2480 context
->registerWithConn();
2481 context
->pullData();
2485 ConnStateData::clientAfterReadingRequests()
2487 // Were we expecting to read more request body from half-closed connection?
2488 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2489 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2490 clientConnection
->close();
2499 ConnStateData::quitAfterError(HttpRequest
*request
)
2501 // From HTTP p.o.v., we do not have to close after every error detected
2502 // at the client-side, but many such errors do require closure and the
2503 // client-side code is bad at handling errors so we play it safe.
2505 request
->flags
.proxyKeepalive
= false;
2506 flags
.readMore
= false;
2507 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2511 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2513 ClientHttpRequest
*http
= context
->http
;
2518 assert(sslServerBump
->entry
);
2519 // Did we create an error entry while processing CONNECT?
2520 if (!sslServerBump
->entry
->isEmpty()) {
2521 quitAfterError(http
->request
);
2523 // Get the saved error entry and send it to the client by replacing the
2524 // ClientHttpRequest store entry with it.
2525 clientStreamNode
*node
= context
->getClientReplyContext();
2526 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2528 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2529 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2531 // save the original request for logging purposes
2532 if (!context
->http
->al
->request
) {
2533 context
->http
->al
->request
= http
->request
;
2534 HTTPMSGLOCK(context
->http
->al
->request
);
2537 // Get error details from the fake certificate-peeking request.
2538 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2539 context
->pullData();
2543 // In bump-server-first mode, we have not necessarily seen the intended
2544 // server name at certificate-peeking time. Check for domain mismatch now,
2545 // when we can extract the intended name from the bumped HTTP request.
2546 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2547 HttpRequest
*request
= http
->request
;
2548 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2549 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2550 "does not match domainname " << request
->GetHost());
2552 bool allowDomainMismatch
= false;
2553 if (Config
.ssl_client
.cert_error
) {
2554 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2555 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2556 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2557 delete check
.sslErrors
;
2558 check
.sslErrors
= NULL
;
2561 if (!allowDomainMismatch
) {
2562 quitAfterError(request
);
2564 clientStreamNode
*node
= context
->getClientReplyContext();
2565 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2566 assert (repContext
);
2568 // Fill the server IP and hostname for error page generation.
2569 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2570 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2572 // Create an error object and fill it
2573 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2574 err
->src_addr
= clientConnection
->remote
;
2575 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2576 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2578 err
->detail
= errDetail
;
2579 // Save the original request for logging purposes.
2580 if (!context
->http
->al
->request
) {
2581 context
->http
->al
->request
= request
;
2582 HTTPMSGLOCK(context
->http
->al
->request
);
2584 repContext
->setReplyToError(request
->method
, err
);
2585 assert(context
->http
->out
.offset
== 0);
2586 context
->pullData();
2597 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2599 ClientHttpRequest
*http
= context
->http
;
2600 HttpRequest::Pointer request
;
2601 bool notedUseOfBuffer
= false;
2602 bool chunked
= false;
2603 bool mustReplyToOptions
= false;
2604 bool unsupportedTe
= false;
2605 bool expectBody
= false;
2607 /* We have an initial client stream in place should it be needed */
2608 /* setup our private context */
2609 context
->registerWithConn();
2611 if (context
->flags
.parsed_ok
== 0) {
2612 clientStreamNode
*node
= context
->getClientReplyContext();
2613 debugs(33, 2, "clientProcessRequest: Invalid Request");
2614 conn
->quitAfterError(NULL
);
2615 // setLogUri should called before repContext->setReplyToError
2616 setLogUri(http
, http
->uri
, true);
2617 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2618 assert (repContext
);
2619 switch (hp
->request_parse_status
) {
2620 case Http::scHeaderTooLarge
:
2621 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
.c_str(), NULL
);
2623 case Http::scMethodNotAllowed
:
2624 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2625 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
.c_str(), NULL
);
2628 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2629 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
.c_str(), NULL
);
2631 assert(context
->http
->out
.offset
== 0);
2632 context
->pullData();
2636 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2637 clientStreamNode
*node
= context
->getClientReplyContext();
2638 debugs(33, 5, "Invalid URL: " << http
->uri
);
2639 conn
->quitAfterError(request
.getRaw());
2640 // setLogUri should called before repContext->setReplyToError
2641 setLogUri(http
, http
->uri
, true);
2642 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2643 assert (repContext
);
2644 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2645 assert(context
->http
->out
.offset
== 0);
2646 context
->pullData();
2650 /* RFC 2616 section 10.5.6 : handle unsupported HTTP major versions cleanly. */
2651 /* We currently only support 0.9, 1.0, 1.1 properly */
2652 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2653 (http_ver
.major
> 1) ) {
2655 clientStreamNode
*node
= context
->getClientReplyContext();
2656 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2657 conn
->quitAfterError(request
.getRaw());
2658 // setLogUri should called before repContext->setReplyToError
2659 setLogUri(http
, http
->uri
, true);
2660 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2661 assert (repContext
);
2662 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2663 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2664 assert(context
->http
->out
.offset
== 0);
2665 context
->pullData();
2669 /* compile headers */
2670 /* we should skip request line! */
2671 /* XXX should actually know the damned buffer size here */
2672 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2673 clientStreamNode
*node
= context
->getClientReplyContext();
2674 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2675 conn
->quitAfterError(request
.getRaw());
2676 // setLogUri should called before repContext->setReplyToError
2677 setLogUri(http
, http
->uri
, true);
2678 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2679 assert (repContext
);
2680 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2681 assert(context
->http
->out
.offset
== 0);
2682 context
->pullData();
2686 request
->clientConnectionManager
= conn
;
2688 request
->flags
.accelerated
= http
->flags
.accel
;
2689 request
->flags
.sslBumped
=conn
->switchedToHttps();
2690 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2691 // TODO: decouple http->flags.accel from request->flags.sslBumped
2692 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2693 !conn
->port
->allow_direct
: 0;
2695 if (request
->flags
.sslBumped
) {
2696 if (conn
->getAuth() != NULL
)
2697 request
->auth_user_request
= conn
->getAuth();
2702 * If transparent or interception mode is working clone the transparent and interception flags
2703 * from the port settings to the request.
2705 if (http
->clientConnection
!= NULL
) {
2706 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2707 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2708 if (request
->flags
.interceptTproxy
) {
2709 if (Config
.accessList
.spoof_client_ip
) {
2710 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2711 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2714 request
->flags
.spoofClientIp
= true;
2716 request
->flags
.spoofClientIp
= false;
2719 if (internalCheck(request
->urlpath
.termedBuf())) {
2720 if (internalHostnameIs(request
->GetHost()) &&
2721 request
->port
== getMyPort()) {
2722 http
->flags
.internal
= true;
2723 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2724 request
->SetHost(internalHostname());
2725 request
->port
= getMyPort();
2726 http
->flags
.internal
= true;
2730 if (http
->flags
.internal
) {
2731 request
->protocol
= AnyP::PROTO_HTTP
;
2732 request
->login
[0] = '\0';
2735 request
->flags
.internal
= http
->flags
.internal
;
2736 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2737 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2738 #if FOLLOW_X_FORWARDED_FOR
2739 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2740 // not a details about teh TCP connection itself
2741 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2742 #endif /* FOLLOW_X_FORWARDED_FOR */
2743 request
->my_addr
= conn
->clientConnection
->local
;
2744 request
->myportname
= conn
->port
->name
;
2745 request
->http_ver
= http_ver
;
2747 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2748 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2749 request
->clientConnectionManager
= conn
;
2751 if (request
->header
.chunked()) {
2753 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2754 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2755 // HTTP/1.1 requires chunking to be the last encoding if there is one
2756 unsupportedTe
= te
.size() && te
!= "identity";
2757 } // else implied identity coding
2759 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2760 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2761 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2762 clientStreamNode
*node
= context
->getClientReplyContext();
2763 conn
->quitAfterError(request
.getRaw());
2764 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2765 assert (repContext
);
2766 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2767 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2768 assert(context
->http
->out
.offset
== 0);
2769 context
->pullData();
2773 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2774 clientStreamNode
*node
= context
->getClientReplyContext();
2775 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2776 assert (repContext
);
2777 conn
->quitAfterError(request
.getRaw());
2778 repContext
->setReplyToError(ERR_INVALID_REQ
,
2779 Http::scLengthRequired
, request
->method
, NULL
,
2780 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2781 assert(context
->http
->out
.offset
== 0);
2782 context
->pullData();
2786 if (request
->header
.has(HDR_EXPECT
)) {
2787 const String expect
= request
->header
.getList(HDR_EXPECT
);
2788 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2789 if (!supportedExpect
) {
2790 clientStreamNode
*node
= context
->getClientReplyContext();
2791 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2792 assert (repContext
);
2793 conn
->quitAfterError(request
.getRaw());
2794 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2795 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2796 assert(context
->http
->out
.offset
== 0);
2797 context
->pullData();
2802 http
->request
= request
.getRaw();
2803 HTTPMSGLOCK(http
->request
);
2804 clientSetKeepaliveFlag(http
);
2806 // Let tunneling code be fully responsible for CONNECT requests
2807 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2808 context
->mayUseConnection(true);
2809 conn
->flags
.readMore
= false;
2813 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2817 /* Do we expect a request-body? */
2818 expectBody
= chunked
|| request
->content_length
> 0;
2819 if (!context
->mayUseConnection() && expectBody
) {
2820 request
->body_pipe
= conn
->expectRequestBody(
2821 chunked
? -1 : request
->content_length
);
2823 // consume header early so that body pipe gets just the body
2824 connNoteUseOfBuffer(conn
, http
->req_sz
);
2825 notedUseOfBuffer
= true;
2827 /* Is it too large? */
2828 if (!chunked
&& // if chunked, we will check as we accumulate
2829 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2830 clientStreamNode
*node
= context
->getClientReplyContext();
2831 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2832 assert (repContext
);
2833 conn
->quitAfterError(request
.getRaw());
2834 repContext
->setReplyToError(ERR_TOO_BIG
,
2835 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2836 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2837 assert(context
->http
->out
.offset
== 0);
2838 context
->pullData();
2842 // We may stop producing, comm_close, and/or call setReplyToError()
2843 // below, so quit on errors to avoid http->doCallouts()
2844 if (!conn
->handleRequestBodyData())
2847 if (!request
->body_pipe
->productionEnded()) {
2848 debugs(33, 5, HERE
<< "need more request body");
2849 context
->mayUseConnection(true);
2850 assert(conn
->flags
.readMore
);
2854 http
->calloutContext
= new ClientRequestContext(http
);
2859 if (!notedUseOfBuffer
)
2860 connNoteUseOfBuffer(conn
, http
->req_sz
);
2864 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2865 * to here because calling comm_reset_close() causes http to
2866 * be freed and the above connNoteUseOfBuffer() would hit an
2867 * assertion, not to mention that we were accessing freed memory.
2869 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2870 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2871 conn
->flags
.readMore
= false;
2872 comm_reset_close(conn
->clientConnection
);
2877 connStripBufferWhitespace (ConnStateData
* conn
)
2879 // XXX: kill this whole function.
2880 while (!conn
->in
.buf
.isEmpty() && xisspace(conn
->in
.buf
.at(0))) {
2881 conn
->in
.buf
.consume(1);
2886 * Limit the number of concurrent requests.
2887 * \return true when there are available position(s) in the pipeline queue for another request.
2888 * \return false when the pipeline queue is full or disabled.
2891 ConnStateData::concurrentRequestQueueFilled() const
2893 const int existingRequestCount
= getConcurrentRequestCount();
2895 // default to the configured pipeline size.
2896 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2897 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2899 // when queue filled already we cant add more.
2900 if (existingRequestCount
>= concurrentRequestLimit
) {
2901 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2902 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2910 * Attempt to parse one or more requests from the input buffer.
2911 * If a request is successfully parsed, even if the next request
2912 * is only partially parsed, it will return TRUE.
2915 ConnStateData::clientParseRequests()
2917 HttpRequestMethod method
;
2918 bool parsed_req
= false;
2920 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2922 // Loop while we have read bytes that are not needed for producing the body
2923 // On errors, bodyPipe may become nil, but readMore will be cleared
2924 while (!in
.buf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2925 connStripBufferWhitespace(this);
2927 /* Don't try to parse if the buffer is empty */
2928 if (in
.buf
.isEmpty())
2931 /* Limit the number of concurrent requests */
2932 if (concurrentRequestQueueFilled())
2935 /* Begin the parsing */
2936 PROF_start(parseHttpRequest
);
2937 HttpParserInit(&parser_
, in
.buf
.c_str(), in
.buf
.length());
2939 /* Process request */
2940 Http::ProtocolVersion http_ver
;
2941 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2942 PROF_stop(parseHttpRequest
);
2944 /* partial or incomplete request */
2946 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2947 // (which becomes context) but checkHeaderLimits cannot?
2948 checkHeaderLimits();
2952 /* status -1 or 1 */
2954 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2955 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2956 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2957 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2959 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2961 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2963 if (context
->mayUseConnection()) {
2964 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2970 /* XXX where to 'finish' the parsing pass? */
2975 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
2977 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
2981 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2983 if (io
.flag
== COMM_ERR_CLOSING
) {
2984 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
2988 assert(Comm::IsConnOpen(clientConnection
));
2989 assert(io
.conn
->fd
== clientConnection
->fd
);
2992 * Don't reset the timeout value here. The timeout value will be
2993 * set to Config.Timeout.request by httpAccept() and
2994 * clientWriteComplete(), and should apply to the request as a
2995 * whole, not individual read() calls. Plus, it breaks our
2996 * lame half-close detection
2998 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
2999 notifyAllContexts(io
.xerrno
);
3004 if (io
.flag
== COMM_OK
) {
3006 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3008 // may comm_close or setReplyToError
3009 if (!handleReadData(io
.buf2
))
3012 } else if (io
.size
== 0) {
3013 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3015 if (connFinishedWithConn(io
.size
)) {
3016 clientConnection
->close();
3020 /* It might be half-closed, we can't tell */
3021 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3023 commMarkHalfClosed(io
.conn
->fd
);
3025 fd_note(io
.conn
->fd
, "half-closed");
3027 /* There is one more close check at the end, to detect aborted
3028 * (partial) requests. At this point we can't tell if the request
3031 /* Continue to process previously read data */
3035 /* Process next request */
3036 if (getConcurrentRequestCount() == 0)
3037 fd_note(io
.fd
, "Reading next request");
3039 if (!clientParseRequests()) {
3043 * If the client here is half closed and we failed
3044 * to parse a request, close the connection.
3045 * The above check with connFinishedWithConn() only
3046 * succeeds _if_ the buffer is empty which it won't
3047 * be if we have an incomplete request.
3048 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3050 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3051 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3052 clientConnection
->close();
3060 clientAfterReadingRequests();
3064 * called when new request data has been read from the socket
3066 * \retval false called comm_close or setReplyToError (the caller should bail)
3067 * \retval true we did not call comm_close or setReplyToError
3070 ConnStateData::handleReadData(SBuf
*buf
)
3072 assert(buf
== &in
.buf
); // XXX: make this abort the transaction if this fails
3074 // if we are reading a body, stuff data into the body pipe
3075 if (bodyPipe
!= NULL
)
3076 return handleRequestBodyData();
3081 * called when new request body data has been buffered in in.buf
3082 * may close the connection if we were closing and piped everything out
3084 * \retval false called comm_close or setReplyToError (the caller should bail)
3085 * \retval true we did not call comm_close or setReplyToError
3088 ConnStateData::handleRequestBodyData()
3090 assert(bodyPipe
!= NULL
);
3094 if (in
.bodyParser
) { // chunked encoding
3095 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3096 abortChunkedRequestBody(error
);
3099 } else { // identity encoding
3100 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3101 putSize
= bodyPipe
->putMoreData(in
.buf
.c_str(), in
.buf
.length());
3102 if (!bodyPipe
->mayNeedMoreData()) {
3103 // BodyPipe will clear us automagically when we produced everything
3109 connNoteUseOfBuffer(this, putSize
);
3112 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3114 if (const char *reason
= stoppedSending()) {
3115 /* we've finished reading like good clients,
3116 * now do the close that initiateClose initiated.
3118 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3119 clientConnection
->close();
3127 /// parses available chunked encoded body bytes, checks size, returns errors
3129 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3131 debugs(33, 7, "chunked from " << clientConnection
<< ": " << in
.buf
.length());
3133 try { // the parser will throw on errors
3135 if (in
.buf
.isEmpty()) // nothing to do
3138 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3139 // add one because MemBuf will assert if it cannot 0-terminate
3140 raw
.init(in
.buf
.length(), in
.buf
.length()+1);
3141 raw
.append(in
.buf
.c_str(), in
.buf
.length());
3143 const mb_size_t wasContentSize
= raw
.contentSize();
3144 BodyPipeCheckout
bpc(*bodyPipe
);
3145 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3147 putSize
= wasContentSize
- raw
.contentSize();
3149 // dechunk then check: the size limit applies to _dechunked_ content
3150 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3154 finishDechunkingRequest(true);
3156 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3159 // if chunk parser needs data, then the body pipe must need it too
3160 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3162 // if parser needs more space and we can consume nothing, we will stall
3163 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3164 } catch (...) { // TODO: be more specific
3165 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3166 return ERR_INVALID_REQ
;
3169 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3173 /// quit on errors related to chunked request body handling
3175 ConnStateData::abortChunkedRequestBody(const err_type error
)
3177 finishDechunkingRequest(false);
3179 // XXX: The code below works if we fail during initial request parsing,
3180 // but if we fail when the server-side works already, the server may send
3181 // us its response too, causing various assertions. How to prevent that?
3182 #if WE_KNOW_HOW_TO_SEND_ERRORS
3183 ClientSocketContext::Pointer context
= getCurrentContext();
3184 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3185 clientStreamNode
*node
= context
->getClientReplyContext();
3186 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3188 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3189 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3190 repContext
->setReplyToError(error
, scode
,
3191 repContext
->http
->request
->method
,
3192 repContext
->http
->uri
,
3194 repContext
->http
->request
,
3196 context
->pullData();
3198 // close or otherwise we may get stuck as nobody will notice the error?
3199 comm_reset_close(clientConnection
);
3202 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3203 comm_reset_close(clientConnection
);
3205 flags
.readMore
= false;
3209 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3211 if (!handleRequestBodyData())
3214 // too late to read more body
3215 if (!isOpen() || stoppedReceiving())
3222 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3224 // request reader may get stuck waiting for space if nobody consumes body
3225 if (bodyPipe
!= NULL
)
3226 bodyPipe
->enableAutoConsumption();
3228 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3231 /** general lifetime handler for HTTP requests */
3233 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3236 * Just close the connection to not confuse browsers
3237 * using persistent connections. Some browsers open
3238 * a connection and then do not use it until much
3239 * later (presumeably because the request triggering
3240 * the open has already been completed on another
3243 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3248 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3250 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3251 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3252 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3253 http
->al
->http
.timedout
= true;
3254 if (Comm::IsConnOpen(io
.conn
))
3258 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3259 AsyncJob("ConnStateData"),
3261 sslBumpMode(Ssl::bumpEnd
),
3262 switchedToHttps_(false),
3263 sslServerBump(NULL
),
3265 stoppedSending_(NULL
),
3266 stoppedReceiving_(NULL
)
3268 pinning
.host
= NULL
;
3270 pinning
.pinned
= false;
3271 pinning
.auth
= false;
3272 pinning
.zeroReply
= false;
3273 pinning
.peer
= NULL
;
3275 // store the details required for creating more MasterXaction objects as new requests come in
3276 clientConnection
= xact
->tcpClient
;
3277 port
= cbdataReference(xact
->squidPort
.get());
3278 log_addr
= xact
->tcpClient
->remote
;
3279 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3281 in
.buf
.reserveCapacity(CLIENT_REQ_BUF_SZ
);
3283 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3284 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3285 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3286 int i
= IP_PMTUDISC_DONT
;
3287 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3288 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3290 static bool reported
= false;
3293 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3299 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3300 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3301 comm_add_close_handler(clientConnection
->fd
, call
);
3303 if (Config
.onoff
.log_fqdn
)
3304 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3307 if (Ident::TheConfig
.identLookup
) {
3308 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3309 identChecklist
.src_addr
= xact
->tcpClient
->remote
;
3310 identChecklist
.my_addr
= xact
->tcpClient
->local
;
3311 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3312 Ident::Start(xact
->tcpClient
, clientIdentDone
, this);
3316 clientdbEstablished(clientConnection
->remote
, 1);
3318 flags
.readMore
= true;
3321 /** Handle a new connection on HTTP socket. */
3323 httpAccept(const CommAcceptCbParams
¶ms
)
3325 MasterXaction::Pointer xact
= params
.xaction
;
3326 AnyP::PortCfgPointer s
= xact
->squidPort
;
3329 // it is possible the call or accept() was still queued when the port was reconfigured
3330 debugs(33, 2, "HTTP accept failure: port reconfigured.");
3334 if (params
.flag
!= COMM_OK
) {
3335 // Its possible the call was still queued when the client disconnected
3336 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3340 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3341 fd_note(params
.conn
->fd
, "client http connect");
3343 if (s
->tcp_keepalive
.enabled
) {
3344 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3347 ++ incoming_sockets_accepted
;
3349 // Socket is ready, setup the connection manager to start using it
3350 ConnStateData
*connState
= new ConnStateData(xact
);
3352 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3353 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3354 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3355 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3357 connState
->readSomeData();
3360 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3362 if (Config
.onoff
.client_db
) {
3363 /* it was said several times that client write limiter does not work if client_db is disabled */
3365 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3366 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3368 // TODO: we check early to limit error response bandwith but we
3369 // should recheck when we can honor delay_pool_uses_indirect
3370 // TODO: we should also pass the port details for myportname here.
3371 ch
.src_addr
= params
.conn
->remote
;
3372 ch
.my_addr
= params
.conn
->local
;
3374 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3376 /* pools require explicit 'allow' to assign a client into them */
3377 if (pools
[pool
].access
) {
3378 ch
.accessList
= pools
[pool
].access
;
3379 allow_t answer
= ch
.fastCheck();
3380 if (answer
== ACCESS_ALLOWED
) {
3382 /* request client information from db after we did all checks
3383 this will save hash lookup if client failed checks */
3384 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3387 /* put client info in FDE */
3388 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3390 /* setup write limiter for this request */
3391 const double burst
= floor(0.5 +
3392 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3393 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3396 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3406 /** Create SSL connection structure and update fd_table */
3408 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3410 SSL
*ssl
= SSL_new(sslContext
);
3413 const int ssl_error
= ERR_get_error();
3414 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3419 SSL_set_fd(ssl
, conn
->fd
);
3420 fd_table
[conn
->fd
].ssl
= ssl
;
3421 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3422 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3424 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3425 fd_note(conn
->fd
, "client https start");
3430 /** negotiate an SSL connection */
3432 clientNegotiateSSL(int fd
, void *data
)
3434 ConnStateData
*conn
= (ConnStateData
*)data
;
3436 SSL
*ssl
= fd_table
[fd
].ssl
;
3439 if ((ret
= SSL_accept(ssl
)) <= 0) {
3440 int ssl_error
= SSL_get_error(ssl
, ret
);
3442 switch (ssl_error
) {
3444 case SSL_ERROR_WANT_READ
:
3445 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3448 case SSL_ERROR_WANT_WRITE
:
3449 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3452 case SSL_ERROR_SYSCALL
:
3455 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3461 if (errno
== ECONNRESET
)
3464 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3465 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3472 case SSL_ERROR_ZERO_RETURN
:
3473 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3478 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3479 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3480 " (" << ssl_error
<< "/" << ret
<< ")");
3488 if (SSL_session_reused(ssl
)) {
3489 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3490 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3492 if (do_debug(83, 4)) {
3493 /* Write out the SSL session details.. actually the call below, but
3494 * OpenSSL headers do strange typecasts confusing GCC.. */
3495 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3496 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3497 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
);
3499 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3501 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3502 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3503 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3504 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3505 * Because there are two possible usable cast, if you get an error here, try the other
3506 * commented line. */
3508 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3509 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3513 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3516 /* Note: This does not automatically fflush the log file.. */
3519 debugs(83, 2, "clientNegotiateSSL: New session " <<
3520 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3521 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3525 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3526 SSL_get_cipher(ssl
));
3528 client_cert
= SSL_get_peer_certificate(ssl
);
3530 if (client_cert
!= NULL
) {
3531 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3532 " client certificate: subject: " <<
3533 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3535 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3536 " client certificate: issuer: " <<
3537 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3539 X509_free(client_cert
);
3541 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3542 " has no certificate.");
3545 conn
->readSomeData();
3549 * If SSL_CTX is given, starts reading the SSL handshake.
3550 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3553 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3557 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3559 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3562 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3563 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3564 connState
, ConnStateData::requestTimeout
);
3565 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3568 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3570 char buf
[MAX_IPSTRLEN
];
3571 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3572 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3573 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3574 fakeRequest
->port
= details
->local
.port();
3575 fakeRequest
->clientConnectionManager
= connState
;
3576 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3577 #if FOLLOW_X_FORWARDED_FOR
3578 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3580 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3581 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3582 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3583 fakeRequest
->myportname
= connState
->port
->name
;
3584 if (fakeRequest
->flags
.interceptTproxy
) {
3585 if (Config
.accessList
.spoof_client_ip
) {
3586 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3587 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3589 fakeRequest
->flags
.spoofClientIp
= true;
3591 fakeRequest
->flags
.spoofClientIp
= false;
3592 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3593 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3598 * A callback function to use with the ACLFilledChecklist callback.
3599 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3600 * else reverts the connection to tunnel mode.
3603 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3605 ConnStateData
*connState
= (ConnStateData
*) data
;
3607 // if the connection is closed or closing, just return.
3608 if (!connState
->isOpen())
3611 // Require both a match and a positive bump mode to work around exceptional
3612 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3613 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3614 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3615 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3616 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3618 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3619 connState
->sslBumpMode
= Ssl::bumpNone
;
3621 // fake a CONNECT request to force connState to tunnel
3622 static char ip
[MAX_IPSTRLEN
];
3623 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3625 reqStr
.append("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n");
3626 bool ret
= connState
->handleReadData(&reqStr
);
3628 ret
= connState
->clientParseRequests();
3630 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3631 connState
->clientConnection
->close();
3636 /** handle a new HTTPS connection */
3638 httpsAccept(const CommAcceptCbParams
¶ms
)
3640 MasterXaction::Pointer xact
= params
.xaction
;
3641 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3644 // it is possible the call or accept() was still queued when the port was reconfigured
3645 debugs(33, 2, "HTTPS accept failure: port reconfigured.");
3649 if (params
.flag
!= COMM_OK
) {
3650 // Its possible the call was still queued when the client disconnected
3651 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3655 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3656 fd_note(params
.conn
->fd
, "client https connect");
3658 if (s
->tcp_keepalive
.enabled
) {
3659 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3662 ++incoming_sockets_accepted
;
3664 // Socket is ready, setup the connection manager to start using it
3665 ConnStateData
*connState
= new ConnStateData(xact
);
3667 if (s
->flags
.tunnelSslBumping
) {
3668 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3670 if (!Config
.accessList
.ssl_bump
) {
3671 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3675 // Create a fake HTTP request for ssl_bump ACL check,
3676 // using tproxy/intercept provided destination IP and port.
3677 HttpRequest
*request
= new HttpRequest();
3678 static char ip
[MAX_IPSTRLEN
];
3679 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3680 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3681 request
->port
= params
.conn
->local
.port();
3682 request
->myportname
= s
->name
;
3684 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3685 acl_checklist
->src_addr
= params
.conn
->remote
;
3686 acl_checklist
->my_addr
= s
->s
;
3687 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3690 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3691 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3696 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3698 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3699 state_data
->sslCrtdHandleReply(reply
);
3703 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3705 if (reply
.result
== HelperReply::BrokenHelper
) {
3706 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3707 } else if (!reply
.other().hasContent()) {
3708 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3710 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3711 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3712 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3714 if (reply
.result
!= HelperReply::Okay
) {
3715 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3717 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3718 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3719 getSslContextDone(ctx
, true);
3724 getSslContextDone(NULL
);
3727 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3729 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3731 // fake certificate adaptation requires bump-server-first mode
3732 if (!sslServerBump
) {
3733 assert(port
->signingCert
.get());
3734 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3735 if (port
->signPkey
.get())
3736 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3737 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3741 // In case of an error while connecting to the secure server, use a fake
3742 // trusted certificate, with no mimicked fields and no adaptation
3743 // algorithms. There is nothing we can mimic so we want to minimize the
3744 // number of warnings the user will have to see to get to the error page.
3745 assert(sslServerBump
->entry
);
3746 if (sslServerBump
->entry
->isEmpty()) {
3747 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3748 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3750 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3751 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3752 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3754 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3755 // If the algorithm already set, then ignore it.
3756 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3757 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3758 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3761 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3762 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3763 const char *param
= ca
->param
;
3765 // For parameterless CN adaptation, use hostname from the
3767 if (ca
->alg
== Ssl::algSetCommonName
) {
3769 param
= sslConnectHostOrIp
.termedBuf();
3770 certProperties
.commonName
= param
;
3771 certProperties
.setCommonName
= true;
3772 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3773 certProperties
.setValidAfter
= true;
3774 else if (ca
->alg
== Ssl::algSetValidBefore
)
3775 certProperties
.setValidBefore
= true;
3777 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3778 alg
<< " param: " << (param
? param
: "-"));
3782 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3783 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3784 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3785 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3789 } else {// if (!sslServerBump->entry->isEmpty())
3790 // Use trusted certificate for a Squid-generated error
3791 // or the user would have to add a security exception
3792 // just to see the error page. We will close the connection
3793 // so that the trust is not extended to non-Squid content.
3794 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3797 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3799 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3800 assert(port
->untrustedSigningCert
.get());
3801 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3802 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3804 assert(port
->signingCert
.get());
3805 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3807 if (port
->signPkey
.get())
3808 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3810 signAlgorithm
= certProperties
.signAlgorithm
;
3814 ConnStateData::getSslContextStart()
3816 assert(areAllContextsForThisConnection());
3818 /* careful: freeAllContexts() above frees request, host, etc. */
3820 if (port
->generateHostCertificates
) {
3821 Ssl::CertificateProperties certProperties
;
3822 buildSslCertGenerationParams(certProperties
);
3823 sslBumpCertKey
= certProperties
.dbKey().c_str();
3824 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3826 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3827 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3828 SSL_CTX
* dynCtx
= NULL
;
3829 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3830 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3831 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3832 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3833 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3834 getSslContextDone(dynCtx
);
3837 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3839 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3842 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3847 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3848 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3849 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3850 request_message
.composeRequest(certProperties
);
3851 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3852 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3854 } catch (const std::exception
&e
) {
3855 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3856 "request for " << certProperties
.commonName
<<
3857 " certificate: " << e
.what() << "; will now block to " <<
3858 "generate that certificate.");
3859 // fall through to do blocking in-process generation.
3861 #endif // USE_SSL_CRTD
3863 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3864 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3865 getSslContextDone(dynCtx
, true);
3868 getSslContextDone(NULL
);
3872 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3874 // Try to add generated ssl context to storage.
3875 if (port
->generateHostCertificates
&& isNew
) {
3877 if (signAlgorithm
== Ssl::algSignTrusted
) {
3878 // Add signing certificate to the certificates chain
3879 X509
*cert
= port
->signingCert
.get();
3880 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3881 // increase the certificate lock
3882 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3884 const int ssl_error
= ERR_get_error();
3885 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3887 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3889 //else it is self-signed or untrusted do not attrach any certificate
3891 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3892 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3894 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3895 // If it is not in storage delete after using. Else storage deleted it.
3896 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3899 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3903 // If generated ssl context = NULL, try to use static ssl context.
3905 if (!port
->staticSslContext
) {
3906 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3907 clientConnection
->close();
3910 debugs(33, 5, HERE
<< "Using static ssl context.");
3911 sslContext
= port
->staticSslContext
.get();
3915 if (!httpsCreate(clientConnection
, sslContext
))
3918 // commSetConnTimeout() was called for this request before we switched.
3920 // Disable the client read handler until CachePeer selection is complete
3921 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3922 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3923 switchedToHttps_
= true;
3927 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3929 assert(!switchedToHttps_
);
3931 sslConnectHostOrIp
= request
->GetHost();
3932 sslCommonName
= request
->GetHost();
3934 // We are going to read new request
3935 flags
.readMore
= true;
3936 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3938 // If sslServerBump is set, then we have decided to deny CONNECT
3939 // and now want to switch to SSL to send the error to the client
3940 // without even peeking at the origin server certificate.
3941 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3942 request
->flags
.sslPeek
= true;
3943 sslServerBump
= new Ssl::ServerBump(request
);
3945 // will call httpsPeeked() with certificate and connection, eventually
3946 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3950 // otherwise, use sslConnectHostOrIp
3951 getSslContextStart();
3955 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3957 Must(sslServerBump
!= NULL
);
3959 if (Comm::IsConnOpen(serverConnection
)) {
3960 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3962 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3963 assert(serverCert
.get() != NULL
);
3964 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
3965 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
3966 " bumped: " << *serverConnection
);
3968 pinConnection(serverConnection
, NULL
, NULL
, false);
3970 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3972 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3973 Ip::Address intendedDest
;
3974 intendedDest
= sslConnectHostOrIp
.termedBuf();
3975 const bool isConnectRequest
= !port
->flags
.isIntercepted();
3977 // Squid serves its own error page and closes, so we want
3978 // a CN that causes no additional browser errors. Possible
3979 // only when bumping CONNECT with a user-typed address.
3980 if (intendedDest
.isAnyAddr() || isConnectRequest
)
3981 sslCommonName
= sslConnectHostOrIp
;
3982 else if (sslServerBump
->serverCert
.get())
3983 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
3985 // copy error detail from bump-server-first request to CONNECT request
3986 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
3987 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3990 getSslContextStart();
3993 #endif /* USE_SSL */
3995 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3997 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3999 if (!Comm::IsConnOpen(c
)) {
4000 Must(NHttpSockets
> 0); // we tried to open some
4001 --NHttpSockets
; // there will be fewer sockets than planned
4002 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4004 if (!NHttpSockets
) // we could not open any listen sockets at all
4005 fatalf("Unable to open %s",FdNote(portType
));
4012 /// find any unused HttpSockets[] slot and store fd there or return false
4014 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4017 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4018 if ((found
= HttpSockets
[i
] < 0))
4019 HttpSockets
[i
] = conn
->fd
;
4025 clientHttpConnectionsOpen(void)
4027 AnyP::PortCfg
*s
= NULL
;
4029 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4030 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4031 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4032 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4037 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4038 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4039 s
->flags
.tunnelSslBumping
= false;
4042 if (s
->flags
.tunnelSslBumping
&&
4043 !s
->staticSslContext
&&
4044 !s
->generateHostCertificates
) {
4045 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4046 s
->flags
.tunnelSslBumping
= false;
4048 if (s
->flags
.tunnelSslBumping
) {
4049 // Create ssl_ctx cache for this port.
4050 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4054 // Fill out a Comm::Connection which IPC will open as a listener for us
4055 // then pass back when active so we can start a TcpAcceptor subscription.
4056 s
->listenConn
= new Comm::Connection
;
4057 s
->listenConn
->local
= s
->s
;
4058 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4060 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4061 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4062 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4063 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4065 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4066 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4067 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4069 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4076 clientHttpsConnectionsOpen(void)
4080 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4081 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4082 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4083 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4087 if (!s
->staticSslContext
) {
4088 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4089 " due to SSL initialization failure.");
4093 // TODO: merge with similar code in clientHttpConnectionsOpen()
4094 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4095 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4096 s
->flags
.tunnelSslBumping
= false;
4099 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4100 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4101 s
->flags
.tunnelSslBumping
= false;
4104 if (s
->flags
.tunnelSslBumping
) {
4105 // Create ssl_ctx cache for this port.
4106 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4109 // Fill out a Comm::Connection which IPC will open as a listener for us
4110 s
->listenConn
= new Comm::Connection
;
4111 s
->listenConn
->local
= s
->s
;
4112 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4113 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4115 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4116 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4117 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4118 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4120 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4121 ListeningStartedDialer(&clientListenerConnectionOpened
,
4122 s
, Ipc::fdnHttpsSocket
, sub
));
4123 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4124 HttpSockets
[NHttpSockets
] = -1;
4130 /// process clientHttpConnectionsOpen result
4132 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4134 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4138 Must(Comm::IsConnOpen(s
->listenConn
));
4140 // TCP: setup a job to handle accept() with subscribed handler
4141 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4143 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4144 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4145 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4146 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4147 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4148 << FdNote(portTypeNote
) << " connections at "
4151 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4155 clientOpenListenSockets(void)
4157 clientHttpConnectionsOpen();
4159 clientHttpsConnectionsOpen();
4162 if (NHttpSockets
< 1)
4163 fatal("No HTTP or HTTPS ports configured");
4167 clientHttpConnectionsClose(void)
4169 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4170 if (s
->listenConn
!= NULL
) {
4171 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4172 s
->listenConn
->close();
4173 s
->listenConn
= NULL
;
4178 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4179 if (s
->listenConn
!= NULL
) {
4180 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4181 s
->listenConn
->close();
4182 s
->listenConn
= NULL
;
4187 // TODO see if we can drop HttpSockets array entirely */
4188 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4189 HttpSockets
[i
] = -1;
4196 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4198 const char *vary
= request
->vary_headers
;
4199 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4200 #if X_ACCELERATOR_VARY
4203 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4206 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4208 /* Oops... something odd is going on here.. */
4209 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4210 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4211 safe_free(request
->vary_headers
);
4216 /* This is not a varying object */
4220 /* virtual "vary" object found. Calculate the vary key and
4221 * continue the search
4223 vary
= httpMakeVaryMark(request
, entry
->getReply());
4226 request
->vary_headers
= xstrdup(vary
);
4229 /* Ouch.. we cannot handle this kind of variance */
4230 /* XXX This cannot really happen, but just to be complete */
4235 vary
= httpMakeVaryMark(request
, entry
->getReply());
4238 request
->vary_headers
= xstrdup(vary
);
4242 /* Ouch.. we cannot handle this kind of variance */
4243 /* XXX This cannot really happen, but just to be complete */
4245 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4248 /* Oops.. we have already been here and still haven't
4249 * found the requested variant. Bail out
4251 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4252 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4258 ACLFilledChecklist
*
4259 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4261 ConnStateData
* conn
= http
->getConn();
4262 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4263 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4266 * hack for ident ACL. It needs to get full addresses, and a place to store
4267 * the ident result on persistent connections...
4269 /* connection oriented auth also needs these two lines for it's operation. */
4273 CBDATA_CLASS_INIT(ConnStateData
);
4276 ConnStateData::transparent() const
4278 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4282 ConnStateData::reading() const
4284 return reader
!= NULL
;
4288 ConnStateData::stopReading()
4291 comm_read_cancel(clientConnection
->fd
, reader
);
4297 ConnStateData::expectRequestBody(int64_t size
)
4299 bodyPipe
= new BodyPipe(this);
4301 bodyPipe
->setBodySize(size
);
4303 startDechunkingRequest();
4308 ConnStateData::mayNeedToReadMoreBody() const
4311 return 0; // request without a body or read/produced all body bytes
4313 if (!bodyPipe
->bodySizeKnown())
4314 return -1; // probably need to read more, but we cannot be sure
4316 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4317 const int64_t haveAvailable
= static_cast<int64_t>(in
.buf
.length());
4319 if (needToProduce
<= haveAvailable
)
4320 return 0; // we have read what we need (but are waiting for pipe space)
4322 return needToProduce
- haveAvailable
;
4326 ConnStateData::stopReceiving(const char *error
)
4328 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4329 "; old sending error: " <<
4330 (stoppedSending() ? stoppedSending_
: "none"));
4332 if (const char *oldError
= stoppedReceiving()) {
4333 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4334 return; // nothing has changed as far as this connection is concerned
4337 stoppedReceiving_
= error
;
4339 if (const char *sendError
= stoppedSending()) {
4340 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4341 clientConnection
->close();
4346 ConnStateData::expectNoForwarding()
4348 if (bodyPipe
!= NULL
) {
4349 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4350 bodyPipe
->expectNoConsumption();
4354 /// initialize dechunking state
4356 ConnStateData::startDechunkingRequest()
4358 Must(bodyPipe
!= NULL
);
4359 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4360 assert(!in
.bodyParser
);
4361 in
.bodyParser
= new ChunkedCodingParser
;
4364 /// put parsed content into input buffer and clean up
4366 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4368 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4370 if (bodyPipe
!= NULL
) {
4371 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4372 BodyPipe::Pointer myPipe
= bodyPipe
;
4373 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4374 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4376 Must(myPipe
->bodySizeKnown());
4377 ClientSocketContext::Pointer context
= getCurrentContext();
4378 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4379 context
->http
->request
->setContentLength(myPipe
->bodySize());
4383 delete in
.bodyParser
;
4384 in
.bodyParser
= NULL
;
4387 ConnStateData::In::In() :
4392 ConnStateData::In::~In()
4394 delete bodyParser
; // TODO: pool
4398 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4401 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4405 ClientSocketContext::Pointer context
= getCurrentContext();
4406 if (context
!= NULL
) {
4407 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4411 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4412 clientConnection
->close();
4415 /// Our close handler called by Comm when the pinned connection is closed
4417 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4419 // FwdState might repin a failed connection sooner than this close
4420 // callback is called for the failed connection.
4421 assert(pinning
.serverConnection
== io
.conn
);
4422 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4423 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4425 if (sawZeroReply
&& clientConnection
!= NULL
) {
4426 debugs(33, 3, "Closing client connection on pinned zero reply.");
4427 clientConnection
->close();
4432 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4434 char desc
[FD_DESC_SZ
];
4436 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4437 if (pinning
.serverConnection
->fd
== pinServer
->fd
) {
4438 startPinnedConnectionMonitoring();
4443 unpinConnection(); // closes pinned connection, if any, and resets fields
4445 pinning
.serverConnection
= pinServer
;
4447 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4449 // when pinning an SSL bumped connection, the request may be NULL
4450 const char *pinnedHost
= "[unknown]";
4452 pinning
.host
= xstrdup(request
->GetHost());
4453 pinning
.port
= request
->port
;
4454 pinnedHost
= pinning
.host
;
4456 pinning
.port
= pinServer
->remote
.port();
4458 pinning
.pinned
= true;
4460 pinning
.peer
= cbdataReference(aPeer
);
4461 pinning
.auth
= auth
;
4462 char stmp
[MAX_IPSTRLEN
];
4463 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4464 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4465 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4466 clientConnection
->fd
);
4467 fd_note(pinning
.serverConnection
->fd
, desc
);
4469 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4470 pinning
.closeHandler
= JobCallback(33, 5,
4471 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4472 // remember the pinned connection so that cb does not unpin a fresher one
4473 typedef CommCloseCbParams Params
;
4474 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4475 params
.conn
= pinning
.serverConnection
;
4476 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4478 startPinnedConnectionMonitoring();
4481 /// Assign a read handler to an idle pinned connection so that we can detect connection closures.
4483 ConnStateData::startPinnedConnectionMonitoring()
4485 if (pinning
.readHandler
!= NULL
)
4486 return; // already monitoring
4488 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4489 pinning
.readHandler
= JobCallback(33, 3,
4490 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4491 static char unusedBuf
[8];
4492 comm_read(pinning
.serverConnection
, unusedBuf
, sizeof(unusedBuf
), pinning
.readHandler
);
4496 ConnStateData::stopPinnedConnectionMonitoring()
4498 if (pinning
.readHandler
!= NULL
) {
4499 comm_read_cancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4500 pinning
.readHandler
= NULL
;
4504 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4505 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4507 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4509 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4511 if (io
.flag
== COMM_ERR_CLOSING
)
4512 return; // close handler will clean up
4514 // We could use getConcurrentRequestCount(), but this may be faster.
4515 const bool clientIsIdle
= !getCurrentContext();
4517 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4518 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4520 assert(pinning
.serverConnection
== io
.conn
);
4521 pinning
.serverConnection
->close();
4523 // If we are still sending data to the client, do not close now. When we are done sending,
4524 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4525 // However, if we are idle, then we must close to inform the idle client and minimize races.
4526 if (clientIsIdle
&& clientConnection
!= NULL
)
4527 clientConnection
->close();
4530 const Comm::ConnectionPointer
4531 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4533 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4536 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4538 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4540 else if (request
&& pinning
.port
!= request
->port
)
4542 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4544 else if (aPeer
!= pinning
.peer
)
4548 /* The pinning info is not safe, remove any pinning info */
4552 return pinning
.serverConnection
;
4556 ConnStateData::unpinConnection()
4558 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4561 cbdataReferenceDone(pinning
.peer
);
4563 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4564 if (pinning
.closeHandler
!= NULL
) {
4565 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4566 pinning
.closeHandler
= NULL
;
4568 /// also close the server side socket, we should not use it for any future requests...
4569 // TODO: do not close if called from our close handler?
4570 pinning
.serverConnection
->close();
4573 safe_free(pinning
.host
);
4575 pinning
.zeroReply
= false;
4577 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4578 * connection has gone away */