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 "http/Http1Parser.h"
108 #include "HttpHdrContRange.h"
109 #include "HttpHeaderTools.h"
110 #include "HttpReply.h"
111 #include "HttpRequest.h"
112 #include "ident/Config.h"
113 #include "ident/Ident.h"
114 #include "internal.h"
115 #include "ipc/FdNotes.h"
116 #include "ipc/StartListening.h"
117 #include "log/access_log.h"
120 #include "MemObject.h"
121 #include "mime_header.h"
122 #include "profiler/Profiler.h"
124 #include "SquidConfig.h"
125 #include "SquidTime.h"
126 #include "StatCounters.h"
127 #include "StatHist.h"
129 #include "TimeOrTag.h"
134 #include "auth/UserRequest.h"
137 #include "ClientInfo.h"
140 #include "ssl/context_storage.h"
141 #include "ssl/gadgets.h"
142 #include "ssl/helper.h"
143 #include "ssl/ProxyCerts.h"
144 #include "ssl/ServerBump.h"
145 #include "ssl/support.h"
148 #include "ssl/certificate_db.h"
149 #include "ssl/crtd_message.h"
163 #define comm_close comm_lingering_close
166 /// dials clientListenerConnectionOpened call
167 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
170 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
171 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
172 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
174 virtual void print(std::ostream
&os
) const {
176 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
179 virtual bool canDial(AsyncCall
&) const { return true; }
180 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
186 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
187 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
188 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
191 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
193 /* our socket-related context */
195 CBDATA_CLASS_INIT(ClientSocketContext
);
197 /* Local functions */
198 static IOCB clientWriteComplete
;
199 static IOCB clientWriteBodyComplete
;
200 static IOACB httpAccept
;
202 static IOACB httpsAccept
;
204 static CTCB clientLifetimeTimeout
;
205 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
206 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, Http1::RequestParser
&);
208 static IDCB clientIdentDone
;
210 static CSCB clientSocketRecipient
;
211 static CSD clientSocketDetach
;
212 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
213 static int clientIsContentLengthValid(HttpRequest
* r
);
214 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
216 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
217 static void clientUpdateStatCounters(LogTags logType
);
218 static void clientUpdateHierCounters(HierarchyLogEntry
*);
219 static bool clientPingHasFinished(ping_data
const *aPing
);
220 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
222 static bool connIsUsable(ConnStateData
* conn
);
224 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
225 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
226 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
228 char *skipLeadingSpace(char *aString
);
229 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
232 ClientSocketContext::getTail() const
234 if (http
->client_stream
.tail
)
235 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
241 ClientSocketContext::getClientReplyContext() const
243 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
247 * This routine should be called to grow the inbuf and then
251 ConnStateData::readSomeData()
256 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
258 if (!maybeMakeSpaceAvailable())
261 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
262 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
263 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
267 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
269 ClientSocketContext::Pointer
*tempContextPointer
;
270 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
271 assert(conn
->getCurrentContext() != NULL
);
272 /* Unlink us from the connection request list */
273 tempContextPointer
= & conn
->currentobject
;
275 while (tempContextPointer
->getRaw()) {
276 if (*tempContextPointer
== this)
279 tempContextPointer
= &(*tempContextPointer
)->next
;
282 assert(tempContextPointer
->getRaw() != NULL
);
283 *tempContextPointer
= next
;
287 ClientSocketContext::~ClientSocketContext()
289 clientStreamNode
*node
= getTail();
292 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
295 /* We are *always* the tail - prevent recursive free */
296 assert(this == streamContext
);
302 deRegisterWithConn();
304 httpRequestFree(http
);
306 /* clean up connection links to us */
307 assert(this != next
.getRaw());
311 ClientSocketContext::registerWithConn()
313 assert (!connRegistered_
);
315 assert (http
->getConn() != NULL
);
316 connRegistered_
= true;
317 http
->getConn()->addContextToQueue(this);
321 ClientSocketContext::deRegisterWithConn()
323 assert (connRegistered_
);
324 removeFromConnectionList(http
->getConn());
325 connRegistered_
= false;
329 ClientSocketContext::connIsFinished()
332 assert (http
->getConn() != NULL
);
333 deRegisterWithConn();
334 /* we can't handle any more stream data - detach */
335 clientStreamDetach(getTail(), http
);
338 ClientSocketContext::ClientSocketContext(const Comm::ConnectionPointer
&aConn
, ClientHttpRequest
*aReq
) :
339 clientConnection(aConn
),
344 mayUseConnection_ (false),
345 connRegistered_ (false)
347 assert(http
!= NULL
);
348 memset (reqbuf
, '\0', sizeof (reqbuf
));
351 deferredparams
.node
= NULL
;
352 deferredparams
.rep
= NULL
;
356 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
358 const HttpReply::Pointer
rep(msg
.reply
);
361 // apply selected clientReplyContext::buildReplyHeader() mods
362 // it is not clear what headers are required for control messages
363 rep
->header
.removeHopByHopEntries();
364 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
365 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
367 // remember the callback
368 cbControlMsgSent
= msg
.cbSuccess
;
370 MemBuf
*mb
= rep
->pack();
372 debugs(11, 2, "HTTP Client " << clientConnection
);
373 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
375 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
376 CommIoCbPtrFun(&WroteControlMsg
, this));
377 Comm::Write(clientConnection
, mb
, call
);
382 /// called when we wrote the 1xx response
384 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
386 if (errflag
== COMM_ERR_CLOSING
)
389 if (errflag
== COMM_OK
) {
390 ScheduleCallHere(cbControlMsgSent
);
394 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
395 // no error notification: see HttpControlMsg.h for rationale and
396 // note that some errors are detected elsewhere (e.g., close handler)
398 // close on 1xx errors to be conservative and to simplify the code
399 // (if we do not close, we must notify the source of a failure!)
403 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
405 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
407 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
408 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
413 clientIdentDone(const char *ident
, void *data
)
415 ConnStateData
*conn
= (ConnStateData
*)data
;
416 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
421 clientUpdateStatCounters(LogTags logType
)
423 ++statCounter
.client_http
.requests
;
425 if (logTypeIsATcpHit(logType
))
426 ++statCounter
.client_http
.hits
;
428 if (logType
== LOG_TCP_HIT
)
429 ++statCounter
.client_http
.disk_hits
;
430 else if (logType
== LOG_TCP_MEM_HIT
)
431 ++statCounter
.client_http
.mem_hits
;
435 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
437 statCounter
.client_http
.allSvcTime
.count(svc_time
);
439 * The idea here is not to be complete, but to get service times
440 * for only well-defined types. For example, we don't include
441 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
442 * (we *tried* to validate it, but failed).
447 case LOG_TCP_REFRESH_UNMODIFIED
:
448 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
451 case LOG_TCP_IMS_HIT
:
452 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
457 case LOG_TCP_MEM_HIT
:
459 case LOG_TCP_OFFLINE_HIT
:
460 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
465 case LOG_TCP_CLIENT_REFRESH_MISS
:
466 statCounter
.client_http
.missSvcTime
.count(svc_time
);
470 /* make compiler warnings go away */
476 clientPingHasFinished(ping_data
const *aPing
)
478 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
485 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
489 switch (someEntry
->code
) {
490 #if USE_CACHE_DIGESTS
495 ++ statCounter
.cd
.times_used
;
503 case FIRST_PARENT_MISS
:
505 case CLOSEST_PARENT_MISS
:
506 ++ statCounter
.icp
.times_used
;
507 i
= &someEntry
->ping
;
509 if (clientPingHasFinished(i
))
510 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
513 ++ statCounter
.icp
.query_timeouts
;
520 ++ statCounter
.netdb
.times_used
;
530 ClientHttpRequest::updateCounters()
532 clientUpdateStatCounters(logType
);
534 if (request
->errType
!= ERR_NONE
)
535 ++ statCounter
.client_http
.errors
;
537 clientUpdateStatHistCounters(logType
,
538 tvSubMsec(al
->cache
.start_time
, current_time
));
540 clientUpdateHierCounters(&request
->hier
);
544 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
547 assert(aLogEntry
!= NULL
);
549 if (Config
.onoff
.log_mime_hdrs
) {
553 packerToMemInit(&p
, &mb
);
554 request
->header
.packInto(&p
);
555 //This is the request after adaptation or redirection
556 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
558 // the virgin request is saved to aLogEntry->request
559 if (aLogEntry
->request
) {
562 packerToMemInit(&p
, &mb
);
563 aLogEntry
->request
->header
.packInto(&p
);
564 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
568 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
572 packerToMemInit(&p
, &mb
);
573 ah
->lastMeta
.packInto(&p
);
574 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
583 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
585 aLogEntry
->icap
.processingTime
= ih
->processingTime();
588 aLogEntry
->http
.method
= request
->method
;
589 aLogEntry
->http
.version
= request
->http_ver
;
590 aLogEntry
->hier
= request
->hier
;
591 if (request
->content_length
> 0) // negative when no body or unknown length
592 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
593 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
595 // Adapted request, if any, inherits and then collects all the stats, but
596 // the virgin request gets logged instead; copy the stats to log them.
597 // TODO: avoid losses by keeping these stats in a shared history object?
598 if (aLogEntry
->request
) {
599 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
600 aLogEntry
->request
->errType
= request
->errType
;
601 aLogEntry
->request
->errDetail
= request
->errDetail
;
606 ClientHttpRequest::logRequest()
608 if (!out
.size
&& !logType
)
609 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
611 al
->icp
.opcode
= ICP_INVALID
;
613 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
616 al
->http
.code
= al
->reply
->sline
.status();
617 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
618 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
619 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
620 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
623 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
625 if (loggingEntry() && loggingEntry()->mem_obj
)
626 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
628 al
->http
.clientRequestSz
.header
= req_sz
;
629 al
->http
.clientReplySz
.header
= out
.headers_sz
;
630 // XXX: calculate without payload encoding or headers !!
631 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
633 al
->cache
.highOffset
= out
.offset
;
635 al
->cache
.code
= logType
;
637 al
->cache
.msec
= tvSubMsec(al
->cache
.start_time
, current_time
);
640 prepareLogWithRequestDetails(request
, al
);
642 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
643 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
647 /* This is broken. Fails if the connection has been closed. Needs
648 * to snarf the ssl details some place earlier..
650 if (getConn() != NULL
)
651 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
656 // The al->notes and request->notes must point to the same object.
657 (void)SyncNotes(*al
, *request
);
658 typedef Notes::iterator ACAMLI
;
659 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
660 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
661 NotePairs
¬es
= SyncNotes(*al
, *request
);
662 notes
.add((*i
)->key
.termedBuf(), value
);
663 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
667 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
669 checklist
.reply
= al
->reply
;
670 HTTPMSGLOCK(checklist
.reply
);
674 al
->adapted_request
= request
;
675 HTTPMSGLOCK(al
->adapted_request
);
677 accessLogLog(al
, &checklist
);
679 bool updatePerformanceCounters
= true;
680 if (Config
.accessList
.stats_collection
) {
681 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
683 statsCheck
.reply
= al
->reply
;
684 HTTPMSGLOCK(statsCheck
.reply
);
686 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
689 if (updatePerformanceCounters
) {
693 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
694 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
699 ClientHttpRequest::freeResources()
703 safe_free(redirect
.location
);
704 range_iter
.boundary
.clean();
705 HTTPMSGUNLOCK(request
);
707 if (client_stream
.tail
)
708 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
712 httpRequestFree(void *data
)
714 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
715 assert(http
!= NULL
);
720 ConnStateData::areAllContextsForThisConnection() const
722 assert(this != NULL
);
723 ClientSocketContext::Pointer context
= getCurrentContext();
725 while (context
.getRaw()) {
726 if (context
->http
->getConn() != this)
729 context
= context
->next
;
736 ConnStateData::freeAllContexts()
738 ClientSocketContext::Pointer context
;
740 while ((context
= getCurrentContext()).getRaw() != NULL
) {
741 assert(getCurrentContext() !=
742 getCurrentContext()->next
);
743 context
->connIsFinished();
744 assert (context
!= currentobject
);
748 /// propagates abort event to all contexts
750 ConnStateData::notifyAllContexts(int xerrno
)
752 typedef ClientSocketContext::Pointer CSCP
;
753 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
754 c
->noteIoError(xerrno
);
757 /* This is a handler normally called by comm_close() */
758 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
760 deleteThis("ConnStateData::connStateClosed");
765 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
769 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
775 // clobered with self-pointer
776 // NP: something nasty is going on in Squid, but harmless.
778 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
783 * Connection-auth relies on a single set of credentials being preserved
784 * for all requests on a connection once they have been setup.
785 * There are several things which need to happen to preserve security
786 * when connection-auth credentials change unexpectedly or are unset.
788 * 1) auth helper released from any active state
790 * They can only be reserved by a handshake process which this
791 * connection can now never complete.
792 * This prevents helpers hanging when their connections close.
794 * 2) pinning is expected to be removed and server conn closed
796 * The upstream link is authenticated with the same credentials.
797 * Expecting the same level of consistency we should have received.
798 * This prevents upstream being faced with multiple or missing
799 * credentials after authentication.
800 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
801 * we just trigger that cleanup here via comm_reset_close() or
802 * ConnStateData::stopReceiving()
804 * 3) the connection needs to close.
806 * This prevents attackers injecting requests into a connection,
807 * or gateways wrongly multiplexing users into a single connection.
809 * When credentials are missing closure needs to follow an auth
810 * challenge for best recovery by the client.
812 * When credentials change there is nothing we can do but abort as
813 * fast as possible. Sending TCP RST instead of an HTTP response
814 * is the best-case action.
817 // clobbered with nul-pointer
819 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
820 auth_
->releaseAuthServer();
822 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
823 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
824 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
825 stopReceiving("connection-auth removed");
829 // clobbered with alternative credentials
831 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
832 auth_
->releaseAuthServer();
834 // this is a fatal type of problem.
835 // Close the connection immediately with TCP RST to abort all traffic flow
836 comm_reset_close(clientConnection
);
844 // cleans up before destructor is called
846 ConnStateData::swanSong()
848 debugs(33, 2, HERE
<< clientConnection
);
849 flags
.readMore
= false;
850 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
851 assert(areAllContextsForThisConnection());
856 if (Comm::IsConnOpen(clientConnection
))
857 clientConnection
->close();
860 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
861 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
864 BodyProducer::swanSong();
865 flags
.swanSang
= true;
869 ConnStateData::isOpen() const
871 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
872 Comm::IsConnOpen(clientConnection
) &&
873 !fd_table
[clientConnection
->fd
].closing();
876 ConnStateData::~ConnStateData()
878 assert(this != NULL
);
879 debugs(33, 3, HERE
<< clientConnection
);
882 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
885 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
887 cbdataReferenceDone(port
);
889 if (bodyPipe
!= NULL
)
890 stopProducingFor(bodyPipe
, false);
893 delete sslServerBump
;
898 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
899 * This is the client-side persistent connection flag. We need
900 * to set this relatively early in the request processing
901 * to handle hacks for broken servers and clients.
904 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
906 HttpRequest
*request
= http
->request
;
908 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
909 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
910 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
911 RequestMethodStr(request
->method
));
913 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
914 request
->flags
.proxyKeepalive
= request
->persistent();
918 clientIsContentLengthValid(HttpRequest
* r
)
920 switch (r
->method
.id()) {
922 case Http::METHOD_GET
:
924 case Http::METHOD_HEAD
:
925 /* We do not want to see a request entity on GET/HEAD requests */
926 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
929 /* For other types of requests we don't care */
937 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
939 if (Config
.maxRequestBodySize
&&
940 bodyLength
> Config
.maxRequestBodySize
)
941 return 1; /* too large */
948 connIsUsable(ConnStateData
* conn
)
950 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
958 // careful: the "current" context may be gone if we wrote an early response
959 ClientSocketContext::Pointer
960 ConnStateData::getCurrentContext() const
963 return currentobject
;
967 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
969 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
970 assert(flags
.deferred
== 0);
972 deferredparams
.node
= node
;
973 deferredparams
.rep
= rep
;
974 deferredparams
.queuedBuffer
= receivedData
;
979 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
981 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
988 ClientSocketContext::startOfOutput() const
990 return http
->out
.size
== 0;
994 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
996 /*the size of available range can always fit in a size_t type*/
997 size_t maximum
= (size_t)available
.size();
999 if (!http
->request
->range
)
1002 assert (canPackMoreRanges());
1004 if (http
->range_iter
.debt() == -1)
1007 assert (http
->range_iter
.debt() > 0);
1009 /* TODO this + the last line could be a range intersection calculation */
1010 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
1013 return min(http
->range_iter
.debt(), (int64_t)maximum
);
1017 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
1019 http
->out
.offset
+= bytes
;
1021 if (!http
->request
->range
)
1024 if (http
->range_iter
.debt() != -1) {
1025 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
1026 assert (http
->range_iter
.debt() >= 0);
1029 /* debt() always stops at -1, below that is a bug */
1030 assert (http
->range_iter
.debt() >= -1);
1034 ClientHttpRequest::multipartRangeRequest() const
1036 return request
->multipartRangeRequest();
1040 ClientSocketContext::multipartRangeRequest() const
1042 return http
->multipartRangeRequest();
1046 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1048 assert(rep
== NULL
);
1050 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1051 size_t length
= lengthToSend(bodyData
.range());
1052 noteSentBodyBytes (length
);
1053 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1054 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1055 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1061 if (multipartRangeRequest())
1062 packRange(bodyData
, &mb
);
1064 packChunk(bodyData
, mb
);
1066 if (mb
.contentSize()) {
1068 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1069 CommIoCbPtrFun(clientWriteComplete
, this));
1070 Comm::Write(clientConnection
, &mb
, call
);
1072 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1076 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1077 * if bodyData is empty.
1080 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1082 const uint64_t length
=
1083 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1084 noteSentBodyBytes(length
);
1086 mb
.Printf("%" PRIX64
"\r\n", length
);
1087 mb
.append(bodyData
.data
, length
);
1091 /** put terminating boundary for multiparts */
1093 clientPackTermBound(String boundary
, MemBuf
* mb
)
1095 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1096 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1099 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1101 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1103 HttpHeader
hdr(hoReply
);
1109 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1110 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1111 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1113 /* stuff the header with required entries and pack it */
1115 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1116 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1118 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1120 packerToMemInit(&p
, mb
);
1128 /* append <crlf> (we packed a header, not a reply) */
1133 * extracts a "range" from *buf and appends them to mb, updating
1134 * all offsets and such.
1137 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1139 HttpHdrRangeIter
* i
= &http
->range_iter
;
1140 Range
<int64_t> available (source
.range());
1141 char const *buf
= source
.data
;
1143 while (i
->currentSpec() && available
.size()) {
1144 const size_t copy_sz
= lengthToSend(available
);
1148 * intersection of "have" and "need" ranges must not be empty
1150 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1151 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1154 * put boundary and headers at the beginning of a range in a
1158 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1159 assert(http
->memObject());
1161 http
->memObject()->getReply(), /* original reply */
1162 i
->currentSpec(), /* current range */
1163 i
->boundary
, /* boundary, the same for all */
1170 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1172 noteSentBodyBytes (copy_sz
);
1174 mb
->append(buf
, copy_sz
);
1179 available
.start
+= copy_sz
;
1185 if (!canPackMoreRanges()) {
1186 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1189 /* put terminating boundary for multiparts */
1190 clientPackTermBound(i
->boundary
, mb
);
1195 int64_t nextOffset
= getNextRangeOffset();
1197 assert (nextOffset
>= http
->out
.offset
);
1199 int64_t skip
= nextOffset
- http
->out
.offset
;
1201 /* adjust for not to be transmitted bytes */
1202 http
->out
.offset
= nextOffset
;
1204 if (available
.size() <= (uint64_t)skip
)
1207 available
.start
+= skip
;
1216 /** returns expected content length for multi-range replies
1217 * note: assumes that httpHdrRangeCanonize has already been called
1218 * warning: assumes that HTTP headers for individual ranges at the
1219 * time of the actuall assembly will be exactly the same as
1220 * the headers when clientMRangeCLen() is called */
1222 ClientHttpRequest::mRangeCLen()
1227 assert(memObject());
1230 HttpHdrRange::iterator pos
= request
->range
->begin();
1232 while (pos
!= request
->range
->end()) {
1233 /* account for headers for this range */
1235 clientPackRangeHdr(memObject()->getReply(),
1236 *pos
, range_iter
.boundary
, &mb
);
1239 /* account for range content */
1240 clen
+= (*pos
)->length
;
1242 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1246 /* account for the terminating boundary */
1249 clientPackTermBound(range_iter
.boundary
, &mb
);
1259 * returns true if If-Range specs match reply, false otherwise
1262 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1264 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1265 /* check for parsing falure */
1272 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1273 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1274 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1277 return 0; /* entity has no etag to compare with! */
1279 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1280 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1281 return 0; /* must use strong validator for sub-range requests */
1284 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1287 /* got modification time? */
1288 if (spec
.time
>= 0) {
1289 return http
->storeEntry()->lastmod
<= spec
.time
;
1292 assert(0); /* should not happen */
1297 * generates a "unique" boundary string for multipart responses
1298 * the caller is responsible for cleaning the string */
1300 ClientHttpRequest::rangeBoundaryStr() const
1304 String
b(APP_FULLNAME
);
1306 key
= storeEntry()->getMD5Text();
1307 b
.append(key
, strlen(key
));
1311 /** adds appropriate Range headers if needed */
1313 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1315 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1316 const char *range_err
= NULL
;
1317 HttpRequest
*request
= http
->request
;
1318 assert(request
->range
);
1319 /* check if we still want to do ranges */
1321 int64_t roffLimit
= request
->getRangeOffsetLimit();
1324 range_err
= "no [parse-able] reply";
1325 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1326 range_err
= "wrong status code";
1327 else if (hdr
->has(HDR_CONTENT_RANGE
))
1328 range_err
= "origin server does ranges";
1329 else if (rep
->content_length
< 0)
1330 range_err
= "unknown length";
1331 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1332 range_err
= "INCONSISTENT length"; /* a bug? */
1334 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1337 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1338 range_err
= "If-Range match failed";
1339 else if (!http
->request
->range
->canonize(rep
))
1340 range_err
= "canonization failed";
1341 else if (http
->request
->range
->isComplex())
1342 range_err
= "too complex range header";
1343 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1344 range_err
= "range outside range_offset_limit";
1346 /* get rid of our range specs on error */
1348 /* XXX We do this here because we need canonisation etc. However, this current
1349 * code will lead to incorrect store offset requests - the store will have the
1350 * offset data, but we won't be requesting it.
1351 * So, we can either re-request, or generate an error
1353 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1354 delete http
->request
->range
;
1355 http
->request
->range
= NULL
;
1357 /* XXX: TODO: Review, this unconditional set may be wrong. */
1358 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1359 // web server responded with a valid, but unexpected range.
1360 // will (try-to) forward as-is.
1361 //TODO: we should cope with multirange request/responses
1362 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1363 request
->range
->contains(rep
->content_range
->spec
) :
1365 const int spec_count
= http
->request
->range
->specs
.size();
1366 int64_t actual_clen
= -1;
1368 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1369 spec_count
<< " virgin clen: " << rep
->content_length
);
1370 assert(spec_count
> 0);
1371 /* append appropriate header(s) */
1373 if (spec_count
== 1) {
1374 if (!replyMatchRequest
) {
1375 hdr
->delById(HDR_CONTENT_RANGE
);
1376 hdr
->putContRange(rep
->content_range
);
1377 actual_clen
= rep
->content_length
;
1378 //http->range_iter.pos = rep->content_range->spec.begin();
1379 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1380 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1383 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1385 /* append Content-Range */
1387 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1388 /* No content range, so this was a full object we are
1391 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1394 /* set new Content-Length to the actual number of bytes
1395 * transmitted in the message-body */
1396 actual_clen
= (*pos
)->length
;
1400 /* generate boundary string */
1401 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1402 /* delete old Content-Type, add ours */
1403 hdr
->delById(HDR_CONTENT_TYPE
);
1404 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1405 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1406 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1407 /* Content-Length is not required in multipart responses
1408 * but it is always nice to have one */
1409 actual_clen
= http
->mRangeCLen();
1410 /* http->out needs to start where we want data at */
1411 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1414 /* replace Content-Length header */
1415 assert(actual_clen
>= 0);
1417 hdr
->delById(HDR_CONTENT_LENGTH
);
1419 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1421 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1423 /* And start the range iter off */
1424 http
->range_iter
.updateSpec();
1429 ClientSocketContext::prepareReply(HttpReply
* rep
)
1433 if (http
->request
->range
)
1434 buildRangeHeader(rep
);
1438 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1442 MemBuf
*mb
= rep
->pack();
1444 // dump now, so we dont output any body.
1445 debugs(11, 2, "HTTP Client " << clientConnection
);
1446 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1448 /* Save length of headers for persistent conn checks */
1449 http
->out
.headers_sz
= mb
->contentSize();
1452 headersLog(0, 0, http
->request
->method
, rep
);
1455 if (bodyData
.data
&& bodyData
.length
) {
1456 if (multipartRangeRequest())
1457 packRange(bodyData
, mb
);
1458 else if (http
->request
->flags
.chunkedReply
) {
1459 packChunk(bodyData
, *mb
);
1461 size_t length
= lengthToSend(bodyData
.range());
1462 noteSentBodyBytes (length
);
1464 mb
->append(bodyData
.data
, length
);
1469 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1470 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1471 CommIoCbPtrFun(clientWriteComplete
, this));
1472 Comm::Write(clientConnection
, mb
, call
);
1477 * Write a chunk of data to a client socket. If the reply is present,
1478 * send the reply headers down the wire too, and clean them up when
1481 * The request is one backed by a connection, not an internal request.
1482 * data context is not NULL
1483 * There are no more entries in the stream chain.
1486 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1487 HttpReply
* rep
, StoreIOBuffer receivedData
)
1489 /* Test preconditions */
1490 assert(node
!= NULL
);
1491 PROF_start(clientSocketRecipient
);
1492 /* TODO: handle this rather than asserting
1493 * - it should only ever happen if we cause an abort and
1494 * the callback chain loops back to here, so we can simply return.
1495 * However, that itself shouldn't happen, so it stays as an assert for now.
1497 assert(cbdataReferenceValid(node
));
1498 assert(node
->node
.next
== NULL
);
1499 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1500 assert(context
!= NULL
);
1501 assert(connIsUsable(http
->getConn()));
1503 /* TODO: check offset is what we asked for */
1505 if (context
!= http
->getConn()->getCurrentContext()) {
1506 context
->deferRecipientForLater(node
, rep
, receivedData
);
1507 PROF_stop(clientSocketRecipient
);
1511 // After sending Transfer-Encoding: chunked (at least), always send
1512 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1513 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1514 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1515 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1516 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1517 PROF_stop(clientSocketRecipient
);
1521 if (!context
->startOfOutput())
1522 context
->sendBody(rep
, receivedData
);
1525 http
->al
->reply
= rep
;
1526 HTTPMSGLOCK(http
->al
->reply
);
1527 context
->sendStartOfMessage(rep
, receivedData
);
1530 PROF_stop(clientSocketRecipient
);
1534 * Called when a downstream node is no longer interested in
1535 * our data. As we are a terminal node, this means on aborts
1539 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1541 /* Test preconditions */
1542 assert(node
!= NULL
);
1543 /* TODO: handle this rather than asserting
1544 * - it should only ever happen if we cause an abort and
1545 * the callback chain loops back to here, so we can simply return.
1546 * However, that itself shouldn't happen, so it stays as an assert for now.
1548 assert(cbdataReferenceValid(node
));
1549 /* Set null by ContextFree */
1550 assert(node
->node
.next
== NULL
);
1551 /* this is the assert discussed above */
1552 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1553 /* We are only called when the client socket shutsdown.
1554 * Tell the prev pipeline member we're finished
1556 clientStreamDetach(node
, http
);
1560 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1562 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1563 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1567 ConnStateData::readNextRequest()
1569 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1571 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1573 * Set the timeout BEFORE calling clientReadRequest().
1575 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1576 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1577 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1578 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1581 /** Please don't do anything with the FD past here! */
1585 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1587 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1589 /** If the client stream is waiting on a socket write to occur, then */
1591 if (deferredRequest
->flags
.deferred
) {
1592 /** NO data is allowed to have been sent. */
1593 assert(deferredRequest
->http
->out
.size
== 0);
1595 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1596 deferredRequest
->http
,
1597 deferredRequest
->deferredparams
.rep
,
1598 deferredRequest
->deferredparams
.queuedBuffer
);
1601 /** otherwise, the request is still active in a callbacksomewhere,
1606 /// called when we have successfully finished writing the response
1608 ClientSocketContext::keepaliveNextRequest()
1610 ConnStateData
* conn
= http
->getConn();
1612 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1615 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1616 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1617 conn
->clientConnection
->close();
1622 * We are done with the response, and we are either still receiving request
1623 * body (early response!) or have already stopped receiving anything.
1625 * If we are still receiving, then clientParseRequest() below will fail.
1626 * (XXX: but then we will call readNextRequest() which may succeed and
1627 * execute a smuggled request as we are not done with the current request).
1629 * If we stopped because we got everything, then try the next request.
1631 * If we stopped receiving because of an error, then close now to avoid
1632 * getting stuck and to prevent accidental request smuggling.
1635 if (const char *reason
= conn
->stoppedReceiving()) {
1636 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1637 conn
->clientConnection
->close();
1642 * Attempt to parse a request from the request buffer.
1643 * If we've been fed a pipelined request it may already
1644 * be in our read buffer.
1647 * This needs to fall through - if we're unlucky and parse the _last_ request
1648 * from our read buffer we may never re-register for another client read.
1651 if (conn
->clientParseRequests()) {
1652 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1656 * Either we need to kick-start another read or, if we have
1657 * a half-closed connection, kill it after the last request.
1658 * This saves waiting for half-closed connections to finished being
1659 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1660 * the keepalive "Waiting for next request" state.
1662 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1663 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1664 conn
->clientConnection
->close();
1668 ClientSocketContext::Pointer deferredRequest
;
1671 * At this point we either have a parsed request (which we've
1672 * kicked off the processing for) or not. If we have a deferred
1673 * request (parsed but deferred for pipeling processing reasons)
1674 * then look at processing it. If not, simply kickstart
1678 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1679 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1680 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1681 } else if (conn
->flags
.readMore
) {
1682 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1683 conn
->readNextRequest();
1685 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1686 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1691 clientUpdateSocketStats(LogTags logType
, size_t size
)
1696 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1698 if (logTypeIsATcpHit(logType
))
1699 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1703 * increments iterator "i"
1704 * used by clientPackMoreRanges
1706 \retval true there is still data available to pack more ranges
1710 ClientSocketContext::canPackMoreRanges() const
1712 /** first update iterator "i" if needed */
1714 if (!http
->range_iter
.debt()) {
1715 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1717 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1718 ++http
->range_iter
.pos
;
1720 http
->range_iter
.updateSpec();
1723 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1725 /* paranoid sync condition */
1726 /* continue condition: need_more_data */
1727 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1728 return http
->range_iter
.currentSpec() ? true : false;
1732 ClientSocketContext::getNextRangeOffset() const
1734 if (http
->request
->range
) {
1735 /* offset in range specs does not count the prefix of an http msg */
1736 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1737 /* check: reply was parsed and range iterator was initialized */
1738 assert(http
->range_iter
.valid
);
1739 /* filter out data according to range specs */
1740 assert (canPackMoreRanges());
1742 int64_t start
; /* offset of still missing data */
1743 assert(http
->range_iter
.currentSpec());
1744 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1745 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1746 debugs(33, 3, "clientPackMoreRanges: out:"
1747 " start: " << start
<<
1748 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1749 " [" << http
->range_iter
.currentSpec()->offset
<<
1750 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1751 " len: " << http
->range_iter
.currentSpec()->length
<<
1752 " debt: " << http
->range_iter
.debt());
1753 if (http
->range_iter
.currentSpec()->length
!= -1)
1754 assert(http
->out
.offset
<= start
); /* we did not miss it */
1759 } else if (reply
&& reply
->content_range
) {
1760 /* request does not have ranges, but reply does */
1761 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1762 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1764 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1767 return http
->out
.offset
;
1771 ClientSocketContext::pullData()
1773 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1775 /* More data will be coming from the stream. */
1776 StoreIOBuffer readBuffer
;
1777 /* XXX: Next requested byte in the range sequence */
1778 /* XXX: length = getmaximumrangelenfgth */
1779 readBuffer
.offset
= getNextRangeOffset();
1780 readBuffer
.length
= HTTP_REQBUF_SZ
;
1781 readBuffer
.data
= reqbuf
;
1782 /* we may note we have reached the end of the wanted ranges */
1783 clientStreamRead(getTail(), http
, readBuffer
);
1786 /** Adapt stream status to account for Range cases
1789 clientStream_status_t
1790 ClientSocketContext::socketState()
1792 switch (clientStreamStatus(getTail(), http
)) {
1795 /* check for range support ending */
1797 if (http
->request
->range
) {
1798 /* check: reply was parsed and range iterator was initialized */
1799 assert(http
->range_iter
.valid
);
1800 /* filter out data according to range specs */
1802 if (!canPackMoreRanges()) {
1803 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1804 "range sequence on " << clientConnection
);
1805 // we got everything we wanted from the store
1806 return STREAM_COMPLETE
;
1808 } else if (reply
&& reply
->content_range
) {
1809 /* reply has content-range, but Squid is not managing ranges */
1810 const int64_t &bytesSent
= http
->out
.offset
;
1811 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1813 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1814 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1815 reply
->content_range
->spec
.offset
<< ")");
1817 // did we get at least what we expected, based on range specs?
1819 if (bytesSent
== bytesExpected
) // got everything
1820 return STREAM_COMPLETE
;
1822 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1823 return STREAM_UNPLANNED_COMPLETE
;
1828 case STREAM_COMPLETE
:
1829 return STREAM_COMPLETE
;
1831 case STREAM_UNPLANNED_COMPLETE
:
1832 return STREAM_UNPLANNED_COMPLETE
;
1835 return STREAM_FAILED
;
1838 fatal ("unreachable code\n");
1843 * A write has just completed to the client, or we have just realised there is
1844 * no more data to send.
1847 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1849 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1850 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1853 /// remembers the abnormal connection termination for logging purposes
1855 ClientSocketContext::noteIoError(const int xerrno
)
1858 if (xerrno
== ETIMEDOUT
)
1859 http
->al
->http
.timedout
= true;
1860 else // even if xerrno is zero (which means read abort/eof)
1861 http
->al
->http
.aborted
= true;
1866 ClientSocketContext::doClose()
1868 clientConnection
->close();
1871 /// called when we encounter a response-related error
1873 ClientSocketContext::initiateClose(const char *reason
)
1875 http
->getConn()->stopSending(reason
); // closes ASAP
1879 ConnStateData::stopSending(const char *error
)
1881 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1882 "; old receiving error: " <<
1883 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1885 if (const char *oldError
= stoppedSending()) {
1886 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1887 return; // nothing has changed as far as this connection is concerned
1889 stoppedSending_
= error
;
1891 if (!stoppedReceiving()) {
1892 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1893 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1894 " request body bytes with " << in
.notYetUsed
<< " unused");
1895 return; // wait for the request receiver to finish reading
1899 clientConnection
->close();
1903 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1905 const StoreEntry
*entry
= http
->storeEntry();
1906 http
->out
.size
+= size
;
1907 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1908 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1909 (entry
? entry
->objectLen() : 0));
1910 clientUpdateSocketStats(http
->logType
, size
);
1912 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1914 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1917 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1918 initiateClose("failure or true request status");
1919 /* Do we leak here ? */
1923 switch (socketState()) {
1929 case STREAM_COMPLETE
:
1930 debugs(33, 5, conn
<< "Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1931 if (http
->request
->flags
.proxyKeepalive
)
1932 keepaliveNextRequest();
1934 initiateClose("STREAM_COMPLETE NOKEEPALIVE");
1937 case STREAM_UNPLANNED_COMPLETE
:
1938 initiateClose("STREAM_UNPLANNED_COMPLETE");
1942 initiateClose("STREAM_FAILED");
1946 fatal("Hit unreachable code in clientWriteComplete\n");
1950 SQUIDCEXTERN CSR clientGetMoreData
;
1951 SQUIDCEXTERN CSS clientReplyStatus
;
1952 SQUIDCEXTERN CSD clientReplyDetach
;
1954 static ClientSocketContext
*
1955 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1957 ClientHttpRequest
*http
;
1958 ClientSocketContext
*context
;
1959 StoreIOBuffer tempBuffer
;
1960 http
= new ClientHttpRequest(csd
);
1961 http
->req_sz
= csd
->in
.notYetUsed
;
1962 http
->uri
= xstrdup(uri
);
1963 setLogUri (http
, uri
);
1964 context
= new ClientSocketContext(csd
->clientConnection
, http
);
1965 tempBuffer
.data
= context
->reqbuf
;
1966 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1967 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1968 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1969 clientSocketDetach
, context
, tempBuffer
);
1974 skipLeadingSpace(char *aString
)
1976 char *result
= aString
;
1978 while (xisspace(*aString
))
1985 * 'end' defaults to NULL for backwards compatibility
1986 * remove default value if we ever get rid of NULL-terminated
1990 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1993 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1997 for (; end
> uriAndHTTPVersion
; --end
) {
1998 if (*end
== '\n' || *end
== '\r')
2001 if (xisspace(*end
)) {
2002 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2013 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2015 safe_free(http
->log_uri
);
2018 // The uri is already clean just dump it.
2019 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2022 switch (Config
.uri_whitespace
) {
2023 case URI_WHITESPACE_ALLOW
:
2024 flags
|= RFC1738_ESCAPE_NOSPACE
;
2026 case URI_WHITESPACE_ENCODE
:
2027 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2028 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2031 case URI_WHITESPACE_CHOP
: {
2032 flags
|= RFC1738_ESCAPE_NOSPACE
;
2033 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2034 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2035 int pos
= strcspn(http
->log_uri
, w_space
);
2036 http
->log_uri
[pos
] = '\0';
2040 case URI_WHITESPACE_DENY
:
2041 case URI_WHITESPACE_STRIP
:
2044 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2048 if (!xisspace(*t
)) {
2055 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2064 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, Http1::RequestParser
&hp
)
2066 int vhost
= conn
->port
->vhost
;
2067 int vport
= conn
->port
->vport
;
2068 static char ipbuf
[MAX_IPSTRLEN
];
2070 http
->flags
.accel
= true;
2072 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2074 static const SBuf
cache_object("cache_object://");
2075 if (hp
.requestUri().startsWith(cache_object
))
2076 return; /* already in good shape */
2078 const char *url
= SBuf(hp
.requestUri()).c_str(); // XXX: performance regression. convert to SBuf parse
2080 if (conn
->port
->vhost
)
2081 return; /* already in good shape */
2083 /* else we need to ignore the host name */
2084 url
= strstr(url
, "//");
2086 #if SHOULD_REJECT_UNKNOWN_URLS
2089 hp
.request_parse_status
= Http::scBadRequest
;
2090 return parseHttpRequestAbort(conn
, "error:invalid-request");
2095 url
= strchr(url
+ 2, '/');
2102 vport
= http
->getConn()->clientConnection
->local
.port();
2104 const bool switchedToHttps
= conn
->switchedToHttps();
2105 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2107 if (tryHostHeader
&& (host
= hp
.getHeaderField("Host"))) {
2108 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2113 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2114 strncpy(thost
, host
, (t
-host
));
2115 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2118 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2121 } // else nothing to alter port-wise.
2122 const int url_sz
= hp
.requestUri().length() + 32 + Config
.appendDomainLen
+
2124 http
->uri
= (char *)xcalloc(url_sz
, 1);
2125 const char *protocol
= switchedToHttps
?
2126 "https" : AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str();
2127 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2128 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2129 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2130 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2131 const int url_sz
= hp
.requestUri().length() + 32 + Config
.appendDomainLen
+
2132 strlen(conn
->port
->defaultsite
);
2133 http
->uri
= (char *)xcalloc(url_sz
, 1);
2137 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2139 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2140 AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, url
);
2141 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2142 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2143 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2144 /* Put the local socket IP address as the hostname, with whatever vport we found */
2145 const int url_sz
= hp
.requestUri().length() + 32 + Config
.appendDomainLen
;
2146 http
->uri
= (char *)xcalloc(url_sz
, 1);
2147 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2148 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2149 AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(),
2151 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2156 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, Http1::RequestParser
&hp
)
2158 static char ipbuf
[MAX_IPSTRLEN
];
2160 // TODO Must() on URI length>0 when the parser supports throw. For now avoid assert().
2161 if (!hp
.requestUri().length() && hp
.requestUri()[0] != '/')
2162 return; /* already in good shape */
2164 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2166 if (const char *host
= hp
.getHeaderField("Host")) {
2167 const int url_sz
= hp
.requestUri().length() + 32 + Config
.appendDomainLen
+
2169 http
->uri
= (char *)xcalloc(url_sz
, 1);
2170 snprintf(http
->uri
, url_sz
, "%s://%s%s", AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(), host
, SBuf(hp
.requestUri()).c_str());
2171 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2173 /* Put the local socket IP address as the hostname. */
2174 const int url_sz
= hp
.requestUri().length() + 32 + Config
.appendDomainLen
;
2175 http
->uri
= (char *)xcalloc(url_sz
, 1);
2176 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2177 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2178 AnyP::UriScheme(http
->getConn()->port
->transport
.protocol
).c_str(),
2179 ipbuf
, http
->getConn()->clientConnection
->local
.port(), SBuf(hp
.requestUri()).c_str());
2180 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2184 /** Parse an HTTP request
2186 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2187 * to 1 if the request was correctly parsed.
2188 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2189 * \param[in] hp an Http1::RequestParser
2190 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2191 * Pointed-to value will be set to Http::METHOD_NONE in case of
2193 * \param[out] http_ver will be set as a side-effect of the parsing
2194 * \return NULL on incomplete requests,
2195 * a ClientSocketContext structure on success or failure.
2197 static ClientSocketContext
*
2198 parseHttpRequest(ConnStateData
*csd
, Http1::RequestParser
&hp
)
2200 /* Attempt to parse the first line; this will define where the method, url, version and header begin */
2202 const bool parsedOk
= hp
.parse();
2205 debugs(33, 5, "Incomplete request, waiting for end of request line");
2210 if (hp
.request_parse_status
== Http::scHeaderTooLarge
)
2211 return parseHttpRequestAbort(csd
, "error:request-too-large");
2213 return parseHttpRequestAbort(csd
, "error:invalid-request");
2217 /* We know the whole request is in hp.buf now */
2219 /* deny CONNECT via accelerated ports */
2220 if (hp
.method() == Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2221 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->transport
.protocol
<< " Accelerator port " << csd
->port
->s
.port());
2222 /* XXX need a way to say "this many character length string" */
2223 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
.buf
);
2224 hp
.request_parse_status
= Http::scMethodNotAllowed
;
2225 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2228 if (hp
.method() == Http::METHOD_NONE
) {
2229 /* XXX need a way to say "this many character length string" */
2230 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
.buf
<< "'");
2231 hp
.request_parse_status
= Http::scMethodNotAllowed
;
2232 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2236 * Process headers after request line
2237 * TODO: Use httpRequestParse here.
2239 debugs(33, 3, Raw("req_hdr", hp
.rawHeaderBuf(), hp
.headerBlockSize()));
2240 debugs(33, 3, "prefix_sz = " << hp
.messageHeaderSize() <<
2241 ", request-line-size=" << hp
.firstLineSize() <<
2242 ", mime-header-size=" << hp
.headerBlockSize());
2244 /* Ok, all headers are received */
2245 ClientHttpRequest
*http
= new ClientHttpRequest(csd
);
2247 http
->req_sz
= hp
.messageHeaderSize();
2248 ClientSocketContext
*result
= new ClientSocketContext(csd
->clientConnection
, http
);
2250 StoreIOBuffer tempBuffer
;
2251 tempBuffer
.data
= result
->reqbuf
;
2252 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2254 ClientStreamData newServer
= new clientReplyContext(http
);
2255 ClientStreamData newClient
= result
;
2256 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2257 clientReplyStatus
, newServer
, clientSocketRecipient
,
2258 clientSocketDetach
, newClient
, tempBuffer
);
2260 debugs(33, 5, "parseHttpRequest: Request Header is\n" << hp
.rawHeaderBuf());
2263 const char *url
= SBuf(hp
.requestUri()).c_str();
2265 debugs(33,5, HERE
<< "repare absolute URL from " <<
2266 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2267 /* Rewrite the URL in transparent or accelerator mode */
2268 /* NP: there are several cases to traverse here:
2269 * - standard mode (forward proxy)
2270 * - transparent mode (TPROXY)
2271 * - transparent mode with failures
2272 * - intercept mode (NAT)
2273 * - intercept mode with failures
2274 * - accelerator mode (reverse proxy)
2276 * - mixed combos of the above with internal URL
2278 if (csd
->transparent()) {
2279 /* intercept or transparent mode, properly working with no failures */
2280 prepareTransparentURL(csd
, http
, hp
);
2282 } else if (internalCheck(url
)) {
2283 /* internal URL mode */
2284 /* prepend our name & port */
2285 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2286 // We just re-wrote the URL. Must replace the Host: header.
2287 // But have not parsed there yet!! flag for local-only handling.
2288 http
->flags
.internal
= true;
2290 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2291 /* accelerator mode */
2292 prepareAcceleratedURL(csd
, http
, hp
);
2296 /* No special rewrites have been applied above, use the
2297 * requested url. may be rewritten later, so make extra room */
2298 int url_sz
= hp
.requestUri().length() + Config
.appendDomainLen
+ 5;
2299 http
->uri
= (char *)xcalloc(url_sz
, 1);
2300 strcpy(http
->uri
, url
);
2303 debugs(33, 5, "parseHttpRequest: Complete request received");
2305 // XXX: crop this dump at the end of headers. No need for extras
2306 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2307 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
2308 hp
.method() << " " << hp
.requestUri() << " " << hp
.messageProtocol() << "\n" <<
2309 hp
.rawHeaderBuf() <<
2312 result
->flags
.parsed_ok
= 1;
2317 ConnStateData::getAvailableBufferLength() const
2319 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2320 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2321 // huge request_header_max_size may lead to more than INT_MAX unused space
2322 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2327 ConnStateData::maybeMakeSpaceAvailable()
2329 if (getAvailableBufferLength() < 2) {
2331 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2332 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2335 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2336 newSize
=Config
.maxRequestBufferSize
;
2338 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2339 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2345 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2347 ClientSocketContext::Pointer
*S
;
2349 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2357 ConnStateData::getConcurrentRequestCount() const
2360 ClientSocketContext::Pointer
*T
;
2362 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2363 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2368 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2370 if (flag
!= COMM_OK
) {
2371 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2376 if (!ignoreErrno(xerrno
)) {
2377 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2379 } else if (in
.notYetUsed
== 0) {
2380 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2388 ConnStateData::connFinishedWithConn(int size
)
2391 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2392 /* no current or pending requests */
2393 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2395 } else if (!Config
.onoff
.half_closed_clients
) {
2396 /* admin doesn't want to support half-closed client sockets */
2397 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2398 notifyAllContexts(0); // no specific error implies abort
2407 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2409 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2410 conn
->in
.notYetUsed
-= byteCount
;
2411 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2413 * If there is still data that will be used,
2414 * move it to the beginning.
2417 if (conn
->in
.notYetUsed
> 0)
2418 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2422 ConnStateData::clientAfterReadingRequests()
2424 // Were we expecting to read more request body from half-closed connection?
2425 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2426 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2427 clientConnection
->close();
2436 ConnStateData::quitAfterError(HttpRequest
*request
)
2438 // From HTTP p.o.v., we do not have to close after every error detected
2439 // at the client-side, but many such errors do require closure and the
2440 // client-side code is bad at handling errors so we play it safe.
2442 request
->flags
.proxyKeepalive
= false;
2443 flags
.readMore
= false;
2444 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2448 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2450 ClientHttpRequest
*http
= context
->http
;
2455 assert(sslServerBump
->entry
);
2456 // Did we create an error entry while processing CONNECT?
2457 if (!sslServerBump
->entry
->isEmpty()) {
2458 quitAfterError(http
->request
);
2460 // Get the saved error entry and send it to the client by replacing the
2461 // ClientHttpRequest store entry with it.
2462 clientStreamNode
*node
= context
->getClientReplyContext();
2463 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2465 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2466 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2468 // save the original request for logging purposes
2469 if (!context
->http
->al
->request
) {
2470 context
->http
->al
->request
= http
->request
;
2471 HTTPMSGLOCK(context
->http
->al
->request
);
2474 // Get error details from the fake certificate-peeking request.
2475 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2476 context
->pullData();
2480 // In bump-server-first mode, we have not necessarily seen the intended
2481 // server name at certificate-peeking time. Check for domain mismatch now,
2482 // when we can extract the intended name from the bumped HTTP request.
2483 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2484 HttpRequest
*request
= http
->request
;
2485 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2486 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2487 "does not match domainname " << request
->GetHost());
2489 bool allowDomainMismatch
= false;
2490 if (Config
.ssl_client
.cert_error
) {
2491 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2492 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2493 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2494 delete check
.sslErrors
;
2495 check
.sslErrors
= NULL
;
2498 if (!allowDomainMismatch
) {
2499 quitAfterError(request
);
2501 clientStreamNode
*node
= context
->getClientReplyContext();
2502 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2503 assert (repContext
);
2505 // Fill the server IP and hostname for error page generation.
2506 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2507 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2509 // Create an error object and fill it
2510 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2511 err
->src_addr
= clientConnection
->remote
;
2512 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2513 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2515 err
->detail
= errDetail
;
2516 // Save the original request for logging purposes.
2517 if (!context
->http
->al
->request
) {
2518 context
->http
->al
->request
= request
;
2519 HTTPMSGLOCK(context
->http
->al
->request
);
2521 repContext
->setReplyToError(request
->method
, err
);
2522 assert(context
->http
->out
.offset
== 0);
2523 context
->pullData();
2534 clientProcessRequest(ConnStateData
*conn
, Http1::RequestParser
&hp
, ClientSocketContext
*context
)
2536 ClientHttpRequest
*http
= context
->http
;
2537 HttpRequest::Pointer request
;
2538 bool chunked
= false;
2539 bool mustReplyToOptions
= false;
2540 bool unsupportedTe
= false;
2541 bool expectBody
= false;
2542 const AnyP::ProtocolVersion
&http_ver
= hp
.messageProtocol();
2543 const HttpRequestMethod
&method
= hp
.method();
2545 /* We have an initial client stream in place should it be needed */
2546 /* setup our private context */
2547 context
->registerWithConn();
2549 if (context
->flags
.parsed_ok
== 0) {
2550 clientStreamNode
*node
= context
->getClientReplyContext();
2551 debugs(33, 2, "Invalid Request");
2552 conn
->quitAfterError(NULL
);
2553 // setLogUri should called before repContext->setReplyToError
2554 setLogUri(http
, http
->uri
, true);
2555 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2556 assert (repContext
);
2557 switch (hp
.request_parse_status
) {
2558 case Http::scHeaderTooLarge
:
2559 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
,
2560 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2562 case Http::scMethodNotAllowed
:
2563 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2564 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2566 case Http::scHttpVersionNotSupported
:
2567 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2568 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2571 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
.request_parse_status
, method
, http
->uri
,
2572 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2574 assert(context
->http
->out
.offset
== 0);
2575 context
->pullData();
2579 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2580 clientStreamNode
*node
= context
->getClientReplyContext();
2581 debugs(33, 5, "Invalid URL: " << http
->uri
);
2582 conn
->quitAfterError(request
.getRaw());
2583 // setLogUri should called before repContext->setReplyToError
2584 setLogUri(http
, http
->uri
, true);
2585 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2586 assert (repContext
);
2587 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2588 assert(context
->http
->out
.offset
== 0);
2589 context
->pullData();
2593 /* compile headers */
2594 if (http_ver
.major
>= 1 && !request
->parseHeader(hp
)) {
2595 clientStreamNode
*node
= context
->getClientReplyContext();
2596 debugs(33, 5, "Failed to parse request headers:\n" << hp
.rawHeaderBuf());
2597 conn
->quitAfterError(request
.getRaw());
2598 // setLogUri should called before repContext->setReplyToError
2599 setLogUri(http
, http
->uri
, true);
2600 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2601 assert (repContext
);
2602 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2603 assert(context
->http
->out
.offset
== 0);
2604 context
->pullData();
2608 request
->clientConnectionManager
= conn
;
2610 request
->flags
.accelerated
= http
->flags
.accel
;
2611 request
->flags
.sslBumped
=conn
->switchedToHttps();
2612 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2613 // TODO: decouple http->flags.accel from request->flags.sslBumped
2614 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2615 !conn
->port
->allow_direct
: 0;
2617 if (request
->flags
.sslBumped
) {
2618 if (conn
->getAuth() != NULL
)
2619 request
->auth_user_request
= conn
->getAuth();
2624 * If transparent or interception mode is working clone the transparent and interception flags
2625 * from the port settings to the request.
2627 if (http
->clientConnection
!= NULL
) {
2628 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2629 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2630 if (request
->flags
.interceptTproxy
) {
2631 if (Config
.accessList
.spoof_client_ip
) {
2632 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2633 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2636 request
->flags
.spoofClientIp
= true;
2638 request
->flags
.spoofClientIp
= false;
2641 if (internalCheck(request
->urlpath
.termedBuf())) {
2642 if (internalHostnameIs(request
->GetHost()) &&
2643 request
->port
== getMyPort()) {
2644 http
->flags
.internal
= true;
2645 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2646 request
->SetHost(internalHostname());
2647 request
->port
= getMyPort();
2648 http
->flags
.internal
= true;
2652 if (http
->flags
.internal
) {
2653 request
->protocol
= AnyP::PROTO_HTTP
;
2654 request
->login
[0] = '\0';
2657 request
->flags
.internal
= http
->flags
.internal
;
2658 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2659 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2660 #if FOLLOW_X_FORWARDED_FOR
2661 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2662 // not a details about teh TCP connection itself
2663 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2664 #endif /* FOLLOW_X_FORWARDED_FOR */
2665 request
->my_addr
= conn
->clientConnection
->local
;
2666 request
->myportname
= conn
->port
->name
;
2667 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
2668 // for now Squid only supports HTTP requests
2669 assert(request
->http_ver
.protocol
== http_ver
.protocol
);
2670 request
->http_ver
.major
= http_ver
.major
;
2671 request
->http_ver
.minor
= http_ver
.minor
;
2673 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2674 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2675 request
->clientConnectionManager
= conn
;
2677 if (request
->header
.chunked()) {
2679 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2680 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2681 // HTTP/1.1 requires chunking to be the last encoding if there is one
2682 unsupportedTe
= te
.size() && te
!= "identity";
2683 } // else implied identity coding
2685 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2686 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2687 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2688 clientStreamNode
*node
= context
->getClientReplyContext();
2689 conn
->quitAfterError(request
.getRaw());
2690 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2691 assert (repContext
);
2692 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2693 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2694 assert(context
->http
->out
.offset
== 0);
2695 context
->pullData();
2699 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2700 clientStreamNode
*node
= context
->getClientReplyContext();
2701 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2702 assert (repContext
);
2703 conn
->quitAfterError(request
.getRaw());
2704 repContext
->setReplyToError(ERR_INVALID_REQ
,
2705 Http::scLengthRequired
, request
->method
, NULL
,
2706 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2707 assert(context
->http
->out
.offset
== 0);
2708 context
->pullData();
2712 if (request
->header
.has(HDR_EXPECT
)) {
2713 const String expect
= request
->header
.getList(HDR_EXPECT
);
2714 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2715 if (!supportedExpect
) {
2716 clientStreamNode
*node
= context
->getClientReplyContext();
2717 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2718 assert (repContext
);
2719 conn
->quitAfterError(request
.getRaw());
2720 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2721 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2722 assert(context
->http
->out
.offset
== 0);
2723 context
->pullData();
2728 http
->request
= request
.getRaw();
2729 HTTPMSGLOCK(http
->request
);
2730 clientSetKeepaliveFlag(http
);
2732 // Let tunneling code be fully responsible for CONNECT requests
2733 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2734 context
->mayUseConnection(true);
2735 conn
->flags
.readMore
= false;
2739 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2743 /* Do we expect a request-body? */
2744 expectBody
= chunked
|| request
->content_length
> 0;
2745 if (!context
->mayUseConnection() && expectBody
) {
2746 request
->body_pipe
= conn
->expectRequestBody(
2747 chunked
? -1 : request
->content_length
);
2749 /* Is it too large? */
2750 if (!chunked
&& // if chunked, we will check as we accumulate
2751 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2752 clientStreamNode
*node
= context
->getClientReplyContext();
2753 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2754 assert (repContext
);
2755 conn
->quitAfterError(request
.getRaw());
2756 repContext
->setReplyToError(ERR_TOO_BIG
,
2757 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2758 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2759 assert(context
->http
->out
.offset
== 0);
2760 context
->pullData();
2764 // We may stop producing, comm_close, and/or call setReplyToError()
2765 // below, so quit on errors to avoid http->doCallouts()
2766 if (!conn
->handleRequestBodyData())
2769 if (!request
->body_pipe
->productionEnded()) {
2770 debugs(33, 5, HERE
<< "need more request body");
2771 context
->mayUseConnection(true);
2772 assert(conn
->flags
.readMore
);
2776 http
->calloutContext
= new ClientRequestContext(http
);
2783 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2784 * to here because calling comm_reset_close() causes http to
2785 * be freed and the above connNoteUseOfBuffer() would hit an
2786 * assertion, not to mention that we were accessing freed memory.
2788 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2789 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2790 conn
->flags
.readMore
= false;
2791 comm_reset_close(conn
->clientConnection
);
2796 connStripBufferWhitespace (ConnStateData
* conn
)
2798 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2799 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2800 -- conn
->in
.notYetUsed
;
2805 * Limit the number of concurrent requests.
2806 * \return true when there are available position(s) in the pipeline queue for another request.
2807 * \return false when the pipeline queue is full or disabled.
2810 ConnStateData::concurrentRequestQueueFilled() const
2812 const int existingRequestCount
= getConcurrentRequestCount();
2814 // default to the configured pipeline size.
2815 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2816 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2818 // when queue filled already we cant add more.
2819 if (existingRequestCount
>= concurrentRequestLimit
) {
2820 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2821 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2829 * Attempt to parse one or more requests from the input buffer.
2830 * If a request is successfully parsed, even if the next request
2831 * is only partially parsed, it will return TRUE.
2834 ConnStateData::clientParseRequests()
2836 bool parsed_req
= false;
2838 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2840 // Loop while we have read bytes that are not needed for producing the body
2841 // On errors, bodyPipe may become nil, but readMore will be cleared
2842 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2843 connStripBufferWhitespace(this); // XXX: should not be needed anymore.
2845 /* Don't try to parse if the buffer is empty */
2846 if (in
.notYetUsed
== 0)
2849 /* Limit the number of concurrent requests */
2850 if (concurrentRequestQueueFilled())
2853 /* Should not be needed anymore */
2854 /* Terminate the string */
2855 in
.buf
[in
.notYetUsed
] = '\0';
2857 /* Begin the parsing */
2858 PROF_start(parseHttpRequest
);
2860 // parser is incremental. Generate new parser state if we,
2861 // a) dont have one already
2862 // b) have completed the previous request parsing already
2863 if (!parser_
|| parser_
->isDone())
2864 parser_
= new Http1::RequestParser(in
.buf
, in
.notYetUsed
);
2865 else // update the buffer space being parsed
2866 parser_
->bufsiz
= in
.notYetUsed
;
2868 /* Process request */
2869 ClientSocketContext
*context
= parseHttpRequest(this, *parser_
);
2870 if (parser_
->messageOffset()) {
2871 // nothing but prefix garbage in the buffer. consume it.
2872 connNoteUseOfBuffer(this, parser_
->messageOffset());
2873 parser_
->noteBufferShift(parser_
->messageOffset());
2875 PROF_stop(parseHttpRequest
);
2877 /* status -1 or 1 */
2879 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2880 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2881 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2882 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2884 // Request has now been shifted out of the buffer.
2885 // Consume header early so that next action starts with just the next bytes.
2886 connNoteUseOfBuffer(this, parser_
->messageHeaderSize() + parser_
->messageOffset());
2887 clientProcessRequest(this, *parser_
, context
);
2889 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2891 if (context
->mayUseConnection()) {
2892 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2898 /* XXX where to 'finish' the parsing pass? */
2903 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
2905 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
2909 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2911 if (io
.flag
== COMM_ERR_CLOSING
) {
2912 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
2916 assert(Comm::IsConnOpen(clientConnection
));
2917 assert(io
.conn
->fd
== clientConnection
->fd
);
2920 * Don't reset the timeout value here. The timeout value will be
2921 * set to Config.Timeout.request by httpAccept() and
2922 * clientWriteComplete(), and should apply to the request as a
2923 * whole, not individual read() calls. Plus, it breaks our
2924 * lame half-close detection
2926 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
2927 notifyAllContexts(io
.xerrno
);
2932 if (io
.flag
== COMM_OK
) {
2934 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
2936 // may comm_close or setReplyToError
2937 if (!handleReadData(io
.buf
, io
.size
))
2940 } else if (io
.size
== 0) {
2941 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
2943 if (connFinishedWithConn(io
.size
)) {
2944 clientConnection
->close();
2948 /* It might be half-closed, we can't tell */
2949 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
2951 commMarkHalfClosed(io
.conn
->fd
);
2953 fd_note(io
.conn
->fd
, "half-closed");
2955 /* There is one more close check at the end, to detect aborted
2956 * (partial) requests. At this point we can't tell if the request
2959 /* Continue to process previously read data */
2963 /* Process next request */
2964 if (getConcurrentRequestCount() == 0)
2965 fd_note(io
.fd
, "Reading next request");
2967 if (!clientParseRequests()) {
2971 * If the client here is half closed and we failed
2972 * to parse a request, close the connection.
2973 * The above check with connFinishedWithConn() only
2974 * succeeds _if_ the buffer is empty which it won't
2975 * be if we have an incomplete request.
2976 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
2978 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
2979 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
2980 clientConnection
->close();
2988 clientAfterReadingRequests();
2992 * called when new request data has been read from the socket
2994 * \retval false called comm_close or setReplyToError (the caller should bail)
2995 * \retval true we did not call comm_close or setReplyToError
2998 ConnStateData::handleReadData(char *buf
, size_t size
)
3000 char *current_buf
= in
.addressToReadInto();
3002 if (buf
!= current_buf
)
3003 memmove(current_buf
, buf
, size
);
3005 in
.notYetUsed
+= size
;
3007 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3009 // if we are reading a body, stuff data into the body pipe
3010 if (bodyPipe
!= NULL
)
3011 return handleRequestBodyData();
3016 * called when new request body data has been buffered in in.buf
3017 * may close the connection if we were closing and piped everything out
3019 * \retval false called comm_close or setReplyToError (the caller should bail)
3020 * \retval true we did not call comm_close or setReplyToError
3023 ConnStateData::handleRequestBodyData()
3025 assert(bodyPipe
!= NULL
);
3029 if (in
.bodyParser
) { // chunked encoding
3030 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3031 abortChunkedRequestBody(error
);
3034 } else { // identity encoding
3035 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3036 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3037 if (!bodyPipe
->mayNeedMoreData()) {
3038 // BodyPipe will clear us automagically when we produced everything
3044 connNoteUseOfBuffer(this, putSize
);
3047 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3049 if (const char *reason
= stoppedSending()) {
3050 /* we've finished reading like good clients,
3051 * now do the close that initiateClose initiated.
3053 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3054 clientConnection
->close();
3062 /// parses available chunked encoded body bytes, checks size, returns errors
3064 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3066 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3068 try { // the parser will throw on errors
3070 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3073 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3074 // add one because MemBuf will assert if it cannot 0-terminate
3075 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3076 raw
.append(in
.buf
, in
.notYetUsed
);
3078 const mb_size_t wasContentSize
= raw
.contentSize();
3079 BodyPipeCheckout
bpc(*bodyPipe
);
3080 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3082 putSize
= wasContentSize
- raw
.contentSize();
3084 // dechunk then check: the size limit applies to _dechunked_ content
3085 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3089 finishDechunkingRequest(true);
3091 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3094 // if chunk parser needs data, then the body pipe must need it too
3095 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3097 // if parser needs more space and we can consume nothing, we will stall
3098 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3099 } catch (...) { // TODO: be more specific
3100 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3101 return ERR_INVALID_REQ
;
3104 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3108 /// quit on errors related to chunked request body handling
3110 ConnStateData::abortChunkedRequestBody(const err_type error
)
3112 finishDechunkingRequest(false);
3114 // XXX: The code below works if we fail during initial request parsing,
3115 // but if we fail when the server-side works already, the server may send
3116 // us its response too, causing various assertions. How to prevent that?
3117 #if WE_KNOW_HOW_TO_SEND_ERRORS
3118 ClientSocketContext::Pointer context
= getCurrentContext();
3119 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3120 clientStreamNode
*node
= context
->getClientReplyContext();
3121 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3123 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3124 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3125 repContext
->setReplyToError(error
, scode
,
3126 repContext
->http
->request
->method
,
3127 repContext
->http
->uri
,
3129 repContext
->http
->request
,
3131 context
->pullData();
3133 // close or otherwise we may get stuck as nobody will notice the error?
3134 comm_reset_close(clientConnection
);
3137 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3138 comm_reset_close(clientConnection
);
3140 flags
.readMore
= false;
3144 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3146 if (!handleRequestBodyData())
3149 // too late to read more body
3150 if (!isOpen() || stoppedReceiving())
3157 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3159 // request reader may get stuck waiting for space if nobody consumes body
3160 if (bodyPipe
!= NULL
)
3161 bodyPipe
->enableAutoConsumption();
3163 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3166 /** general lifetime handler for HTTP requests */
3168 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3171 * Just close the connection to not confuse browsers
3172 * using persistent connections. Some browsers open
3173 * a connection and then do not use it until much
3174 * later (presumeably because the request triggering
3175 * the open has already been completed on another
3178 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3183 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3185 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3186 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3187 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3188 http
->al
->http
.timedout
= true;
3189 if (Comm::IsConnOpen(io
.conn
))
3193 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3194 AsyncJob("ConnStateData"),
3196 sslBumpMode(Ssl::bumpEnd
),
3197 switchedToHttps_(false),
3198 sslServerBump(NULL
),
3200 stoppedSending_(NULL
),
3201 stoppedReceiving_(NULL
)
3203 pinning
.host
= NULL
;
3205 pinning
.pinned
= false;
3206 pinning
.auth
= false;
3207 pinning
.zeroReply
= false;
3208 pinning
.peer
= NULL
;
3210 // store the details required for creating more MasterXaction objects as new requests come in
3211 clientConnection
= xact
->tcpClient
;
3212 port
= cbdataReference(xact
->squidPort
.get());
3213 log_addr
= xact
->tcpClient
->remote
;
3214 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3216 in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &in
.allocatedSize
);
3218 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3219 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3220 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3221 int i
= IP_PMTUDISC_DONT
;
3222 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3223 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3225 static bool reported
= false;
3228 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3234 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3235 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3236 comm_add_close_handler(clientConnection
->fd
, call
);
3238 if (Config
.onoff
.log_fqdn
)
3239 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3242 if (Ident::TheConfig
.identLookup
) {
3243 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3244 identChecklist
.src_addr
= xact
->tcpClient
->remote
;
3245 identChecklist
.my_addr
= xact
->tcpClient
->local
;
3246 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3247 Ident::Start(xact
->tcpClient
, clientIdentDone
, this);
3251 clientdbEstablished(clientConnection
->remote
, 1);
3253 flags
.readMore
= true;
3256 /** Handle a new connection on HTTP socket. */
3258 httpAccept(const CommAcceptCbParams
¶ms
)
3260 MasterXaction::Pointer xact
= params
.xaction
;
3261 AnyP::PortCfgPointer s
= xact
->squidPort
;
3264 // it is possible the call or accept() was still queued when the port was reconfigured
3265 debugs(33, 2, "HTTP accept failure: port reconfigured.");
3269 if (params
.flag
!= COMM_OK
) {
3270 // Its possible the call was still queued when the client disconnected
3271 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3275 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3276 fd_note(params
.conn
->fd
, "client http connect");
3278 if (s
->tcp_keepalive
.enabled
) {
3279 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3282 ++ incoming_sockets_accepted
;
3284 // Socket is ready, setup the connection manager to start using it
3285 ConnStateData
*connState
= new ConnStateData(xact
);
3287 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3288 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3289 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3290 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3292 connState
->readSomeData();
3295 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3297 if (Config
.onoff
.client_db
) {
3298 /* it was said several times that client write limiter does not work if client_db is disabled */
3300 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3301 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3303 // TODO: we check early to limit error response bandwith but we
3304 // should recheck when we can honor delay_pool_uses_indirect
3305 // TODO: we should also pass the port details for myportname here.
3306 ch
.src_addr
= params
.conn
->remote
;
3307 ch
.my_addr
= params
.conn
->local
;
3309 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3311 /* pools require explicit 'allow' to assign a client into them */
3312 if (pools
[pool
].access
) {
3313 ch
.accessList
= pools
[pool
].access
;
3314 allow_t answer
= ch
.fastCheck();
3315 if (answer
== ACCESS_ALLOWED
) {
3317 /* request client information from db after we did all checks
3318 this will save hash lookup if client failed checks */
3319 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3322 /* put client info in FDE */
3323 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3325 /* setup write limiter for this request */
3326 const double burst
= floor(0.5 +
3327 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3328 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3331 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3341 /** Create SSL connection structure and update fd_table */
3343 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3345 SSL
*ssl
= SSL_new(sslContext
);
3348 const int ssl_error
= ERR_get_error();
3349 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3354 SSL_set_fd(ssl
, conn
->fd
);
3355 fd_table
[conn
->fd
].ssl
= ssl
;
3356 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3357 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3359 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3360 fd_note(conn
->fd
, "client https start");
3365 /** negotiate an SSL connection */
3367 clientNegotiateSSL(int fd
, void *data
)
3369 ConnStateData
*conn
= (ConnStateData
*)data
;
3371 SSL
*ssl
= fd_table
[fd
].ssl
;
3374 if ((ret
= SSL_accept(ssl
)) <= 0) {
3375 int ssl_error
= SSL_get_error(ssl
, ret
);
3377 switch (ssl_error
) {
3379 case SSL_ERROR_WANT_READ
:
3380 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3383 case SSL_ERROR_WANT_WRITE
:
3384 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3387 case SSL_ERROR_SYSCALL
:
3390 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3396 if (errno
== ECONNRESET
)
3399 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3400 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3407 case SSL_ERROR_ZERO_RETURN
:
3408 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3413 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3414 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3415 " (" << ssl_error
<< "/" << ret
<< ")");
3423 if (SSL_session_reused(ssl
)) {
3424 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3425 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3427 if (do_debug(83, 4)) {
3428 /* Write out the SSL session details.. actually the call below, but
3429 * OpenSSL headers do strange typecasts confusing GCC.. */
3430 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3431 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3432 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
);
3434 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3436 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3437 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3438 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3439 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3440 * Because there are two possible usable cast, if you get an error here, try the other
3441 * commented line. */
3443 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3444 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3448 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3451 /* Note: This does not automatically fflush the log file.. */
3454 debugs(83, 2, "clientNegotiateSSL: New session " <<
3455 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3456 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3460 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3461 SSL_get_cipher(ssl
));
3463 client_cert
= SSL_get_peer_certificate(ssl
);
3465 if (client_cert
!= NULL
) {
3466 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3467 " client certificate: subject: " <<
3468 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3470 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3471 " client certificate: issuer: " <<
3472 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3474 X509_free(client_cert
);
3476 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3477 " has no certificate.");
3480 conn
->readSomeData();
3484 * If SSL_CTX is given, starts reading the SSL handshake.
3485 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3488 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3492 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3494 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3497 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3498 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3499 connState
, ConnStateData::requestTimeout
);
3500 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3503 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3505 char buf
[MAX_IPSTRLEN
];
3506 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3507 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3508 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3509 fakeRequest
->port
= details
->local
.port();
3510 fakeRequest
->clientConnectionManager
= connState
;
3511 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3512 #if FOLLOW_X_FORWARDED_FOR
3513 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3515 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3516 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3517 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3518 fakeRequest
->myportname
= connState
->port
->name
;
3519 if (fakeRequest
->flags
.interceptTproxy
) {
3520 if (Config
.accessList
.spoof_client_ip
) {
3521 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3522 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3524 fakeRequest
->flags
.spoofClientIp
= true;
3526 fakeRequest
->flags
.spoofClientIp
= false;
3527 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3528 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3533 * A callback function to use with the ACLFilledChecklist callback.
3534 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3535 * else reverts the connection to tunnel mode.
3538 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3540 ConnStateData
*connState
= (ConnStateData
*) data
;
3542 // if the connection is closed or closing, just return.
3543 if (!connState
->isOpen())
3546 // Require both a match and a positive bump mode to work around exceptional
3547 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3548 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3549 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3550 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3551 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3553 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3554 connState
->sslBumpMode
= Ssl::bumpNone
;
3556 // fake a CONNECT request to force connState to tunnel
3557 static char ip
[MAX_IPSTRLEN
];
3558 static char reqStr
[MAX_IPSTRLEN
+ 80];
3559 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3560 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, ip
);
3561 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3563 ret
= connState
->clientParseRequests();
3566 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3567 connState
->clientConnection
->close();
3572 /** handle a new HTTPS connection */
3574 httpsAccept(const CommAcceptCbParams
¶ms
)
3576 MasterXaction::Pointer xact
= params
.xaction
;
3577 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3580 // it is possible the call or accept() was still queued when the port was reconfigured
3581 debugs(33, 2, "HTTPS accept failure: port reconfigured.");
3585 if (params
.flag
!= COMM_OK
) {
3586 // Its possible the call was still queued when the client disconnected
3587 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3591 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3592 fd_note(params
.conn
->fd
, "client https connect");
3594 if (s
->tcp_keepalive
.enabled
) {
3595 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3598 ++incoming_sockets_accepted
;
3600 // Socket is ready, setup the connection manager to start using it
3601 ConnStateData
*connState
= new ConnStateData(xact
);
3603 if (s
->flags
.tunnelSslBumping
) {
3604 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3606 if (!Config
.accessList
.ssl_bump
) {
3607 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3611 // Create a fake HTTP request for ssl_bump ACL check,
3612 // using tproxy/intercept provided destination IP and port.
3613 HttpRequest
*request
= new HttpRequest();
3614 static char ip
[MAX_IPSTRLEN
];
3615 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3616 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3617 request
->port
= params
.conn
->local
.port();
3618 request
->myportname
= s
->name
;
3620 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3621 acl_checklist
->src_addr
= params
.conn
->remote
;
3622 acl_checklist
->my_addr
= s
->s
;
3623 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3626 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3627 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3632 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3634 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3635 state_data
->sslCrtdHandleReply(reply
);
3639 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3641 if (reply
.result
== HelperReply::BrokenHelper
) {
3642 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3643 } else if (!reply
.other().hasContent()) {
3644 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3646 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3647 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3648 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3650 if (reply
.result
!= HelperReply::Okay
) {
3651 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3653 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3654 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3655 getSslContextDone(ctx
, true);
3660 getSslContextDone(NULL
);
3663 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3665 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3667 // fake certificate adaptation requires bump-server-first mode
3668 if (!sslServerBump
) {
3669 assert(port
->signingCert
.get());
3670 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3671 if (port
->signPkey
.get())
3672 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3673 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3677 // In case of an error while connecting to the secure server, use a fake
3678 // trusted certificate, with no mimicked fields and no adaptation
3679 // algorithms. There is nothing we can mimic so we want to minimize the
3680 // number of warnings the user will have to see to get to the error page.
3681 assert(sslServerBump
->entry
);
3682 if (sslServerBump
->entry
->isEmpty()) {
3683 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3684 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3686 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3687 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3688 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3690 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3691 // If the algorithm already set, then ignore it.
3692 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3693 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3694 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3697 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3698 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3699 const char *param
= ca
->param
;
3701 // For parameterless CN adaptation, use hostname from the
3703 if (ca
->alg
== Ssl::algSetCommonName
) {
3705 param
= sslConnectHostOrIp
.termedBuf();
3706 certProperties
.commonName
= param
;
3707 certProperties
.setCommonName
= true;
3708 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3709 certProperties
.setValidAfter
= true;
3710 else if (ca
->alg
== Ssl::algSetValidBefore
)
3711 certProperties
.setValidBefore
= true;
3713 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3714 alg
<< " param: " << (param
? param
: "-"));
3718 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3719 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3720 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3721 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3725 } else {// if (!sslServerBump->entry->isEmpty())
3726 // Use trusted certificate for a Squid-generated error
3727 // or the user would have to add a security exception
3728 // just to see the error page. We will close the connection
3729 // so that the trust is not extended to non-Squid content.
3730 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3733 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3735 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3736 assert(port
->untrustedSigningCert
.get());
3737 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3738 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3740 assert(port
->signingCert
.get());
3741 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3743 if (port
->signPkey
.get())
3744 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3746 signAlgorithm
= certProperties
.signAlgorithm
;
3750 ConnStateData::getSslContextStart()
3752 assert(areAllContextsForThisConnection());
3754 /* careful: freeAllContexts() above frees request, host, etc. */
3756 if (port
->generateHostCertificates
) {
3757 Ssl::CertificateProperties certProperties
;
3758 buildSslCertGenerationParams(certProperties
);
3759 sslBumpCertKey
= certProperties
.dbKey().c_str();
3760 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3762 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3763 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3764 SSL_CTX
* dynCtx
= NULL
;
3765 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
.get(sslBumpCertKey
.termedBuf());
3766 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3767 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3768 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3769 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3770 getSslContextDone(dynCtx
);
3773 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3774 ssl_ctx_cache
.del(sslBumpCertKey
.termedBuf());
3777 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3782 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3783 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3784 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3785 request_message
.composeRequest(certProperties
);
3786 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3787 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3789 } catch (const std::exception
&e
) {
3790 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3791 "request for " << certProperties
.commonName
<<
3792 " certificate: " << e
.what() << "; will now block to " <<
3793 "generate that certificate.");
3794 // fall through to do blocking in-process generation.
3796 #endif // USE_SSL_CRTD
3798 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3799 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3800 getSslContextDone(dynCtx
, true);
3803 getSslContextDone(NULL
);
3807 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3809 // Try to add generated ssl context to storage.
3810 if (port
->generateHostCertificates
&& isNew
) {
3812 if (signAlgorithm
== Ssl::algSignTrusted
) {
3813 // Add signing certificate to the certificates chain
3814 X509
*cert
= port
->signingCert
.get();
3815 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3816 // increase the certificate lock
3817 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3819 const int ssl_error
= ERR_get_error();
3820 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3822 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3824 //else it is self-signed or untrusted do not attrach any certificate
3826 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3827 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3829 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3830 // If it is not in storage delete after using. Else storage deleted it.
3831 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3834 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3838 // If generated ssl context = NULL, try to use static ssl context.
3840 if (!port
->staticSslContext
) {
3841 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3842 clientConnection
->close();
3845 debugs(33, 5, HERE
<< "Using static ssl context.");
3846 sslContext
= port
->staticSslContext
.get();
3850 if (!httpsCreate(clientConnection
, sslContext
))
3853 // commSetConnTimeout() was called for this request before we switched.
3855 // Disable the client read handler until CachePeer selection is complete
3856 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3857 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3858 switchedToHttps_
= true;
3862 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3864 assert(!switchedToHttps_
);
3866 sslConnectHostOrIp
= request
->GetHost();
3867 sslCommonName
= request
->GetHost();
3869 // We are going to read new request
3870 flags
.readMore
= true;
3871 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3873 // If sslServerBump is set, then we have decided to deny CONNECT
3874 // and now want to switch to SSL to send the error to the client
3875 // without even peeking at the origin server certificate.
3876 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3877 request
->flags
.sslPeek
= true;
3878 sslServerBump
= new Ssl::ServerBump(request
);
3880 // will call httpsPeeked() with certificate and connection, eventually
3881 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3885 // otherwise, use sslConnectHostOrIp
3886 getSslContextStart();
3890 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3892 Must(sslServerBump
!= NULL
);
3894 if (Comm::IsConnOpen(serverConnection
)) {
3895 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3897 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3898 assert(serverCert
.get() != NULL
);
3899 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
3900 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
3901 " bumped: " << *serverConnection
);
3903 pinConnection(serverConnection
, NULL
, NULL
, false);
3905 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3907 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3908 Ip::Address intendedDest
;
3909 intendedDest
= sslConnectHostOrIp
.termedBuf();
3910 const bool isConnectRequest
= !port
->flags
.isIntercepted();
3912 // Squid serves its own error page and closes, so we want
3913 // a CN that causes no additional browser errors. Possible
3914 // only when bumping CONNECT with a user-typed address.
3915 if (intendedDest
.isAnyAddr() || isConnectRequest
)
3916 sslCommonName
= sslConnectHostOrIp
;
3917 else if (sslServerBump
->serverCert
.get())
3918 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
3920 // copy error detail from bump-server-first request to CONNECT request
3921 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
3922 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3925 getSslContextStart();
3928 #endif /* USE_SSL */
3930 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3932 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3934 if (!Comm::IsConnOpen(c
)) {
3935 Must(NHttpSockets
> 0); // we tried to open some
3936 --NHttpSockets
; // there will be fewer sockets than planned
3937 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3939 if (!NHttpSockets
) // we could not open any listen sockets at all
3940 fatalf("Unable to open %s",FdNote(portType
));
3947 /// find any unused HttpSockets[] slot and store fd there or return false
3949 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
3952 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
3953 if ((found
= HttpSockets
[i
] < 0))
3954 HttpSockets
[i
] = conn
->fd
;
3960 clientHttpConnectionsOpen(void)
3962 AnyP::PortCfg
*s
= NULL
;
3964 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
3965 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
3966 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
3967 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
3972 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
3973 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
3974 s
->flags
.tunnelSslBumping
= false;
3977 if (s
->flags
.tunnelSslBumping
&&
3978 !s
->staticSslContext
&&
3979 !s
->generateHostCertificates
) {
3980 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
3981 s
->flags
.tunnelSslBumping
= false;
3983 if (s
->flags
.tunnelSslBumping
) {
3984 // Create ssl_ctx cache for this port.
3985 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
3989 // Fill out a Comm::Connection which IPC will open as a listener for us
3990 // then pass back when active so we can start a TcpAcceptor subscription.
3991 s
->listenConn
= new Comm::Connection
;
3992 s
->listenConn
->local
= s
->s
;
3993 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
3995 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
3996 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
3997 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
3998 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4000 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4001 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4002 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4004 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4011 clientHttpsConnectionsOpen(void)
4015 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4016 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4017 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4018 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4022 if (!s
->staticSslContext
) {
4023 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4024 " due to SSL initialization failure.");
4028 // TODO: merge with similar code in clientHttpConnectionsOpen()
4029 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4030 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4031 s
->flags
.tunnelSslBumping
= false;
4034 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4035 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4036 s
->flags
.tunnelSslBumping
= false;
4039 if (s
->flags
.tunnelSslBumping
) {
4040 // Create ssl_ctx cache for this port.
4041 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4044 // Fill out a Comm::Connection which IPC will open as a listener for us
4045 s
->listenConn
= new Comm::Connection
;
4046 s
->listenConn
->local
= s
->s
;
4047 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4048 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4050 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4051 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4052 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4053 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4055 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4056 ListeningStartedDialer(&clientListenerConnectionOpened
,
4057 s
, Ipc::fdnHttpsSocket
, sub
));
4058 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4059 HttpSockets
[NHttpSockets
] = -1;
4065 /// process clientHttpConnectionsOpen result
4067 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4069 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4073 Must(Comm::IsConnOpen(s
->listenConn
));
4075 // TCP: setup a job to handle accept() with subscribed handler
4076 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4078 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4079 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4080 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4081 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4082 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4083 << FdNote(portTypeNote
) << " connections at "
4086 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4090 clientOpenListenSockets(void)
4092 clientHttpConnectionsOpen();
4094 clientHttpsConnectionsOpen();
4097 if (NHttpSockets
< 1)
4098 fatal("No HTTP or HTTPS ports configured");
4102 clientHttpConnectionsClose(void)
4104 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4105 if (s
->listenConn
!= NULL
) {
4106 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4107 s
->listenConn
->close();
4108 s
->listenConn
= NULL
;
4113 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4114 if (s
->listenConn
!= NULL
) {
4115 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4116 s
->listenConn
->close();
4117 s
->listenConn
= NULL
;
4122 // TODO see if we can drop HttpSockets array entirely */
4123 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4124 HttpSockets
[i
] = -1;
4131 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4133 const char *vary
= request
->vary_headers
;
4134 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4135 #if X_ACCELERATOR_VARY
4138 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4141 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4143 /* Oops... something odd is going on here.. */
4144 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4145 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4146 safe_free(request
->vary_headers
);
4151 /* This is not a varying object */
4155 /* virtual "vary" object found. Calculate the vary key and
4156 * continue the search
4158 vary
= httpMakeVaryMark(request
, entry
->getReply());
4161 request
->vary_headers
= xstrdup(vary
);
4164 /* Ouch.. we cannot handle this kind of variance */
4165 /* XXX This cannot really happen, but just to be complete */
4170 vary
= httpMakeVaryMark(request
, entry
->getReply());
4173 request
->vary_headers
= xstrdup(vary
);
4177 /* Ouch.. we cannot handle this kind of variance */
4178 /* XXX This cannot really happen, but just to be complete */
4180 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4183 /* Oops.. we have already been here and still haven't
4184 * found the requested variant. Bail out
4186 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4187 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4193 ACLFilledChecklist
*
4194 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4196 ConnStateData
* conn
= http
->getConn();
4197 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4198 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4201 * hack for ident ACL. It needs to get full addresses, and a place to store
4202 * the ident result on persistent connections...
4204 /* connection oriented auth also needs these two lines for it's operation. */
4208 CBDATA_CLASS_INIT(ConnStateData
);
4211 ConnStateData::transparent() const
4213 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4217 ConnStateData::reading() const
4219 return reader
!= NULL
;
4223 ConnStateData::stopReading()
4226 comm_read_cancel(clientConnection
->fd
, reader
);
4232 ConnStateData::expectRequestBody(int64_t size
)
4234 bodyPipe
= new BodyPipe(this);
4236 bodyPipe
->setBodySize(size
);
4238 startDechunkingRequest();
4243 ConnStateData::mayNeedToReadMoreBody() const
4246 return 0; // request without a body or read/produced all body bytes
4248 if (!bodyPipe
->bodySizeKnown())
4249 return -1; // probably need to read more, but we cannot be sure
4251 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4252 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4254 if (needToProduce
<= haveAvailable
)
4255 return 0; // we have read what we need (but are waiting for pipe space)
4257 return needToProduce
- haveAvailable
;
4261 ConnStateData::stopReceiving(const char *error
)
4263 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4264 "; old sending error: " <<
4265 (stoppedSending() ? stoppedSending_
: "none"));
4267 if (const char *oldError
= stoppedReceiving()) {
4268 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4269 return; // nothing has changed as far as this connection is concerned
4272 stoppedReceiving_
= error
;
4274 if (const char *sendError
= stoppedSending()) {
4275 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4276 clientConnection
->close();
4281 ConnStateData::expectNoForwarding()
4283 if (bodyPipe
!= NULL
) {
4284 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4285 bodyPipe
->expectNoConsumption();
4289 /// initialize dechunking state
4291 ConnStateData::startDechunkingRequest()
4293 Must(bodyPipe
!= NULL
);
4294 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4295 assert(!in
.bodyParser
);
4296 in
.bodyParser
= new ChunkedCodingParser
;
4299 /// put parsed content into input buffer and clean up
4301 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4303 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4305 if (bodyPipe
!= NULL
) {
4306 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4307 BodyPipe::Pointer myPipe
= bodyPipe
;
4308 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4309 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4311 Must(myPipe
->bodySizeKnown());
4312 ClientSocketContext::Pointer context
= getCurrentContext();
4313 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4314 context
->http
->request
->setContentLength(myPipe
->bodySize());
4318 delete in
.bodyParser
;
4319 in
.bodyParser
= NULL
;
4323 ConnStateData::In::addressToReadInto() const
4325 return buf
+ notYetUsed
;
4328 ConnStateData::In::In() : bodyParser(NULL
),
4329 buf (NULL
), notYetUsed (0), allocatedSize (0)
4332 ConnStateData::In::~In()
4335 memFreeBuf(allocatedSize
, buf
);
4336 delete bodyParser
; // TODO: pool
4340 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4343 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4347 ClientSocketContext::Pointer context
= getCurrentContext();
4348 if (context
!= NULL
) {
4349 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4353 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4354 clientConnection
->close();
4357 /// Our close handler called by Comm when the pinned connection is closed
4359 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4361 // FwdState might repin a failed connection sooner than this close
4362 // callback is called for the failed connection.
4363 assert(pinning
.serverConnection
== io
.conn
);
4364 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4365 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4367 if (sawZeroReply
&& clientConnection
!= NULL
) {
4368 debugs(33, 3, "Closing client connection on pinned zero reply.");
4369 clientConnection
->close();
4374 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4376 char desc
[FD_DESC_SZ
];
4378 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4379 if (pinning
.serverConnection
->fd
== pinServer
->fd
) {
4380 startPinnedConnectionMonitoring();
4385 unpinConnection(); // closes pinned connection, if any, and resets fields
4387 pinning
.serverConnection
= pinServer
;
4389 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4391 // when pinning an SSL bumped connection, the request may be NULL
4392 const char *pinnedHost
= "[unknown]";
4394 pinning
.host
= xstrdup(request
->GetHost());
4395 pinning
.port
= request
->port
;
4396 pinnedHost
= pinning
.host
;
4398 pinning
.port
= pinServer
->remote
.port();
4400 pinning
.pinned
= true;
4402 pinning
.peer
= cbdataReference(aPeer
);
4403 pinning
.auth
= auth
;
4404 char stmp
[MAX_IPSTRLEN
];
4405 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4406 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4407 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4408 clientConnection
->fd
);
4409 fd_note(pinning
.serverConnection
->fd
, desc
);
4411 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4412 pinning
.closeHandler
= JobCallback(33, 5,
4413 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4414 // remember the pinned connection so that cb does not unpin a fresher one
4415 typedef CommCloseCbParams Params
;
4416 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4417 params
.conn
= pinning
.serverConnection
;
4418 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4420 startPinnedConnectionMonitoring();
4423 /// Assign a read handler to an idle pinned connection so that we can detect connection closures.
4425 ConnStateData::startPinnedConnectionMonitoring()
4427 if (pinning
.readHandler
!= NULL
)
4428 return; // already monitoring
4430 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4431 pinning
.readHandler
= JobCallback(33, 3,
4432 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4433 static char unusedBuf
[8];
4434 comm_read(pinning
.serverConnection
, unusedBuf
, sizeof(unusedBuf
), pinning
.readHandler
);
4438 ConnStateData::stopPinnedConnectionMonitoring()
4440 if (pinning
.readHandler
!= NULL
) {
4441 comm_read_cancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4442 pinning
.readHandler
= NULL
;
4446 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4447 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4449 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4451 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4453 if (io
.flag
== COMM_ERR_CLOSING
)
4454 return; // close handler will clean up
4456 // We could use getConcurrentRequestCount(), but this may be faster.
4457 const bool clientIsIdle
= !getCurrentContext();
4459 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4460 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4462 assert(pinning
.serverConnection
== io
.conn
);
4463 pinning
.serverConnection
->close();
4465 // If we are still sending data to the client, do not close now. When we are done sending,
4466 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4467 // However, if we are idle, then we must close to inform the idle client and minimize races.
4468 if (clientIsIdle
&& clientConnection
!= NULL
)
4469 clientConnection
->close();
4472 const Comm::ConnectionPointer
4473 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4475 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4478 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4480 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4482 else if (request
&& pinning
.port
!= request
->port
)
4484 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4486 else if (aPeer
!= pinning
.peer
)
4490 /* The pinning info is not safe, remove any pinning info */
4494 return pinning
.serverConnection
;
4498 ConnStateData::unpinConnection()
4500 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4503 cbdataReferenceDone(pinning
.peer
);
4505 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4506 if (pinning
.closeHandler
!= NULL
) {
4507 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4508 pinning
.closeHandler
= NULL
;
4510 /// also close the server side socket, we should not use it for any future requests...
4511 // TODO: do not close if called from our close handler?
4512 pinning
.serverConnection
->close();
4515 safe_free(pinning
.host
);
4517 pinning
.zeroReply
= false;
4519 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4520 * connection has gone away */