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_reply.h"
90 #include "client_side_request.h"
91 #include "client_side.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/ProxyCerts.h"
140 #include "ssl/context_storage.h"
141 #include "ssl/helper.h"
142 #include "ssl/ServerBump.h"
143 #include "ssl/support.h"
144 #include "ssl/gadgets.h"
147 #include "ssl/crtd_message.h"
148 #include "ssl/certificate_db.h"
162 #define comm_close comm_lingering_close
165 /// dials clientListenerConnectionOpened call
166 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
169 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
170 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
171 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
173 virtual void print(std::ostream
&os
) const {
175 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
178 virtual bool canDial(AsyncCall
&) const { return true; }
179 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
185 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
186 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
187 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
190 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
192 /* our socket-related context */
194 CBDATA_CLASS_INIT(ClientSocketContext
);
197 ClientSocketContext::operator new (size_t byteCount
)
199 /* derived classes with different sizes must implement their own new */
200 assert (byteCount
== sizeof (ClientSocketContext
));
201 CBDATA_INIT_TYPE(ClientSocketContext
);
202 return cbdataAlloc(ClientSocketContext
);
206 ClientSocketContext::operator delete (void *address
)
208 cbdataFree (address
);
211 /* Local functions */
212 /* ClientSocketContext */
213 static ClientSocketContext
*ClientSocketContextNew(const Comm::ConnectionPointer
&clientConn
, ClientHttpRequest
*);
215 static IOCB clientWriteComplete
;
216 static IOCB clientWriteBodyComplete
;
217 static IOACB httpAccept
;
219 static IOACB httpsAccept
;
221 static CTCB clientLifetimeTimeout
;
222 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
223 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, Http::ProtocolVersion
*);
225 static IDCB clientIdentDone
;
227 static CSCB clientSocketRecipient
;
228 static CSD clientSocketDetach
;
229 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
230 static int clientIsContentLengthValid(HttpRequest
* r
);
231 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
233 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
234 static void clientUpdateStatCounters(LogTags logType
);
235 static void clientUpdateHierCounters(HierarchyLogEntry
*);
236 static bool clientPingHasFinished(ping_data
const *aPing
);
237 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
239 static bool connIsUsable(ConnStateData
* conn
);
241 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
242 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
243 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
245 char *skipLeadingSpace(char *aString
);
246 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
248 static ConnStateData
*connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
);
251 ClientSocketContext::getTail() const
253 if (http
->client_stream
.tail
)
254 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
260 ClientSocketContext::getClientReplyContext() const
262 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
266 * This routine should be called to grow the inbuf and then
270 ConnStateData::readSomeData()
275 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
277 if (!maybeMakeSpaceAvailable())
280 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
281 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
282 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
286 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
288 ClientSocketContext::Pointer
*tempContextPointer
;
289 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
290 assert(conn
->getCurrentContext() != NULL
);
291 /* Unlink us from the connection request list */
292 tempContextPointer
= & conn
->currentobject
;
294 while (tempContextPointer
->getRaw()) {
295 if (*tempContextPointer
== this)
298 tempContextPointer
= &(*tempContextPointer
)->next
;
301 assert(tempContextPointer
->getRaw() != NULL
);
302 *tempContextPointer
= next
;
306 ClientSocketContext::~ClientSocketContext()
308 clientStreamNode
*node
= getTail();
311 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
314 /* We are *always* the tail - prevent recursive free */
315 assert(this == streamContext
);
321 deRegisterWithConn();
323 httpRequestFree(http
);
325 /* clean up connection links to us */
326 assert(this != next
.getRaw());
330 ClientSocketContext::registerWithConn()
332 assert (!connRegistered_
);
334 assert (http
->getConn() != NULL
);
335 connRegistered_
= true;
336 http
->getConn()->addContextToQueue(this);
340 ClientSocketContext::deRegisterWithConn()
342 assert (connRegistered_
);
343 removeFromConnectionList(http
->getConn());
344 connRegistered_
= false;
348 ClientSocketContext::connIsFinished()
351 assert (http
->getConn() != NULL
);
352 deRegisterWithConn();
353 /* we can't handle any more stream data - detach */
354 clientStreamDetach(getTail(), http
);
357 ClientSocketContext::ClientSocketContext() : http(NULL
), reply(NULL
), next(NULL
),
359 mayUseConnection_ (false),
360 connRegistered_ (false)
362 memset (reqbuf
, '\0', sizeof (reqbuf
));
365 deferredparams
.node
= NULL
;
366 deferredparams
.rep
= NULL
;
369 ClientSocketContext
*
370 ClientSocketContextNew(const Comm::ConnectionPointer
&client
, ClientHttpRequest
* http
)
372 ClientSocketContext
*newContext
;
373 assert(http
!= NULL
);
374 newContext
= new ClientSocketContext
;
375 newContext
->http
= http
;
376 newContext
->clientConnection
= client
;
381 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
383 const HttpReply::Pointer
rep(msg
.reply
);
386 // apply selected clientReplyContext::buildReplyHeader() mods
387 // it is not clear what headers are required for control messages
388 rep
->header
.removeHopByHopEntries();
389 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
390 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
392 // remember the callback
393 cbControlMsgSent
= msg
.cbSuccess
;
395 MemBuf
*mb
= rep
->pack();
397 debugs(11, 2, "HTTP Client " << clientConnection
);
398 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
400 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
401 CommIoCbPtrFun(&WroteControlMsg
, this));
402 Comm::Write(clientConnection
, mb
, call
);
407 /// called when we wrote the 1xx response
409 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
411 if (errflag
== COMM_ERR_CLOSING
)
414 if (errflag
== COMM_OK
) {
415 ScheduleCallHere(cbControlMsgSent
);
419 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
420 // no error notification: see HttpControlMsg.h for rationale and
421 // note that some errors are detected elsewhere (e.g., close handler)
423 // close on 1xx errors to be conservative and to simplify the code
424 // (if we do not close, we must notify the source of a failure!)
428 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
430 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
432 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
433 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
438 clientIdentDone(const char *ident
, void *data
)
440 ConnStateData
*conn
= (ConnStateData
*)data
;
441 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
446 clientUpdateStatCounters(LogTags logType
)
448 ++statCounter
.client_http
.requests
;
450 if (logTypeIsATcpHit(logType
))
451 ++statCounter
.client_http
.hits
;
453 if (logType
== LOG_TCP_HIT
)
454 ++statCounter
.client_http
.disk_hits
;
455 else if (logType
== LOG_TCP_MEM_HIT
)
456 ++statCounter
.client_http
.mem_hits
;
460 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
462 statCounter
.client_http
.allSvcTime
.count(svc_time
);
464 * The idea here is not to be complete, but to get service times
465 * for only well-defined types. For example, we don't include
466 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
467 * (we *tried* to validate it, but failed).
472 case LOG_TCP_REFRESH_UNMODIFIED
:
473 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
476 case LOG_TCP_IMS_HIT
:
477 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
482 case LOG_TCP_MEM_HIT
:
484 case LOG_TCP_OFFLINE_HIT
:
485 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
490 case LOG_TCP_CLIENT_REFRESH_MISS
:
491 statCounter
.client_http
.missSvcTime
.count(svc_time
);
495 /* make compiler warnings go away */
501 clientPingHasFinished(ping_data
const *aPing
)
503 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
510 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
514 switch (someEntry
->code
) {
515 #if USE_CACHE_DIGESTS
520 ++ statCounter
.cd
.times_used
;
528 case FIRST_PARENT_MISS
:
530 case CLOSEST_PARENT_MISS
:
531 ++ statCounter
.icp
.times_used
;
532 i
= &someEntry
->ping
;
534 if (clientPingHasFinished(i
))
535 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
538 ++ statCounter
.icp
.query_timeouts
;
545 ++ statCounter
.netdb
.times_used
;
555 ClientHttpRequest::updateCounters()
557 clientUpdateStatCounters(logType
);
559 if (request
->errType
!= ERR_NONE
)
560 ++ statCounter
.client_http
.errors
;
562 clientUpdateStatHistCounters(logType
,
563 tvSubMsec(start_time
, current_time
));
565 clientUpdateHierCounters(&request
->hier
);
569 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
572 assert(aLogEntry
!= NULL
);
574 if (Config
.onoff
.log_mime_hdrs
) {
578 packerToMemInit(&p
, &mb
);
579 request
->header
.packInto(&p
);
580 //This is the request after adaptation or redirection
581 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
583 // the virgin request is saved to aLogEntry->request
584 if (aLogEntry
->request
) {
587 packerToMemInit(&p
, &mb
);
588 aLogEntry
->request
->header
.packInto(&p
);
589 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
593 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
597 packerToMemInit(&p
, &mb
);
598 ah
->lastMeta
.packInto(&p
);
599 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
608 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
610 aLogEntry
->icap
.processingTime
= ih
->processingTime();
613 aLogEntry
->http
.method
= request
->method
;
614 aLogEntry
->http
.version
= request
->http_ver
;
615 aLogEntry
->hier
= request
->hier
;
616 if (request
->content_length
> 0) // negative when no body or unknown length
617 aLogEntry
->cache
.requestSize
+= request
->content_length
;
618 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
620 // Adapted request, if any, inherits and then collects all the stats, but
621 // the virgin request gets logged instead; copy the stats to log them.
622 // TODO: avoid losses by keeping these stats in a shared history object?
623 if (aLogEntry
->request
) {
624 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
625 aLogEntry
->request
->errType
= request
->errType
;
626 aLogEntry
->request
->errDetail
= request
->errDetail
;
631 ClientHttpRequest::logRequest()
633 if (!out
.size
&& !logType
)
634 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
636 al
->icp
.opcode
= ICP_INVALID
;
638 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
641 al
->http
.code
= al
->reply
->sline
.status();
642 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
643 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
644 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
645 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
648 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
650 if (loggingEntry() && loggingEntry()->mem_obj
)
651 al
->cache
.objectSize
= loggingEntry()->contentLen();
653 al
->cache
.caddr
.setNoAddr();
655 if (getConn() != NULL
) {
656 al
->cache
.caddr
= getConn()->log_addr
;
657 al
->cache
.port
= cbdataReference(getConn()->port
);
660 al
->cache
.requestSize
= req_sz
;
661 al
->cache
.requestHeadersSize
= req_sz
;
663 al
->cache
.replySize
= out
.size
;
664 al
->cache
.replyHeadersSize
= out
.headers_sz
;
666 al
->cache
.highOffset
= out
.offset
;
668 al
->cache
.code
= logType
;
670 al
->cache
.msec
= tvSubMsec(start_time
, current_time
);
673 prepareLogWithRequestDetails(request
, al
);
675 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
676 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
680 /* This is broken. Fails if the connection has been closed. Needs
681 * to snarf the ssl details some place earlier..
683 if (getConn() != NULL
)
684 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
689 // The al->notes and request->notes must point to the same object.
690 // Enable the following assertion to check for possible bugs.
691 // assert(request->notes == al->notes);
692 typedef Notes::iterator ACAMLI
;
693 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
694 if (const char *value
= (*i
)->match(request
, al
->reply
)) {
695 NotePairs
¬es
= SyncNotes(*al
, *request
);
696 notes
.add((*i
)->key
.termedBuf(), value
);
697 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
701 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.log
, this);
704 checklist
->reply
= al
->reply
;
705 HTTPMSGLOCK(checklist
->reply
);
708 if (!Config
.accessList
.log
|| checklist
->fastCheck() == ACCESS_ALLOWED
) {
710 al
->adapted_request
= request
;
711 HTTPMSGLOCK(al
->adapted_request
);
713 accessLogLog(al
, checklist
);
717 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
718 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
725 ClientHttpRequest::freeResources()
729 safe_free(redirect
.location
);
730 range_iter
.boundary
.clean();
731 HTTPMSGUNLOCK(request
);
733 if (client_stream
.tail
)
734 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
738 httpRequestFree(void *data
)
740 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
741 assert(http
!= NULL
);
746 ConnStateData::areAllContextsForThisConnection() const
748 assert(this != NULL
);
749 ClientSocketContext::Pointer context
= getCurrentContext();
751 while (context
.getRaw()) {
752 if (context
->http
->getConn() != this)
755 context
= context
->next
;
762 ConnStateData::freeAllContexts()
764 ClientSocketContext::Pointer context
;
766 while ((context
= getCurrentContext()).getRaw() != NULL
) {
767 assert(getCurrentContext() !=
768 getCurrentContext()->next
);
769 context
->connIsFinished();
770 assert (context
!= currentobject
);
774 /// propagates abort event to all contexts
776 ConnStateData::notifyAllContexts(int xerrno
)
778 typedef ClientSocketContext::Pointer CSCP
;
779 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
780 c
->noteIoError(xerrno
);
783 /* This is a handler normally called by comm_close() */
784 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
786 deleteThis("ConnStateData::connStateClosed");
791 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
795 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
801 // clobered with self-pointer
802 // NP: something nasty is going on in Squid, but harmless.
804 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
809 * Connection-auth relies on a single set of credentials being preserved
810 * for all requests on a connection once they have been setup.
811 * There are several things which need to happen to preserve security
812 * when connection-auth credentials change unexpectedly or are unset.
814 * 1) auth helper released from any active state
816 * They can only be reserved by a handshake process which this
817 * connection can now never complete.
818 * This prevents helpers hanging when their connections close.
820 * 2) pinning is expected to be removed and server conn closed
822 * The upstream link is authenticated with the same credentials.
823 * Expecting the same level of consistency we should have received.
824 * This prevents upstream being faced with multiple or missing
825 * credentials after authentication.
826 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
827 * we just trigger that cleanup here via comm_reset_close() or
828 * ConnStateData::stopReceiving()
830 * 3) the connection needs to close.
832 * This prevents attackers injecting requests into a connection,
833 * or gateways wrongly multiplexing users into a single connection.
835 * When credentials are missing closure needs to follow an auth
836 * challenge for best recovery by the client.
838 * When credentials change there is nothing we can do but abort as
839 * fast as possible. Sending TCP RST instead of an HTTP response
840 * is the best-case action.
843 // clobbered with nul-pointer
845 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
846 auth_
->releaseAuthServer();
848 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
849 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
850 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
851 stopReceiving("connection-auth removed");
855 // clobbered with alternative credentials
857 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
858 auth_
->releaseAuthServer();
860 // this is a fatal type of problem.
861 // Close the connection immediately with TCP RST to abort all traffic flow
862 comm_reset_close(clientConnection
);
870 // cleans up before destructor is called
872 ConnStateData::swanSong()
874 debugs(33, 2, HERE
<< clientConnection
);
875 flags
.readMore
= false;
876 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
877 assert(areAllContextsForThisConnection());
882 if (Comm::IsConnOpen(clientConnection
))
883 clientConnection
->close();
884 clientConnection
= NULL
;
887 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
888 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
891 BodyProducer::swanSong();
892 flags
.swanSang
= true;
896 ConnStateData::isOpen() const
898 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
899 Comm::IsConnOpen(clientConnection
) &&
900 !fd_table
[clientConnection
->fd
].closing();
903 ConnStateData::~ConnStateData()
905 assert(this != NULL
);
906 debugs(33, 3, HERE
<< clientConnection
);
909 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
912 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
914 cbdataReferenceDone(port
);
916 if (bodyPipe
!= NULL
)
917 stopProducingFor(bodyPipe
, false);
920 delete sslServerBump
;
925 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
926 * This is the client-side persistent connection flag. We need
927 * to set this relatively early in the request processing
928 * to handle hacks for broken servers and clients.
931 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
933 HttpRequest
*request
= http
->request
;
935 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
936 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
937 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
938 RequestMethodStr(request
->method
));
940 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
941 request
->flags
.proxyKeepalive
= request
->persistent();
945 clientIsContentLengthValid(HttpRequest
* r
)
947 switch (r
->method
.id()) {
949 case Http::METHOD_GET
:
951 case Http::METHOD_HEAD
:
952 /* We do not want to see a request entity on GET/HEAD requests */
953 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
956 /* For other types of requests we don't care */
964 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
966 if (Config
.maxRequestBodySize
&&
967 bodyLength
> Config
.maxRequestBodySize
)
968 return 1; /* too large */
975 connIsUsable(ConnStateData
* conn
)
977 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
985 // careful: the "current" context may be gone if we wrote an early response
986 ClientSocketContext::Pointer
987 ConnStateData::getCurrentContext() const
990 return currentobject
;
994 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
996 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
997 assert(flags
.deferred
== 0);
999 deferredparams
.node
= node
;
1000 deferredparams
.rep
= rep
;
1001 deferredparams
.queuedBuffer
= receivedData
;
1006 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
1008 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
1015 ClientSocketContext::startOfOutput() const
1017 return http
->out
.size
== 0;
1021 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
1023 /*the size of available range can always fit in a size_t type*/
1024 size_t maximum
= (size_t)available
.size();
1026 if (!http
->request
->range
)
1029 assert (canPackMoreRanges());
1031 if (http
->range_iter
.debt() == -1)
1034 assert (http
->range_iter
.debt() > 0);
1036 /* TODO this + the last line could be a range intersection calculation */
1037 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
1040 return min(http
->range_iter
.debt(), (int64_t)maximum
);
1044 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
1046 http
->out
.offset
+= bytes
;
1048 if (!http
->request
->range
)
1051 if (http
->range_iter
.debt() != -1) {
1052 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
1053 assert (http
->range_iter
.debt() >= 0);
1056 /* debt() always stops at -1, below that is a bug */
1057 assert (http
->range_iter
.debt() >= -1);
1061 ClientHttpRequest::multipartRangeRequest() const
1063 return request
->multipartRangeRequest();
1067 ClientSocketContext::multipartRangeRequest() const
1069 return http
->multipartRangeRequest();
1073 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1075 assert(rep
== NULL
);
1077 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1078 size_t length
= lengthToSend(bodyData
.range());
1079 noteSentBodyBytes (length
);
1080 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1081 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1082 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1088 if (multipartRangeRequest())
1089 packRange(bodyData
, &mb
);
1091 packChunk(bodyData
, mb
);
1093 if (mb
.contentSize()) {
1095 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1096 CommIoCbPtrFun(clientWriteComplete
, this));
1097 Comm::Write(clientConnection
, &mb
, call
);
1099 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1103 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1104 * if bodyData is empty.
1107 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1109 const uint64_t length
=
1110 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1111 noteSentBodyBytes(length
);
1113 mb
.Printf("%" PRIX64
"\r\n", length
);
1114 mb
.append(bodyData
.data
, length
);
1118 /** put terminating boundary for multiparts */
1120 clientPackTermBound(String boundary
, MemBuf
* mb
)
1122 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1123 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1126 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1128 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1130 HttpHeader
hdr(hoReply
);
1136 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1137 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1138 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1140 /* stuff the header with required entries and pack it */
1142 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1143 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1145 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1147 packerToMemInit(&p
, mb
);
1155 /* append <crlf> (we packed a header, not a reply) */
1160 * extracts a "range" from *buf and appends them to mb, updating
1161 * all offsets and such.
1164 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1166 HttpHdrRangeIter
* i
= &http
->range_iter
;
1167 Range
<int64_t> available (source
.range());
1168 char const *buf
= source
.data
;
1170 while (i
->currentSpec() && available
.size()) {
1171 const size_t copy_sz
= lengthToSend(available
);
1175 * intersection of "have" and "need" ranges must not be empty
1177 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1178 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1181 * put boundary and headers at the beginning of a range in a
1185 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1186 assert(http
->memObject());
1188 http
->memObject()->getReply(), /* original reply */
1189 i
->currentSpec(), /* current range */
1190 i
->boundary
, /* boundary, the same for all */
1197 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1199 noteSentBodyBytes (copy_sz
);
1201 mb
->append(buf
, copy_sz
);
1206 available
.start
+= copy_sz
;
1212 if (!canPackMoreRanges()) {
1213 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1216 /* put terminating boundary for multiparts */
1217 clientPackTermBound(i
->boundary
, mb
);
1222 int64_t nextOffset
= getNextRangeOffset();
1224 assert (nextOffset
>= http
->out
.offset
);
1226 int64_t skip
= nextOffset
- http
->out
.offset
;
1228 /* adjust for not to be transmitted bytes */
1229 http
->out
.offset
= nextOffset
;
1231 if (available
.size() <= (uint64_t)skip
)
1234 available
.start
+= skip
;
1243 /** returns expected content length for multi-range replies
1244 * note: assumes that httpHdrRangeCanonize has already been called
1245 * warning: assumes that HTTP headers for individual ranges at the
1246 * time of the actuall assembly will be exactly the same as
1247 * the headers when clientMRangeCLen() is called */
1249 ClientHttpRequest::mRangeCLen()
1254 assert(memObject());
1257 HttpHdrRange::iterator pos
= request
->range
->begin();
1259 while (pos
!= request
->range
->end()) {
1260 /* account for headers for this range */
1262 clientPackRangeHdr(memObject()->getReply(),
1263 *pos
, range_iter
.boundary
, &mb
);
1266 /* account for range content */
1267 clen
+= (*pos
)->length
;
1269 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1273 /* account for the terminating boundary */
1276 clientPackTermBound(range_iter
.boundary
, &mb
);
1286 * returns true if If-Range specs match reply, false otherwise
1289 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1291 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1292 /* check for parsing falure */
1299 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1300 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1301 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1304 return 0; /* entity has no etag to compare with! */
1306 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1307 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1308 return 0; /* must use strong validator for sub-range requests */
1311 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1314 /* got modification time? */
1315 if (spec
.time
>= 0) {
1316 return http
->storeEntry()->lastmod
<= spec
.time
;
1319 assert(0); /* should not happen */
1324 * generates a "unique" boundary string for multipart responses
1325 * the caller is responsible for cleaning the string */
1327 ClientHttpRequest::rangeBoundaryStr() const
1331 String
b(APP_FULLNAME
);
1333 key
= storeEntry()->getMD5Text();
1334 b
.append(key
, strlen(key
));
1338 /** adds appropriate Range headers if needed */
1340 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1342 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1343 const char *range_err
= NULL
;
1344 HttpRequest
*request
= http
->request
;
1345 assert(request
->range
);
1346 /* check if we still want to do ranges */
1348 int64_t roffLimit
= request
->getRangeOffsetLimit();
1351 range_err
= "no [parse-able] reply";
1352 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1353 range_err
= "wrong status code";
1354 else if (hdr
->has(HDR_CONTENT_RANGE
))
1355 range_err
= "origin server does ranges";
1356 else if (rep
->content_length
< 0)
1357 range_err
= "unknown length";
1358 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1359 range_err
= "INCONSISTENT length"; /* a bug? */
1361 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1364 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1365 range_err
= "If-Range match failed";
1366 else if (!http
->request
->range
->canonize(rep
))
1367 range_err
= "canonization failed";
1368 else if (http
->request
->range
->isComplex())
1369 range_err
= "too complex range header";
1370 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1371 range_err
= "range outside range_offset_limit";
1373 /* get rid of our range specs on error */
1375 /* XXX We do this here because we need canonisation etc. However, this current
1376 * code will lead to incorrect store offset requests - the store will have the
1377 * offset data, but we won't be requesting it.
1378 * So, we can either re-request, or generate an error
1380 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1381 delete http
->request
->range
;
1382 http
->request
->range
= NULL
;
1384 /* XXX: TODO: Review, this unconditional set may be wrong. */
1385 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1386 // web server responded with a valid, but unexpected range.
1387 // will (try-to) forward as-is.
1388 //TODO: we should cope with multirange request/responses
1389 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1390 request
->range
->contains(rep
->content_range
->spec
) :
1392 const int spec_count
= http
->request
->range
->specs
.count
;
1393 int64_t actual_clen
= -1;
1395 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1396 spec_count
<< " virgin clen: " << rep
->content_length
);
1397 assert(spec_count
> 0);
1398 /* append appropriate header(s) */
1400 if (spec_count
== 1) {
1401 if (!replyMatchRequest
) {
1402 hdr
->delById(HDR_CONTENT_RANGE
);
1403 hdr
->putContRange(rep
->content_range
);
1404 actual_clen
= rep
->content_length
;
1405 //http->range_iter.pos = rep->content_range->spec.begin();
1406 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1407 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1410 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1412 /* append Content-Range */
1414 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1415 /* No content range, so this was a full object we are
1418 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1421 /* set new Content-Length to the actual number of bytes
1422 * transmitted in the message-body */
1423 actual_clen
= (*pos
)->length
;
1427 /* generate boundary string */
1428 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1429 /* delete old Content-Type, add ours */
1430 hdr
->delById(HDR_CONTENT_TYPE
);
1431 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1432 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1433 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1434 /* Content-Length is not required in multipart responses
1435 * but it is always nice to have one */
1436 actual_clen
= http
->mRangeCLen();
1437 /* http->out needs to start where we want data at */
1438 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1441 /* replace Content-Length header */
1442 assert(actual_clen
>= 0);
1444 hdr
->delById(HDR_CONTENT_LENGTH
);
1446 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1448 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1450 /* And start the range iter off */
1451 http
->range_iter
.updateSpec();
1456 ClientSocketContext::prepareReply(HttpReply
* rep
)
1460 if (http
->request
->range
)
1461 buildRangeHeader(rep
);
1465 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1469 MemBuf
*mb
= rep
->pack();
1471 // dump now, so we dont output any body.
1472 debugs(11, 2, "HTTP Client " << clientConnection
);
1473 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1475 /* Save length of headers for persistent conn checks */
1476 http
->out
.headers_sz
= mb
->contentSize();
1479 headersLog(0, 0, http
->request
->method
, rep
);
1482 if (bodyData
.data
&& bodyData
.length
) {
1483 if (multipartRangeRequest())
1484 packRange(bodyData
, mb
);
1485 else if (http
->request
->flags
.chunkedReply
) {
1486 packChunk(bodyData
, *mb
);
1488 size_t length
= lengthToSend(bodyData
.range());
1489 noteSentBodyBytes (length
);
1491 mb
->append(bodyData
.data
, length
);
1496 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1497 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1498 CommIoCbPtrFun(clientWriteComplete
, this));
1499 Comm::Write(clientConnection
, mb
, call
);
1504 * Write a chunk of data to a client socket. If the reply is present,
1505 * send the reply headers down the wire too, and clean them up when
1508 * The request is one backed by a connection, not an internal request.
1509 * data context is not NULL
1510 * There are no more entries in the stream chain.
1513 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1514 HttpReply
* rep
, StoreIOBuffer receivedData
)
1516 /* Test preconditions */
1517 assert(node
!= NULL
);
1518 PROF_start(clientSocketRecipient
);
1519 /* TODO: handle this rather than asserting
1520 * - it should only ever happen if we cause an abort and
1521 * the callback chain loops back to here, so we can simply return.
1522 * However, that itself shouldn't happen, so it stays as an assert for now.
1524 assert(cbdataReferenceValid(node
));
1525 assert(node
->node
.next
== NULL
);
1526 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1527 assert(context
!= NULL
);
1528 assert(connIsUsable(http
->getConn()));
1530 /* TODO: check offset is what we asked for */
1532 if (context
!= http
->getConn()->getCurrentContext()) {
1533 context
->deferRecipientForLater(node
, rep
, receivedData
);
1534 PROF_stop(clientSocketRecipient
);
1538 // After sending Transfer-Encoding: chunked (at least), always send
1539 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1540 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1541 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1542 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1543 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1544 PROF_stop(clientSocketRecipient
);
1548 if (!context
->startOfOutput())
1549 context
->sendBody(rep
, receivedData
);
1552 http
->al
->reply
= rep
;
1553 HTTPMSGLOCK(http
->al
->reply
);
1554 context
->sendStartOfMessage(rep
, receivedData
);
1557 PROF_stop(clientSocketRecipient
);
1561 * Called when a downstream node is no longer interested in
1562 * our data. As we are a terminal node, this means on aborts
1566 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1568 /* Test preconditions */
1569 assert(node
!= NULL
);
1570 /* TODO: handle this rather than asserting
1571 * - it should only ever happen if we cause an abort and
1572 * the callback chain loops back to here, so we can simply return.
1573 * However, that itself shouldn't happen, so it stays as an assert for now.
1575 assert(cbdataReferenceValid(node
));
1576 /* Set null by ContextFree */
1577 assert(node
->node
.next
== NULL
);
1578 /* this is the assert discussed above */
1579 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1580 /* We are only called when the client socket shutsdown.
1581 * Tell the prev pipeline member we're finished
1583 clientStreamDetach(node
, http
);
1587 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1589 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1590 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1594 ConnStateData::readNextRequest()
1596 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1598 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1600 * Set the timeout BEFORE calling clientReadRequest().
1602 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1603 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1604 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1605 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1608 /** Please don't do anything with the FD past here! */
1612 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1614 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1616 /** If the client stream is waiting on a socket write to occur, then */
1618 if (deferredRequest
->flags
.deferred
) {
1619 /** NO data is allowed to have been sent. */
1620 assert(deferredRequest
->http
->out
.size
== 0);
1622 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1623 deferredRequest
->http
,
1624 deferredRequest
->deferredparams
.rep
,
1625 deferredRequest
->deferredparams
.queuedBuffer
);
1628 /** otherwise, the request is still active in a callbacksomewhere,
1633 /// called when we have successfully finished writing the response
1635 ClientSocketContext::keepaliveNextRequest()
1637 ConnStateData
* conn
= http
->getConn();
1639 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1642 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1643 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1644 conn
->clientConnection
->close();
1649 * We are done with the response, and we are either still receiving request
1650 * body (early response!) or have already stopped receiving anything.
1652 * If we are still receiving, then clientParseRequest() below will fail.
1653 * (XXX: but then we will call readNextRequest() which may succeed and
1654 * execute a smuggled request as we are not done with the current request).
1656 * If we stopped because we got everything, then try the next request.
1658 * If we stopped receiving because of an error, then close now to avoid
1659 * getting stuck and to prevent accidental request smuggling.
1662 if (const char *reason
= conn
->stoppedReceiving()) {
1663 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1664 conn
->clientConnection
->close();
1669 * Attempt to parse a request from the request buffer.
1670 * If we've been fed a pipelined request it may already
1671 * be in our read buffer.
1674 * This needs to fall through - if we're unlucky and parse the _last_ request
1675 * from our read buffer we may never re-register for another client read.
1678 if (conn
->clientParseRequests()) {
1679 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1683 * Either we need to kick-start another read or, if we have
1684 * a half-closed connection, kill it after the last request.
1685 * This saves waiting for half-closed connections to finished being
1686 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1687 * the keepalive "Waiting for next request" state.
1689 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1690 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1691 conn
->clientConnection
->close();
1695 ClientSocketContext::Pointer deferredRequest
;
1698 * At this point we either have a parsed request (which we've
1699 * kicked off the processing for) or not. If we have a deferred
1700 * request (parsed but deferred for pipeling processing reasons)
1701 * then look at processing it. If not, simply kickstart
1705 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1706 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1707 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1708 } else if (conn
->flags
.readMore
) {
1709 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1710 conn
->readNextRequest();
1712 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1713 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1718 clientUpdateSocketStats(LogTags logType
, size_t size
)
1723 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1725 if (logTypeIsATcpHit(logType
))
1726 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1730 * increments iterator "i"
1731 * used by clientPackMoreRanges
1733 \retval true there is still data available to pack more ranges
1737 ClientSocketContext::canPackMoreRanges() const
1739 /** first update iterator "i" if needed */
1741 if (!http
->range_iter
.debt()) {
1742 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1744 if (http
->range_iter
.pos
.incrementable())
1745 ++http
->range_iter
.pos
;
1747 http
->range_iter
.updateSpec();
1750 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1752 /* paranoid sync condition */
1753 /* continue condition: need_more_data */
1754 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1755 return http
->range_iter
.currentSpec() ? true : false;
1759 ClientSocketContext::getNextRangeOffset() const
1761 if (http
->request
->range
) {
1762 /* offset in range specs does not count the prefix of an http msg */
1763 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1764 /* check: reply was parsed and range iterator was initialized */
1765 assert(http
->range_iter
.valid
);
1766 /* filter out data according to range specs */
1767 assert (canPackMoreRanges());
1769 int64_t start
; /* offset of still missing data */
1770 assert(http
->range_iter
.currentSpec());
1771 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1772 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1773 debugs(33, 3, "clientPackMoreRanges: out:"
1774 " start: " << start
<<
1775 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1776 " [" << http
->range_iter
.currentSpec()->offset
<<
1777 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1778 " len: " << http
->range_iter
.currentSpec()->length
<<
1779 " debt: " << http
->range_iter
.debt());
1780 if (http
->range_iter
.currentSpec()->length
!= -1)
1781 assert(http
->out
.offset
<= start
); /* we did not miss it */
1786 } else if (reply
&& reply
->content_range
) {
1787 /* request does not have ranges, but reply does */
1788 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1789 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1791 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1794 return http
->out
.offset
;
1798 ClientSocketContext::pullData()
1800 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1802 /* More data will be coming from the stream. */
1803 StoreIOBuffer readBuffer
;
1804 /* XXX: Next requested byte in the range sequence */
1805 /* XXX: length = getmaximumrangelenfgth */
1806 readBuffer
.offset
= getNextRangeOffset();
1807 readBuffer
.length
= HTTP_REQBUF_SZ
;
1808 readBuffer
.data
= reqbuf
;
1809 /* we may note we have reached the end of the wanted ranges */
1810 clientStreamRead(getTail(), http
, readBuffer
);
1813 clientStream_status_t
1814 ClientSocketContext::socketState()
1816 switch (clientStreamStatus(getTail(), http
)) {
1819 /* check for range support ending */
1821 if (http
->request
->range
) {
1822 /* check: reply was parsed and range iterator was initialized */
1823 assert(http
->range_iter
.valid
);
1824 /* filter out data according to range specs */
1826 if (!canPackMoreRanges()) {
1827 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1828 "range sequence on " << clientConnection
);
1830 if (http
->request
->flags
.proxyKeepalive
)
1831 return STREAM_COMPLETE
;
1833 return STREAM_UNPLANNED_COMPLETE
;
1835 } else if (reply
&& reply
->content_range
) {
1836 /* reply has content-range, but Squid is not managing ranges */
1837 const int64_t &bytesSent
= http
->out
.offset
;
1838 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1840 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1841 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1842 reply
->content_range
->spec
.offset
<< ")");
1844 // did we get at least what we expected, based on range specs?
1846 if (bytesSent
== bytesExpected
) { // got everything
1847 if (http
->request
->flags
.proxyKeepalive
)
1848 return STREAM_COMPLETE
;
1850 return STREAM_UNPLANNED_COMPLETE
;
1853 // The logic below is not clear: If we got more than we
1854 // expected why would persistency matter? Should not this
1855 // always be an error?
1856 if (bytesSent
> bytesExpected
) { // got extra
1857 if (http
->request
->flags
.proxyKeepalive
)
1858 return STREAM_COMPLETE
;
1860 return STREAM_UNPLANNED_COMPLETE
;
1863 // did not get enough yet, expecting more
1868 case STREAM_COMPLETE
:
1869 return STREAM_COMPLETE
;
1871 case STREAM_UNPLANNED_COMPLETE
:
1872 return STREAM_UNPLANNED_COMPLETE
;
1875 return STREAM_FAILED
;
1878 fatal ("unreachable code\n");
1883 * A write has just completed to the client, or we have just realised there is
1884 * no more data to send.
1887 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1889 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1890 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1893 /// remembers the abnormal connection termination for logging purposes
1895 ClientSocketContext::noteIoError(const int xerrno
)
1898 if (xerrno
== ETIMEDOUT
)
1899 http
->al
->http
.timedout
= true;
1900 else // even if xerrno is zero (which means read abort/eof)
1901 http
->al
->http
.aborted
= true;
1906 ClientSocketContext::doClose()
1908 clientConnection
->close();
1911 /// called when we encounter a response-related error
1913 ClientSocketContext::initiateClose(const char *reason
)
1915 http
->getConn()->stopSending(reason
); // closes ASAP
1919 ConnStateData::stopSending(const char *error
)
1921 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1922 "; old receiving error: " <<
1923 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1925 if (const char *oldError
= stoppedSending()) {
1926 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1927 return; // nothing has changed as far as this connection is concerned
1929 stoppedSending_
= error
;
1931 if (!stoppedReceiving()) {
1932 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1933 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1934 " request body bytes with " << in
.notYetUsed
<< " unused");
1935 return; // wait for the request receiver to finish reading
1939 clientConnection
->close();
1943 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1945 const StoreEntry
*entry
= http
->storeEntry();
1946 http
->out
.size
+= size
;
1947 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1948 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1949 (entry
? entry
->objectLen() : 0));
1950 clientUpdateSocketStats(http
->logType
, size
);
1952 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1954 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1957 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1958 initiateClose("failure or true request status");
1959 /* Do we leak here ? */
1963 switch (socketState()) {
1969 case STREAM_COMPLETE
:
1970 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1971 keepaliveNextRequest();
1974 case STREAM_UNPLANNED_COMPLETE
:
1975 initiateClose("STREAM_UNPLANNED_COMPLETE");
1979 initiateClose("STREAM_FAILED");
1983 fatal("Hit unreachable code in clientWriteComplete\n");
1987 SQUIDCEXTERN CSR clientGetMoreData
;
1988 SQUIDCEXTERN CSS clientReplyStatus
;
1989 SQUIDCEXTERN CSD clientReplyDetach
;
1991 static ClientSocketContext
*
1992 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1994 ClientHttpRequest
*http
;
1995 ClientSocketContext
*context
;
1996 StoreIOBuffer tempBuffer
;
1997 http
= new ClientHttpRequest(csd
);
1998 http
->req_sz
= csd
->in
.notYetUsed
;
1999 http
->uri
= xstrdup(uri
);
2000 setLogUri (http
, uri
);
2001 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
2002 tempBuffer
.data
= context
->reqbuf
;
2003 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2004 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2005 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
2006 clientSocketDetach
, context
, tempBuffer
);
2011 skipLeadingSpace(char *aString
)
2013 char *result
= aString
;
2015 while (xisspace(*aString
))
2022 * 'end' defaults to NULL for backwards compatibility
2023 * remove default value if we ever get rid of NULL-terminated
2027 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
2030 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
2034 for (; end
> uriAndHTTPVersion
; --end
) {
2035 if (*end
== '\n' || *end
== '\r')
2038 if (xisspace(*end
)) {
2039 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2050 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2052 safe_free(http
->log_uri
);
2055 // The uri is already clean just dump it.
2056 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2059 switch (Config
.uri_whitespace
) {
2060 case URI_WHITESPACE_ALLOW
:
2061 flags
|= RFC1738_ESCAPE_NOSPACE
;
2063 case URI_WHITESPACE_ENCODE
:
2064 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2065 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2068 case URI_WHITESPACE_CHOP
: {
2069 flags
|= RFC1738_ESCAPE_NOSPACE
;
2070 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2071 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2072 int pos
= strcspn(http
->log_uri
, w_space
);
2073 http
->log_uri
[pos
] = '\0';
2077 case URI_WHITESPACE_DENY
:
2078 case URI_WHITESPACE_STRIP
:
2081 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2085 if (!xisspace(*t
)) {
2092 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2101 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2103 int vhost
= conn
->port
->vhost
;
2104 int vport
= conn
->port
->vport
;
2106 char ipbuf
[MAX_IPSTRLEN
];
2108 http
->flags
.accel
= true;
2110 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2112 if (strncasecmp(url
, "cache_object://", 15) == 0)
2113 return; /* already in good shape */
2116 if (conn
->port
->vhost
)
2117 return; /* already in good shape */
2119 /* else we need to ignore the host name */
2120 url
= strstr(url
, "//");
2122 #if SHOULD_REJECT_UNKNOWN_URLS
2125 hp
->request_parse_status
= Http::scBadRequest
;
2126 return parseHttpRequestAbort(conn
, "error:invalid-request");
2131 url
= strchr(url
+ 2, '/');
2138 vport
= http
->getConn()->clientConnection
->local
.port();
2140 const bool switchedToHttps
= conn
->switchedToHttps();
2141 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2142 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2143 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2148 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2149 strncpy(thost
, host
, (t
-host
));
2150 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2153 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2156 } // else nothing to alter port-wise.
2157 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2159 http
->uri
= (char *)xcalloc(url_sz
, 1);
2160 const char *protocol
= switchedToHttps
?
2161 "https" : conn
->port
->protocol
;
2162 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2163 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2164 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2165 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2166 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2167 strlen(conn
->port
->defaultsite
);
2168 http
->uri
= (char *)xcalloc(url_sz
, 1);
2172 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2174 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2175 conn
->port
->protocol
, conn
->port
->defaultsite
, vportStr
, url
);
2176 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2177 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2178 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2179 /* Put the local socket IP address as the hostname, with whatever vport we found */
2180 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2181 http
->uri
= (char *)xcalloc(url_sz
, 1);
2182 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2183 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2184 http
->getConn()->port
->protocol
,
2186 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2191 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2194 char ipbuf
[MAX_IPSTRLEN
];
2197 return; /* already in good shape */
2199 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2201 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2202 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2204 http
->uri
= (char *)xcalloc(url_sz
, 1);
2205 snprintf(http
->uri
, url_sz
, "%s://%s%s", conn
->port
->protocol
, host
, url
);
2206 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2208 /* Put the local socket IP address as the hostname. */
2209 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2210 http
->uri
= (char *)xcalloc(url_sz
, 1);
2211 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2212 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2213 http
->getConn()->port
->protocol
,
2214 ipbuf
, http
->getConn()->clientConnection
->local
.port(), url
);
2215 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2219 /** Parse an HTTP request
2221 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2222 * to 1 if the request was correctly parsed.
2223 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2224 * \param[in] hp an HttpParser
2225 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2226 * Pointed-to value will be set to Http::METHOD_NONE in case of
2228 * \param[out] http_ver will be set as a side-effect of the parsing
2229 * \return NULL on incomplete requests,
2230 * a ClientSocketContext structure on success or failure.
2232 static ClientSocketContext
*
2233 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2235 char *req_hdr
= NULL
;
2238 ClientHttpRequest
*http
;
2239 ClientSocketContext
*result
;
2240 StoreIOBuffer tempBuffer
;
2243 /* pre-set these values to make aborting simpler */
2244 *method_p
= Http::METHOD_NONE
;
2246 /* NP: don't be tempted to move this down or remove again.
2247 * It's the only DDoS protection old-String has against long URL */
2248 if ( hp
->bufsiz
<= 0) {
2249 debugs(33, 5, "Incomplete request, waiting for end of request line");
2251 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2252 debugs(33, 5, "parseHttpRequest: Too large request");
2253 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2254 return parseHttpRequestAbort(csd
, "error:request-too-large");
2257 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2258 r
= HttpParserParseReqLine(hp
);
2261 debugs(33, 5, "Incomplete request, waiting for end of request line");
2266 return parseHttpRequestAbort(csd
, "error:invalid-request");
2269 /* Request line is valid here .. */
2270 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2272 /* This call scans the entire request, not just the headers */
2273 if (hp
->req
.v_maj
> 0) {
2274 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2275 debugs(33, 5, "Incomplete request, waiting for end of headers");
2279 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2280 req_sz
= HttpParserReqSz(hp
);
2283 /* We know the whole request is in hp->buf now */
2285 assert(req_sz
<= (size_t) hp
->bufsiz
);
2287 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2288 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2291 hp
->hdr_end
= req_sz
- 1;
2293 hp
->hdr_start
= hp
->req
.end
+ 1;
2295 /* Enforce max_request_size */
2296 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2297 debugs(33, 5, "parseHttpRequest: Too large request");
2298 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2299 return parseHttpRequestAbort(csd
, "error:request-too-large");
2303 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2305 /* deny CONNECT via accelerated ports */
2306 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2307 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->protocol
<< " Accelerator port " << csd
->port
->s
.port() );
2308 /* XXX need a way to say "this many character length string" */
2309 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2310 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2311 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2314 if (*method_p
== Http::METHOD_NONE
) {
2315 /* XXX need a way to say "this many character length string" */
2316 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2317 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2318 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2322 * Process headers after request line
2323 * TODO: Use httpRequestParse here.
2325 /* XXX this code should be modified to take a const char * later! */
2326 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2328 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2330 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2332 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2334 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2335 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2336 HttpParserReqSz(hp
));
2338 /* Ok, all headers are received */
2339 http
= new ClientHttpRequest(csd
);
2341 http
->req_sz
= HttpParserRequestLen(hp
);
2342 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2343 tempBuffer
.data
= result
->reqbuf
;
2344 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2346 ClientStreamData newServer
= new clientReplyContext(http
);
2347 ClientStreamData newClient
= result
;
2348 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2349 clientReplyStatus
, newServer
, clientSocketRecipient
,
2350 clientSocketDetach
, newClient
, tempBuffer
);
2352 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2356 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2357 * below needs to be modified to not expect a mutable nul-terminated string.
2359 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2361 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2363 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2365 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2367 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2372 debugs(33,5, HERE
<< "repare absolute URL from " <<
2373 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2374 /* Rewrite the URL in transparent or accelerator mode */
2375 /* NP: there are several cases to traverse here:
2376 * - standard mode (forward proxy)
2377 * - transparent mode (TPROXY)
2378 * - transparent mode with failures
2379 * - intercept mode (NAT)
2380 * - intercept mode with failures
2381 * - accelerator mode (reverse proxy)
2383 * - mixed combos of the above with internal URL
2385 if (csd
->transparent()) {
2386 /* intercept or transparent mode, properly working with no failures */
2387 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2389 } else if (internalCheck(url
)) {
2390 /* internal URL mode */
2391 /* prepend our name & port */
2392 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2393 // We just re-wrote the URL. Must replace the Host: header.
2394 // But have not parsed there yet!! flag for local-only handling.
2395 http
->flags
.internal
= true;
2397 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2398 /* accelerator mode */
2399 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2403 /* No special rewrites have been applied above, use the
2404 * requested url. may be rewritten later, so make extra room */
2405 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2406 http
->uri
= (char *)xcalloc(url_sz
, 1);
2407 strcpy(http
->uri
, url
);
2410 debugs(33, 5, "parseHttpRequest: Complete request received");
2412 // XXX: crop this dump at the end of headers. No need for extras
2413 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2414 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2416 result
->flags
.parsed_ok
= 1;
2422 ConnStateData::getAvailableBufferLength() const
2424 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2425 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2426 // huge request_header_max_size may lead to more than INT_MAX unused space
2427 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2432 ConnStateData::maybeMakeSpaceAvailable()
2434 if (getAvailableBufferLength() < 2) {
2436 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2437 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2440 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2441 newSize
=Config
.maxRequestBufferSize
;
2443 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2444 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2450 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2452 ClientSocketContext::Pointer
*S
;
2454 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2462 ConnStateData::getConcurrentRequestCount() const
2465 ClientSocketContext::Pointer
*T
;
2467 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2468 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2473 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2475 if (flag
!= COMM_OK
) {
2476 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2481 if (!ignoreErrno(xerrno
)) {
2482 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2484 } else if (in
.notYetUsed
== 0) {
2485 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2493 ConnStateData::connFinishedWithConn(int size
)
2496 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2497 /* no current or pending requests */
2498 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2500 } else if (!Config
.onoff
.half_closed_clients
) {
2501 /* admin doesn't want to support half-closed client sockets */
2502 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2503 notifyAllContexts(0); // no specific error implies abort
2512 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2514 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2515 conn
->in
.notYetUsed
-= byteCount
;
2516 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2518 * If there is still data that will be used,
2519 * move it to the beginning.
2522 if (conn
->in
.notYetUsed
> 0)
2523 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2526 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2528 ConnStateData::checkHeaderLimits()
2530 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2531 return; // can accumulte more header data
2533 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2534 Config
.maxRequestHeaderSize
<< " bytes)");
2536 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2537 clientStreamNode
*node
= context
->getClientReplyContext();
2538 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2539 assert (repContext
);
2540 repContext
->setReplyToError(ERR_TOO_BIG
,
2541 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2542 clientConnection
->remote
, NULL
, NULL
, NULL
);
2543 context
->registerWithConn();
2544 context
->pullData();
2548 ConnStateData::clientAfterReadingRequests()
2550 // Were we expecting to read more request body from half-closed connection?
2551 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2552 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2553 clientConnection
->close();
2562 ConnStateData::quitAfterError(HttpRequest
*request
)
2564 // From HTTP p.o.v., we do not have to close after every error detected
2565 // at the client-side, but many such errors do require closure and the
2566 // client-side code is bad at handling errors so we play it safe.
2568 request
->flags
.proxyKeepalive
= false;
2569 flags
.readMore
= false;
2570 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2574 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2576 ClientHttpRequest
*http
= context
->http
;
2581 assert(sslServerBump
->entry
);
2582 // Did we create an error entry while processing CONNECT?
2583 if (!sslServerBump
->entry
->isEmpty()) {
2584 quitAfterError(http
->request
);
2586 // Get the saved error entry and send it to the client by replacing the
2587 // ClientHttpRequest store entry with it.
2588 clientStreamNode
*node
= context
->getClientReplyContext();
2589 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2591 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2592 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2594 // save the original request for logging purposes
2595 if (!context
->http
->al
->request
) {
2596 context
->http
->al
->request
= http
->request
;
2597 HTTPMSGLOCK(context
->http
->al
->request
);
2600 // Get error details from the fake certificate-peeking request.
2601 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2602 context
->pullData();
2606 // In bump-server-first mode, we have not necessarily seen the intended
2607 // server name at certificate-peeking time. Check for domain mismatch now,
2608 // when we can extract the intended name from the bumped HTTP request.
2609 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2610 HttpRequest
*request
= http
->request
;
2611 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2612 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2613 "does not match domainname " << request
->GetHost());
2615 bool allowDomainMismatch
= false;
2616 if (Config
.ssl_client
.cert_error
) {
2617 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2618 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2619 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2620 delete check
.sslErrors
;
2621 check
.sslErrors
= NULL
;
2624 if (!allowDomainMismatch
) {
2625 quitAfterError(request
);
2627 clientStreamNode
*node
= context
->getClientReplyContext();
2628 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2629 assert (repContext
);
2631 // Fill the server IP and hostname for error page generation.
2632 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2633 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2635 // Create an error object and fill it
2636 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2637 err
->src_addr
= clientConnection
->remote
;
2638 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2639 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2641 err
->detail
= errDetail
;
2642 // Save the original request for logging purposes.
2643 if (!context
->http
->al
->request
) {
2644 context
->http
->al
->request
= request
;
2645 HTTPMSGLOCK(context
->http
->al
->request
);
2647 repContext
->setReplyToError(request
->method
, err
);
2648 assert(context
->http
->out
.offset
== 0);
2649 context
->pullData();
2660 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2662 ClientHttpRequest
*http
= context
->http
;
2663 HttpRequest::Pointer request
;
2664 bool notedUseOfBuffer
= false;
2665 bool chunked
= false;
2666 bool mustReplyToOptions
= false;
2667 bool unsupportedTe
= false;
2668 bool expectBody
= false;
2670 /* We have an initial client stream in place should it be needed */
2671 /* setup our private context */
2672 context
->registerWithConn();
2674 if (context
->flags
.parsed_ok
== 0) {
2675 clientStreamNode
*node
= context
->getClientReplyContext();
2676 debugs(33, 2, "clientProcessRequest: Invalid Request");
2677 conn
->quitAfterError(NULL
);
2678 // setLogUri should called before repContext->setReplyToError
2679 setLogUri(http
, http
->uri
, true);
2680 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2681 assert (repContext
);
2682 switch (hp
->request_parse_status
) {
2683 case Http::scHeaderTooLarge
:
2684 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2686 case Http::scMethodNotAllowed
:
2687 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2688 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2691 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2692 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2694 assert(context
->http
->out
.offset
== 0);
2695 context
->pullData();
2699 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2700 clientStreamNode
*node
= context
->getClientReplyContext();
2701 debugs(33, 5, "Invalid URL: " << http
->uri
);
2702 conn
->quitAfterError(request
.getRaw());
2703 // setLogUri should called before repContext->setReplyToError
2704 setLogUri(http
, http
->uri
, true);
2705 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2706 assert (repContext
);
2707 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2708 assert(context
->http
->out
.offset
== 0);
2709 context
->pullData();
2713 /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */
2714 /* We currently only accept 0.9, 1.0, 1.1 */
2715 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2716 (http_ver
.major
== 1 && http_ver
.minor
> 1 ) ||
2717 (http_ver
.major
> 1) ) {
2719 clientStreamNode
*node
= context
->getClientReplyContext();
2720 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2721 conn
->quitAfterError(request
.getRaw());
2722 // setLogUri should called before repContext->setReplyToError
2723 setLogUri(http
, http
->uri
, true);
2724 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2725 assert (repContext
);
2726 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2727 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2728 assert(context
->http
->out
.offset
== 0);
2729 context
->pullData();
2733 /* compile headers */
2734 /* we should skip request line! */
2735 /* XXX should actually know the damned buffer size here */
2736 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2737 clientStreamNode
*node
= context
->getClientReplyContext();
2738 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2739 conn
->quitAfterError(request
.getRaw());
2740 // setLogUri should called before repContext->setReplyToError
2741 setLogUri(http
, http
->uri
, true);
2742 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2743 assert (repContext
);
2744 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2745 assert(context
->http
->out
.offset
== 0);
2746 context
->pullData();
2750 request
->clientConnectionManager
= conn
;
2752 request
->flags
.accelerated
= http
->flags
.accel
;
2753 request
->flags
.sslBumped
=conn
->switchedToHttps();
2754 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2755 // TODO: decouple http->flags.accel from request->flags.sslBumped
2756 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2757 !conn
->port
->allow_direct
: 0;
2759 if (request
->flags
.sslBumped
) {
2760 if (conn
->getAuth() != NULL
)
2761 request
->auth_user_request
= conn
->getAuth();
2766 * If transparent or interception mode is working clone the transparent and interception flags
2767 * from the port settings to the request.
2769 if (http
->clientConnection
!= NULL
) {
2770 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2771 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2772 if (request
->flags
.interceptTproxy
) {
2773 if (Config
.accessList
.spoof_client_ip
) {
2774 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2775 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2778 request
->flags
.spoofClientIp
= true;
2780 request
->flags
.spoofClientIp
= false;
2783 if (internalCheck(request
->urlpath
.termedBuf())) {
2784 if (internalHostnameIs(request
->GetHost()) &&
2785 request
->port
== getMyPort()) {
2786 http
->flags
.internal
= true;
2787 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2788 request
->SetHost(internalHostname());
2789 request
->port
= getMyPort();
2790 http
->flags
.internal
= true;
2794 if (http
->flags
.internal
) {
2795 request
->protocol
= AnyP::PROTO_HTTP
;
2796 request
->login
[0] = '\0';
2799 request
->flags
.internal
= http
->flags
.internal
;
2800 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2801 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2802 #if FOLLOW_X_FORWARDED_FOR
2803 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2804 // not a details about teh TCP connection itself
2805 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2806 #endif /* FOLLOW_X_FORWARDED_FOR */
2807 request
->my_addr
= conn
->clientConnection
->local
;
2808 request
->myportname
= conn
->port
->name
;
2809 request
->http_ver
= http_ver
;
2811 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2812 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2813 request
->clientConnectionManager
= conn
;
2815 if (request
->header
.chunked()) {
2817 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2818 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2819 // HTTP/1.1 requires chunking to be the last encoding if there is one
2820 unsupportedTe
= te
.size() && te
!= "identity";
2821 } // else implied identity coding
2823 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2824 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2825 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2826 clientStreamNode
*node
= context
->getClientReplyContext();
2827 conn
->quitAfterError(request
.getRaw());
2828 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2829 assert (repContext
);
2830 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2831 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2832 assert(context
->http
->out
.offset
== 0);
2833 context
->pullData();
2837 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2838 clientStreamNode
*node
= context
->getClientReplyContext();
2839 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2840 assert (repContext
);
2841 conn
->quitAfterError(request
.getRaw());
2842 repContext
->setReplyToError(ERR_INVALID_REQ
,
2843 Http::scLengthRequired
, request
->method
, NULL
,
2844 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2845 assert(context
->http
->out
.offset
== 0);
2846 context
->pullData();
2850 if (request
->header
.has(HDR_EXPECT
)) {
2851 const String expect
= request
->header
.getList(HDR_EXPECT
);
2852 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2853 if (!supportedExpect
) {
2854 clientStreamNode
*node
= context
->getClientReplyContext();
2855 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2856 assert (repContext
);
2857 conn
->quitAfterError(request
.getRaw());
2858 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2859 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2860 assert(context
->http
->out
.offset
== 0);
2861 context
->pullData();
2866 http
->request
= request
.getRaw();
2867 HTTPMSGLOCK(http
->request
);
2868 clientSetKeepaliveFlag(http
);
2870 // Let tunneling code be fully responsible for CONNECT requests
2871 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2872 context
->mayUseConnection(true);
2873 conn
->flags
.readMore
= false;
2877 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2881 /* Do we expect a request-body? */
2882 expectBody
= chunked
|| request
->content_length
> 0;
2883 if (!context
->mayUseConnection() && expectBody
) {
2884 request
->body_pipe
= conn
->expectRequestBody(
2885 chunked
? -1 : request
->content_length
);
2887 // consume header early so that body pipe gets just the body
2888 connNoteUseOfBuffer(conn
, http
->req_sz
);
2889 notedUseOfBuffer
= true;
2891 /* Is it too large? */
2892 if (!chunked
&& // if chunked, we will check as we accumulate
2893 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2894 clientStreamNode
*node
= context
->getClientReplyContext();
2895 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2896 assert (repContext
);
2897 conn
->quitAfterError(request
.getRaw());
2898 repContext
->setReplyToError(ERR_TOO_BIG
,
2899 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2900 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2901 assert(context
->http
->out
.offset
== 0);
2902 context
->pullData();
2906 // We may stop producing, comm_close, and/or call setReplyToError()
2907 // below, so quit on errors to avoid http->doCallouts()
2908 if (!conn
->handleRequestBodyData())
2911 if (!request
->body_pipe
->productionEnded()) {
2912 debugs(33, 5, HERE
<< "need more request body");
2913 context
->mayUseConnection(true);
2914 assert(conn
->flags
.readMore
);
2918 http
->calloutContext
= new ClientRequestContext(http
);
2923 if (!notedUseOfBuffer
)
2924 connNoteUseOfBuffer(conn
, http
->req_sz
);
2928 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2929 * to here because calling comm_reset_close() causes http to
2930 * be freed and the above connNoteUseOfBuffer() would hit an
2931 * assertion, not to mention that we were accessing freed memory.
2933 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2934 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2935 conn
->flags
.readMore
= false;
2936 comm_reset_close(conn
->clientConnection
);
2941 connStripBufferWhitespace (ConnStateData
* conn
)
2943 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2944 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2945 -- conn
->in
.notYetUsed
;
2950 * Limit the number of concurrent requests.
2951 * \return true when there are available position(s) in the pipeline queue for another request.
2952 * \return false when the pipeline queue is full or disabled.
2955 ConnStateData::concurrentRequestQueueFilled() const
2957 const int existingRequestCount
= getConcurrentRequestCount();
2959 // default to the configured pipeline size.
2960 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2961 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2963 // when queue filled already we cant add more.
2964 if (existingRequestCount
>= concurrentRequestLimit
) {
2965 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2966 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2974 * Attempt to parse one or more requests from the input buffer.
2975 * If a request is successfully parsed, even if the next request
2976 * is only partially parsed, it will return TRUE.
2979 ConnStateData::clientParseRequests()
2981 HttpRequestMethod method
;
2982 bool parsed_req
= false;
2984 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2986 // Loop while we have read bytes that are not needed for producing the body
2987 // On errors, bodyPipe may become nil, but readMore will be cleared
2988 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2989 connStripBufferWhitespace(this);
2991 /* Don't try to parse if the buffer is empty */
2992 if (in
.notYetUsed
== 0)
2995 /* Limit the number of concurrent requests */
2996 if (concurrentRequestQueueFilled())
2999 /* Should not be needed anymore */
3000 /* Terminate the string */
3001 in
.buf
[in
.notYetUsed
] = '\0';
3003 /* Begin the parsing */
3004 PROF_start(parseHttpRequest
);
3005 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
3007 /* Process request */
3008 Http::ProtocolVersion http_ver
;
3009 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
3010 PROF_stop(parseHttpRequest
);
3012 /* partial or incomplete request */
3014 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
3015 // (which becomes context) but checkHeaderLimits cannot?
3016 checkHeaderLimits();
3020 /* status -1 or 1 */
3022 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
3023 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3024 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
3025 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3027 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
3029 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3031 if (context
->mayUseConnection()) {
3032 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3038 /* XXX where to 'finish' the parsing pass? */
3043 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3045 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3049 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
3051 if (io
.flag
== COMM_ERR_CLOSING
) {
3052 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
3056 assert(Comm::IsConnOpen(clientConnection
));
3057 assert(io
.conn
->fd
== clientConnection
->fd
);
3060 * Don't reset the timeout value here. The timeout value will be
3061 * set to Config.Timeout.request by httpAccept() and
3062 * clientWriteComplete(), and should apply to the request as a
3063 * whole, not individual read() calls. Plus, it breaks our
3064 * lame half-close detection
3066 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3067 notifyAllContexts(io
.xerrno
);
3072 if (io
.flag
== COMM_OK
) {
3074 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3076 // may comm_close or setReplyToError
3077 if (!handleReadData(io
.buf
, io
.size
))
3080 } else if (io
.size
== 0) {
3081 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3083 if (connFinishedWithConn(io
.size
)) {
3084 clientConnection
->close();
3088 /* It might be half-closed, we can't tell */
3089 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3091 commMarkHalfClosed(io
.conn
->fd
);
3093 fd_note(io
.conn
->fd
, "half-closed");
3095 /* There is one more close check at the end, to detect aborted
3096 * (partial) requests. At this point we can't tell if the request
3099 /* Continue to process previously read data */
3103 /* Process next request */
3104 if (getConcurrentRequestCount() == 0)
3105 fd_note(io
.fd
, "Reading next request");
3107 if (!clientParseRequests()) {
3111 * If the client here is half closed and we failed
3112 * to parse a request, close the connection.
3113 * The above check with connFinishedWithConn() only
3114 * succeeds _if_ the buffer is empty which it won't
3115 * be if we have an incomplete request.
3116 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3118 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3119 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3120 clientConnection
->close();
3128 clientAfterReadingRequests();
3132 * called when new request data has been read from the socket
3134 * \retval false called comm_close or setReplyToError (the caller should bail)
3135 * \retval true we did not call comm_close or setReplyToError
3138 ConnStateData::handleReadData(char *buf
, size_t size
)
3140 char *current_buf
= in
.addressToReadInto();
3142 if (buf
!= current_buf
)
3143 memmove(current_buf
, buf
, size
);
3145 in
.notYetUsed
+= size
;
3147 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3149 // if we are reading a body, stuff data into the body pipe
3150 if (bodyPipe
!= NULL
)
3151 return handleRequestBodyData();
3156 * called when new request body data has been buffered in in.buf
3157 * may close the connection if we were closing and piped everything out
3159 * \retval false called comm_close or setReplyToError (the caller should bail)
3160 * \retval true we did not call comm_close or setReplyToError
3163 ConnStateData::handleRequestBodyData()
3165 assert(bodyPipe
!= NULL
);
3169 if (in
.bodyParser
) { // chunked encoding
3170 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3171 abortChunkedRequestBody(error
);
3174 } else { // identity encoding
3175 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3176 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3177 if (!bodyPipe
->mayNeedMoreData()) {
3178 // BodyPipe will clear us automagically when we produced everything
3184 connNoteUseOfBuffer(this, putSize
);
3187 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3189 if (const char *reason
= stoppedSending()) {
3190 /* we've finished reading like good clients,
3191 * now do the close that initiateClose initiated.
3193 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3194 clientConnection
->close();
3202 /// parses available chunked encoded body bytes, checks size, returns errors
3204 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3206 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3208 try { // the parser will throw on errors
3210 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3213 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3214 // add one because MemBuf will assert if it cannot 0-terminate
3215 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3216 raw
.append(in
.buf
, in
.notYetUsed
);
3218 const mb_size_t wasContentSize
= raw
.contentSize();
3219 BodyPipeCheckout
bpc(*bodyPipe
);
3220 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3222 putSize
= wasContentSize
- raw
.contentSize();
3224 // dechunk then check: the size limit applies to _dechunked_ content
3225 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3229 finishDechunkingRequest(true);
3231 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3234 // if chunk parser needs data, then the body pipe must need it too
3235 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3237 // if parser needs more space and we can consume nothing, we will stall
3238 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3239 } catch (...) { // TODO: be more specific
3240 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3241 return ERR_INVALID_REQ
;
3244 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3248 /// quit on errors related to chunked request body handling
3250 ConnStateData::abortChunkedRequestBody(const err_type error
)
3252 finishDechunkingRequest(false);
3254 // XXX: The code below works if we fail during initial request parsing,
3255 // but if we fail when the server-side works already, the server may send
3256 // us its response too, causing various assertions. How to prevent that?
3257 #if WE_KNOW_HOW_TO_SEND_ERRORS
3258 ClientSocketContext::Pointer context
= getCurrentContext();
3259 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3260 clientStreamNode
*node
= context
->getClientReplyContext();
3261 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3263 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3264 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3265 repContext
->setReplyToError(error
, scode
,
3266 repContext
->http
->request
->method
,
3267 repContext
->http
->uri
,
3269 repContext
->http
->request
,
3271 context
->pullData();
3273 // close or otherwise we may get stuck as nobody will notice the error?
3274 comm_reset_close(clientConnection
);
3277 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3278 comm_reset_close(clientConnection
);
3280 flags
.readMore
= false;
3284 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3286 if (!handleRequestBodyData())
3289 // too late to read more body
3290 if (!isOpen() || stoppedReceiving())
3297 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3299 // request reader may get stuck waiting for space if nobody consumes body
3300 if (bodyPipe
!= NULL
)
3301 bodyPipe
->enableAutoConsumption();
3303 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3306 /** general lifetime handler for HTTP requests */
3308 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3311 * Just close the connection to not confuse browsers
3312 * using persistent connections. Some browsers open
3313 * a connection and then do not use it until much
3314 * later (presumeably because the request triggering
3315 * the open has already been completed on another
3318 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3323 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3325 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3326 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3327 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3328 http
->al
->http
.timedout
= true;
3329 if (Comm::IsConnOpen(io
.conn
))
3334 connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
)
3336 ConnStateData
*result
= new ConnStateData
;
3338 result
->clientConnection
= client
;
3339 result
->log_addr
= client
->remote
;
3340 result
->log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3341 result
->in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &result
->in
.allocatedSize
);
3342 result
->port
= cbdataReference(port
);
3344 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3345 (result
->transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3346 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3347 int i
= IP_PMTUDISC_DONT
;
3348 if (setsockopt(client
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3349 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << client
<< " : " << xstrerror());
3351 static bool reported
= false;
3354 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3360 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3361 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, result
, ConnStateData::connStateClosed
);
3362 comm_add_close_handler(client
->fd
, call
);
3364 if (Config
.onoff
.log_fqdn
)
3365 fqdncache_gethostbyaddr(client
->remote
, FQDN_LOOKUP_IF_MISS
);
3368 if (Ident::TheConfig
.identLookup
) {
3369 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3370 identChecklist
.src_addr
= client
->remote
;
3371 identChecklist
.my_addr
= client
->local
;
3372 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3373 Ident::Start(client
, clientIdentDone
, result
);
3377 clientdbEstablished(client
->remote
, 1);
3379 result
->flags
.readMore
= true;
3383 /** Handle a new connection on HTTP socket. */
3385 httpAccept(const CommAcceptCbParams
¶ms
)
3387 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3389 if (params
.flag
!= COMM_OK
) {
3390 // Its possible the call was still queued when the client disconnected
3391 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3395 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3396 fd_note(params
.conn
->fd
, "client http connect");
3398 if (s
->tcp_keepalive
.enabled
) {
3399 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3402 ++ incoming_sockets_accepted
;
3404 // Socket is ready, setup the connection manager to start using it
3405 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3407 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3408 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3409 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3410 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3412 connState
->readSomeData();
3415 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3417 if (Config
.onoff
.client_db
) {
3418 /* it was said several times that client write limiter does not work if client_db is disabled */
3420 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3421 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3423 // TODO: we check early to limit error response bandwith but we
3424 // should recheck when we can honor delay_pool_uses_indirect
3425 // TODO: we should also pass the port details for myportname here.
3426 ch
.src_addr
= params
.conn
->remote
;
3427 ch
.my_addr
= params
.conn
->local
;
3429 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3431 /* pools require explicit 'allow' to assign a client into them */
3432 if (pools
[pool
].access
) {
3433 ch
.accessList
= pools
[pool
].access
;
3434 allow_t answer
= ch
.fastCheck();
3435 if (answer
== ACCESS_ALLOWED
) {
3437 /* request client information from db after we did all checks
3438 this will save hash lookup if client failed checks */
3439 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3442 /* put client info in FDE */
3443 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3445 /* setup write limiter for this request */
3446 const double burst
= floor(0.5 +
3447 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3448 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3451 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3461 /** Create SSL connection structure and update fd_table */
3463 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3465 SSL
*ssl
= SSL_new(sslContext
);
3468 const int ssl_error
= ERR_get_error();
3469 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3474 SSL_set_fd(ssl
, conn
->fd
);
3475 fd_table
[conn
->fd
].ssl
= ssl
;
3476 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3477 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3479 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3480 fd_note(conn
->fd
, "client https start");
3485 /** negotiate an SSL connection */
3487 clientNegotiateSSL(int fd
, void *data
)
3489 ConnStateData
*conn
= (ConnStateData
*)data
;
3491 SSL
*ssl
= fd_table
[fd
].ssl
;
3494 if ((ret
= SSL_accept(ssl
)) <= 0) {
3495 int ssl_error
= SSL_get_error(ssl
, ret
);
3497 switch (ssl_error
) {
3499 case SSL_ERROR_WANT_READ
:
3500 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3503 case SSL_ERROR_WANT_WRITE
:
3504 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3507 case SSL_ERROR_SYSCALL
:
3510 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3516 if (errno
== ECONNRESET
)
3519 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3520 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3527 case SSL_ERROR_ZERO_RETURN
:
3528 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3533 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3534 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3535 " (" << ssl_error
<< "/" << ret
<< ")");
3543 if (SSL_session_reused(ssl
)) {
3544 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3545 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3547 if (do_debug(83, 4)) {
3548 /* Write out the SSL session details.. actually the call below, but
3549 * OpenSSL headers do strange typecasts confusing GCC.. */
3550 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3551 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3552 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
);
3554 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3556 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3557 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3558 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3559 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3560 * Because there are two possible usable cast, if you get an error here, try the other
3561 * commented line. */
3563 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3564 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3568 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3571 /* Note: This does not automatically fflush the log file.. */
3574 debugs(83, 2, "clientNegotiateSSL: New session " <<
3575 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3576 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3580 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3581 SSL_get_cipher(ssl
));
3583 client_cert
= SSL_get_peer_certificate(ssl
);
3585 if (client_cert
!= NULL
) {
3586 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3587 " client certificate: subject: " <<
3588 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3590 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3591 " client certificate: issuer: " <<
3592 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3594 X509_free(client_cert
);
3596 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3597 " has no certificate.");
3600 conn
->readSomeData();
3604 * If SSL_CTX is given, starts reading the SSL handshake.
3605 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3608 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3612 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3614 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3617 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3618 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3619 connState
, ConnStateData::requestTimeout
);
3620 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3623 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3625 char buf
[MAX_IPSTRLEN
];
3626 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3627 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3628 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3629 fakeRequest
->port
= details
->local
.port();
3630 fakeRequest
->clientConnectionManager
= connState
;
3631 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3632 #if FOLLOW_X_FORWARDED_FOR
3633 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3635 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3636 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3637 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3638 fakeRequest
->myportname
= connState
->port
->name
;
3639 if (fakeRequest
->flags
.interceptTproxy
) {
3640 if (Config
.accessList
.spoof_client_ip
) {
3641 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3642 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3644 fakeRequest
->flags
.spoofClientIp
= true;
3646 fakeRequest
->flags
.spoofClientIp
= false;
3647 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3648 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3653 * A callback function to use with the ACLFilledChecklist callback.
3654 * In the case of ACCES_ALLOWED answer initializes a bumped SSL connection,
3655 * else reverts the connection to tunnel mode.
3658 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3660 ConnStateData
*connState
= (ConnStateData
*) data
;
3662 // if the connection is closed or closing, just return.
3663 if (!connState
->isOpen())
3666 // Require both a match and a positive bump mode to work around exceptional
3667 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3668 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3669 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3670 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3671 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3673 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3674 connState
->sslBumpMode
= Ssl::bumpNone
;
3676 // fake a CONNECT request to force connState to tunnel
3677 static char ip
[MAX_IPSTRLEN
];
3678 static char reqStr
[MAX_IPSTRLEN
+ 80];
3679 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3680 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, ip
);
3681 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3683 ret
= connState
->clientParseRequests();
3686 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3687 connState
->clientConnection
->close();
3692 /** handle a new HTTPS connection */
3694 httpsAccept(const CommAcceptCbParams
¶ms
)
3696 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3698 if (params
.flag
!= COMM_OK
) {
3699 // Its possible the call was still queued when the client disconnected
3700 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3704 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3705 fd_note(params
.conn
->fd
, "client https connect");
3707 if (s
->tcp_keepalive
.enabled
) {
3708 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3711 ++incoming_sockets_accepted
;
3713 // Socket is ready, setup the connection manager to start using it
3714 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3716 if (s
->flags
.tunnelSslBumping
) {
3717 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3719 if (!Config
.accessList
.ssl_bump
) {
3720 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3724 // Create a fake HTTP request for ssl_bump ACL check,
3725 // using tproxy/intercept provided destination IP and port.
3726 HttpRequest
*request
= new HttpRequest();
3727 static char ip
[MAX_IPSTRLEN
];
3728 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3729 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3730 request
->port
= params
.conn
->local
.port();
3731 request
->myportname
= s
->name
;
3733 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3734 acl_checklist
->src_addr
= params
.conn
->remote
;
3735 acl_checklist
->my_addr
= s
->s
;
3736 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3739 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3740 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3745 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3747 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3748 state_data
->sslCrtdHandleReply(reply
);
3752 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3754 if (reply
.result
== HelperReply::BrokenHelper
) {
3755 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3756 } else if (!reply
.other().hasContent()) {
3757 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3759 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3760 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3761 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3763 if (reply
.result
!= HelperReply::Okay
) {
3764 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3766 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3767 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3768 getSslContextDone(ctx
, true);
3773 getSslContextDone(NULL
);
3776 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3778 certProperties
.commonName
= sslCommonName
.defined() ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3780 // fake certificate adaptation requires bump-server-first mode
3781 if (!sslServerBump
) {
3782 assert(port
->signingCert
.get());
3783 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3784 if (port
->signPkey
.get())
3785 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3786 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3790 // In case of an error while connecting to the secure server, use a fake
3791 // trusted certificate, with no mimicked fields and no adaptation
3792 // algorithms. There is nothing we can mimic so we want to minimize the
3793 // number of warnings the user will have to see to get to the error page.
3794 assert(sslServerBump
->entry
);
3795 if (sslServerBump
->entry
->isEmpty()) {
3796 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3797 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3799 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3800 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3801 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3803 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3804 // If the algorithm already set, then ignore it.
3805 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3806 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3807 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3810 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3811 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3812 const char *param
= ca
->param
;
3814 // For parameterless CN adaptation, use hostname from the
3816 if (ca
->alg
== Ssl::algSetCommonName
) {
3818 param
= sslConnectHostOrIp
.termedBuf();
3819 certProperties
.commonName
= param
;
3820 certProperties
.setCommonName
= true;
3821 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3822 certProperties
.setValidAfter
= true;
3823 else if (ca
->alg
== Ssl::algSetValidBefore
)
3824 certProperties
.setValidBefore
= true;
3826 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3827 alg
<< " param: " << (param
? param
: "-"));
3831 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3832 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3833 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3834 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3838 } else {// if (!sslServerBump->entry->isEmpty())
3839 // Use trusted certificate for a Squid-generated error
3840 // or the user would have to add a security exception
3841 // just to see the error page. We will close the connection
3842 // so that the trust is not extended to non-Squid content.
3843 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3846 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3848 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3849 assert(port
->untrustedSigningCert
.get());
3850 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3851 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3853 assert(port
->signingCert
.get());
3854 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3856 if (port
->signPkey
.get())
3857 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3859 signAlgorithm
= certProperties
.signAlgorithm
;
3863 ConnStateData::getSslContextStart()
3865 assert(areAllContextsForThisConnection());
3867 /* careful: freeAllContexts() above frees request, host, etc. */
3869 if (port
->generateHostCertificates
) {
3870 Ssl::CertificateProperties certProperties
;
3871 buildSslCertGenerationParams(certProperties
);
3872 sslBumpCertKey
= certProperties
.dbKey().c_str();
3873 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3875 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3876 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3877 SSL_CTX
* dynCtx
= NULL
;
3878 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
.get(sslBumpCertKey
.termedBuf());
3879 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3880 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3881 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3882 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3883 getSslContextDone(dynCtx
);
3886 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3887 ssl_ctx_cache
.del(sslBumpCertKey
.termedBuf());
3890 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3895 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3896 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3897 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3898 request_message
.composeRequest(certProperties
);
3899 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3900 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3902 } catch (const std::exception
&e
) {
3903 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3904 "request for " << certProperties
.commonName
<<
3905 " certificate: " << e
.what() << "; will now block to " <<
3906 "generate that certificate.");
3907 // fall through to do blocking in-process generation.
3909 #endif // USE_SSL_CRTD
3911 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3912 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3913 getSslContextDone(dynCtx
, true);
3916 getSslContextDone(NULL
);
3920 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3922 // Try to add generated ssl context to storage.
3923 if (port
->generateHostCertificates
&& isNew
) {
3925 if (signAlgorithm
== Ssl::algSignTrusted
)
3926 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3927 //else it is self-signed or untrusted do not attrach any certificate
3929 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3930 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3932 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3933 // If it is not in storage delete after using. Else storage deleted it.
3934 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3937 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3941 // If generated ssl context = NULL, try to use static ssl context.
3943 if (!port
->staticSslContext
) {
3944 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3945 clientConnection
->close();
3948 debugs(33, 5, HERE
<< "Using static ssl context.");
3949 sslContext
= port
->staticSslContext
.get();
3953 if (!httpsCreate(clientConnection
, sslContext
))
3956 // commSetConnTimeout() was called for this request before we switched.
3958 // Disable the client read handler until CachePeer selection is complete
3959 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3960 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3961 switchedToHttps_
= true;
3965 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3967 assert(!switchedToHttps_
);
3969 sslConnectHostOrIp
= request
->GetHost();
3970 sslCommonName
= request
->GetHost();
3972 // We are going to read new request
3973 flags
.readMore
= true;
3974 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3976 // If sslServerBump is set, then we have decided to deny CONNECT
3977 // and now want to switch to SSL to send the error to the client
3978 // without even peeking at the origin server certificate.
3979 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3980 request
->flags
.sslPeek
= true;
3981 sslServerBump
= new Ssl::ServerBump(request
);
3983 // will call httpsPeeked() with certificate and connection, eventually
3984 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3988 // otherwise, use sslConnectHostOrIp
3989 getSslContextStart();
3993 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3995 Must(sslServerBump
!= NULL
);
3997 if (Comm::IsConnOpen(serverConnection
)) {
3998 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
4000 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
4001 assert(serverCert
.get() != NULL
);
4002 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4003 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4004 " bumped: " << *serverConnection
);
4006 pinConnection(serverConnection
, NULL
, NULL
, false);
4008 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4010 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4011 Ip::Address intendedDest
;
4012 intendedDest
= sslConnectHostOrIp
.termedBuf();
4013 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4015 // Squid serves its own error page and closes, so we want
4016 // a CN that causes no additional browser errors. Possible
4017 // only when bumping CONNECT with a user-typed address.
4018 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4019 sslCommonName
= sslConnectHostOrIp
;
4020 else if (sslServerBump
->serverCert
.get())
4021 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4023 // copy error detail from bump-server-first request to CONNECT request
4024 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4025 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4028 getSslContextStart();
4031 #endif /* USE_SSL */
4033 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4035 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4037 if (!Comm::IsConnOpen(c
)) {
4038 Must(NHttpSockets
> 0); // we tried to open some
4039 --NHttpSockets
; // there will be fewer sockets than planned
4040 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4042 if (!NHttpSockets
) // we could not open any listen sockets at all
4043 fatalf("Unable to open %s",FdNote(portType
));
4050 /// find any unused HttpSockets[] slot and store fd there or return false
4052 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4055 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4056 if ((found
= HttpSockets
[i
] < 0))
4057 HttpSockets
[i
] = conn
->fd
;
4063 clientHttpConnectionsOpen(void)
4065 AnyP::PortCfg
*s
= NULL
;
4067 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4068 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4069 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4070 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4075 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4076 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4077 s
->flags
.tunnelSslBumping
= false;
4080 if (s
->flags
.tunnelSslBumping
&&
4081 !s
->staticSslContext
&&
4082 !s
->generateHostCertificates
) {
4083 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4084 s
->flags
.tunnelSslBumping
= false;
4086 if (s
->flags
.tunnelSslBumping
) {
4087 // Create ssl_ctx cache for this port.
4088 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4092 // Fill out a Comm::Connection which IPC will open as a listener for us
4093 // then pass back when active so we can start a TcpAcceptor subscription.
4094 s
->listenConn
= new Comm::Connection
;
4095 s
->listenConn
->local
= s
->s
;
4096 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4098 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4099 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4100 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4101 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4103 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4104 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4105 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4107 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4114 clientHttpsConnectionsOpen(void)
4118 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4119 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4120 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4121 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4125 if (!s
->staticSslContext
) {
4126 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4127 " due to SSL initialization failure.");
4131 // TODO: merge with similar code in clientHttpConnectionsOpen()
4132 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4133 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4134 s
->flags
.tunnelSslBumping
= false;
4137 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4138 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4139 s
->flags
.tunnelSslBumping
= false;
4142 if (s
->flags
.tunnelSslBumping
) {
4143 // Create ssl_ctx cache for this port.
4144 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4147 // Fill out a Comm::Connection which IPC will open as a listener for us
4148 s
->listenConn
= new Comm::Connection
;
4149 s
->listenConn
->local
= s
->s
;
4150 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4151 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4153 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4154 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4155 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4156 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4158 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4159 ListeningStartedDialer(&clientListenerConnectionOpened
,
4160 s
, Ipc::fdnHttpsSocket
, sub
));
4161 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4162 HttpSockets
[NHttpSockets
] = -1;
4168 /// process clientHttpConnectionsOpen result
4170 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4172 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4176 Must(Comm::IsConnOpen(s
->listenConn
));
4178 // TCP: setup a job to handle accept() with subscribed handler
4179 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4181 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4182 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4183 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4184 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4185 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4186 << FdNote(portTypeNote
) << " connections at "
4189 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4193 clientOpenListenSockets(void)
4195 clientHttpConnectionsOpen();
4197 clientHttpsConnectionsOpen();
4200 if (NHttpSockets
< 1)
4201 fatal("No HTTP or HTTPS ports configured");
4205 clientHttpConnectionsClose(void)
4207 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4208 if (s
->listenConn
!= NULL
) {
4209 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4210 s
->listenConn
->close();
4211 s
->listenConn
= NULL
;
4216 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4217 if (s
->listenConn
!= NULL
) {
4218 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4219 s
->listenConn
->close();
4220 s
->listenConn
= NULL
;
4225 // TODO see if we can drop HttpSockets array entirely */
4226 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4227 HttpSockets
[i
] = -1;
4234 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4236 const char *vary
= request
->vary_headers
;
4237 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4238 #if X_ACCELERATOR_VARY
4241 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4244 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4246 /* Oops... something odd is going on here.. */
4247 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4248 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4249 safe_free(request
->vary_headers
);
4254 /* This is not a varying object */
4258 /* virtual "vary" object found. Calculate the vary key and
4259 * continue the search
4261 vary
= httpMakeVaryMark(request
, entry
->getReply());
4264 request
->vary_headers
= xstrdup(vary
);
4267 /* Ouch.. we cannot handle this kind of variance */
4268 /* XXX This cannot really happen, but just to be complete */
4273 vary
= httpMakeVaryMark(request
, entry
->getReply());
4276 request
->vary_headers
= xstrdup(vary
);
4280 /* Ouch.. we cannot handle this kind of variance */
4281 /* XXX This cannot really happen, but just to be complete */
4283 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4286 /* Oops.. we have already been here and still haven't
4287 * found the requested variant. Bail out
4289 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4290 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4296 ACLFilledChecklist
*
4297 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4299 ConnStateData
* conn
= http
->getConn();
4300 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4301 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4304 * hack for ident ACL. It needs to get full addresses, and a place to store
4305 * the ident result on persistent connections...
4307 /* connection oriented auth also needs these two lines for it's operation. */
4311 CBDATA_CLASS_INIT(ConnStateData
);
4313 ConnStateData::ConnStateData() :
4314 AsyncJob("ConnStateData"),
4316 sslBumpMode(Ssl::bumpEnd
),
4317 switchedToHttps_(false),
4318 sslServerBump(NULL
),
4320 stoppedSending_(NULL
),
4321 stoppedReceiving_(NULL
)
4323 pinning
.host
= NULL
;
4325 pinning
.pinned
= false;
4326 pinning
.auth
= false;
4327 pinning
.zeroReply
= false;
4328 pinning
.peer
= NULL
;
4332 ConnStateData::transparent() const
4334 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4338 ConnStateData::reading() const
4340 return reader
!= NULL
;
4344 ConnStateData::stopReading()
4347 comm_read_cancel(clientConnection
->fd
, reader
);
4353 ConnStateData::expectRequestBody(int64_t size
)
4355 bodyPipe
= new BodyPipe(this);
4357 bodyPipe
->setBodySize(size
);
4359 startDechunkingRequest();
4364 ConnStateData::mayNeedToReadMoreBody() const
4367 return 0; // request without a body or read/produced all body bytes
4369 if (!bodyPipe
->bodySizeKnown())
4370 return -1; // probably need to read more, but we cannot be sure
4372 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4373 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4375 if (needToProduce
<= haveAvailable
)
4376 return 0; // we have read what we need (but are waiting for pipe space)
4378 return needToProduce
- haveAvailable
;
4382 ConnStateData::stopReceiving(const char *error
)
4384 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4385 "; old sending error: " <<
4386 (stoppedSending() ? stoppedSending_
: "none"));
4388 if (const char *oldError
= stoppedReceiving()) {
4389 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4390 return; // nothing has changed as far as this connection is concerned
4393 stoppedReceiving_
= error
;
4395 if (const char *sendError
= stoppedSending()) {
4396 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4397 clientConnection
->close();
4402 ConnStateData::expectNoForwarding()
4404 if (bodyPipe
!= NULL
) {
4405 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4406 bodyPipe
->expectNoConsumption();
4410 /// initialize dechunking state
4412 ConnStateData::startDechunkingRequest()
4414 Must(bodyPipe
!= NULL
);
4415 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4416 assert(!in
.bodyParser
);
4417 in
.bodyParser
= new ChunkedCodingParser
;
4420 /// put parsed content into input buffer and clean up
4422 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4424 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4426 if (bodyPipe
!= NULL
) {
4427 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4428 BodyPipe::Pointer myPipe
= bodyPipe
;
4429 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4430 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4432 Must(myPipe
->bodySizeKnown());
4433 ClientSocketContext::Pointer context
= getCurrentContext();
4434 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4435 context
->http
->request
->setContentLength(myPipe
->bodySize());
4439 delete in
.bodyParser
;
4440 in
.bodyParser
= NULL
;
4444 ConnStateData::In::addressToReadInto() const
4446 return buf
+ notYetUsed
;
4449 ConnStateData::In::In() : bodyParser(NULL
),
4450 buf (NULL
), notYetUsed (0), allocatedSize (0)
4453 ConnStateData::In::~In()
4456 memFreeBuf(allocatedSize
, buf
);
4457 delete bodyParser
; // TODO: pool
4461 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4464 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4468 ClientSocketContext::Pointer context
= getCurrentContext();
4469 if (context
!= NULL
) {
4470 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4474 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4475 clientConnection
->close();
4478 /// Our close handler called by Comm when the pinned connection is closed
4480 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4482 // FwdState might repin a failed connection sooner than this close
4483 // callback is called for the failed connection.
4484 assert(pinning
.serverConnection
== io
.conn
);
4485 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4486 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4489 debugs(33, 3, "Closing client connection on pinned zero reply.");
4490 clientConnection
->close();
4495 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4497 char desc
[FD_DESC_SZ
];
4499 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4500 if (pinning
.serverConnection
->fd
== pinServer
->fd
)
4504 unpinConnection(); // closes pinned connection, if any, and resets fields
4506 pinning
.serverConnection
= pinServer
;
4508 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4510 // when pinning an SSL bumped connection, the request may be NULL
4511 const char *pinnedHost
= "[unknown]";
4513 pinning
.host
= xstrdup(request
->GetHost());
4514 pinning
.port
= request
->port
;
4515 pinnedHost
= pinning
.host
;
4517 pinning
.port
= pinServer
->remote
.port();
4519 pinning
.pinned
= true;
4521 pinning
.peer
= cbdataReference(aPeer
);
4522 pinning
.auth
= auth
;
4523 char stmp
[MAX_IPSTRLEN
];
4524 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4525 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4526 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4527 clientConnection
->fd
);
4528 fd_note(pinning
.serverConnection
->fd
, desc
);
4530 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4531 pinning
.closeHandler
= JobCallback(33, 5,
4532 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4533 // remember the pinned connection so that cb does not unpin a fresher one
4534 typedef CommCloseCbParams Params
;
4535 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4536 params
.conn
= pinning
.serverConnection
;
4537 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4540 const Comm::ConnectionPointer
4541 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4543 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4546 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4548 if (pinning
.auth
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0) {
4551 if (request
&& pinning
.port
!= request
->port
) {
4554 if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
)) {
4557 if (aPeer
!= pinning
.peer
) {
4562 /* The pinning info is not safe, remove any pinning info */
4566 return pinning
.serverConnection
;
4570 ConnStateData::unpinConnection()
4572 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4575 cbdataReferenceDone(pinning
.peer
);
4577 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4578 if (pinning
.closeHandler
!= NULL
) {
4579 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4580 pinning
.closeHandler
= NULL
;
4582 /// also close the server side socket, we should not use it for any future requests...
4583 // TODO: do not close if called from our close handler?
4584 pinning
.serverConnection
->close();
4587 safe_free(pinning
.host
);
4589 pinning
.zeroReply
= false;
4591 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4592 * connection has gone away */