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 http
->request
->ignoreRange(range_err
);
1348 /* XXX: TODO: Review, this unconditional set may be wrong. */
1349 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1350 // web server responded with a valid, but unexpected range.
1351 // will (try-to) forward as-is.
1352 //TODO: we should cope with multirange request/responses
1353 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1354 request
->range
->contains(rep
->content_range
->spec
) :
1356 const int spec_count
= http
->request
->range
->specs
.size();
1357 int64_t actual_clen
= -1;
1359 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1360 spec_count
<< " virgin clen: " << rep
->content_length
);
1361 assert(spec_count
> 0);
1362 /* append appropriate header(s) */
1364 if (spec_count
== 1) {
1365 if (!replyMatchRequest
) {
1366 hdr
->delById(HDR_CONTENT_RANGE
);
1367 hdr
->putContRange(rep
->content_range
);
1368 actual_clen
= rep
->content_length
;
1369 //http->range_iter.pos = rep->content_range->spec.begin();
1370 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1371 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1374 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1376 /* append Content-Range */
1378 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1379 /* No content range, so this was a full object we are
1382 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1385 /* set new Content-Length to the actual number of bytes
1386 * transmitted in the message-body */
1387 actual_clen
= (*pos
)->length
;
1391 /* generate boundary string */
1392 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1393 /* delete old Content-Type, add ours */
1394 hdr
->delById(HDR_CONTENT_TYPE
);
1395 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1396 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1397 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1398 /* Content-Length is not required in multipart responses
1399 * but it is always nice to have one */
1400 actual_clen
= http
->mRangeCLen();
1401 /* http->out needs to start where we want data at */
1402 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1405 /* replace Content-Length header */
1406 assert(actual_clen
>= 0);
1408 hdr
->delById(HDR_CONTENT_LENGTH
);
1410 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1412 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1414 /* And start the range iter off */
1415 http
->range_iter
.updateSpec();
1420 ClientSocketContext::prepareReply(HttpReply
* rep
)
1424 if (http
->request
->range
)
1425 buildRangeHeader(rep
);
1429 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1433 MemBuf
*mb
= rep
->pack();
1435 // dump now, so we dont output any body.
1436 debugs(11, 2, "HTTP Client " << clientConnection
);
1437 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1439 /* Save length of headers for persistent conn checks */
1440 http
->out
.headers_sz
= mb
->contentSize();
1443 headersLog(0, 0, http
->request
->method
, rep
);
1446 if (bodyData
.data
&& bodyData
.length
) {
1447 if (multipartRangeRequest())
1448 packRange(bodyData
, mb
);
1449 else if (http
->request
->flags
.chunkedReply
) {
1450 packChunk(bodyData
, *mb
);
1452 size_t length
= lengthToSend(bodyData
.range());
1453 noteSentBodyBytes (length
);
1455 mb
->append(bodyData
.data
, length
);
1460 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1461 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1462 CommIoCbPtrFun(clientWriteComplete
, this));
1463 Comm::Write(clientConnection
, mb
, call
);
1468 * Write a chunk of data to a client socket. If the reply is present,
1469 * send the reply headers down the wire too, and clean them up when
1472 * The request is one backed by a connection, not an internal request.
1473 * data context is not NULL
1474 * There are no more entries in the stream chain.
1477 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1478 HttpReply
* rep
, StoreIOBuffer receivedData
)
1480 /* Test preconditions */
1481 assert(node
!= NULL
);
1482 PROF_start(clientSocketRecipient
);
1483 /* TODO: handle this rather than asserting
1484 * - it should only ever happen if we cause an abort and
1485 * the callback chain loops back to here, so we can simply return.
1486 * However, that itself shouldn't happen, so it stays as an assert for now.
1488 assert(cbdataReferenceValid(node
));
1489 assert(node
->node
.next
== NULL
);
1490 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1491 assert(context
!= NULL
);
1492 assert(connIsUsable(http
->getConn()));
1494 /* TODO: check offset is what we asked for */
1496 if (context
!= http
->getConn()->getCurrentContext()) {
1497 context
->deferRecipientForLater(node
, rep
, receivedData
);
1498 PROF_stop(clientSocketRecipient
);
1502 // After sending Transfer-Encoding: chunked (at least), always send
1503 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1504 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1505 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1506 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1507 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1508 PROF_stop(clientSocketRecipient
);
1512 if (!context
->startOfOutput())
1513 context
->sendBody(rep
, receivedData
);
1516 http
->al
->reply
= rep
;
1517 HTTPMSGLOCK(http
->al
->reply
);
1518 context
->sendStartOfMessage(rep
, receivedData
);
1521 PROF_stop(clientSocketRecipient
);
1525 * Called when a downstream node is no longer interested in
1526 * our data. As we are a terminal node, this means on aborts
1530 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1532 /* Test preconditions */
1533 assert(node
!= NULL
);
1534 /* TODO: handle this rather than asserting
1535 * - it should only ever happen if we cause an abort and
1536 * the callback chain loops back to here, so we can simply return.
1537 * However, that itself shouldn't happen, so it stays as an assert for now.
1539 assert(cbdataReferenceValid(node
));
1540 /* Set null by ContextFree */
1541 assert(node
->node
.next
== NULL
);
1542 /* this is the assert discussed above */
1543 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1544 /* We are only called when the client socket shutsdown.
1545 * Tell the prev pipeline member we're finished
1547 clientStreamDetach(node
, http
);
1551 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1553 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1554 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1558 ConnStateData::readNextRequest()
1560 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1562 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1564 * Set the timeout BEFORE calling readSomeData().
1566 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1567 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1568 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1569 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1572 /** Please don't do anything with the FD past here! */
1576 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1578 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1580 /** If the client stream is waiting on a socket write to occur, then */
1582 if (deferredRequest
->flags
.deferred
) {
1583 /** NO data is allowed to have been sent. */
1584 assert(deferredRequest
->http
->out
.size
== 0);
1586 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1587 deferredRequest
->http
,
1588 deferredRequest
->deferredparams
.rep
,
1589 deferredRequest
->deferredparams
.queuedBuffer
);
1592 /** otherwise, the request is still active in a callbacksomewhere,
1597 /// called when we have successfully finished writing the response
1599 ClientSocketContext::keepaliveNextRequest()
1601 ConnStateData
* conn
= http
->getConn();
1603 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1606 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1607 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1608 conn
->clientConnection
->close();
1613 * We are done with the response, and we are either still receiving request
1614 * body (early response!) or have already stopped receiving anything.
1616 * If we are still receiving, then clientParseRequest() below will fail.
1617 * (XXX: but then we will call readNextRequest() which may succeed and
1618 * execute a smuggled request as we are not done with the current request).
1620 * If we stopped because we got everything, then try the next request.
1622 * If we stopped receiving because of an error, then close now to avoid
1623 * getting stuck and to prevent accidental request smuggling.
1626 if (const char *reason
= conn
->stoppedReceiving()) {
1627 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1628 conn
->clientConnection
->close();
1633 * Attempt to parse a request from the request buffer.
1634 * If we've been fed a pipelined request it may already
1635 * be in our read buffer.
1638 * This needs to fall through - if we're unlucky and parse the _last_ request
1639 * from our read buffer we may never re-register for another client read.
1642 if (conn
->clientParseRequests()) {
1643 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1647 * Either we need to kick-start another read or, if we have
1648 * a half-closed connection, kill it after the last request.
1649 * This saves waiting for half-closed connections to finished being
1650 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1651 * the keepalive "Waiting for next request" state.
1653 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1654 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1655 conn
->clientConnection
->close();
1659 ClientSocketContext::Pointer deferredRequest
;
1662 * At this point we either have a parsed request (which we've
1663 * kicked off the processing for) or not. If we have a deferred
1664 * request (parsed but deferred for pipeling processing reasons)
1665 * then look at processing it. If not, simply kickstart
1669 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1670 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1671 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1672 } else if (conn
->flags
.readMore
) {
1673 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1674 conn
->readNextRequest();
1676 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1677 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1682 clientUpdateSocketStats(LogTags logType
, size_t size
)
1687 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1689 if (logTypeIsATcpHit(logType
))
1690 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1694 * increments iterator "i"
1695 * used by clientPackMoreRanges
1697 \retval true there is still data available to pack more ranges
1701 ClientSocketContext::canPackMoreRanges() const
1703 /** first update iterator "i" if needed */
1705 if (!http
->range_iter
.debt()) {
1706 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1708 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1709 ++http
->range_iter
.pos
;
1711 http
->range_iter
.updateSpec();
1714 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1716 /* paranoid sync condition */
1717 /* continue condition: need_more_data */
1718 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1719 return http
->range_iter
.currentSpec() ? true : false;
1723 ClientSocketContext::getNextRangeOffset() const
1725 debugs (33, 5, "range: " << http
->request
->range
<<
1726 "; http offset " << http
->out
.offset
<<
1727 "; reply " << reply
);
1729 // XXX: This method is called from many places, including pullData() which
1730 // may be called before prepareReply() [on some Squid-generated errors].
1731 // Hence, we may not even know yet whether we should honor/do ranges.
1733 if (http
->request
->range
) {
1734 /* offset in range specs does not count the prefix of an http msg */
1735 /* check: reply was parsed and range iterator was initialized */
1736 assert(http
->range_iter
.valid
);
1737 /* filter out data according to range specs */
1738 assert (canPackMoreRanges());
1740 int64_t start
; /* offset of still missing data */
1741 assert(http
->range_iter
.currentSpec());
1742 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1743 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1744 debugs(33, 3, "clientPackMoreRanges: out:"
1745 " start: " << start
<<
1746 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1747 " [" << http
->range_iter
.currentSpec()->offset
<<
1748 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1749 " len: " << http
->range_iter
.currentSpec()->length
<<
1750 " debt: " << http
->range_iter
.debt());
1751 if (http
->range_iter
.currentSpec()->length
!= -1)
1752 assert(http
->out
.offset
<= start
); /* we did not miss it */
1757 } else if (reply
&& reply
->content_range
) {
1758 /* request does not have ranges, but reply does */
1759 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1760 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1762 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1765 return http
->out
.offset
;
1769 ClientSocketContext::pullData()
1771 debugs(33, 5, reply
<< " written " << http
->out
.size
<< " into " << clientConnection
);
1773 /* More data will be coming from the stream. */
1774 StoreIOBuffer readBuffer
;
1775 /* XXX: Next requested byte in the range sequence */
1776 /* XXX: length = getmaximumrangelenfgth */
1777 readBuffer
.offset
= getNextRangeOffset();
1778 readBuffer
.length
= HTTP_REQBUF_SZ
;
1779 readBuffer
.data
= reqbuf
;
1780 /* we may note we have reached the end of the wanted ranges */
1781 clientStreamRead(getTail(), http
, readBuffer
);
1784 /** Adapt stream status to account for Range cases
1787 clientStream_status_t
1788 ClientSocketContext::socketState()
1790 switch (clientStreamStatus(getTail(), http
)) {
1793 /* check for range support ending */
1795 if (http
->request
->range
) {
1796 /* check: reply was parsed and range iterator was initialized */
1797 assert(http
->range_iter
.valid
);
1798 /* filter out data according to range specs */
1800 if (!canPackMoreRanges()) {
1801 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1802 "range sequence on " << clientConnection
);
1803 // we got everything we wanted from the store
1804 return STREAM_COMPLETE
;
1806 } else if (reply
&& reply
->content_range
) {
1807 /* reply has content-range, but Squid is not managing ranges */
1808 const int64_t &bytesSent
= http
->out
.offset
;
1809 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1811 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1812 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1813 reply
->content_range
->spec
.offset
<< ")");
1815 // did we get at least what we expected, based on range specs?
1817 if (bytesSent
== bytesExpected
) // got everything
1818 return STREAM_COMPLETE
;
1820 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1821 return STREAM_UNPLANNED_COMPLETE
;
1826 case STREAM_COMPLETE
:
1827 return STREAM_COMPLETE
;
1829 case STREAM_UNPLANNED_COMPLETE
:
1830 return STREAM_UNPLANNED_COMPLETE
;
1833 return STREAM_FAILED
;
1836 fatal ("unreachable code\n");
1841 * A write has just completed to the client, or we have just realised there is
1842 * no more data to send.
1845 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1847 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1848 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1851 /// remembers the abnormal connection termination for logging purposes
1853 ClientSocketContext::noteIoError(const int xerrno
)
1856 if (xerrno
== ETIMEDOUT
)
1857 http
->al
->http
.timedout
= true;
1858 else // even if xerrno is zero (which means read abort/eof)
1859 http
->al
->http
.aborted
= true;
1864 ClientSocketContext::doClose()
1866 clientConnection
->close();
1869 /// called when we encounter a response-related error
1871 ClientSocketContext::initiateClose(const char *reason
)
1873 http
->getConn()->stopSending(reason
); // closes ASAP
1877 ConnStateData::stopSending(const char *error
)
1879 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1880 "; old receiving error: " <<
1881 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1883 if (const char *oldError
= stoppedSending()) {
1884 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1885 return; // nothing has changed as far as this connection is concerned
1887 stoppedSending_
= error
;
1889 if (!stoppedReceiving()) {
1890 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1891 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1892 " request body bytes with " << in
.buf
.length() << " unused");
1893 return; // wait for the request receiver to finish reading
1897 clientConnection
->close();
1901 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1903 const StoreEntry
*entry
= http
->storeEntry();
1904 http
->out
.size
+= size
;
1905 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1906 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1907 (entry
? entry
->objectLen() : 0));
1908 clientUpdateSocketStats(http
->logType
, size
);
1910 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1912 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1915 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1916 initiateClose("failure or true request status");
1917 /* Do we leak here ? */
1921 switch (socketState()) {
1927 case STREAM_COMPLETE
:
1928 debugs(33, 5, conn
<< "Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1929 if (http
->request
->flags
.proxyKeepalive
)
1930 keepaliveNextRequest();
1932 initiateClose("STREAM_COMPLETE NOKEEPALIVE");
1935 case STREAM_UNPLANNED_COMPLETE
:
1936 initiateClose("STREAM_UNPLANNED_COMPLETE");
1940 initiateClose("STREAM_FAILED");
1944 fatal("Hit unreachable code in clientWriteComplete\n");
1948 SQUIDCEXTERN CSR clientGetMoreData
;
1949 SQUIDCEXTERN CSS clientReplyStatus
;
1950 SQUIDCEXTERN CSD clientReplyDetach
;
1952 static ClientSocketContext
*
1953 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1955 ClientHttpRequest
*http
;
1956 ClientSocketContext
*context
;
1957 StoreIOBuffer tempBuffer
;
1958 http
= new ClientHttpRequest(csd
);
1959 http
->req_sz
= csd
->in
.buf
.length();
1960 http
->uri
= xstrdup(uri
);
1961 setLogUri (http
, uri
);
1962 context
= new ClientSocketContext(csd
->clientConnection
, http
);
1963 tempBuffer
.data
= context
->reqbuf
;
1964 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1965 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1966 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1967 clientSocketDetach
, context
, tempBuffer
);
1972 skipLeadingSpace(char *aString
)
1974 char *result
= aString
;
1976 while (xisspace(*aString
))
1983 * 'end' defaults to NULL for backwards compatibility
1984 * remove default value if we ever get rid of NULL-terminated
1988 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1991 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1995 for (; end
> uriAndHTTPVersion
; --end
) {
1996 if (*end
== '\n' || *end
== '\r')
1999 if (xisspace(*end
)) {
2000 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2011 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2013 safe_free(http
->log_uri
);
2016 // The uri is already clean just dump it.
2017 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2020 switch (Config
.uri_whitespace
) {
2021 case URI_WHITESPACE_ALLOW
:
2022 flags
|= RFC1738_ESCAPE_NOSPACE
;
2024 case URI_WHITESPACE_ENCODE
:
2025 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2026 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2029 case URI_WHITESPACE_CHOP
: {
2030 flags
|= RFC1738_ESCAPE_NOSPACE
;
2031 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2032 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2033 int pos
= strcspn(http
->log_uri
, w_space
);
2034 http
->log_uri
[pos
] = '\0';
2038 case URI_WHITESPACE_DENY
:
2039 case URI_WHITESPACE_STRIP
:
2042 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2046 if (!xisspace(*t
)) {
2053 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2062 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2064 int vhost
= conn
->port
->vhost
;
2065 int vport
= conn
->port
->vport
;
2067 char ipbuf
[MAX_IPSTRLEN
];
2069 http
->flags
.accel
= true;
2071 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2073 if (strncasecmp(url
, "cache_object://", 15) == 0)
2074 return; /* already in good shape */
2077 if (conn
->port
->vhost
)
2078 return; /* already in good shape */
2080 /* else we need to ignore the host name */
2081 url
= strstr(url
, "//");
2083 #if SHOULD_REJECT_UNKNOWN_URLS
2086 hp
->request_parse_status
= Http::scBadRequest
;
2087 return parseHttpRequestAbort(conn
, "error:invalid-request");
2092 url
= strchr(url
+ 2, '/');
2099 vport
= http
->getConn()->clientConnection
->local
.port();
2101 const bool switchedToHttps
= conn
->switchedToHttps();
2102 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2103 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2104 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2109 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2110 strncpy(thost
, host
, (t
-host
));
2111 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2114 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2117 } // else nothing to alter port-wise.
2118 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2120 http
->uri
= (char *)xcalloc(url_sz
, 1);
2121 const char *protocol
= switchedToHttps
?
2122 "https" : AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str();
2123 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2124 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2125 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2126 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2127 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2128 strlen(conn
->port
->defaultsite
);
2129 http
->uri
= (char *)xcalloc(url_sz
, 1);
2133 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2135 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2136 AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, url
);
2137 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2138 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2139 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2140 /* Put the local socket IP address as the hostname, with whatever vport we found */
2141 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2142 http
->uri
= (char *)xcalloc(url_sz
, 1);
2143 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2144 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2145 AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(),
2147 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2152 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2155 char ipbuf
[MAX_IPSTRLEN
];
2158 return; /* already in good shape */
2160 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2162 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2163 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2165 http
->uri
= (char *)xcalloc(url_sz
, 1);
2166 snprintf(http
->uri
, url_sz
, "%s://%s%s", AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(), host
, url
);
2167 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2169 /* Put the local socket IP address as the hostname. */
2170 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2171 http
->uri
= (char *)xcalloc(url_sz
, 1);
2172 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2173 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2174 AnyP::UriScheme(http
->getConn()->port
->transport
.protocol
).c_str(),
2175 ipbuf
, http
->getConn()->clientConnection
->local
.port(), url
);
2176 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2180 /** Parse an HTTP request
2182 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2183 * to 1 if the request was correctly parsed.
2184 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2185 * \param[in] hp an HttpParser
2186 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2187 * Pointed-to value will be set to Http::METHOD_NONE in case of
2189 * \param[out] http_ver will be set as a side-effect of the parsing
2190 * \return NULL on incomplete requests,
2191 * a ClientSocketContext structure on success or failure.
2193 static ClientSocketContext
*
2194 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2196 char *req_hdr
= NULL
;
2199 ClientHttpRequest
*http
;
2200 ClientSocketContext
*result
;
2201 StoreIOBuffer tempBuffer
;
2204 /* pre-set these values to make aborting simpler */
2205 *method_p
= Http::METHOD_NONE
;
2207 /* NP: don't be tempted to move this down or remove again.
2208 * It's the only DDoS protection old-String has against long URL */
2209 if ( hp
->bufsiz
<= 0) {
2210 debugs(33, 5, "Incomplete request, waiting for end of request line");
2212 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2213 debugs(33, 5, "parseHttpRequest: Too large request");
2214 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2215 return parseHttpRequestAbort(csd
, "error:request-too-large");
2218 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2219 r
= HttpParserParseReqLine(hp
);
2222 debugs(33, 5, "Incomplete request, waiting for end of request line");
2227 return parseHttpRequestAbort(csd
, "error:invalid-request");
2230 /* Request line is valid here .. */
2231 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2233 /* This call scans the entire request, not just the headers */
2234 if (hp
->req
.v_maj
> 0) {
2235 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2236 debugs(33, 5, "Incomplete request, waiting for end of headers");
2240 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2241 req_sz
= HttpParserReqSz(hp
);
2244 /* We know the whole request is in hp->buf now */
2246 assert(req_sz
<= (size_t) hp
->bufsiz
);
2248 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2249 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2252 hp
->hdr_end
= req_sz
- 1;
2254 hp
->hdr_start
= hp
->req
.end
+ 1;
2256 /* Enforce max_request_size */
2257 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2258 debugs(33, 5, "parseHttpRequest: Too large request");
2259 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2260 return parseHttpRequestAbort(csd
, "error:request-too-large");
2264 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2266 /* deny CONNECT via accelerated ports */
2267 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2268 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->transport
.protocol
<< " Accelerator port " << csd
->port
->s
.port());
2269 /* XXX need a way to say "this many character length string" */
2270 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2271 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2272 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2275 if (*method_p
== Http::METHOD_NONE
) {
2276 /* XXX need a way to say "this many character length string" */
2277 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2278 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2279 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2283 * Process headers after request line
2284 * TODO: Use httpRequestParse here.
2286 /* XXX this code should be modified to take a const char * later! */
2287 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2289 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2291 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2293 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2295 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2296 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2297 HttpParserReqSz(hp
));
2299 /* Ok, all headers are received */
2300 http
= new ClientHttpRequest(csd
);
2302 http
->req_sz
= HttpParserRequestLen(hp
);
2303 result
= new ClientSocketContext(csd
->clientConnection
, http
);
2304 tempBuffer
.data
= result
->reqbuf
;
2305 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2307 ClientStreamData newServer
= new clientReplyContext(http
);
2308 ClientStreamData newClient
= result
;
2309 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2310 clientReplyStatus
, newServer
, clientSocketRecipient
,
2311 clientSocketDetach
, newClient
, tempBuffer
);
2313 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2317 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2318 * below needs to be modified to not expect a mutable nul-terminated string.
2320 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2322 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2324 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2326 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2328 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2333 debugs(33,5, HERE
<< "repare absolute URL from " <<
2334 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2335 /* Rewrite the URL in transparent or accelerator mode */
2336 /* NP: there are several cases to traverse here:
2337 * - standard mode (forward proxy)
2338 * - transparent mode (TPROXY)
2339 * - transparent mode with failures
2340 * - intercept mode (NAT)
2341 * - intercept mode with failures
2342 * - accelerator mode (reverse proxy)
2344 * - mixed combos of the above with internal URL
2346 if (csd
->transparent()) {
2347 /* intercept or transparent mode, properly working with no failures */
2348 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2350 } else if (internalCheck(url
)) {
2351 /* internal URL mode */
2352 /* prepend our name & port */
2353 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2354 // We just re-wrote the URL. Must replace the Host: header.
2355 // But have not parsed there yet!! flag for local-only handling.
2356 http
->flags
.internal
= true;
2358 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2359 /* accelerator mode */
2360 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2364 /* No special rewrites have been applied above, use the
2365 * requested url. may be rewritten later, so make extra room */
2366 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2367 http
->uri
= (char *)xcalloc(url_sz
, 1);
2368 strcpy(http
->uri
, url
);
2371 debugs(33, 5, "parseHttpRequest: Complete request received");
2373 // XXX: crop this dump at the end of headers. No need for extras
2374 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2375 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2377 result
->flags
.parsed_ok
= 1;
2383 ConnStateData::In::maybeMakeSpaceAvailable()
2385 if (buf
.spaceSize() < 2) {
2386 const SBuf::size_type haveCapacity
= buf
.length() + buf
.spaceSize();
2387 if (haveCapacity
>= Config
.maxRequestBufferSize
) {
2388 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2391 const SBuf::size_type wantCapacity
= min(Config
.maxRequestBufferSize
, haveCapacity
*2);
2392 buf
.reserveCapacity(wantCapacity
);
2393 debugs(33, 2, "growing request buffer: available=" << buf
.spaceSize() << " used=" << buf
.length());
2395 return (buf
.spaceSize() >= 2);
2399 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2401 ClientSocketContext::Pointer
*S
;
2403 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2411 ConnStateData::getConcurrentRequestCount() const
2414 ClientSocketContext::Pointer
*T
;
2416 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2417 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2422 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2424 if (flag
!= COMM_OK
) {
2425 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2430 if (!ignoreErrno(xerrno
)) {
2431 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2433 } else if (in
.buf
.isEmpty()) {
2434 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2442 ConnStateData::connFinishedWithConn(int size
)
2445 if (getConcurrentRequestCount() == 0 && in
.buf
.isEmpty()) {
2446 /* no current or pending requests */
2447 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2449 } else if (!Config
.onoff
.half_closed_clients
) {
2450 /* admin doesn't want to support half-closed client sockets */
2451 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2452 notifyAllContexts(0); // no specific error implies abort
2461 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2463 assert(byteCount
> 0 && byteCount
<= conn
->in
.buf
.length());
2464 conn
->in
.buf
.consume(byteCount
);
2465 debugs(33, 5, "conn->in.buf has " << conn
->in
.buf
.length() << " bytes unused.");
2468 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2470 ConnStateData::checkHeaderLimits()
2472 if (in
.buf
.length() < Config
.maxRequestHeaderSize
)
2473 return; // can accumulte more header data
2475 debugs(33, 3, "Request header is too large (" << in
.buf
.length() << " > " <<
2476 Config
.maxRequestHeaderSize
<< " bytes)");
2478 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2479 clientStreamNode
*node
= context
->getClientReplyContext();
2480 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2481 assert (repContext
);
2482 repContext
->setReplyToError(ERR_TOO_BIG
,
2483 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2484 clientConnection
->remote
, NULL
, NULL
, NULL
);
2485 context
->registerWithConn();
2486 context
->pullData();
2490 ConnStateData::clientAfterReadingRequests()
2492 // Were we expecting to read more request body from half-closed connection?
2493 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2494 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2495 clientConnection
->close();
2504 ConnStateData::quitAfterError(HttpRequest
*request
)
2506 // From HTTP p.o.v., we do not have to close after every error detected
2507 // at the client-side, but many such errors do require closure and the
2508 // client-side code is bad at handling errors so we play it safe.
2510 request
->flags
.proxyKeepalive
= false;
2511 flags
.readMore
= false;
2512 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2516 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2518 ClientHttpRequest
*http
= context
->http
;
2523 assert(sslServerBump
->entry
);
2524 // Did we create an error entry while processing CONNECT?
2525 if (!sslServerBump
->entry
->isEmpty()) {
2526 quitAfterError(http
->request
);
2528 // Get the saved error entry and send it to the client by replacing the
2529 // ClientHttpRequest store entry with it.
2530 clientStreamNode
*node
= context
->getClientReplyContext();
2531 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2533 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2534 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
2536 // save the original request for logging purposes
2537 if (!context
->http
->al
->request
) {
2538 context
->http
->al
->request
= http
->request
;
2539 HTTPMSGLOCK(context
->http
->al
->request
);
2542 // Get error details from the fake certificate-peeking request.
2543 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2544 context
->pullData();
2548 // In bump-server-first mode, we have not necessarily seen the intended
2549 // server name at certificate-peeking time. Check for domain mismatch now,
2550 // when we can extract the intended name from the bumped HTTP request.
2551 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2552 HttpRequest
*request
= http
->request
;
2553 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2554 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2555 "does not match domainname " << request
->GetHost());
2557 bool allowDomainMismatch
= false;
2558 if (Config
.ssl_client
.cert_error
) {
2559 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2560 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2561 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2562 delete check
.sslErrors
;
2563 check
.sslErrors
= NULL
;
2566 if (!allowDomainMismatch
) {
2567 quitAfterError(request
);
2569 clientStreamNode
*node
= context
->getClientReplyContext();
2570 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2571 assert (repContext
);
2573 // Fill the server IP and hostname for error page generation.
2574 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2575 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2577 // Create an error object and fill it
2578 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2579 err
->src_addr
= clientConnection
->remote
;
2580 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2581 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2583 err
->detail
= errDetail
;
2584 // Save the original request for logging purposes.
2585 if (!context
->http
->al
->request
) {
2586 context
->http
->al
->request
= request
;
2587 HTTPMSGLOCK(context
->http
->al
->request
);
2589 repContext
->setReplyToError(request
->method
, err
);
2590 assert(context
->http
->out
.offset
== 0);
2591 context
->pullData();
2602 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2604 ClientHttpRequest
*http
= context
->http
;
2605 HttpRequest::Pointer request
;
2606 bool notedUseOfBuffer
= false;
2607 bool chunked
= false;
2608 bool mustReplyToOptions
= false;
2609 bool unsupportedTe
= false;
2610 bool expectBody
= false;
2612 /* We have an initial client stream in place should it be needed */
2613 /* setup our private context */
2614 context
->registerWithConn();
2616 if (context
->flags
.parsed_ok
== 0) {
2617 clientStreamNode
*node
= context
->getClientReplyContext();
2618 debugs(33, 2, "clientProcessRequest: Invalid Request");
2619 conn
->quitAfterError(NULL
);
2620 // setLogUri should called before repContext->setReplyToError
2621 setLogUri(http
, http
->uri
, true);
2622 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2623 assert (repContext
);
2624 switch (hp
->request_parse_status
) {
2625 case Http::scHeaderTooLarge
:
2626 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
.c_str(), NULL
);
2628 case Http::scMethodNotAllowed
:
2629 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2630 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
.c_str(), NULL
);
2633 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2634 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
.c_str(), NULL
);
2636 assert(context
->http
->out
.offset
== 0);
2637 context
->pullData();
2641 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2642 clientStreamNode
*node
= context
->getClientReplyContext();
2643 debugs(33, 5, "Invalid URL: " << http
->uri
);
2644 conn
->quitAfterError(request
.getRaw());
2645 // setLogUri should called before repContext->setReplyToError
2646 setLogUri(http
, http
->uri
, true);
2647 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2648 assert (repContext
);
2649 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2650 assert(context
->http
->out
.offset
== 0);
2651 context
->pullData();
2655 /* RFC 2616 section 10.5.6 : handle unsupported HTTP major versions cleanly. */
2656 /* We currently only support 0.9, 1.0, 1.1 properly */
2657 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2658 (http_ver
.major
> 1) ) {
2660 clientStreamNode
*node
= context
->getClientReplyContext();
2661 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2662 conn
->quitAfterError(request
.getRaw());
2663 // setLogUri should called before repContext->setReplyToError
2664 setLogUri(http
, http
->uri
, true);
2665 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2666 assert (repContext
);
2667 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2668 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2669 assert(context
->http
->out
.offset
== 0);
2670 context
->pullData();
2674 /* compile headers */
2675 /* we should skip request line! */
2676 /* XXX should actually know the damned buffer size here */
2677 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2678 clientStreamNode
*node
= context
->getClientReplyContext();
2679 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2680 conn
->quitAfterError(request
.getRaw());
2681 // setLogUri should called before repContext->setReplyToError
2682 setLogUri(http
, http
->uri
, true);
2683 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2684 assert (repContext
);
2685 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2686 assert(context
->http
->out
.offset
== 0);
2687 context
->pullData();
2691 request
->clientConnectionManager
= conn
;
2693 request
->flags
.accelerated
= http
->flags
.accel
;
2694 request
->flags
.sslBumped
=conn
->switchedToHttps();
2695 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2696 // TODO: decouple http->flags.accel from request->flags.sslBumped
2697 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2698 !conn
->port
->allow_direct
: 0;
2700 if (request
->flags
.sslBumped
) {
2701 if (conn
->getAuth() != NULL
)
2702 request
->auth_user_request
= conn
->getAuth();
2707 * If transparent or interception mode is working clone the transparent and interception flags
2708 * from the port settings to the request.
2710 if (http
->clientConnection
!= NULL
) {
2711 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2712 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2713 if (request
->flags
.interceptTproxy
) {
2714 if (Config
.accessList
.spoof_client_ip
) {
2715 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2716 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2719 request
->flags
.spoofClientIp
= true;
2721 request
->flags
.spoofClientIp
= false;
2724 if (internalCheck(request
->urlpath
.termedBuf())) {
2725 if (internalHostnameIs(request
->GetHost()) &&
2726 request
->port
== getMyPort()) {
2727 http
->flags
.internal
= true;
2728 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2729 request
->SetHost(internalHostname());
2730 request
->port
= getMyPort();
2731 http
->flags
.internal
= true;
2735 if (http
->flags
.internal
) {
2736 request
->protocol
= AnyP::PROTO_HTTP
;
2737 request
->login
[0] = '\0';
2740 request
->flags
.internal
= http
->flags
.internal
;
2741 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2742 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2743 #if FOLLOW_X_FORWARDED_FOR
2744 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2745 // not a details about teh TCP connection itself
2746 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2747 #endif /* FOLLOW_X_FORWARDED_FOR */
2748 request
->my_addr
= conn
->clientConnection
->local
;
2749 request
->myportname
= conn
->port
->name
;
2750 request
->http_ver
= http_ver
;
2752 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2753 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2754 request
->clientConnectionManager
= conn
;
2756 if (request
->header
.chunked()) {
2758 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2759 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2760 // HTTP/1.1 requires chunking to be the last encoding if there is one
2761 unsupportedTe
= te
.size() && te
!= "identity";
2762 } // else implied identity coding
2764 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2765 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2766 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2767 clientStreamNode
*node
= context
->getClientReplyContext();
2768 conn
->quitAfterError(request
.getRaw());
2769 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2770 assert (repContext
);
2771 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2772 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2773 assert(context
->http
->out
.offset
== 0);
2774 context
->pullData();
2778 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2779 clientStreamNode
*node
= context
->getClientReplyContext();
2780 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2781 assert (repContext
);
2782 conn
->quitAfterError(request
.getRaw());
2783 repContext
->setReplyToError(ERR_INVALID_REQ
,
2784 Http::scLengthRequired
, request
->method
, NULL
,
2785 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2786 assert(context
->http
->out
.offset
== 0);
2787 context
->pullData();
2791 if (request
->header
.has(HDR_EXPECT
)) {
2792 const String expect
= request
->header
.getList(HDR_EXPECT
);
2793 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2794 if (!supportedExpect
) {
2795 clientStreamNode
*node
= context
->getClientReplyContext();
2796 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2797 assert (repContext
);
2798 conn
->quitAfterError(request
.getRaw());
2799 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2800 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2801 assert(context
->http
->out
.offset
== 0);
2802 context
->pullData();
2807 http
->request
= request
.getRaw();
2808 HTTPMSGLOCK(http
->request
);
2809 clientSetKeepaliveFlag(http
);
2811 // Let tunneling code be fully responsible for CONNECT requests
2812 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2813 context
->mayUseConnection(true);
2814 conn
->flags
.readMore
= false;
2818 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2822 /* Do we expect a request-body? */
2823 expectBody
= chunked
|| request
->content_length
> 0;
2824 if (!context
->mayUseConnection() && expectBody
) {
2825 request
->body_pipe
= conn
->expectRequestBody(
2826 chunked
? -1 : request
->content_length
);
2828 // consume header early so that body pipe gets just the body
2829 connNoteUseOfBuffer(conn
, http
->req_sz
);
2830 notedUseOfBuffer
= true;
2832 /* Is it too large? */
2833 if (!chunked
&& // if chunked, we will check as we accumulate
2834 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2835 clientStreamNode
*node
= context
->getClientReplyContext();
2836 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2837 assert (repContext
);
2838 conn
->quitAfterError(request
.getRaw());
2839 repContext
->setReplyToError(ERR_TOO_BIG
,
2840 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2841 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2842 assert(context
->http
->out
.offset
== 0);
2843 context
->pullData();
2847 // We may stop producing, comm_close, and/or call setReplyToError()
2848 // below, so quit on errors to avoid http->doCallouts()
2849 if (!conn
->handleRequestBodyData())
2852 if (!request
->body_pipe
->productionEnded()) {
2853 debugs(33, 5, HERE
<< "need more request body");
2854 context
->mayUseConnection(true);
2855 assert(conn
->flags
.readMore
);
2859 http
->calloutContext
= new ClientRequestContext(http
);
2864 if (!notedUseOfBuffer
)
2865 connNoteUseOfBuffer(conn
, http
->req_sz
);
2869 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2870 * to here because calling comm_reset_close() causes http to
2871 * be freed and the above connNoteUseOfBuffer() would hit an
2872 * assertion, not to mention that we were accessing freed memory.
2874 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2875 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2876 conn
->flags
.readMore
= false;
2877 comm_reset_close(conn
->clientConnection
);
2882 connStripBufferWhitespace (ConnStateData
* conn
)
2884 // XXX: kill this whole function.
2885 while (!conn
->in
.buf
.isEmpty() && xisspace(conn
->in
.buf
.at(0))) {
2886 conn
->in
.buf
.consume(1);
2891 * Limit the number of concurrent requests.
2892 * \return true when there are available position(s) in the pipeline queue for another request.
2893 * \return false when the pipeline queue is full or disabled.
2896 ConnStateData::concurrentRequestQueueFilled() const
2898 const int existingRequestCount
= getConcurrentRequestCount();
2900 // default to the configured pipeline size.
2901 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2902 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2904 // when queue filled already we cant add more.
2905 if (existingRequestCount
>= concurrentRequestLimit
) {
2906 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2907 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2915 * Attempt to parse one or more requests from the input buffer.
2916 * If a request is successfully parsed, even if the next request
2917 * is only partially parsed, it will return TRUE.
2920 ConnStateData::clientParseRequests()
2922 HttpRequestMethod method
;
2923 bool parsed_req
= false;
2925 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2927 // Loop while we have read bytes that are not needed for producing the body
2928 // On errors, bodyPipe may become nil, but readMore will be cleared
2929 while (!in
.buf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2930 connStripBufferWhitespace(this);
2932 /* Don't try to parse if the buffer is empty */
2933 if (in
.buf
.isEmpty())
2936 /* Limit the number of concurrent requests */
2937 if (concurrentRequestQueueFilled())
2940 /* Begin the parsing */
2941 PROF_start(parseHttpRequest
);
2942 HttpParserInit(&parser_
, in
.buf
.c_str(), in
.buf
.length());
2944 /* Process request */
2945 Http::ProtocolVersion http_ver
;
2946 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2947 PROF_stop(parseHttpRequest
);
2949 /* partial or incomplete request */
2951 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2952 // (which becomes context) but checkHeaderLimits cannot?
2953 checkHeaderLimits();
2957 /* status -1 or 1 */
2959 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2960 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2961 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2962 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2964 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2966 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2968 if (context
->mayUseConnection()) {
2969 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2975 /* XXX where to 'finish' the parsing pass? */
2980 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
2982 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
2986 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2988 if (io
.flag
== COMM_ERR_CLOSING
) {
2989 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
2993 assert(Comm::IsConnOpen(clientConnection
));
2994 assert(io
.conn
->fd
== clientConnection
->fd
);
2997 * Don't reset the timeout value here. The timeout value will be
2998 * set to Config.Timeout.request by httpAccept() and
2999 * clientWriteComplete(), and should apply to the request as a
3000 * whole, not individual read() calls. Plus, it breaks our
3001 * lame half-close detection
3003 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3004 notifyAllContexts(io
.xerrno
);
3009 if (io
.flag
== COMM_OK
) {
3011 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3013 // may comm_close or setReplyToError
3014 if (!handleReadData(io
.buf2
))
3017 } else if (io
.size
== 0) {
3018 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3020 if (connFinishedWithConn(io
.size
)) {
3021 clientConnection
->close();
3025 /* It might be half-closed, we can't tell */
3026 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3028 commMarkHalfClosed(io
.conn
->fd
);
3030 fd_note(io
.conn
->fd
, "half-closed");
3032 /* There is one more close check at the end, to detect aborted
3033 * (partial) requests. At this point we can't tell if the request
3036 /* Continue to process previously read data */
3040 /* Process next request */
3041 if (getConcurrentRequestCount() == 0)
3042 fd_note(io
.fd
, "Reading next request");
3044 if (!clientParseRequests()) {
3048 * If the client here is half closed and we failed
3049 * to parse a request, close the connection.
3050 * The above check with connFinishedWithConn() only
3051 * succeeds _if_ the buffer is empty which it won't
3052 * be if we have an incomplete request.
3053 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3055 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3056 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3057 clientConnection
->close();
3065 clientAfterReadingRequests();
3069 * called when new request data has been read from the socket
3071 * \retval false called comm_close or setReplyToError (the caller should bail)
3072 * \retval true we did not call comm_close or setReplyToError
3075 ConnStateData::handleReadData(SBuf
*buf
)
3077 assert(buf
== &in
.buf
); // XXX: make this abort the transaction if this fails
3079 // if we are reading a body, stuff data into the body pipe
3080 if (bodyPipe
!= NULL
)
3081 return handleRequestBodyData();
3086 * called when new request body data has been buffered in in.buf
3087 * may close the connection if we were closing and piped everything out
3089 * \retval false called comm_close or setReplyToError (the caller should bail)
3090 * \retval true we did not call comm_close or setReplyToError
3093 ConnStateData::handleRequestBodyData()
3095 assert(bodyPipe
!= NULL
);
3099 if (in
.bodyParser
) { // chunked encoding
3100 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3101 abortChunkedRequestBody(error
);
3104 } else { // identity encoding
3105 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3106 putSize
= bodyPipe
->putMoreData(in
.buf
.c_str(), in
.buf
.length());
3107 if (!bodyPipe
->mayNeedMoreData()) {
3108 // BodyPipe will clear us automagically when we produced everything
3114 connNoteUseOfBuffer(this, putSize
);
3117 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3119 if (const char *reason
= stoppedSending()) {
3120 /* we've finished reading like good clients,
3121 * now do the close that initiateClose initiated.
3123 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3124 clientConnection
->close();
3132 /// parses available chunked encoded body bytes, checks size, returns errors
3134 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3136 debugs(33, 7, "chunked from " << clientConnection
<< ": " << in
.buf
.length());
3138 try { // the parser will throw on errors
3140 if (in
.buf
.isEmpty()) // nothing to do
3143 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3144 // add one because MemBuf will assert if it cannot 0-terminate
3145 raw
.init(in
.buf
.length(), in
.buf
.length()+1);
3146 raw
.append(in
.buf
.c_str(), in
.buf
.length());
3148 const mb_size_t wasContentSize
= raw
.contentSize();
3149 BodyPipeCheckout
bpc(*bodyPipe
);
3150 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3152 putSize
= wasContentSize
- raw
.contentSize();
3154 // dechunk then check: the size limit applies to _dechunked_ content
3155 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3159 finishDechunkingRequest(true);
3161 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3164 // if chunk parser needs data, then the body pipe must need it too
3165 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3167 // if parser needs more space and we can consume nothing, we will stall
3168 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3169 } catch (...) { // TODO: be more specific
3170 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3171 return ERR_INVALID_REQ
;
3174 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3178 /// quit on errors related to chunked request body handling
3180 ConnStateData::abortChunkedRequestBody(const err_type error
)
3182 finishDechunkingRequest(false);
3184 // XXX: The code below works if we fail during initial request parsing,
3185 // but if we fail when the server-side works already, the server may send
3186 // us its response too, causing various assertions. How to prevent that?
3187 #if WE_KNOW_HOW_TO_SEND_ERRORS
3188 ClientSocketContext::Pointer context
= getCurrentContext();
3189 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3190 clientStreamNode
*node
= context
->getClientReplyContext();
3191 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3193 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3194 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3195 repContext
->setReplyToError(error
, scode
,
3196 repContext
->http
->request
->method
,
3197 repContext
->http
->uri
,
3199 repContext
->http
->request
,
3201 context
->pullData();
3203 // close or otherwise we may get stuck as nobody will notice the error?
3204 comm_reset_close(clientConnection
);
3207 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3208 comm_reset_close(clientConnection
);
3210 flags
.readMore
= false;
3214 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3216 if (!handleRequestBodyData())
3219 // too late to read more body
3220 if (!isOpen() || stoppedReceiving())
3227 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3229 // request reader may get stuck waiting for space if nobody consumes body
3230 if (bodyPipe
!= NULL
)
3231 bodyPipe
->enableAutoConsumption();
3233 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3236 /** general lifetime handler for HTTP requests */
3238 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3241 * Just close the connection to not confuse browsers
3242 * using persistent connections. Some browsers open
3243 * a connection and then do not use it until much
3244 * later (presumeably because the request triggering
3245 * the open has already been completed on another
3248 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3253 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3255 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3256 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3257 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3258 http
->al
->http
.timedout
= true;
3259 if (Comm::IsConnOpen(io
.conn
))
3263 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3264 AsyncJob("ConnStateData"),
3266 sslBumpMode(Ssl::bumpEnd
),
3267 switchedToHttps_(false),
3268 sslServerBump(NULL
),
3270 stoppedSending_(NULL
),
3271 stoppedReceiving_(NULL
)
3273 pinning
.host
= NULL
;
3275 pinning
.pinned
= false;
3276 pinning
.auth
= false;
3277 pinning
.zeroReply
= false;
3278 pinning
.peer
= NULL
;
3280 // store the details required for creating more MasterXaction objects as new requests come in
3281 clientConnection
= xact
->tcpClient
;
3282 port
= cbdataReference(xact
->squidPort
.get());
3283 log_addr
= xact
->tcpClient
->remote
;
3284 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3286 in
.buf
.reserveCapacity(CLIENT_REQ_BUF_SZ
);
3288 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3289 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3290 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3291 int i
= IP_PMTUDISC_DONT
;
3292 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3293 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3295 static bool reported
= false;
3298 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3304 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3305 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3306 comm_add_close_handler(clientConnection
->fd
, call
);
3308 if (Config
.onoff
.log_fqdn
)
3309 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3312 if (Ident::TheConfig
.identLookup
) {
3313 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3314 identChecklist
.src_addr
= xact
->tcpClient
->remote
;
3315 identChecklist
.my_addr
= xact
->tcpClient
->local
;
3316 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3317 Ident::Start(xact
->tcpClient
, clientIdentDone
, this);
3321 clientdbEstablished(clientConnection
->remote
, 1);
3323 flags
.readMore
= true;
3326 /** Handle a new connection on HTTP socket. */
3328 httpAccept(const CommAcceptCbParams
¶ms
)
3330 MasterXaction::Pointer xact
= params
.xaction
;
3331 AnyP::PortCfgPointer s
= xact
->squidPort
;
3334 // it is possible the call or accept() was still queued when the port was reconfigured
3335 debugs(33, 2, "HTTP accept failure: port reconfigured.");
3339 if (params
.flag
!= COMM_OK
) {
3340 // Its possible the call was still queued when the client disconnected
3341 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3345 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3346 fd_note(params
.conn
->fd
, "client http connect");
3348 if (s
->tcp_keepalive
.enabled
) {
3349 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3352 ++ incoming_sockets_accepted
;
3354 // Socket is ready, setup the connection manager to start using it
3355 ConnStateData
*connState
= new ConnStateData(xact
);
3357 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3358 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3359 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3360 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3362 connState
->readSomeData();
3365 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3367 if (Config
.onoff
.client_db
) {
3368 /* it was said several times that client write limiter does not work if client_db is disabled */
3370 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3371 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3373 // TODO: we check early to limit error response bandwith but we
3374 // should recheck when we can honor delay_pool_uses_indirect
3375 // TODO: we should also pass the port details for myportname here.
3376 ch
.src_addr
= params
.conn
->remote
;
3377 ch
.my_addr
= params
.conn
->local
;
3379 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3381 /* pools require explicit 'allow' to assign a client into them */
3382 if (pools
[pool
].access
) {
3383 ch
.accessList
= pools
[pool
].access
;
3384 allow_t answer
= ch
.fastCheck();
3385 if (answer
== ACCESS_ALLOWED
) {
3387 /* request client information from db after we did all checks
3388 this will save hash lookup if client failed checks */
3389 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3392 /* put client info in FDE */
3393 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3395 /* setup write limiter for this request */
3396 const double burst
= floor(0.5 +
3397 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3398 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3401 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3411 /** Create SSL connection structure and update fd_table */
3413 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3415 SSL
*ssl
= SSL_new(sslContext
);
3418 const int ssl_error
= ERR_get_error();
3419 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3424 SSL_set_fd(ssl
, conn
->fd
);
3425 fd_table
[conn
->fd
].ssl
= ssl
;
3426 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3427 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3429 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3430 fd_note(conn
->fd
, "client https start");
3435 /** negotiate an SSL connection */
3437 clientNegotiateSSL(int fd
, void *data
)
3439 ConnStateData
*conn
= (ConnStateData
*)data
;
3441 SSL
*ssl
= fd_table
[fd
].ssl
;
3444 if ((ret
= SSL_accept(ssl
)) <= 0) {
3445 int ssl_error
= SSL_get_error(ssl
, ret
);
3447 switch (ssl_error
) {
3449 case SSL_ERROR_WANT_READ
:
3450 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3453 case SSL_ERROR_WANT_WRITE
:
3454 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3457 case SSL_ERROR_SYSCALL
:
3460 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3466 if (errno
== ECONNRESET
)
3469 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3470 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3477 case SSL_ERROR_ZERO_RETURN
:
3478 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3483 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3484 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3485 " (" << ssl_error
<< "/" << ret
<< ")");
3493 if (SSL_session_reused(ssl
)) {
3494 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3495 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3497 if (do_debug(83, 4)) {
3498 /* Write out the SSL session details.. actually the call below, but
3499 * OpenSSL headers do strange typecasts confusing GCC.. */
3500 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3501 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3502 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
);
3504 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3506 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3507 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3508 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3509 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3510 * Because there are two possible usable cast, if you get an error here, try the other
3511 * commented line. */
3513 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3514 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3518 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3521 /* Note: This does not automatically fflush the log file.. */
3524 debugs(83, 2, "clientNegotiateSSL: New session " <<
3525 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3526 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3530 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3531 SSL_get_cipher(ssl
));
3533 client_cert
= SSL_get_peer_certificate(ssl
);
3535 if (client_cert
!= NULL
) {
3536 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3537 " client certificate: subject: " <<
3538 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3540 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3541 " client certificate: issuer: " <<
3542 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3544 X509_free(client_cert
);
3546 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3547 " has no certificate.");
3550 conn
->readSomeData();
3554 * If SSL_CTX is given, starts reading the SSL handshake.
3555 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3558 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3562 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3564 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3567 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3568 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3569 connState
, ConnStateData::requestTimeout
);
3570 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3573 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3575 char buf
[MAX_IPSTRLEN
];
3576 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3577 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3578 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3579 fakeRequest
->port
= details
->local
.port();
3580 fakeRequest
->clientConnectionManager
= connState
;
3581 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3582 #if FOLLOW_X_FORWARDED_FOR
3583 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3585 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3586 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3587 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3588 fakeRequest
->myportname
= connState
->port
->name
;
3589 if (fakeRequest
->flags
.interceptTproxy
) {
3590 if (Config
.accessList
.spoof_client_ip
) {
3591 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3592 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3594 fakeRequest
->flags
.spoofClientIp
= true;
3596 fakeRequest
->flags
.spoofClientIp
= false;
3597 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3598 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3603 * A callback function to use with the ACLFilledChecklist callback.
3604 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3605 * else reverts the connection to tunnel mode.
3608 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3610 ConnStateData
*connState
= (ConnStateData
*) data
;
3612 // if the connection is closed or closing, just return.
3613 if (!connState
->isOpen())
3616 // Require both a match and a positive bump mode to work around exceptional
3617 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3618 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3619 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3620 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3621 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3623 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3624 connState
->sslBumpMode
= Ssl::bumpNone
;
3626 // fake a CONNECT request to force connState to tunnel
3627 static char ip
[MAX_IPSTRLEN
];
3628 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3630 reqStr
.append("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n");
3631 bool ret
= connState
->handleReadData(&reqStr
);
3633 ret
= connState
->clientParseRequests();
3636 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3637 connState
->clientConnection
->close();
3642 /** handle a new HTTPS connection */
3644 httpsAccept(const CommAcceptCbParams
¶ms
)
3646 MasterXaction::Pointer xact
= params
.xaction
;
3647 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3650 // it is possible the call or accept() was still queued when the port was reconfigured
3651 debugs(33, 2, "HTTPS accept failure: port reconfigured.");
3655 if (params
.flag
!= COMM_OK
) {
3656 // Its possible the call was still queued when the client disconnected
3657 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3661 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3662 fd_note(params
.conn
->fd
, "client https connect");
3664 if (s
->tcp_keepalive
.enabled
) {
3665 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3668 ++incoming_sockets_accepted
;
3670 // Socket is ready, setup the connection manager to start using it
3671 ConnStateData
*connState
= new ConnStateData(xact
);
3673 if (s
->flags
.tunnelSslBumping
) {
3674 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3676 if (!Config
.accessList
.ssl_bump
) {
3677 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3681 // Create a fake HTTP request for ssl_bump ACL check,
3682 // using tproxy/intercept provided destination IP and port.
3683 HttpRequest
*request
= new HttpRequest();
3684 static char ip
[MAX_IPSTRLEN
];
3685 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3686 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3687 request
->port
= params
.conn
->local
.port();
3688 request
->myportname
= s
->name
;
3690 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3691 acl_checklist
->src_addr
= params
.conn
->remote
;
3692 acl_checklist
->my_addr
= s
->s
;
3693 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3696 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3697 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3702 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3704 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3705 state_data
->sslCrtdHandleReply(reply
);
3709 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3711 if (reply
.result
== HelperReply::BrokenHelper
) {
3712 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3713 } else if (!reply
.other().hasContent()) {
3714 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3716 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3717 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3718 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3720 if (reply
.result
!= HelperReply::Okay
) {
3721 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3723 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3724 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3725 getSslContextDone(ctx
, true);
3730 getSslContextDone(NULL
);
3733 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3735 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3737 // fake certificate adaptation requires bump-server-first mode
3738 if (!sslServerBump
) {
3739 assert(port
->signingCert
.get());
3740 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3741 if (port
->signPkey
.get())
3742 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3743 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3747 // In case of an error while connecting to the secure server, use a fake
3748 // trusted certificate, with no mimicked fields and no adaptation
3749 // algorithms. There is nothing we can mimic so we want to minimize the
3750 // number of warnings the user will have to see to get to the error page.
3751 assert(sslServerBump
->entry
);
3752 if (sslServerBump
->entry
->isEmpty()) {
3753 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3754 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3756 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3757 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3758 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3760 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3761 // If the algorithm already set, then ignore it.
3762 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3763 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3764 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3767 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3768 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3769 const char *param
= ca
->param
;
3771 // For parameterless CN adaptation, use hostname from the
3773 if (ca
->alg
== Ssl::algSetCommonName
) {
3775 param
= sslConnectHostOrIp
.termedBuf();
3776 certProperties
.commonName
= param
;
3777 certProperties
.setCommonName
= true;
3778 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3779 certProperties
.setValidAfter
= true;
3780 else if (ca
->alg
== Ssl::algSetValidBefore
)
3781 certProperties
.setValidBefore
= true;
3783 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3784 alg
<< " param: " << (param
? param
: "-"));
3788 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3789 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3790 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3791 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3795 } else {// if (!sslServerBump->entry->isEmpty())
3796 // Use trusted certificate for a Squid-generated error
3797 // or the user would have to add a security exception
3798 // just to see the error page. We will close the connection
3799 // so that the trust is not extended to non-Squid content.
3800 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3803 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3805 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3806 assert(port
->untrustedSigningCert
.get());
3807 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3808 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3810 assert(port
->signingCert
.get());
3811 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3813 if (port
->signPkey
.get())
3814 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3816 signAlgorithm
= certProperties
.signAlgorithm
;
3820 ConnStateData::getSslContextStart()
3822 assert(areAllContextsForThisConnection());
3824 /* careful: freeAllContexts() above frees request, host, etc. */
3826 if (port
->generateHostCertificates
) {
3827 Ssl::CertificateProperties certProperties
;
3828 buildSslCertGenerationParams(certProperties
);
3829 sslBumpCertKey
= certProperties
.dbKey().c_str();
3830 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3832 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3833 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3834 SSL_CTX
* dynCtx
= NULL
;
3835 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3836 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3837 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3838 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3839 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3840 getSslContextDone(dynCtx
);
3843 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3845 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3848 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3853 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3854 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3855 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3856 request_message
.composeRequest(certProperties
);
3857 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3858 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3860 } catch (const std::exception
&e
) {
3861 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3862 "request for " << certProperties
.commonName
<<
3863 " certificate: " << e
.what() << "; will now block to " <<
3864 "generate that certificate.");
3865 // fall through to do blocking in-process generation.
3867 #endif // USE_SSL_CRTD
3869 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3870 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3871 getSslContextDone(dynCtx
, true);
3874 getSslContextDone(NULL
);
3878 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3880 // Try to add generated ssl context to storage.
3881 if (port
->generateHostCertificates
&& isNew
) {
3883 if (signAlgorithm
== Ssl::algSignTrusted
) {
3884 // Add signing certificate to the certificates chain
3885 X509
*cert
= port
->signingCert
.get();
3886 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3887 // increase the certificate lock
3888 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3890 const int ssl_error
= ERR_get_error();
3891 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3893 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3895 //else it is self-signed or untrusted do not attrach any certificate
3897 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3898 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3900 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3901 // If it is not in storage delete after using. Else storage deleted it.
3902 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3905 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3909 // If generated ssl context = NULL, try to use static ssl context.
3911 if (!port
->staticSslContext
) {
3912 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3913 clientConnection
->close();
3916 debugs(33, 5, HERE
<< "Using static ssl context.");
3917 sslContext
= port
->staticSslContext
.get();
3921 if (!httpsCreate(clientConnection
, sslContext
))
3924 // commSetConnTimeout() was called for this request before we switched.
3926 // Disable the client read handler until CachePeer selection is complete
3927 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3928 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3929 switchedToHttps_
= true;
3933 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3935 assert(!switchedToHttps_
);
3937 sslConnectHostOrIp
= request
->GetHost();
3938 sslCommonName
= request
->GetHost();
3940 // We are going to read new request
3941 flags
.readMore
= true;
3942 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3944 // If sslServerBump is set, then we have decided to deny CONNECT
3945 // and now want to switch to SSL to send the error to the client
3946 // without even peeking at the origin server certificate.
3947 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3948 request
->flags
.sslPeek
= true;
3949 sslServerBump
= new Ssl::ServerBump(request
);
3951 // will call httpsPeeked() with certificate and connection, eventually
3952 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3956 // otherwise, use sslConnectHostOrIp
3957 getSslContextStart();
3961 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3963 Must(sslServerBump
!= NULL
);
3965 if (Comm::IsConnOpen(serverConnection
)) {
3966 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3968 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3969 assert(serverCert
.get() != NULL
);
3970 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
3971 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
3972 " bumped: " << *serverConnection
);
3974 pinConnection(serverConnection
, NULL
, NULL
, false);
3976 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3978 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3979 Ip::Address intendedDest
;
3980 intendedDest
= sslConnectHostOrIp
.termedBuf();
3981 const bool isConnectRequest
= !port
->flags
.isIntercepted();
3983 // Squid serves its own error page and closes, so we want
3984 // a CN that causes no additional browser errors. Possible
3985 // only when bumping CONNECT with a user-typed address.
3986 if (intendedDest
.isAnyAddr() || isConnectRequest
)
3987 sslCommonName
= sslConnectHostOrIp
;
3988 else if (sslServerBump
->serverCert
.get())
3989 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
3991 // copy error detail from bump-server-first request to CONNECT request
3992 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
3993 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3996 getSslContextStart();
3999 #endif /* USE_SSL */
4001 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4003 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4005 if (!Comm::IsConnOpen(c
)) {
4006 Must(NHttpSockets
> 0); // we tried to open some
4007 --NHttpSockets
; // there will be fewer sockets than planned
4008 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4010 if (!NHttpSockets
) // we could not open any listen sockets at all
4011 fatalf("Unable to open %s",FdNote(portType
));
4018 /// find any unused HttpSockets[] slot and store fd there or return false
4020 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4023 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4024 if ((found
= HttpSockets
[i
] < 0))
4025 HttpSockets
[i
] = conn
->fd
;
4031 clientHttpConnectionsOpen(void)
4033 AnyP::PortCfg
*s
= NULL
;
4035 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4036 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4037 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4038 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4043 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4044 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4045 s
->flags
.tunnelSslBumping
= false;
4048 if (s
->flags
.tunnelSslBumping
&&
4049 !s
->staticSslContext
&&
4050 !s
->generateHostCertificates
) {
4051 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4052 s
->flags
.tunnelSslBumping
= false;
4054 if (s
->flags
.tunnelSslBumping
) {
4055 // Create ssl_ctx cache for this port.
4056 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4060 // Fill out a Comm::Connection which IPC will open as a listener for us
4061 // then pass back when active so we can start a TcpAcceptor subscription.
4062 s
->listenConn
= new Comm::Connection
;
4063 s
->listenConn
->local
= s
->s
;
4064 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4066 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4067 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4068 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4069 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4071 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4072 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4073 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4075 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4082 clientHttpsConnectionsOpen(void)
4086 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4087 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4088 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4089 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4093 if (!s
->staticSslContext
) {
4094 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4095 " due to SSL initialization failure.");
4099 // TODO: merge with similar code in clientHttpConnectionsOpen()
4100 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4101 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4102 s
->flags
.tunnelSslBumping
= false;
4105 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4106 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4107 s
->flags
.tunnelSslBumping
= false;
4110 if (s
->flags
.tunnelSslBumping
) {
4111 // Create ssl_ctx cache for this port.
4112 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4115 // Fill out a Comm::Connection which IPC will open as a listener for us
4116 s
->listenConn
= new Comm::Connection
;
4117 s
->listenConn
->local
= s
->s
;
4118 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4119 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4121 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4122 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4123 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4124 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4126 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4127 ListeningStartedDialer(&clientListenerConnectionOpened
,
4128 s
, Ipc::fdnHttpsSocket
, sub
));
4129 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4130 HttpSockets
[NHttpSockets
] = -1;
4136 /// process clientHttpConnectionsOpen result
4138 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4140 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4144 Must(Comm::IsConnOpen(s
->listenConn
));
4146 // TCP: setup a job to handle accept() with subscribed handler
4147 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4149 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4150 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4151 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4152 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4153 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4154 << FdNote(portTypeNote
) << " connections at "
4157 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4161 clientOpenListenSockets(void)
4163 clientHttpConnectionsOpen();
4165 clientHttpsConnectionsOpen();
4168 if (NHttpSockets
< 1)
4169 fatal("No HTTP or HTTPS ports configured");
4173 clientHttpConnectionsClose(void)
4175 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4176 if (s
->listenConn
!= NULL
) {
4177 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4178 s
->listenConn
->close();
4179 s
->listenConn
= NULL
;
4184 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4185 if (s
->listenConn
!= NULL
) {
4186 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4187 s
->listenConn
->close();
4188 s
->listenConn
= NULL
;
4193 // TODO see if we can drop HttpSockets array entirely */
4194 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4195 HttpSockets
[i
] = -1;
4202 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4204 const char *vary
= request
->vary_headers
;
4205 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4206 #if X_ACCELERATOR_VARY
4209 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4212 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4214 /* Oops... something odd is going on here.. */
4215 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4216 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4217 safe_free(request
->vary_headers
);
4222 /* This is not a varying object */
4226 /* virtual "vary" object found. Calculate the vary key and
4227 * continue the search
4229 vary
= httpMakeVaryMark(request
, entry
->getReply());
4232 request
->vary_headers
= xstrdup(vary
);
4235 /* Ouch.. we cannot handle this kind of variance */
4236 /* XXX This cannot really happen, but just to be complete */
4241 vary
= httpMakeVaryMark(request
, entry
->getReply());
4244 request
->vary_headers
= xstrdup(vary
);
4248 /* Ouch.. we cannot handle this kind of variance */
4249 /* XXX This cannot really happen, but just to be complete */
4251 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4254 /* Oops.. we have already been here and still haven't
4255 * found the requested variant. Bail out
4257 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4258 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4264 ACLFilledChecklist
*
4265 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4267 ConnStateData
* conn
= http
->getConn();
4268 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4269 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4272 * hack for ident ACL. It needs to get full addresses, and a place to store
4273 * the ident result on persistent connections...
4275 /* connection oriented auth also needs these two lines for it's operation. */
4279 CBDATA_CLASS_INIT(ConnStateData
);
4282 ConnStateData::transparent() const
4284 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4288 ConnStateData::reading() const
4290 return reader
!= NULL
;
4294 ConnStateData::stopReading()
4297 comm_read_cancel(clientConnection
->fd
, reader
);
4303 ConnStateData::expectRequestBody(int64_t size
)
4305 bodyPipe
= new BodyPipe(this);
4307 bodyPipe
->setBodySize(size
);
4309 startDechunkingRequest();
4314 ConnStateData::mayNeedToReadMoreBody() const
4317 return 0; // request without a body or read/produced all body bytes
4319 if (!bodyPipe
->bodySizeKnown())
4320 return -1; // probably need to read more, but we cannot be sure
4322 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4323 const int64_t haveAvailable
= static_cast<int64_t>(in
.buf
.length());
4325 if (needToProduce
<= haveAvailable
)
4326 return 0; // we have read what we need (but are waiting for pipe space)
4328 return needToProduce
- haveAvailable
;
4332 ConnStateData::stopReceiving(const char *error
)
4334 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4335 "; old sending error: " <<
4336 (stoppedSending() ? stoppedSending_
: "none"));
4338 if (const char *oldError
= stoppedReceiving()) {
4339 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4340 return; // nothing has changed as far as this connection is concerned
4343 stoppedReceiving_
= error
;
4345 if (const char *sendError
= stoppedSending()) {
4346 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4347 clientConnection
->close();
4352 ConnStateData::expectNoForwarding()
4354 if (bodyPipe
!= NULL
) {
4355 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4356 bodyPipe
->expectNoConsumption();
4360 /// initialize dechunking state
4362 ConnStateData::startDechunkingRequest()
4364 Must(bodyPipe
!= NULL
);
4365 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4366 assert(!in
.bodyParser
);
4367 in
.bodyParser
= new ChunkedCodingParser
;
4370 /// put parsed content into input buffer and clean up
4372 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4374 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4376 if (bodyPipe
!= NULL
) {
4377 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4378 BodyPipe::Pointer myPipe
= bodyPipe
;
4379 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4380 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4382 Must(myPipe
->bodySizeKnown());
4383 ClientSocketContext::Pointer context
= getCurrentContext();
4384 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4385 context
->http
->request
->setContentLength(myPipe
->bodySize());
4389 delete in
.bodyParser
;
4390 in
.bodyParser
= NULL
;
4393 ConnStateData::In::In() :
4398 ConnStateData::In::~In()
4400 delete bodyParser
; // TODO: pool
4404 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4407 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4411 ClientSocketContext::Pointer context
= getCurrentContext();
4412 if (context
!= NULL
) {
4413 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4417 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4418 clientConnection
->close();
4421 /// Our close handler called by Comm when the pinned connection is closed
4423 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4425 // FwdState might repin a failed connection sooner than this close
4426 // callback is called for the failed connection.
4427 assert(pinning
.serverConnection
== io
.conn
);
4428 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4429 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4431 if (sawZeroReply
&& clientConnection
!= NULL
) {
4432 debugs(33, 3, "Closing client connection on pinned zero reply.");
4433 clientConnection
->close();
4438 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4440 char desc
[FD_DESC_SZ
];
4442 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4443 if (pinning
.serverConnection
->fd
== pinServer
->fd
) {
4444 startPinnedConnectionMonitoring();
4449 unpinConnection(); // closes pinned connection, if any, and resets fields
4451 pinning
.serverConnection
= pinServer
;
4453 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4455 // when pinning an SSL bumped connection, the request may be NULL
4456 const char *pinnedHost
= "[unknown]";
4458 pinning
.host
= xstrdup(request
->GetHost());
4459 pinning
.port
= request
->port
;
4460 pinnedHost
= pinning
.host
;
4462 pinning
.port
= pinServer
->remote
.port();
4464 pinning
.pinned
= true;
4466 pinning
.peer
= cbdataReference(aPeer
);
4467 pinning
.auth
= auth
;
4468 char stmp
[MAX_IPSTRLEN
];
4469 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4470 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4471 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4472 clientConnection
->fd
);
4473 fd_note(pinning
.serverConnection
->fd
, desc
);
4475 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4476 pinning
.closeHandler
= JobCallback(33, 5,
4477 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4478 // remember the pinned connection so that cb does not unpin a fresher one
4479 typedef CommCloseCbParams Params
;
4480 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4481 params
.conn
= pinning
.serverConnection
;
4482 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4484 startPinnedConnectionMonitoring();
4487 /// Assign a read handler to an idle pinned connection so that we can detect connection closures.
4489 ConnStateData::startPinnedConnectionMonitoring()
4491 if (pinning
.readHandler
!= NULL
)
4492 return; // already monitoring
4494 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4495 pinning
.readHandler
= JobCallback(33, 3,
4496 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4497 static char unusedBuf
[8];
4498 comm_read(pinning
.serverConnection
, unusedBuf
, sizeof(unusedBuf
), pinning
.readHandler
);
4502 ConnStateData::stopPinnedConnectionMonitoring()
4504 if (pinning
.readHandler
!= NULL
) {
4505 comm_read_cancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4506 pinning
.readHandler
= NULL
;
4510 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4511 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4513 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4515 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4517 if (io
.flag
== COMM_ERR_CLOSING
)
4518 return; // close handler will clean up
4520 // We could use getConcurrentRequestCount(), but this may be faster.
4521 const bool clientIsIdle
= !getCurrentContext();
4523 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4524 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4526 assert(pinning
.serverConnection
== io
.conn
);
4527 pinning
.serverConnection
->close();
4529 // If we are still sending data to the client, do not close now. When we are done sending,
4530 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4531 // However, if we are idle, then we must close to inform the idle client and minimize races.
4532 if (clientIsIdle
&& clientConnection
!= NULL
)
4533 clientConnection
->close();
4536 const Comm::ConnectionPointer
4537 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4539 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4542 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4544 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4546 else if (request
&& pinning
.port
!= request
->port
)
4548 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4550 else if (aPeer
!= pinning
.peer
)
4554 /* The pinning info is not safe, remove any pinning info */
4558 return pinning
.serverConnection
;
4562 ConnStateData::unpinConnection()
4564 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4567 cbdataReferenceDone(pinning
.peer
);
4569 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4570 if (pinning
.closeHandler
!= NULL
) {
4571 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4572 pinning
.closeHandler
= NULL
;
4574 /// also close the server side socket, we should not use it for any future requests...
4575 // TODO: do not close if called from our close handler?
4576 pinning
.serverConnection
->close();
4579 safe_free(pinning
.host
);
4581 pinning
.zeroReply
= false;
4583 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4584 * connection has gone away */