2 * DEBUG: section 33 Client-side Routines
3 * AUTHOR: Duane Wessels
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 \defgroup ClientSide Client-Side Logics
35 \section cserrors Errors and client side
37 \par Problem the first:
38 * the store entry is no longer authoritative on the
39 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
40 * of client_side_reply.c.
41 * Problem the second: resources are wasted if we delay in cleaning up.
42 * Problem the third we can't depend on a connection close to clean up.
44 \par Nice thing the first:
45 * Any step in the stream can callback with data
46 * representing an error.
47 * Nice thing the second: once you stop requesting reads from upstream,
48 * upstream can be stopped too.
51 * Error has a callback mechanism to hand over a membuf
52 * with the error content. The failing node pushes that back as the
53 * reply. Can this be generalised to reduce duplicate efforts?
54 * A: Possibly. For now, only one location uses this.
55 * How to deal with pre-stream errors?
56 * Tell client_side_reply that we *want* an error page before any
57 * stream calls occur. Then we simply read as normal.
60 \section pconn_logic Persistent connection logic:
63 * requests (httpClientRequest structs) get added to the connection
64 * list, with the current one being chr
67 * The request is *immediately* kicked off, and data flows through
68 * to clientSocketRecipient.
71 * If the data that arrives at clientSocketRecipient is not for the current
72 * request, clientSocketRecipient simply returns, without requesting more
73 * data, or sending it.
76 * ClientKeepAliveNextRequest will then detect the presence of data in
77 * the next ClientHttpRequest, and will send it, restablishing the
82 #include "acl/FilledChecklist.h"
83 #include "anyp/PortCfg.h"
84 #include "base/Subscription.h"
85 #include "base/TextException.h"
86 #include "CachePeer.h"
87 #include "ChunkedCodingParser.h"
88 #include "client_db.h"
89 #include "client_side.h"
90 #include "client_side_reply.h"
91 #include "client_side_request.h"
92 #include "ClientRequestContext.h"
93 #include "clientStream.h"
95 #include "comm/Connection.h"
96 #include "comm/Loops.h"
97 #include "comm/TcpAcceptor.h"
98 #include "comm/Write.h"
99 #include "CommCalls.h"
100 #include "errorpage.h"
103 #include "fqdncache.h"
104 #include "FwdState.h"
107 #include "HttpHdrContRange.h"
108 #include "HttpHeaderTools.h"
109 #include "HttpReply.h"
110 #include "HttpRequest.h"
111 #include "ident/Config.h"
112 #include "ident/Ident.h"
113 #include "internal.h"
114 #include "ipc/FdNotes.h"
115 #include "ipc/StartListening.h"
116 #include "log/access_log.h"
119 #include "MemObject.h"
120 #include "mime_header.h"
121 #include "profiler/Profiler.h"
123 #include "SquidConfig.h"
124 #include "SquidTime.h"
125 #include "StatCounters.h"
126 #include "StatHist.h"
128 #include "TimeOrTag.h"
133 #include "auth/UserRequest.h"
136 #include "ClientInfo.h"
139 #include "ssl/context_storage.h"
140 #include "ssl/gadgets.h"
141 #include "ssl/helper.h"
142 #include "ssl/ProxyCerts.h"
143 #include "ssl/ServerBump.h"
144 #include "ssl/support.h"
147 #include "ssl/certificate_db.h"
148 #include "ssl/crtd_message.h"
162 #define comm_close comm_lingering_close
165 /// dials clientListenerConnectionOpened call
166 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
169 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
170 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
171 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
173 virtual void print(std::ostream
&os
) const {
175 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
178 virtual bool canDial(AsyncCall
&) const { return true; }
179 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
185 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
186 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
187 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
190 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
192 /* our socket-related context */
194 CBDATA_CLASS_INIT(ClientSocketContext
);
196 /* Local functions */
197 /* ClientSocketContext */
198 static ClientSocketContext
*ClientSocketContextNew(const Comm::ConnectionPointer
&clientConn
, ClientHttpRequest
*);
200 static IOCB clientWriteComplete
;
201 static IOCB clientWriteBodyComplete
;
202 static IOACB httpAccept
;
204 static IOACB httpsAccept
;
206 static CTCB clientLifetimeTimeout
;
207 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
208 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, Http::ProtocolVersion
*);
210 static IDCB clientIdentDone
;
212 static CSCB clientSocketRecipient
;
213 static CSD clientSocketDetach
;
214 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
215 static int clientIsContentLengthValid(HttpRequest
* r
);
216 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
218 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
219 static void clientUpdateStatCounters(LogTags logType
);
220 static void clientUpdateHierCounters(HierarchyLogEntry
*);
221 static bool clientPingHasFinished(ping_data
const *aPing
);
222 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
224 static bool connIsUsable(ConnStateData
* conn
);
226 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
227 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
228 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
230 char *skipLeadingSpace(char *aString
);
231 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
234 ClientSocketContext::getTail() const
236 if (http
->client_stream
.tail
)
237 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
243 ClientSocketContext::getClientReplyContext() const
245 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
249 * This routine should be called to grow the inbuf and then
253 ConnStateData::readSomeData()
258 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
260 if (!maybeMakeSpaceAvailable())
263 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
264 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
265 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
269 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
271 ClientSocketContext::Pointer
*tempContextPointer
;
272 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
273 assert(conn
->getCurrentContext() != NULL
);
274 /* Unlink us from the connection request list */
275 tempContextPointer
= & conn
->currentobject
;
277 while (tempContextPointer
->getRaw()) {
278 if (*tempContextPointer
== this)
281 tempContextPointer
= &(*tempContextPointer
)->next
;
284 assert(tempContextPointer
->getRaw() != NULL
);
285 *tempContextPointer
= next
;
289 ClientSocketContext::~ClientSocketContext()
291 clientStreamNode
*node
= getTail();
294 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
297 /* We are *always* the tail - prevent recursive free */
298 assert(this == streamContext
);
304 deRegisterWithConn();
306 httpRequestFree(http
);
308 /* clean up connection links to us */
309 assert(this != next
.getRaw());
313 ClientSocketContext::registerWithConn()
315 assert (!connRegistered_
);
317 assert (http
->getConn() != NULL
);
318 connRegistered_
= true;
319 http
->getConn()->addContextToQueue(this);
323 ClientSocketContext::deRegisterWithConn()
325 assert (connRegistered_
);
326 removeFromConnectionList(http
->getConn());
327 connRegistered_
= false;
331 ClientSocketContext::connIsFinished()
334 assert (http
->getConn() != NULL
);
335 deRegisterWithConn();
336 /* we can't handle any more stream data - detach */
337 clientStreamDetach(getTail(), http
);
340 ClientSocketContext::ClientSocketContext() : http(NULL
), reply(NULL
), next(NULL
),
342 mayUseConnection_ (false),
343 connRegistered_ (false)
345 memset (reqbuf
, '\0', sizeof (reqbuf
));
348 deferredparams
.node
= NULL
;
349 deferredparams
.rep
= NULL
;
352 ClientSocketContext
*
353 ClientSocketContextNew(const Comm::ConnectionPointer
&client
, ClientHttpRequest
* http
)
355 ClientSocketContext
*newContext
;
356 assert(http
!= NULL
);
357 newContext
= new ClientSocketContext
;
358 newContext
->http
= http
;
359 newContext
->clientConnection
= client
;
364 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
366 const HttpReply::Pointer
rep(msg
.reply
);
369 // apply selected clientReplyContext::buildReplyHeader() mods
370 // it is not clear what headers are required for control messages
371 rep
->header
.removeHopByHopEntries();
372 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
373 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
375 // remember the callback
376 cbControlMsgSent
= msg
.cbSuccess
;
378 MemBuf
*mb
= rep
->pack();
380 debugs(11, 2, "HTTP Client " << clientConnection
);
381 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
383 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
384 CommIoCbPtrFun(&WroteControlMsg
, this));
385 Comm::Write(clientConnection
, mb
, call
);
390 /// called when we wrote the 1xx response
392 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
394 if (errflag
== COMM_ERR_CLOSING
)
397 if (errflag
== COMM_OK
) {
398 ScheduleCallHere(cbControlMsgSent
);
402 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
403 // no error notification: see HttpControlMsg.h for rationale and
404 // note that some errors are detected elsewhere (e.g., close handler)
406 // close on 1xx errors to be conservative and to simplify the code
407 // (if we do not close, we must notify the source of a failure!)
411 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
413 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
415 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
416 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
421 clientIdentDone(const char *ident
, void *data
)
423 ConnStateData
*conn
= (ConnStateData
*)data
;
424 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
429 clientUpdateStatCounters(LogTags logType
)
431 ++statCounter
.client_http
.requests
;
433 if (logTypeIsATcpHit(logType
))
434 ++statCounter
.client_http
.hits
;
436 if (logType
== LOG_TCP_HIT
)
437 ++statCounter
.client_http
.disk_hits
;
438 else if (logType
== LOG_TCP_MEM_HIT
)
439 ++statCounter
.client_http
.mem_hits
;
443 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
445 statCounter
.client_http
.allSvcTime
.count(svc_time
);
447 * The idea here is not to be complete, but to get service times
448 * for only well-defined types. For example, we don't include
449 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
450 * (we *tried* to validate it, but failed).
455 case LOG_TCP_REFRESH_UNMODIFIED
:
456 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
459 case LOG_TCP_IMS_HIT
:
460 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
465 case LOG_TCP_MEM_HIT
:
467 case LOG_TCP_OFFLINE_HIT
:
468 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
473 case LOG_TCP_CLIENT_REFRESH_MISS
:
474 statCounter
.client_http
.missSvcTime
.count(svc_time
);
478 /* make compiler warnings go away */
484 clientPingHasFinished(ping_data
const *aPing
)
486 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
493 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
497 switch (someEntry
->code
) {
498 #if USE_CACHE_DIGESTS
503 ++ statCounter
.cd
.times_used
;
511 case FIRST_PARENT_MISS
:
513 case CLOSEST_PARENT_MISS
:
514 ++ statCounter
.icp
.times_used
;
515 i
= &someEntry
->ping
;
517 if (clientPingHasFinished(i
))
518 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
521 ++ statCounter
.icp
.query_timeouts
;
528 ++ statCounter
.netdb
.times_used
;
538 ClientHttpRequest::updateCounters()
540 clientUpdateStatCounters(logType
);
542 if (request
->errType
!= ERR_NONE
)
543 ++ statCounter
.client_http
.errors
;
545 clientUpdateStatHistCounters(logType
,
546 tvSubMsec(al
->cache
.start_time
, current_time
));
548 clientUpdateHierCounters(&request
->hier
);
552 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
555 assert(aLogEntry
!= NULL
);
557 if (Config
.onoff
.log_mime_hdrs
) {
561 packerToMemInit(&p
, &mb
);
562 request
->header
.packInto(&p
);
563 //This is the request after adaptation or redirection
564 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
566 // the virgin request is saved to aLogEntry->request
567 if (aLogEntry
->request
) {
570 packerToMemInit(&p
, &mb
);
571 aLogEntry
->request
->header
.packInto(&p
);
572 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
576 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
580 packerToMemInit(&p
, &mb
);
581 ah
->lastMeta
.packInto(&p
);
582 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
591 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
593 aLogEntry
->icap
.processingTime
= ih
->processingTime();
596 aLogEntry
->http
.method
= request
->method
;
597 aLogEntry
->http
.version
= request
->http_ver
;
598 aLogEntry
->hier
= request
->hier
;
599 if (request
->content_length
> 0) // negative when no body or unknown length
600 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
601 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
603 // Adapted request, if any, inherits and then collects all the stats, but
604 // the virgin request gets logged instead; copy the stats to log them.
605 // TODO: avoid losses by keeping these stats in a shared history object?
606 if (aLogEntry
->request
) {
607 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
608 aLogEntry
->request
->errType
= request
->errType
;
609 aLogEntry
->request
->errDetail
= request
->errDetail
;
614 ClientHttpRequest::logRequest()
616 if (!out
.size
&& !logType
)
617 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
619 al
->icp
.opcode
= ICP_INVALID
;
621 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
624 al
->http
.code
= al
->reply
->sline
.status();
625 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
626 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
627 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
628 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
631 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
633 if (loggingEntry() && loggingEntry()->mem_obj
)
634 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
636 al
->http
.clientRequestSz
.header
= req_sz
;
637 al
->http
.clientReplySz
.header
= out
.headers_sz
;
638 // XXX: calculate without payload encoding or headers !!
639 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
641 al
->cache
.highOffset
= out
.offset
;
643 al
->cache
.code
= logType
;
645 al
->cache
.msec
= tvSubMsec(al
->cache
.start_time
, current_time
);
648 prepareLogWithRequestDetails(request
, al
);
650 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
651 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
655 /* This is broken. Fails if the connection has been closed. Needs
656 * to snarf the ssl details some place earlier..
658 if (getConn() != NULL
)
659 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
664 // The al->notes and request->notes must point to the same object.
665 (void)SyncNotes(*al
, *request
);
666 typedef Notes::iterator ACAMLI
;
667 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
668 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
669 NotePairs
¬es
= SyncNotes(*al
, *request
);
670 notes
.add((*i
)->key
.termedBuf(), value
);
671 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
675 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
677 checklist
.reply
= al
->reply
;
678 HTTPMSGLOCK(checklist
.reply
);
682 al
->adapted_request
= request
;
683 HTTPMSGLOCK(al
->adapted_request
);
685 accessLogLog(al
, &checklist
);
687 bool updatePerformanceCounters
= true;
688 if (Config
.accessList
.stats_collection
) {
689 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
691 statsCheck
.reply
= al
->reply
;
692 HTTPMSGLOCK(statsCheck
.reply
);
694 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
697 if (updatePerformanceCounters
) {
701 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
702 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
707 ClientHttpRequest::freeResources()
711 safe_free(redirect
.location
);
712 range_iter
.boundary
.clean();
713 HTTPMSGUNLOCK(request
);
715 if (client_stream
.tail
)
716 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
720 httpRequestFree(void *data
)
722 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
723 assert(http
!= NULL
);
728 ConnStateData::areAllContextsForThisConnection() const
730 assert(this != NULL
);
731 ClientSocketContext::Pointer context
= getCurrentContext();
733 while (context
.getRaw()) {
734 if (context
->http
->getConn() != this)
737 context
= context
->next
;
744 ConnStateData::freeAllContexts()
746 ClientSocketContext::Pointer context
;
748 while ((context
= getCurrentContext()).getRaw() != NULL
) {
749 assert(getCurrentContext() !=
750 getCurrentContext()->next
);
751 context
->connIsFinished();
752 assert (context
!= currentobject
);
756 /// propagates abort event to all contexts
758 ConnStateData::notifyAllContexts(int xerrno
)
760 typedef ClientSocketContext::Pointer CSCP
;
761 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
762 c
->noteIoError(xerrno
);
765 /* This is a handler normally called by comm_close() */
766 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
768 deleteThis("ConnStateData::connStateClosed");
773 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
777 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
783 // clobered with self-pointer
784 // NP: something nasty is going on in Squid, but harmless.
786 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
791 * Connection-auth relies on a single set of credentials being preserved
792 * for all requests on a connection once they have been setup.
793 * There are several things which need to happen to preserve security
794 * when connection-auth credentials change unexpectedly or are unset.
796 * 1) auth helper released from any active state
798 * They can only be reserved by a handshake process which this
799 * connection can now never complete.
800 * This prevents helpers hanging when their connections close.
802 * 2) pinning is expected to be removed and server conn closed
804 * The upstream link is authenticated with the same credentials.
805 * Expecting the same level of consistency we should have received.
806 * This prevents upstream being faced with multiple or missing
807 * credentials after authentication.
808 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
809 * we just trigger that cleanup here via comm_reset_close() or
810 * ConnStateData::stopReceiving()
812 * 3) the connection needs to close.
814 * This prevents attackers injecting requests into a connection,
815 * or gateways wrongly multiplexing users into a single connection.
817 * When credentials are missing closure needs to follow an auth
818 * challenge for best recovery by the client.
820 * When credentials change there is nothing we can do but abort as
821 * fast as possible. Sending TCP RST instead of an HTTP response
822 * is the best-case action.
825 // clobbered with nul-pointer
827 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
828 auth_
->releaseAuthServer();
830 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
831 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
832 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
833 stopReceiving("connection-auth removed");
837 // clobbered with alternative credentials
839 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
840 auth_
->releaseAuthServer();
842 // this is a fatal type of problem.
843 // Close the connection immediately with TCP RST to abort all traffic flow
844 comm_reset_close(clientConnection
);
852 // cleans up before destructor is called
854 ConnStateData::swanSong()
856 debugs(33, 2, HERE
<< clientConnection
);
857 flags
.readMore
= false;
858 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
859 assert(areAllContextsForThisConnection());
864 if (Comm::IsConnOpen(clientConnection
))
865 clientConnection
->close();
868 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
869 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
872 BodyProducer::swanSong();
873 flags
.swanSang
= true;
877 ConnStateData::isOpen() const
879 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
880 Comm::IsConnOpen(clientConnection
) &&
881 !fd_table
[clientConnection
->fd
].closing();
884 ConnStateData::~ConnStateData()
886 assert(this != NULL
);
887 debugs(33, 3, HERE
<< clientConnection
);
890 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
893 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
895 cbdataReferenceDone(port
);
897 if (bodyPipe
!= NULL
)
898 stopProducingFor(bodyPipe
, false);
901 delete sslServerBump
;
906 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
907 * This is the client-side persistent connection flag. We need
908 * to set this relatively early in the request processing
909 * to handle hacks for broken servers and clients.
912 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
914 HttpRequest
*request
= http
->request
;
916 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
917 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
918 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
919 RequestMethodStr(request
->method
));
921 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
922 request
->flags
.proxyKeepalive
= request
->persistent();
926 clientIsContentLengthValid(HttpRequest
* r
)
928 switch (r
->method
.id()) {
930 case Http::METHOD_GET
:
932 case Http::METHOD_HEAD
:
933 /* We do not want to see a request entity on GET/HEAD requests */
934 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
937 /* For other types of requests we don't care */
945 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
947 if (Config
.maxRequestBodySize
&&
948 bodyLength
> Config
.maxRequestBodySize
)
949 return 1; /* too large */
956 connIsUsable(ConnStateData
* conn
)
958 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
966 // careful: the "current" context may be gone if we wrote an early response
967 ClientSocketContext::Pointer
968 ConnStateData::getCurrentContext() const
971 return currentobject
;
975 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
977 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
978 assert(flags
.deferred
== 0);
980 deferredparams
.node
= node
;
981 deferredparams
.rep
= rep
;
982 deferredparams
.queuedBuffer
= receivedData
;
987 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
989 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
996 ClientSocketContext::startOfOutput() const
998 return http
->out
.size
== 0;
1002 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
1004 /*the size of available range can always fit in a size_t type*/
1005 size_t maximum
= (size_t)available
.size();
1007 if (!http
->request
->range
)
1010 assert (canPackMoreRanges());
1012 if (http
->range_iter
.debt() == -1)
1015 assert (http
->range_iter
.debt() > 0);
1017 /* TODO this + the last line could be a range intersection calculation */
1018 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
1021 return min(http
->range_iter
.debt(), (int64_t)maximum
);
1025 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
1027 http
->out
.offset
+= bytes
;
1029 if (!http
->request
->range
)
1032 if (http
->range_iter
.debt() != -1) {
1033 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
1034 assert (http
->range_iter
.debt() >= 0);
1037 /* debt() always stops at -1, below that is a bug */
1038 assert (http
->range_iter
.debt() >= -1);
1042 ClientHttpRequest::multipartRangeRequest() const
1044 return request
->multipartRangeRequest();
1048 ClientSocketContext::multipartRangeRequest() const
1050 return http
->multipartRangeRequest();
1054 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1056 assert(rep
== NULL
);
1058 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1059 size_t length
= lengthToSend(bodyData
.range());
1060 noteSentBodyBytes (length
);
1061 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1062 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1063 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1069 if (multipartRangeRequest())
1070 packRange(bodyData
, &mb
);
1072 packChunk(bodyData
, mb
);
1074 if (mb
.contentSize()) {
1076 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1077 CommIoCbPtrFun(clientWriteComplete
, this));
1078 Comm::Write(clientConnection
, &mb
, call
);
1080 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1084 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1085 * if bodyData is empty.
1088 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1090 const uint64_t length
=
1091 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1092 noteSentBodyBytes(length
);
1094 mb
.Printf("%" PRIX64
"\r\n", length
);
1095 mb
.append(bodyData
.data
, length
);
1099 /** put terminating boundary for multiparts */
1101 clientPackTermBound(String boundary
, MemBuf
* mb
)
1103 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1104 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1107 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1109 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1111 HttpHeader
hdr(hoReply
);
1117 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1118 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1119 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1121 /* stuff the header with required entries and pack it */
1123 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1124 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1126 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1128 packerToMemInit(&p
, mb
);
1136 /* append <crlf> (we packed a header, not a reply) */
1141 * extracts a "range" from *buf and appends them to mb, updating
1142 * all offsets and such.
1145 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1147 HttpHdrRangeIter
* i
= &http
->range_iter
;
1148 Range
<int64_t> available (source
.range());
1149 char const *buf
= source
.data
;
1151 while (i
->currentSpec() && available
.size()) {
1152 const size_t copy_sz
= lengthToSend(available
);
1156 * intersection of "have" and "need" ranges must not be empty
1158 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1159 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1162 * put boundary and headers at the beginning of a range in a
1166 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1167 assert(http
->memObject());
1169 http
->memObject()->getReply(), /* original reply */
1170 i
->currentSpec(), /* current range */
1171 i
->boundary
, /* boundary, the same for all */
1178 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1180 noteSentBodyBytes (copy_sz
);
1182 mb
->append(buf
, copy_sz
);
1187 available
.start
+= copy_sz
;
1193 if (!canPackMoreRanges()) {
1194 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1197 /* put terminating boundary for multiparts */
1198 clientPackTermBound(i
->boundary
, mb
);
1203 int64_t nextOffset
= getNextRangeOffset();
1205 assert (nextOffset
>= http
->out
.offset
);
1207 int64_t skip
= nextOffset
- http
->out
.offset
;
1209 /* adjust for not to be transmitted bytes */
1210 http
->out
.offset
= nextOffset
;
1212 if (available
.size() <= (uint64_t)skip
)
1215 available
.start
+= skip
;
1224 /** returns expected content length for multi-range replies
1225 * note: assumes that httpHdrRangeCanonize has already been called
1226 * warning: assumes that HTTP headers for individual ranges at the
1227 * time of the actuall assembly will be exactly the same as
1228 * the headers when clientMRangeCLen() is called */
1230 ClientHttpRequest::mRangeCLen()
1235 assert(memObject());
1238 HttpHdrRange::iterator pos
= request
->range
->begin();
1240 while (pos
!= request
->range
->end()) {
1241 /* account for headers for this range */
1243 clientPackRangeHdr(memObject()->getReply(),
1244 *pos
, range_iter
.boundary
, &mb
);
1247 /* account for range content */
1248 clen
+= (*pos
)->length
;
1250 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1254 /* account for the terminating boundary */
1257 clientPackTermBound(range_iter
.boundary
, &mb
);
1267 * returns true if If-Range specs match reply, false otherwise
1270 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1272 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1273 /* check for parsing falure */
1280 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1281 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1282 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1285 return 0; /* entity has no etag to compare with! */
1287 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1288 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1289 return 0; /* must use strong validator for sub-range requests */
1292 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1295 /* got modification time? */
1296 if (spec
.time
>= 0) {
1297 return http
->storeEntry()->lastmod
<= spec
.time
;
1300 assert(0); /* should not happen */
1305 * generates a "unique" boundary string for multipart responses
1306 * the caller is responsible for cleaning the string */
1308 ClientHttpRequest::rangeBoundaryStr() const
1312 String
b(APP_FULLNAME
);
1314 key
= storeEntry()->getMD5Text();
1315 b
.append(key
, strlen(key
));
1319 /** adds appropriate Range headers if needed */
1321 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1323 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1324 const char *range_err
= NULL
;
1325 HttpRequest
*request
= http
->request
;
1326 assert(request
->range
);
1327 /* check if we still want to do ranges */
1329 int64_t roffLimit
= request
->getRangeOffsetLimit();
1332 range_err
= "no [parse-able] reply";
1333 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1334 range_err
= "wrong status code";
1335 else if (hdr
->has(HDR_CONTENT_RANGE
))
1336 range_err
= "origin server does ranges";
1337 else if (rep
->content_length
< 0)
1338 range_err
= "unknown length";
1339 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1340 range_err
= "INCONSISTENT length"; /* a bug? */
1342 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1345 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1346 range_err
= "If-Range match failed";
1347 else if (!http
->request
->range
->canonize(rep
))
1348 range_err
= "canonization failed";
1349 else if (http
->request
->range
->isComplex())
1350 range_err
= "too complex range header";
1351 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1352 range_err
= "range outside range_offset_limit";
1354 /* get rid of our range specs on error */
1356 /* XXX We do this here because we need canonisation etc. However, this current
1357 * code will lead to incorrect store offset requests - the store will have the
1358 * offset data, but we won't be requesting it.
1359 * So, we can either re-request, or generate an error
1361 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1362 delete http
->request
->range
;
1363 http
->request
->range
= NULL
;
1365 /* XXX: TODO: Review, this unconditional set may be wrong. */
1366 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1367 // web server responded with a valid, but unexpected range.
1368 // will (try-to) forward as-is.
1369 //TODO: we should cope with multirange request/responses
1370 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1371 request
->range
->contains(rep
->content_range
->spec
) :
1373 const int spec_count
= http
->request
->range
->specs
.count
;
1374 int64_t actual_clen
= -1;
1376 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1377 spec_count
<< " virgin clen: " << rep
->content_length
);
1378 assert(spec_count
> 0);
1379 /* append appropriate header(s) */
1381 if (spec_count
== 1) {
1382 if (!replyMatchRequest
) {
1383 hdr
->delById(HDR_CONTENT_RANGE
);
1384 hdr
->putContRange(rep
->content_range
);
1385 actual_clen
= rep
->content_length
;
1386 //http->range_iter.pos = rep->content_range->spec.begin();
1387 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1388 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1391 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1393 /* append Content-Range */
1395 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1396 /* No content range, so this was a full object we are
1399 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1402 /* set new Content-Length to the actual number of bytes
1403 * transmitted in the message-body */
1404 actual_clen
= (*pos
)->length
;
1408 /* generate boundary string */
1409 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1410 /* delete old Content-Type, add ours */
1411 hdr
->delById(HDR_CONTENT_TYPE
);
1412 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1413 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1414 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1415 /* Content-Length is not required in multipart responses
1416 * but it is always nice to have one */
1417 actual_clen
= http
->mRangeCLen();
1418 /* http->out needs to start where we want data at */
1419 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1422 /* replace Content-Length header */
1423 assert(actual_clen
>= 0);
1425 hdr
->delById(HDR_CONTENT_LENGTH
);
1427 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1429 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1431 /* And start the range iter off */
1432 http
->range_iter
.updateSpec();
1437 ClientSocketContext::prepareReply(HttpReply
* rep
)
1441 if (http
->request
->range
)
1442 buildRangeHeader(rep
);
1446 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1450 MemBuf
*mb
= rep
->pack();
1452 // dump now, so we dont output any body.
1453 debugs(11, 2, "HTTP Client " << clientConnection
);
1454 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1456 /* Save length of headers for persistent conn checks */
1457 http
->out
.headers_sz
= mb
->contentSize();
1460 headersLog(0, 0, http
->request
->method
, rep
);
1463 if (bodyData
.data
&& bodyData
.length
) {
1464 if (multipartRangeRequest())
1465 packRange(bodyData
, mb
);
1466 else if (http
->request
->flags
.chunkedReply
) {
1467 packChunk(bodyData
, *mb
);
1469 size_t length
= lengthToSend(bodyData
.range());
1470 noteSentBodyBytes (length
);
1472 mb
->append(bodyData
.data
, length
);
1477 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1478 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1479 CommIoCbPtrFun(clientWriteComplete
, this));
1480 Comm::Write(clientConnection
, mb
, call
);
1485 * Write a chunk of data to a client socket. If the reply is present,
1486 * send the reply headers down the wire too, and clean them up when
1489 * The request is one backed by a connection, not an internal request.
1490 * data context is not NULL
1491 * There are no more entries in the stream chain.
1494 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1495 HttpReply
* rep
, StoreIOBuffer receivedData
)
1497 /* Test preconditions */
1498 assert(node
!= NULL
);
1499 PROF_start(clientSocketRecipient
);
1500 /* TODO: handle this rather than asserting
1501 * - it should only ever happen if we cause an abort and
1502 * the callback chain loops back to here, so we can simply return.
1503 * However, that itself shouldn't happen, so it stays as an assert for now.
1505 assert(cbdataReferenceValid(node
));
1506 assert(node
->node
.next
== NULL
);
1507 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1508 assert(context
!= NULL
);
1509 assert(connIsUsable(http
->getConn()));
1511 /* TODO: check offset is what we asked for */
1513 if (context
!= http
->getConn()->getCurrentContext()) {
1514 context
->deferRecipientForLater(node
, rep
, receivedData
);
1515 PROF_stop(clientSocketRecipient
);
1519 // After sending Transfer-Encoding: chunked (at least), always send
1520 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1521 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1522 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1523 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1524 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1525 PROF_stop(clientSocketRecipient
);
1529 if (!context
->startOfOutput())
1530 context
->sendBody(rep
, receivedData
);
1533 http
->al
->reply
= rep
;
1534 HTTPMSGLOCK(http
->al
->reply
);
1535 context
->sendStartOfMessage(rep
, receivedData
);
1538 PROF_stop(clientSocketRecipient
);
1542 * Called when a downstream node is no longer interested in
1543 * our data. As we are a terminal node, this means on aborts
1547 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1549 /* Test preconditions */
1550 assert(node
!= NULL
);
1551 /* TODO: handle this rather than asserting
1552 * - it should only ever happen if we cause an abort and
1553 * the callback chain loops back to here, so we can simply return.
1554 * However, that itself shouldn't happen, so it stays as an assert for now.
1556 assert(cbdataReferenceValid(node
));
1557 /* Set null by ContextFree */
1558 assert(node
->node
.next
== NULL
);
1559 /* this is the assert discussed above */
1560 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1561 /* We are only called when the client socket shutsdown.
1562 * Tell the prev pipeline member we're finished
1564 clientStreamDetach(node
, http
);
1568 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1570 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1571 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1575 ConnStateData::readNextRequest()
1577 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1579 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1581 * Set the timeout BEFORE calling clientReadRequest().
1583 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1584 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1585 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1586 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1589 /** Please don't do anything with the FD past here! */
1593 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1595 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1597 /** If the client stream is waiting on a socket write to occur, then */
1599 if (deferredRequest
->flags
.deferred
) {
1600 /** NO data is allowed to have been sent. */
1601 assert(deferredRequest
->http
->out
.size
== 0);
1603 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1604 deferredRequest
->http
,
1605 deferredRequest
->deferredparams
.rep
,
1606 deferredRequest
->deferredparams
.queuedBuffer
);
1609 /** otherwise, the request is still active in a callbacksomewhere,
1614 /// called when we have successfully finished writing the response
1616 ClientSocketContext::keepaliveNextRequest()
1618 ConnStateData
* conn
= http
->getConn();
1620 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1623 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1624 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1625 conn
->clientConnection
->close();
1630 * We are done with the response, and we are either still receiving request
1631 * body (early response!) or have already stopped receiving anything.
1633 * If we are still receiving, then clientParseRequest() below will fail.
1634 * (XXX: but then we will call readNextRequest() which may succeed and
1635 * execute a smuggled request as we are not done with the current request).
1637 * If we stopped because we got everything, then try the next request.
1639 * If we stopped receiving because of an error, then close now to avoid
1640 * getting stuck and to prevent accidental request smuggling.
1643 if (const char *reason
= conn
->stoppedReceiving()) {
1644 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1645 conn
->clientConnection
->close();
1650 * Attempt to parse a request from the request buffer.
1651 * If we've been fed a pipelined request it may already
1652 * be in our read buffer.
1655 * This needs to fall through - if we're unlucky and parse the _last_ request
1656 * from our read buffer we may never re-register for another client read.
1659 if (conn
->clientParseRequests()) {
1660 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1664 * Either we need to kick-start another read or, if we have
1665 * a half-closed connection, kill it after the last request.
1666 * This saves waiting for half-closed connections to finished being
1667 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1668 * the keepalive "Waiting for next request" state.
1670 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1671 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1672 conn
->clientConnection
->close();
1676 ClientSocketContext::Pointer deferredRequest
;
1679 * At this point we either have a parsed request (which we've
1680 * kicked off the processing for) or not. If we have a deferred
1681 * request (parsed but deferred for pipeling processing reasons)
1682 * then look at processing it. If not, simply kickstart
1686 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1687 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1688 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1689 } else if (conn
->flags
.readMore
) {
1690 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1691 conn
->readNextRequest();
1693 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1694 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1699 clientUpdateSocketStats(LogTags logType
, size_t size
)
1704 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1706 if (logTypeIsATcpHit(logType
))
1707 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1711 * increments iterator "i"
1712 * used by clientPackMoreRanges
1714 \retval true there is still data available to pack more ranges
1718 ClientSocketContext::canPackMoreRanges() const
1720 /** first update iterator "i" if needed */
1722 if (!http
->range_iter
.debt()) {
1723 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1725 if (http
->range_iter
.pos
.incrementable())
1726 ++http
->range_iter
.pos
;
1728 http
->range_iter
.updateSpec();
1731 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1733 /* paranoid sync condition */
1734 /* continue condition: need_more_data */
1735 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1736 return http
->range_iter
.currentSpec() ? true : false;
1740 ClientSocketContext::getNextRangeOffset() const
1742 if (http
->request
->range
) {
1743 /* offset in range specs does not count the prefix of an http msg */
1744 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1745 /* check: reply was parsed and range iterator was initialized */
1746 assert(http
->range_iter
.valid
);
1747 /* filter out data according to range specs */
1748 assert (canPackMoreRanges());
1750 int64_t start
; /* offset of still missing data */
1751 assert(http
->range_iter
.currentSpec());
1752 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1753 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1754 debugs(33, 3, "clientPackMoreRanges: out:"
1755 " start: " << start
<<
1756 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1757 " [" << http
->range_iter
.currentSpec()->offset
<<
1758 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1759 " len: " << http
->range_iter
.currentSpec()->length
<<
1760 " debt: " << http
->range_iter
.debt());
1761 if (http
->range_iter
.currentSpec()->length
!= -1)
1762 assert(http
->out
.offset
<= start
); /* we did not miss it */
1767 } else if (reply
&& reply
->content_range
) {
1768 /* request does not have ranges, but reply does */
1769 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1770 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1772 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1775 return http
->out
.offset
;
1779 ClientSocketContext::pullData()
1781 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1783 /* More data will be coming from the stream. */
1784 StoreIOBuffer readBuffer
;
1785 /* XXX: Next requested byte in the range sequence */
1786 /* XXX: length = getmaximumrangelenfgth */
1787 readBuffer
.offset
= getNextRangeOffset();
1788 readBuffer
.length
= HTTP_REQBUF_SZ
;
1789 readBuffer
.data
= reqbuf
;
1790 /* we may note we have reached the end of the wanted ranges */
1791 clientStreamRead(getTail(), http
, readBuffer
);
1794 clientStream_status_t
1795 ClientSocketContext::socketState()
1797 switch (clientStreamStatus(getTail(), http
)) {
1800 /* check for range support ending */
1802 if (http
->request
->range
) {
1803 /* check: reply was parsed and range iterator was initialized */
1804 assert(http
->range_iter
.valid
);
1805 /* filter out data according to range specs */
1807 if (!canPackMoreRanges()) {
1808 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1809 "range sequence on " << clientConnection
);
1811 if (http
->request
->flags
.proxyKeepalive
)
1812 return STREAM_COMPLETE
;
1814 return STREAM_UNPLANNED_COMPLETE
;
1816 } else if (reply
&& reply
->content_range
) {
1817 /* reply has content-range, but Squid is not managing ranges */
1818 const int64_t &bytesSent
= http
->out
.offset
;
1819 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1821 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1822 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1823 reply
->content_range
->spec
.offset
<< ")");
1825 // did we get at least what we expected, based on range specs?
1827 if (bytesSent
== bytesExpected
) { // got everything
1828 if (http
->request
->flags
.proxyKeepalive
)
1829 return STREAM_COMPLETE
;
1831 return STREAM_UNPLANNED_COMPLETE
;
1834 // The logic below is not clear: If we got more than we
1835 // expected why would persistency matter? Should not this
1836 // always be an error?
1837 if (bytesSent
> bytesExpected
) { // got extra
1838 if (http
->request
->flags
.proxyKeepalive
)
1839 return STREAM_COMPLETE
;
1841 return STREAM_UNPLANNED_COMPLETE
;
1844 // did not get enough yet, expecting more
1849 case STREAM_COMPLETE
:
1850 return STREAM_COMPLETE
;
1852 case STREAM_UNPLANNED_COMPLETE
:
1853 return STREAM_UNPLANNED_COMPLETE
;
1856 return STREAM_FAILED
;
1859 fatal ("unreachable code\n");
1864 * A write has just completed to the client, or we have just realised there is
1865 * no more data to send.
1868 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1870 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1871 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1874 /// remembers the abnormal connection termination for logging purposes
1876 ClientSocketContext::noteIoError(const int xerrno
)
1879 if (xerrno
== ETIMEDOUT
)
1880 http
->al
->http
.timedout
= true;
1881 else // even if xerrno is zero (which means read abort/eof)
1882 http
->al
->http
.aborted
= true;
1887 ClientSocketContext::doClose()
1889 clientConnection
->close();
1892 /// called when we encounter a response-related error
1894 ClientSocketContext::initiateClose(const char *reason
)
1896 http
->getConn()->stopSending(reason
); // closes ASAP
1900 ConnStateData::stopSending(const char *error
)
1902 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1903 "; old receiving error: " <<
1904 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1906 if (const char *oldError
= stoppedSending()) {
1907 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1908 return; // nothing has changed as far as this connection is concerned
1910 stoppedSending_
= error
;
1912 if (!stoppedReceiving()) {
1913 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1914 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1915 " request body bytes with " << in
.notYetUsed
<< " unused");
1916 return; // wait for the request receiver to finish reading
1920 clientConnection
->close();
1924 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1926 const StoreEntry
*entry
= http
->storeEntry();
1927 http
->out
.size
+= size
;
1928 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1929 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1930 (entry
? entry
->objectLen() : 0));
1931 clientUpdateSocketStats(http
->logType
, size
);
1933 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1935 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1938 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1939 initiateClose("failure or true request status");
1940 /* Do we leak here ? */
1944 switch (socketState()) {
1950 case STREAM_COMPLETE
:
1951 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1952 keepaliveNextRequest();
1955 case STREAM_UNPLANNED_COMPLETE
:
1956 initiateClose("STREAM_UNPLANNED_COMPLETE");
1960 initiateClose("STREAM_FAILED");
1964 fatal("Hit unreachable code in clientWriteComplete\n");
1968 SQUIDCEXTERN CSR clientGetMoreData
;
1969 SQUIDCEXTERN CSS clientReplyStatus
;
1970 SQUIDCEXTERN CSD clientReplyDetach
;
1972 static ClientSocketContext
*
1973 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1975 ClientHttpRequest
*http
;
1976 ClientSocketContext
*context
;
1977 StoreIOBuffer tempBuffer
;
1978 http
= new ClientHttpRequest(csd
);
1979 http
->req_sz
= csd
->in
.notYetUsed
;
1980 http
->uri
= xstrdup(uri
);
1981 setLogUri (http
, uri
);
1982 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
1983 tempBuffer
.data
= context
->reqbuf
;
1984 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1985 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1986 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1987 clientSocketDetach
, context
, tempBuffer
);
1992 skipLeadingSpace(char *aString
)
1994 char *result
= aString
;
1996 while (xisspace(*aString
))
2003 * 'end' defaults to NULL for backwards compatibility
2004 * remove default value if we ever get rid of NULL-terminated
2008 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
2011 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
2015 for (; end
> uriAndHTTPVersion
; --end
) {
2016 if (*end
== '\n' || *end
== '\r')
2019 if (xisspace(*end
)) {
2020 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2031 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2033 safe_free(http
->log_uri
);
2036 // The uri is already clean just dump it.
2037 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2040 switch (Config
.uri_whitespace
) {
2041 case URI_WHITESPACE_ALLOW
:
2042 flags
|= RFC1738_ESCAPE_NOSPACE
;
2044 case URI_WHITESPACE_ENCODE
:
2045 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2046 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2049 case URI_WHITESPACE_CHOP
: {
2050 flags
|= RFC1738_ESCAPE_NOSPACE
;
2051 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2052 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2053 int pos
= strcspn(http
->log_uri
, w_space
);
2054 http
->log_uri
[pos
] = '\0';
2058 case URI_WHITESPACE_DENY
:
2059 case URI_WHITESPACE_STRIP
:
2062 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2066 if (!xisspace(*t
)) {
2073 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2082 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2084 int vhost
= conn
->port
->vhost
;
2085 int vport
= conn
->port
->vport
;
2087 char ipbuf
[MAX_IPSTRLEN
];
2089 http
->flags
.accel
= true;
2091 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2093 if (strncasecmp(url
, "cache_object://", 15) == 0)
2094 return; /* already in good shape */
2097 if (conn
->port
->vhost
)
2098 return; /* already in good shape */
2100 /* else we need to ignore the host name */
2101 url
= strstr(url
, "//");
2103 #if SHOULD_REJECT_UNKNOWN_URLS
2106 hp
->request_parse_status
= Http::scBadRequest
;
2107 return parseHttpRequestAbort(conn
, "error:invalid-request");
2112 url
= strchr(url
+ 2, '/');
2119 vport
= http
->getConn()->clientConnection
->local
.port();
2121 const bool switchedToHttps
= conn
->switchedToHttps();
2122 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2123 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2124 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2129 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2130 strncpy(thost
, host
, (t
-host
));
2131 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2134 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2137 } // else nothing to alter port-wise.
2138 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2140 http
->uri
= (char *)xcalloc(url_sz
, 1);
2141 const char *protocol
= switchedToHttps
?
2142 "https" : URLScheme(conn
->port
->transport
.protocol
).const_str();
2143 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2144 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2145 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2146 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2147 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2148 strlen(conn
->port
->defaultsite
);
2149 http
->uri
= (char *)xcalloc(url_sz
, 1);
2153 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2155 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2156 URLScheme(conn
->port
->transport
.protocol
).const_str(), conn
->port
->defaultsite
, vportStr
, url
);
2157 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2158 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2159 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2160 /* Put the local socket IP address as the hostname, with whatever vport we found */
2161 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2162 http
->uri
= (char *)xcalloc(url_sz
, 1);
2163 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2164 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2165 URLScheme(conn
->port
->transport
.protocol
).const_str(),
2167 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2172 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2175 char ipbuf
[MAX_IPSTRLEN
];
2178 return; /* already in good shape */
2180 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2182 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2183 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2185 http
->uri
= (char *)xcalloc(url_sz
, 1);
2186 snprintf(http
->uri
, url_sz
, "%s://%s%s", URLScheme(conn
->port
->transport
.protocol
).const_str(), host
, url
);
2187 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2189 /* Put the local socket IP address as the hostname. */
2190 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2191 http
->uri
= (char *)xcalloc(url_sz
, 1);
2192 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2193 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2194 URLScheme(http
->getConn()->port
->transport
.protocol
).const_str(),
2195 ipbuf
, http
->getConn()->clientConnection
->local
.port(), url
);
2196 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2200 /** Parse an HTTP request
2202 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2203 * to 1 if the request was correctly parsed.
2204 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2205 * \param[in] hp an HttpParser
2206 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2207 * Pointed-to value will be set to Http::METHOD_NONE in case of
2209 * \param[out] http_ver will be set as a side-effect of the parsing
2210 * \return NULL on incomplete requests,
2211 * a ClientSocketContext structure on success or failure.
2213 static ClientSocketContext
*
2214 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2216 char *req_hdr
= NULL
;
2219 ClientHttpRequest
*http
;
2220 ClientSocketContext
*result
;
2221 StoreIOBuffer tempBuffer
;
2224 /* pre-set these values to make aborting simpler */
2225 *method_p
= Http::METHOD_NONE
;
2227 /* NP: don't be tempted to move this down or remove again.
2228 * It's the only DDoS protection old-String has against long URL */
2229 if ( hp
->bufsiz
<= 0) {
2230 debugs(33, 5, "Incomplete request, waiting for end of request line");
2232 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2233 debugs(33, 5, "parseHttpRequest: Too large request");
2234 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2235 return parseHttpRequestAbort(csd
, "error:request-too-large");
2238 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2239 r
= HttpParserParseReqLine(hp
);
2242 debugs(33, 5, "Incomplete request, waiting for end of request line");
2247 return parseHttpRequestAbort(csd
, "error:invalid-request");
2250 /* Request line is valid here .. */
2251 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2253 /* This call scans the entire request, not just the headers */
2254 if (hp
->req
.v_maj
> 0) {
2255 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2256 debugs(33, 5, "Incomplete request, waiting for end of headers");
2260 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2261 req_sz
= HttpParserReqSz(hp
);
2264 /* We know the whole request is in hp->buf now */
2266 assert(req_sz
<= (size_t) hp
->bufsiz
);
2268 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2269 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2272 hp
->hdr_end
= req_sz
- 1;
2274 hp
->hdr_start
= hp
->req
.end
+ 1;
2276 /* Enforce max_request_size */
2277 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2278 debugs(33, 5, "parseHttpRequest: Too large request");
2279 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2280 return parseHttpRequestAbort(csd
, "error:request-too-large");
2284 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2286 /* deny CONNECT via accelerated ports */
2287 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2288 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->transport
.protocol
<< " Accelerator port " << csd
->port
->s
.port());
2289 /* XXX need a way to say "this many character length string" */
2290 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2291 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2292 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2295 if (*method_p
== Http::METHOD_NONE
) {
2296 /* XXX need a way to say "this many character length string" */
2297 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2298 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2299 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2303 * Process headers after request line
2304 * TODO: Use httpRequestParse here.
2306 /* XXX this code should be modified to take a const char * later! */
2307 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2309 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2311 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2313 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2315 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2316 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2317 HttpParserReqSz(hp
));
2319 /* Ok, all headers are received */
2320 http
= new ClientHttpRequest(csd
);
2322 http
->req_sz
= HttpParserRequestLen(hp
);
2323 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2324 tempBuffer
.data
= result
->reqbuf
;
2325 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2327 ClientStreamData newServer
= new clientReplyContext(http
);
2328 ClientStreamData newClient
= result
;
2329 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2330 clientReplyStatus
, newServer
, clientSocketRecipient
,
2331 clientSocketDetach
, newClient
, tempBuffer
);
2333 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2337 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2338 * below needs to be modified to not expect a mutable nul-terminated string.
2340 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2342 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2344 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2346 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2348 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2353 debugs(33,5, HERE
<< "repare absolute URL from " <<
2354 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2355 /* Rewrite the URL in transparent or accelerator mode */
2356 /* NP: there are several cases to traverse here:
2357 * - standard mode (forward proxy)
2358 * - transparent mode (TPROXY)
2359 * - transparent mode with failures
2360 * - intercept mode (NAT)
2361 * - intercept mode with failures
2362 * - accelerator mode (reverse proxy)
2364 * - mixed combos of the above with internal URL
2366 if (csd
->transparent()) {
2367 /* intercept or transparent mode, properly working with no failures */
2368 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2370 } else if (internalCheck(url
)) {
2371 /* internal URL mode */
2372 /* prepend our name & port */
2373 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2374 // We just re-wrote the URL. Must replace the Host: header.
2375 // But have not parsed there yet!! flag for local-only handling.
2376 http
->flags
.internal
= true;
2378 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2379 /* accelerator mode */
2380 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2384 /* No special rewrites have been applied above, use the
2385 * requested url. may be rewritten later, so make extra room */
2386 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2387 http
->uri
= (char *)xcalloc(url_sz
, 1);
2388 strcpy(http
->uri
, url
);
2391 debugs(33, 5, "parseHttpRequest: Complete request received");
2393 // XXX: crop this dump at the end of headers. No need for extras
2394 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2395 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2397 result
->flags
.parsed_ok
= 1;
2403 ConnStateData::getAvailableBufferLength() const
2405 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2406 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2407 // huge request_header_max_size may lead to more than INT_MAX unused space
2408 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2413 ConnStateData::maybeMakeSpaceAvailable()
2415 if (getAvailableBufferLength() < 2) {
2417 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2418 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2421 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2422 newSize
=Config
.maxRequestBufferSize
;
2424 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2425 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2431 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2433 ClientSocketContext::Pointer
*S
;
2435 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2443 ConnStateData::getConcurrentRequestCount() const
2446 ClientSocketContext::Pointer
*T
;
2448 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2449 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2454 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2456 if (flag
!= COMM_OK
) {
2457 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2462 if (!ignoreErrno(xerrno
)) {
2463 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2465 } else if (in
.notYetUsed
== 0) {
2466 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2474 ConnStateData::connFinishedWithConn(int size
)
2477 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2478 /* no current or pending requests */
2479 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2481 } else if (!Config
.onoff
.half_closed_clients
) {
2482 /* admin doesn't want to support half-closed client sockets */
2483 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2484 notifyAllContexts(0); // no specific error implies abort
2493 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2495 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2496 conn
->in
.notYetUsed
-= byteCount
;
2497 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2499 * If there is still data that will be used,
2500 * move it to the beginning.
2503 if (conn
->in
.notYetUsed
> 0)
2504 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2507 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2509 ConnStateData::checkHeaderLimits()
2511 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2512 return; // can accumulte more header data
2514 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2515 Config
.maxRequestHeaderSize
<< " bytes)");
2517 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2518 clientStreamNode
*node
= context
->getClientReplyContext();
2519 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2520 assert (repContext
);
2521 repContext
->setReplyToError(ERR_TOO_BIG
,
2522 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2523 clientConnection
->remote
, NULL
, NULL
, NULL
);
2524 context
->registerWithConn();
2525 context
->pullData();
2529 ConnStateData::clientAfterReadingRequests()
2531 // Were we expecting to read more request body from half-closed connection?
2532 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2533 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2534 clientConnection
->close();
2543 ConnStateData::quitAfterError(HttpRequest
*request
)
2545 // From HTTP p.o.v., we do not have to close after every error detected
2546 // at the client-side, but many such errors do require closure and the
2547 // client-side code is bad at handling errors so we play it safe.
2549 request
->flags
.proxyKeepalive
= false;
2550 flags
.readMore
= false;
2551 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2555 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2557 ClientHttpRequest
*http
= context
->http
;
2562 assert(sslServerBump
->entry
);
2563 // Did we create an error entry while processing CONNECT?
2564 if (!sslServerBump
->entry
->isEmpty()) {
2565 quitAfterError(http
->request
);
2567 // Get the saved error entry and send it to the client by replacing the
2568 // ClientHttpRequest store entry with it.
2569 clientStreamNode
*node
= context
->getClientReplyContext();
2570 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2572 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2573 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2575 // save the original request for logging purposes
2576 if (!context
->http
->al
->request
) {
2577 context
->http
->al
->request
= http
->request
;
2578 HTTPMSGLOCK(context
->http
->al
->request
);
2581 // Get error details from the fake certificate-peeking request.
2582 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2583 context
->pullData();
2587 // In bump-server-first mode, we have not necessarily seen the intended
2588 // server name at certificate-peeking time. Check for domain mismatch now,
2589 // when we can extract the intended name from the bumped HTTP request.
2590 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2591 HttpRequest
*request
= http
->request
;
2592 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2593 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2594 "does not match domainname " << request
->GetHost());
2596 bool allowDomainMismatch
= false;
2597 if (Config
.ssl_client
.cert_error
) {
2598 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2599 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2600 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2601 delete check
.sslErrors
;
2602 check
.sslErrors
= NULL
;
2605 if (!allowDomainMismatch
) {
2606 quitAfterError(request
);
2608 clientStreamNode
*node
= context
->getClientReplyContext();
2609 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2610 assert (repContext
);
2612 // Fill the server IP and hostname for error page generation.
2613 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2614 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2616 // Create an error object and fill it
2617 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2618 err
->src_addr
= clientConnection
->remote
;
2619 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2620 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2622 err
->detail
= errDetail
;
2623 // Save the original request for logging purposes.
2624 if (!context
->http
->al
->request
) {
2625 context
->http
->al
->request
= request
;
2626 HTTPMSGLOCK(context
->http
->al
->request
);
2628 repContext
->setReplyToError(request
->method
, err
);
2629 assert(context
->http
->out
.offset
== 0);
2630 context
->pullData();
2641 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2643 ClientHttpRequest
*http
= context
->http
;
2644 HttpRequest::Pointer request
;
2645 bool notedUseOfBuffer
= false;
2646 bool chunked
= false;
2647 bool mustReplyToOptions
= false;
2648 bool unsupportedTe
= false;
2649 bool expectBody
= false;
2651 /* We have an initial client stream in place should it be needed */
2652 /* setup our private context */
2653 context
->registerWithConn();
2655 if (context
->flags
.parsed_ok
== 0) {
2656 clientStreamNode
*node
= context
->getClientReplyContext();
2657 debugs(33, 2, "clientProcessRequest: Invalid Request");
2658 conn
->quitAfterError(NULL
);
2659 // setLogUri should called before repContext->setReplyToError
2660 setLogUri(http
, http
->uri
, true);
2661 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2662 assert (repContext
);
2663 switch (hp
->request_parse_status
) {
2664 case Http::scHeaderTooLarge
:
2665 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2667 case Http::scMethodNotAllowed
:
2668 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2669 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2672 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2673 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2675 assert(context
->http
->out
.offset
== 0);
2676 context
->pullData();
2680 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2681 clientStreamNode
*node
= context
->getClientReplyContext();
2682 debugs(33, 5, "Invalid URL: " << http
->uri
);
2683 conn
->quitAfterError(request
.getRaw());
2684 // setLogUri should called before repContext->setReplyToError
2685 setLogUri(http
, http
->uri
, true);
2686 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2687 assert (repContext
);
2688 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2689 assert(context
->http
->out
.offset
== 0);
2690 context
->pullData();
2694 /* RFC 2616 section 10.5.6 : handle unsupported HTTP major versions cleanly. */
2695 /* We currently only support 0.9, 1.0, 1.1 properly */
2696 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2697 (http_ver
.major
> 1) ) {
2699 clientStreamNode
*node
= context
->getClientReplyContext();
2700 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2701 conn
->quitAfterError(request
.getRaw());
2702 // setLogUri should called before repContext->setReplyToError
2703 setLogUri(http
, http
->uri
, true);
2704 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2705 assert (repContext
);
2706 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2707 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2708 assert(context
->http
->out
.offset
== 0);
2709 context
->pullData();
2713 /* compile headers */
2714 /* we should skip request line! */
2715 /* XXX should actually know the damned buffer size here */
2716 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2717 clientStreamNode
*node
= context
->getClientReplyContext();
2718 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2719 conn
->quitAfterError(request
.getRaw());
2720 // setLogUri should called before repContext->setReplyToError
2721 setLogUri(http
, http
->uri
, true);
2722 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2723 assert (repContext
);
2724 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2725 assert(context
->http
->out
.offset
== 0);
2726 context
->pullData();
2730 request
->clientConnectionManager
= conn
;
2732 request
->flags
.accelerated
= http
->flags
.accel
;
2733 request
->flags
.sslBumped
=conn
->switchedToHttps();
2734 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2735 // TODO: decouple http->flags.accel from request->flags.sslBumped
2736 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2737 !conn
->port
->allow_direct
: 0;
2739 if (request
->flags
.sslBumped
) {
2740 if (conn
->getAuth() != NULL
)
2741 request
->auth_user_request
= conn
->getAuth();
2746 * If transparent or interception mode is working clone the transparent and interception flags
2747 * from the port settings to the request.
2749 if (http
->clientConnection
!= NULL
) {
2750 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2751 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2752 if (request
->flags
.interceptTproxy
) {
2753 if (Config
.accessList
.spoof_client_ip
) {
2754 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2755 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2758 request
->flags
.spoofClientIp
= true;
2760 request
->flags
.spoofClientIp
= false;
2763 if (internalCheck(request
->urlpath
.termedBuf())) {
2764 if (internalHostnameIs(request
->GetHost()) &&
2765 request
->port
== getMyPort()) {
2766 http
->flags
.internal
= true;
2767 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2768 request
->SetHost(internalHostname());
2769 request
->port
= getMyPort();
2770 http
->flags
.internal
= true;
2774 if (http
->flags
.internal
) {
2775 request
->protocol
= AnyP::PROTO_HTTP
;
2776 request
->login
[0] = '\0';
2779 request
->flags
.internal
= http
->flags
.internal
;
2780 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2781 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2782 #if FOLLOW_X_FORWARDED_FOR
2783 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2784 // not a details about teh TCP connection itself
2785 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2786 #endif /* FOLLOW_X_FORWARDED_FOR */
2787 request
->my_addr
= conn
->clientConnection
->local
;
2788 request
->myportname
= conn
->port
->name
;
2789 request
->http_ver
= http_ver
;
2791 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2792 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2793 request
->clientConnectionManager
= conn
;
2795 if (request
->header
.chunked()) {
2797 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2798 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2799 // HTTP/1.1 requires chunking to be the last encoding if there is one
2800 unsupportedTe
= te
.size() && te
!= "identity";
2801 } // else implied identity coding
2803 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2804 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2805 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2806 clientStreamNode
*node
= context
->getClientReplyContext();
2807 conn
->quitAfterError(request
.getRaw());
2808 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2809 assert (repContext
);
2810 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2811 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2812 assert(context
->http
->out
.offset
== 0);
2813 context
->pullData();
2817 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2818 clientStreamNode
*node
= context
->getClientReplyContext();
2819 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2820 assert (repContext
);
2821 conn
->quitAfterError(request
.getRaw());
2822 repContext
->setReplyToError(ERR_INVALID_REQ
,
2823 Http::scLengthRequired
, request
->method
, NULL
,
2824 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2825 assert(context
->http
->out
.offset
== 0);
2826 context
->pullData();
2830 if (request
->header
.has(HDR_EXPECT
)) {
2831 const String expect
= request
->header
.getList(HDR_EXPECT
);
2832 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2833 if (!supportedExpect
) {
2834 clientStreamNode
*node
= context
->getClientReplyContext();
2835 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2836 assert (repContext
);
2837 conn
->quitAfterError(request
.getRaw());
2838 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2839 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2840 assert(context
->http
->out
.offset
== 0);
2841 context
->pullData();
2846 http
->request
= request
.getRaw();
2847 HTTPMSGLOCK(http
->request
);
2848 clientSetKeepaliveFlag(http
);
2850 // Let tunneling code be fully responsible for CONNECT requests
2851 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2852 context
->mayUseConnection(true);
2853 conn
->flags
.readMore
= false;
2857 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2861 /* Do we expect a request-body? */
2862 expectBody
= chunked
|| request
->content_length
> 0;
2863 if (!context
->mayUseConnection() && expectBody
) {
2864 request
->body_pipe
= conn
->expectRequestBody(
2865 chunked
? -1 : request
->content_length
);
2867 // consume header early so that body pipe gets just the body
2868 connNoteUseOfBuffer(conn
, http
->req_sz
);
2869 notedUseOfBuffer
= true;
2871 /* Is it too large? */
2872 if (!chunked
&& // if chunked, we will check as we accumulate
2873 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2874 clientStreamNode
*node
= context
->getClientReplyContext();
2875 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2876 assert (repContext
);
2877 conn
->quitAfterError(request
.getRaw());
2878 repContext
->setReplyToError(ERR_TOO_BIG
,
2879 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2880 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2881 assert(context
->http
->out
.offset
== 0);
2882 context
->pullData();
2886 // We may stop producing, comm_close, and/or call setReplyToError()
2887 // below, so quit on errors to avoid http->doCallouts()
2888 if (!conn
->handleRequestBodyData())
2891 if (!request
->body_pipe
->productionEnded()) {
2892 debugs(33, 5, HERE
<< "need more request body");
2893 context
->mayUseConnection(true);
2894 assert(conn
->flags
.readMore
);
2898 http
->calloutContext
= new ClientRequestContext(http
);
2903 if (!notedUseOfBuffer
)
2904 connNoteUseOfBuffer(conn
, http
->req_sz
);
2908 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2909 * to here because calling comm_reset_close() causes http to
2910 * be freed and the above connNoteUseOfBuffer() would hit an
2911 * assertion, not to mention that we were accessing freed memory.
2913 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2914 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2915 conn
->flags
.readMore
= false;
2916 comm_reset_close(conn
->clientConnection
);
2921 connStripBufferWhitespace (ConnStateData
* conn
)
2923 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2924 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2925 -- conn
->in
.notYetUsed
;
2930 * Limit the number of concurrent requests.
2931 * \return true when there are available position(s) in the pipeline queue for another request.
2932 * \return false when the pipeline queue is full or disabled.
2935 ConnStateData::concurrentRequestQueueFilled() const
2937 const int existingRequestCount
= getConcurrentRequestCount();
2939 // default to the configured pipeline size.
2940 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2941 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2943 // when queue filled already we cant add more.
2944 if (existingRequestCount
>= concurrentRequestLimit
) {
2945 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2946 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2954 * Attempt to parse one or more requests from the input buffer.
2955 * If a request is successfully parsed, even if the next request
2956 * is only partially parsed, it will return TRUE.
2959 ConnStateData::clientParseRequests()
2961 HttpRequestMethod method
;
2962 bool parsed_req
= false;
2964 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2966 // Loop while we have read bytes that are not needed for producing the body
2967 // On errors, bodyPipe may become nil, but readMore will be cleared
2968 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2969 connStripBufferWhitespace(this);
2971 /* Don't try to parse if the buffer is empty */
2972 if (in
.notYetUsed
== 0)
2975 /* Limit the number of concurrent requests */
2976 if (concurrentRequestQueueFilled())
2979 /* Should not be needed anymore */
2980 /* Terminate the string */
2981 in
.buf
[in
.notYetUsed
] = '\0';
2983 /* Begin the parsing */
2984 PROF_start(parseHttpRequest
);
2985 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
2987 /* Process request */
2988 Http::ProtocolVersion http_ver
;
2989 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2990 PROF_stop(parseHttpRequest
);
2992 /* partial or incomplete request */
2994 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2995 // (which becomes context) but checkHeaderLimits cannot?
2996 checkHeaderLimits();
3000 /* status -1 or 1 */
3002 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
3003 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3004 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
3005 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3007 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
3009 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3011 if (context
->mayUseConnection()) {
3012 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3018 /* XXX where to 'finish' the parsing pass? */
3023 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3025 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3029 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
3031 if (io
.flag
== COMM_ERR_CLOSING
) {
3032 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
3036 assert(Comm::IsConnOpen(clientConnection
));
3037 assert(io
.conn
->fd
== clientConnection
->fd
);
3040 * Don't reset the timeout value here. The timeout value will be
3041 * set to Config.Timeout.request by httpAccept() and
3042 * clientWriteComplete(), and should apply to the request as a
3043 * whole, not individual read() calls. Plus, it breaks our
3044 * lame half-close detection
3046 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3047 notifyAllContexts(io
.xerrno
);
3052 if (io
.flag
== COMM_OK
) {
3054 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3056 // may comm_close or setReplyToError
3057 if (!handleReadData(io
.buf
, io
.size
))
3060 } else if (io
.size
== 0) {
3061 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3063 if (connFinishedWithConn(io
.size
)) {
3064 clientConnection
->close();
3068 /* It might be half-closed, we can't tell */
3069 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3071 commMarkHalfClosed(io
.conn
->fd
);
3073 fd_note(io
.conn
->fd
, "half-closed");
3075 /* There is one more close check at the end, to detect aborted
3076 * (partial) requests. At this point we can't tell if the request
3079 /* Continue to process previously read data */
3083 /* Process next request */
3084 if (getConcurrentRequestCount() == 0)
3085 fd_note(io
.fd
, "Reading next request");
3087 if (!clientParseRequests()) {
3091 * If the client here is half closed and we failed
3092 * to parse a request, close the connection.
3093 * The above check with connFinishedWithConn() only
3094 * succeeds _if_ the buffer is empty which it won't
3095 * be if we have an incomplete request.
3096 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3098 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3099 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3100 clientConnection
->close();
3108 clientAfterReadingRequests();
3112 * called when new request data has been read from the socket
3114 * \retval false called comm_close or setReplyToError (the caller should bail)
3115 * \retval true we did not call comm_close or setReplyToError
3118 ConnStateData::handleReadData(char *buf
, size_t size
)
3120 char *current_buf
= in
.addressToReadInto();
3122 if (buf
!= current_buf
)
3123 memmove(current_buf
, buf
, size
);
3125 in
.notYetUsed
+= size
;
3127 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3129 // if we are reading a body, stuff data into the body pipe
3130 if (bodyPipe
!= NULL
)
3131 return handleRequestBodyData();
3136 * called when new request body data has been buffered in in.buf
3137 * may close the connection if we were closing and piped everything out
3139 * \retval false called comm_close or setReplyToError (the caller should bail)
3140 * \retval true we did not call comm_close or setReplyToError
3143 ConnStateData::handleRequestBodyData()
3145 assert(bodyPipe
!= NULL
);
3149 if (in
.bodyParser
) { // chunked encoding
3150 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3151 abortChunkedRequestBody(error
);
3154 } else { // identity encoding
3155 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3156 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3157 if (!bodyPipe
->mayNeedMoreData()) {
3158 // BodyPipe will clear us automagically when we produced everything
3164 connNoteUseOfBuffer(this, putSize
);
3167 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3169 if (const char *reason
= stoppedSending()) {
3170 /* we've finished reading like good clients,
3171 * now do the close that initiateClose initiated.
3173 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3174 clientConnection
->close();
3182 /// parses available chunked encoded body bytes, checks size, returns errors
3184 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3186 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3188 try { // the parser will throw on errors
3190 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3193 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3194 // add one because MemBuf will assert if it cannot 0-terminate
3195 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3196 raw
.append(in
.buf
, in
.notYetUsed
);
3198 const mb_size_t wasContentSize
= raw
.contentSize();
3199 BodyPipeCheckout
bpc(*bodyPipe
);
3200 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3202 putSize
= wasContentSize
- raw
.contentSize();
3204 // dechunk then check: the size limit applies to _dechunked_ content
3205 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3209 finishDechunkingRequest(true);
3211 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3214 // if chunk parser needs data, then the body pipe must need it too
3215 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3217 // if parser needs more space and we can consume nothing, we will stall
3218 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3219 } catch (...) { // TODO: be more specific
3220 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3221 return ERR_INVALID_REQ
;
3224 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3228 /// quit on errors related to chunked request body handling
3230 ConnStateData::abortChunkedRequestBody(const err_type error
)
3232 finishDechunkingRequest(false);
3234 // XXX: The code below works if we fail during initial request parsing,
3235 // but if we fail when the server-side works already, the server may send
3236 // us its response too, causing various assertions. How to prevent that?
3237 #if WE_KNOW_HOW_TO_SEND_ERRORS
3238 ClientSocketContext::Pointer context
= getCurrentContext();
3239 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3240 clientStreamNode
*node
= context
->getClientReplyContext();
3241 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3243 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3244 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3245 repContext
->setReplyToError(error
, scode
,
3246 repContext
->http
->request
->method
,
3247 repContext
->http
->uri
,
3249 repContext
->http
->request
,
3251 context
->pullData();
3253 // close or otherwise we may get stuck as nobody will notice the error?
3254 comm_reset_close(clientConnection
);
3257 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3258 comm_reset_close(clientConnection
);
3260 flags
.readMore
= false;
3264 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3266 if (!handleRequestBodyData())
3269 // too late to read more body
3270 if (!isOpen() || stoppedReceiving())
3277 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3279 // request reader may get stuck waiting for space if nobody consumes body
3280 if (bodyPipe
!= NULL
)
3281 bodyPipe
->enableAutoConsumption();
3283 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3286 /** general lifetime handler for HTTP requests */
3288 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3291 * Just close the connection to not confuse browsers
3292 * using persistent connections. Some browsers open
3293 * a connection and then do not use it until much
3294 * later (presumeably because the request triggering
3295 * the open has already been completed on another
3298 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3303 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3305 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3306 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3307 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3308 http
->al
->http
.timedout
= true;
3309 if (Comm::IsConnOpen(io
.conn
))
3313 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3314 AsyncJob("ConnStateData"),
3316 sslBumpMode(Ssl::bumpEnd
),
3317 switchedToHttps_(false),
3318 sslServerBump(NULL
),
3320 stoppedSending_(NULL
),
3321 stoppedReceiving_(NULL
)
3323 pinning
.host
= NULL
;
3325 pinning
.pinned
= false;
3326 pinning
.auth
= false;
3327 pinning
.zeroReply
= false;
3328 pinning
.peer
= NULL
;
3330 // store the details required for creating more MasterXaction objects as new requests come in
3331 clientConnection
= xact
->tcpClient
;
3332 port
= cbdataReference(xact
->squidPort
.get());
3333 log_addr
= xact
->tcpClient
->remote
;
3334 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3336 in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &in
.allocatedSize
);
3338 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3339 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3340 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3341 int i
= IP_PMTUDISC_DONT
;
3342 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3343 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3345 static bool reported
= false;
3348 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3354 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3355 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3356 comm_add_close_handler(clientConnection
->fd
, call
);
3358 if (Config
.onoff
.log_fqdn
)
3359 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3362 if (Ident::TheConfig
.identLookup
) {
3363 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3364 identChecklist
.src_addr
= xact
->tcpClient
->remote
;
3365 identChecklist
.my_addr
= xact
->tcpClient
->local
;
3366 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3367 Ident::Start(xact
->tcpClient
, clientIdentDone
, this);
3371 clientdbEstablished(clientConnection
->remote
, 1);
3373 flags
.readMore
= true;
3376 /** Handle a new connection on HTTP socket. */
3378 httpAccept(const CommAcceptCbParams
¶ms
)
3380 MasterXaction::Pointer xact
= params
.xaction
;
3381 AnyP::PortCfgPointer s
= xact
->squidPort
;
3384 // it is possible the call or accept() was still queued when the port was reconfigured
3385 debugs(33, 2, "HTTP accept failure: port reconfigured.");
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
= new ConnStateData(xact
);
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 ACCESS_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 MasterXaction::Pointer xact
= params
.xaction
;
3697 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3700 // it is possible the call or accept() was still queued when the port was reconfigured
3701 debugs(33, 2, "HTTPS accept failure: port reconfigured.");
3705 if (params
.flag
!= COMM_OK
) {
3706 // Its possible the call was still queued when the client disconnected
3707 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3711 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3712 fd_note(params
.conn
->fd
, "client https connect");
3714 if (s
->tcp_keepalive
.enabled
) {
3715 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3718 ++incoming_sockets_accepted
;
3720 // Socket is ready, setup the connection manager to start using it
3721 ConnStateData
*connState
= new ConnStateData(xact
);
3723 if (s
->flags
.tunnelSslBumping
) {
3724 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3726 if (!Config
.accessList
.ssl_bump
) {
3727 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3731 // Create a fake HTTP request for ssl_bump ACL check,
3732 // using tproxy/intercept provided destination IP and port.
3733 HttpRequest
*request
= new HttpRequest();
3734 static char ip
[MAX_IPSTRLEN
];
3735 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3736 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3737 request
->port
= params
.conn
->local
.port();
3738 request
->myportname
= s
->name
;
3740 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3741 acl_checklist
->src_addr
= params
.conn
->remote
;
3742 acl_checklist
->my_addr
= s
->s
;
3743 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3746 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3747 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3752 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3754 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3755 state_data
->sslCrtdHandleReply(reply
);
3759 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3761 if (reply
.result
== HelperReply::BrokenHelper
) {
3762 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3763 } else if (!reply
.other().hasContent()) {
3764 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3766 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3767 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3768 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3770 if (reply
.result
!= HelperReply::Okay
) {
3771 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3773 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3774 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3775 getSslContextDone(ctx
, true);
3780 getSslContextDone(NULL
);
3783 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3785 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3787 // fake certificate adaptation requires bump-server-first mode
3788 if (!sslServerBump
) {
3789 assert(port
->signingCert
.get());
3790 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3791 if (port
->signPkey
.get())
3792 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3793 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3797 // In case of an error while connecting to the secure server, use a fake
3798 // trusted certificate, with no mimicked fields and no adaptation
3799 // algorithms. There is nothing we can mimic so we want to minimize the
3800 // number of warnings the user will have to see to get to the error page.
3801 assert(sslServerBump
->entry
);
3802 if (sslServerBump
->entry
->isEmpty()) {
3803 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3804 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3806 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3807 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3808 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3810 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3811 // If the algorithm already set, then ignore it.
3812 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3813 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3814 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3817 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3818 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3819 const char *param
= ca
->param
;
3821 // For parameterless CN adaptation, use hostname from the
3823 if (ca
->alg
== Ssl::algSetCommonName
) {
3825 param
= sslConnectHostOrIp
.termedBuf();
3826 certProperties
.commonName
= param
;
3827 certProperties
.setCommonName
= true;
3828 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3829 certProperties
.setValidAfter
= true;
3830 else if (ca
->alg
== Ssl::algSetValidBefore
)
3831 certProperties
.setValidBefore
= true;
3833 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3834 alg
<< " param: " << (param
? param
: "-"));
3838 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3839 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3840 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3841 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3845 } else {// if (!sslServerBump->entry->isEmpty())
3846 // Use trusted certificate for a Squid-generated error
3847 // or the user would have to add a security exception
3848 // just to see the error page. We will close the connection
3849 // so that the trust is not extended to non-Squid content.
3850 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3853 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3855 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3856 assert(port
->untrustedSigningCert
.get());
3857 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3858 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3860 assert(port
->signingCert
.get());
3861 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3863 if (port
->signPkey
.get())
3864 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3866 signAlgorithm
= certProperties
.signAlgorithm
;
3870 ConnStateData::getSslContextStart()
3872 assert(areAllContextsForThisConnection());
3874 /* careful: freeAllContexts() above frees request, host, etc. */
3876 if (port
->generateHostCertificates
) {
3877 Ssl::CertificateProperties certProperties
;
3878 buildSslCertGenerationParams(certProperties
);
3879 sslBumpCertKey
= certProperties
.dbKey().c_str();
3880 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3882 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3883 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3884 SSL_CTX
* dynCtx
= NULL
;
3885 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
.get(sslBumpCertKey
.termedBuf());
3886 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3887 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3888 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3889 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3890 getSslContextDone(dynCtx
);
3893 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3894 ssl_ctx_cache
.del(sslBumpCertKey
.termedBuf());
3897 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3902 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3903 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3904 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3905 request_message
.composeRequest(certProperties
);
3906 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3907 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3909 } catch (const std::exception
&e
) {
3910 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3911 "request for " << certProperties
.commonName
<<
3912 " certificate: " << e
.what() << "; will now block to " <<
3913 "generate that certificate.");
3914 // fall through to do blocking in-process generation.
3916 #endif // USE_SSL_CRTD
3918 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3919 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3920 getSslContextDone(dynCtx
, true);
3923 getSslContextDone(NULL
);
3927 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3929 // Try to add generated ssl context to storage.
3930 if (port
->generateHostCertificates
&& isNew
) {
3932 if (signAlgorithm
== Ssl::algSignTrusted
) {
3933 // Add signing certificate to the certificates chain
3934 X509
*cert
= port
->signingCert
.get();
3935 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3936 // increase the certificate lock
3937 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3939 const int ssl_error
= ERR_get_error();
3940 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3942 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3944 //else it is self-signed or untrusted do not attrach any certificate
3946 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3947 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3949 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3950 // If it is not in storage delete after using. Else storage deleted it.
3951 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3954 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3958 // If generated ssl context = NULL, try to use static ssl context.
3960 if (!port
->staticSslContext
) {
3961 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3962 clientConnection
->close();
3965 debugs(33, 5, HERE
<< "Using static ssl context.");
3966 sslContext
= port
->staticSslContext
.get();
3970 if (!httpsCreate(clientConnection
, sslContext
))
3973 // commSetConnTimeout() was called for this request before we switched.
3975 // Disable the client read handler until CachePeer selection is complete
3976 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3977 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3978 switchedToHttps_
= true;
3982 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3984 assert(!switchedToHttps_
);
3986 sslConnectHostOrIp
= request
->GetHost();
3987 sslCommonName
= request
->GetHost();
3989 // We are going to read new request
3990 flags
.readMore
= true;
3991 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3993 // If sslServerBump is set, then we have decided to deny CONNECT
3994 // and now want to switch to SSL to send the error to the client
3995 // without even peeking at the origin server certificate.
3996 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3997 request
->flags
.sslPeek
= true;
3998 sslServerBump
= new Ssl::ServerBump(request
);
4000 // will call httpsPeeked() with certificate and connection, eventually
4001 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4005 // otherwise, use sslConnectHostOrIp
4006 getSslContextStart();
4010 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4012 Must(sslServerBump
!= NULL
);
4014 if (Comm::IsConnOpen(serverConnection
)) {
4015 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
4017 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
4018 assert(serverCert
.get() != NULL
);
4019 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4020 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4021 " bumped: " << *serverConnection
);
4023 pinConnection(serverConnection
, NULL
, NULL
, false);
4025 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4027 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4028 Ip::Address intendedDest
;
4029 intendedDest
= sslConnectHostOrIp
.termedBuf();
4030 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4032 // Squid serves its own error page and closes, so we want
4033 // a CN that causes no additional browser errors. Possible
4034 // only when bumping CONNECT with a user-typed address.
4035 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4036 sslCommonName
= sslConnectHostOrIp
;
4037 else if (sslServerBump
->serverCert
.get())
4038 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4040 // copy error detail from bump-server-first request to CONNECT request
4041 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4042 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4045 getSslContextStart();
4048 #endif /* USE_SSL */
4050 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4052 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4054 if (!Comm::IsConnOpen(c
)) {
4055 Must(NHttpSockets
> 0); // we tried to open some
4056 --NHttpSockets
; // there will be fewer sockets than planned
4057 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4059 if (!NHttpSockets
) // we could not open any listen sockets at all
4060 fatalf("Unable to open %s",FdNote(portType
));
4067 /// find any unused HttpSockets[] slot and store fd there or return false
4069 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4072 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4073 if ((found
= HttpSockets
[i
] < 0))
4074 HttpSockets
[i
] = conn
->fd
;
4080 clientHttpConnectionsOpen(void)
4082 AnyP::PortCfg
*s
= NULL
;
4084 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4085 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4086 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4087 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4092 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4093 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << URLScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4094 s
->flags
.tunnelSslBumping
= false;
4097 if (s
->flags
.tunnelSslBumping
&&
4098 !s
->staticSslContext
&&
4099 !s
->generateHostCertificates
) {
4100 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4101 s
->flags
.tunnelSslBumping
= false;
4103 if (s
->flags
.tunnelSslBumping
) {
4104 // Create ssl_ctx cache for this port.
4105 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4109 // Fill out a Comm::Connection which IPC will open as a listener for us
4110 // then pass back when active so we can start a TcpAcceptor subscription.
4111 s
->listenConn
= new Comm::Connection
;
4112 s
->listenConn
->local
= s
->s
;
4113 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4115 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4116 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4117 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4118 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4120 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4121 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4122 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4124 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4131 clientHttpsConnectionsOpen(void)
4135 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4136 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4137 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4138 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4142 if (!s
->staticSslContext
) {
4143 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4144 " due to SSL initialization failure.");
4148 // TODO: merge with similar code in clientHttpConnectionsOpen()
4149 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4150 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << URLScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4151 s
->flags
.tunnelSslBumping
= false;
4154 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4155 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4156 s
->flags
.tunnelSslBumping
= false;
4159 if (s
->flags
.tunnelSslBumping
) {
4160 // Create ssl_ctx cache for this port.
4161 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4164 // Fill out a Comm::Connection which IPC will open as a listener for us
4165 s
->listenConn
= new Comm::Connection
;
4166 s
->listenConn
->local
= s
->s
;
4167 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4168 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4170 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4171 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4172 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4173 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4175 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4176 ListeningStartedDialer(&clientListenerConnectionOpened
,
4177 s
, Ipc::fdnHttpsSocket
, sub
));
4178 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4179 HttpSockets
[NHttpSockets
] = -1;
4185 /// process clientHttpConnectionsOpen result
4187 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4189 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4193 Must(Comm::IsConnOpen(s
->listenConn
));
4195 // TCP: setup a job to handle accept() with subscribed handler
4196 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4198 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4199 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4200 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4201 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4202 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4203 << FdNote(portTypeNote
) << " connections at "
4206 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4210 clientOpenListenSockets(void)
4212 clientHttpConnectionsOpen();
4214 clientHttpsConnectionsOpen();
4217 if (NHttpSockets
< 1)
4218 fatal("No HTTP or HTTPS ports configured");
4222 clientHttpConnectionsClose(void)
4224 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4225 if (s
->listenConn
!= NULL
) {
4226 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4227 s
->listenConn
->close();
4228 s
->listenConn
= NULL
;
4233 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4234 if (s
->listenConn
!= NULL
) {
4235 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4236 s
->listenConn
->close();
4237 s
->listenConn
= NULL
;
4242 // TODO see if we can drop HttpSockets array entirely */
4243 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4244 HttpSockets
[i
] = -1;
4251 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4253 const char *vary
= request
->vary_headers
;
4254 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4255 #if X_ACCELERATOR_VARY
4258 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4261 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4263 /* Oops... something odd is going on here.. */
4264 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4265 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4266 safe_free(request
->vary_headers
);
4271 /* This is not a varying object */
4275 /* virtual "vary" object found. Calculate the vary key and
4276 * continue the search
4278 vary
= httpMakeVaryMark(request
, entry
->getReply());
4281 request
->vary_headers
= xstrdup(vary
);
4284 /* Ouch.. we cannot handle this kind of variance */
4285 /* XXX This cannot really happen, but just to be complete */
4290 vary
= httpMakeVaryMark(request
, entry
->getReply());
4293 request
->vary_headers
= xstrdup(vary
);
4297 /* Ouch.. we cannot handle this kind of variance */
4298 /* XXX This cannot really happen, but just to be complete */
4300 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4303 /* Oops.. we have already been here and still haven't
4304 * found the requested variant. Bail out
4306 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4307 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4313 ACLFilledChecklist
*
4314 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4316 ConnStateData
* conn
= http
->getConn();
4317 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4318 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4321 * hack for ident ACL. It needs to get full addresses, and a place to store
4322 * the ident result on persistent connections...
4324 /* connection oriented auth also needs these two lines for it's operation. */
4328 CBDATA_CLASS_INIT(ConnStateData
);
4331 ConnStateData::transparent() const
4333 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4337 ConnStateData::reading() const
4339 return reader
!= NULL
;
4343 ConnStateData::stopReading()
4346 comm_read_cancel(clientConnection
->fd
, reader
);
4352 ConnStateData::expectRequestBody(int64_t size
)
4354 bodyPipe
= new BodyPipe(this);
4356 bodyPipe
->setBodySize(size
);
4358 startDechunkingRequest();
4363 ConnStateData::mayNeedToReadMoreBody() const
4366 return 0; // request without a body or read/produced all body bytes
4368 if (!bodyPipe
->bodySizeKnown())
4369 return -1; // probably need to read more, but we cannot be sure
4371 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4372 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4374 if (needToProduce
<= haveAvailable
)
4375 return 0; // we have read what we need (but are waiting for pipe space)
4377 return needToProduce
- haveAvailable
;
4381 ConnStateData::stopReceiving(const char *error
)
4383 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4384 "; old sending error: " <<
4385 (stoppedSending() ? stoppedSending_
: "none"));
4387 if (const char *oldError
= stoppedReceiving()) {
4388 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4389 return; // nothing has changed as far as this connection is concerned
4392 stoppedReceiving_
= error
;
4394 if (const char *sendError
= stoppedSending()) {
4395 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4396 clientConnection
->close();
4401 ConnStateData::expectNoForwarding()
4403 if (bodyPipe
!= NULL
) {
4404 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4405 bodyPipe
->expectNoConsumption();
4409 /// initialize dechunking state
4411 ConnStateData::startDechunkingRequest()
4413 Must(bodyPipe
!= NULL
);
4414 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4415 assert(!in
.bodyParser
);
4416 in
.bodyParser
= new ChunkedCodingParser
;
4419 /// put parsed content into input buffer and clean up
4421 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4423 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4425 if (bodyPipe
!= NULL
) {
4426 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4427 BodyPipe::Pointer myPipe
= bodyPipe
;
4428 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4429 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4431 Must(myPipe
->bodySizeKnown());
4432 ClientSocketContext::Pointer context
= getCurrentContext();
4433 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4434 context
->http
->request
->setContentLength(myPipe
->bodySize());
4438 delete in
.bodyParser
;
4439 in
.bodyParser
= NULL
;
4443 ConnStateData::In::addressToReadInto() const
4445 return buf
+ notYetUsed
;
4448 ConnStateData::In::In() : bodyParser(NULL
),
4449 buf (NULL
), notYetUsed (0), allocatedSize (0)
4452 ConnStateData::In::~In()
4455 memFreeBuf(allocatedSize
, buf
);
4456 delete bodyParser
; // TODO: pool
4460 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4463 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4467 ClientSocketContext::Pointer context
= getCurrentContext();
4468 if (context
!= NULL
) {
4469 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4473 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4474 clientConnection
->close();
4477 /// Our close handler called by Comm when the pinned connection is closed
4479 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4481 // FwdState might repin a failed connection sooner than this close
4482 // callback is called for the failed connection.
4483 assert(pinning
.serverConnection
== io
.conn
);
4484 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4485 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4487 if (sawZeroReply
&& clientConnection
!= NULL
) {
4488 debugs(33, 3, "Closing client connection on pinned zero reply.");
4489 clientConnection
->close();
4494 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4496 char desc
[FD_DESC_SZ
];
4498 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4499 if (pinning
.serverConnection
->fd
== pinServer
->fd
) {
4500 startPinnedConnectionMonitoring();
4505 unpinConnection(); // closes pinned connection, if any, and resets fields
4507 pinning
.serverConnection
= pinServer
;
4509 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4511 // when pinning an SSL bumped connection, the request may be NULL
4512 const char *pinnedHost
= "[unknown]";
4514 pinning
.host
= xstrdup(request
->GetHost());
4515 pinning
.port
= request
->port
;
4516 pinnedHost
= pinning
.host
;
4518 pinning
.port
= pinServer
->remote
.port();
4520 pinning
.pinned
= true;
4522 pinning
.peer
= cbdataReference(aPeer
);
4523 pinning
.auth
= auth
;
4524 char stmp
[MAX_IPSTRLEN
];
4525 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4526 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4527 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4528 clientConnection
->fd
);
4529 fd_note(pinning
.serverConnection
->fd
, desc
);
4531 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4532 pinning
.closeHandler
= JobCallback(33, 5,
4533 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4534 // remember the pinned connection so that cb does not unpin a fresher one
4535 typedef CommCloseCbParams Params
;
4536 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4537 params
.conn
= pinning
.serverConnection
;
4538 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4540 startPinnedConnectionMonitoring();
4543 /// Assign a read handler to an idle pinned connection so that we can detect connection closures.
4545 ConnStateData::startPinnedConnectionMonitoring()
4547 if (pinning
.readHandler
!= NULL
)
4548 return; // already monitoring
4550 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4551 pinning
.readHandler
= JobCallback(33, 3,
4552 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4553 static char unusedBuf
[8];
4554 comm_read(pinning
.serverConnection
, unusedBuf
, sizeof(unusedBuf
), pinning
.readHandler
);
4558 ConnStateData::stopPinnedConnectionMonitoring()
4560 if (pinning
.readHandler
!= NULL
) {
4561 comm_read_cancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4562 pinning
.readHandler
= NULL
;
4566 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4567 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4569 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4571 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4573 if (io
.flag
== COMM_ERR_CLOSING
)
4574 return; // close handler will clean up
4576 // We could use getConcurrentRequestCount(), but this may be faster.
4577 const bool clientIsIdle
= !getCurrentContext();
4579 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4580 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4582 assert(pinning
.serverConnection
== io
.conn
);
4583 pinning
.serverConnection
->close();
4585 // If we are still sending data to the client, do not close now. When we are done sending,
4586 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4587 // However, if we are idle, then we must close to inform the idle client and minimize races.
4588 if (clientIsIdle
&& clientConnection
!= NULL
)
4589 clientConnection
->close();
4592 const Comm::ConnectionPointer
4593 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4595 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4598 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4600 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4602 else if (request
&& pinning
.port
!= request
->port
)
4604 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4606 else if (aPeer
!= pinning
.peer
)
4610 /* The pinning info is not safe, remove any pinning info */
4614 return pinning
.serverConnection
;
4618 ConnStateData::unpinConnection()
4620 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4623 cbdataReferenceDone(pinning
.peer
);
4625 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4626 if (pinning
.closeHandler
!= NULL
) {
4627 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4628 pinning
.closeHandler
= NULL
;
4630 /// also close the server side socket, we should not use it for any future requests...
4631 // TODO: do not close if called from our close handler?
4632 pinning
.serverConnection
->close();
4635 safe_free(pinning
.host
);
4637 pinning
.zeroReply
= false;
4639 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4640 * connection has gone away */