2 * DEBUG: section 33 Client-side Routines
3 * AUTHOR: Duane Wessels
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 \defgroup ClientSide Client-Side Logics
35 \section cserrors Errors and client side
37 \par Problem the first:
38 * the store entry is no longer authoritative on the
39 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
40 * of client_side_reply.c.
41 * Problem the second: resources are wasted if we delay in cleaning up.
42 * Problem the third we can't depend on a connection close to clean up.
44 \par Nice thing the first:
45 * Any step in the stream can callback with data
46 * representing an error.
47 * Nice thing the second: once you stop requesting reads from upstream,
48 * upstream can be stopped too.
51 * Error has a callback mechanism to hand over a membuf
52 * with the error content. The failing node pushes that back as the
53 * reply. Can this be generalised to reduce duplicate efforts?
54 * A: Possibly. For now, only one location uses this.
55 * How to deal with pre-stream errors?
56 * Tell client_side_reply that we *want* an error page before any
57 * stream calls occur. Then we simply read as normal.
60 \section pconn_logic Persistent connection logic:
63 * requests (httpClientRequest structs) get added to the connection
64 * list, with the current one being chr
67 * The request is *immediately* kicked off, and data flows through
68 * to clientSocketRecipient.
71 * If the data that arrives at clientSocketRecipient is not for the current
72 * request, clientSocketRecipient simply returns, without requesting more
73 * data, or sending it.
76 * ClientKeepAliveNextRequest will then detect the presence of data in
77 * the next ClientHttpRequest, and will send it, restablishing the
82 #include "acl/FilledChecklist.h"
83 #include "anyp/PortCfg.h"
84 #include "base/Subscription.h"
85 #include "base/TextException.h"
86 #include "CachePeer.h"
87 #include "ChunkedCodingParser.h"
88 #include "client_db.h"
89 #include "client_side.h"
90 #include "client_side_reply.h"
91 #include "client_side_request.h"
92 #include "ClientRequestContext.h"
93 #include "clientStream.h"
95 #include "comm/Connection.h"
96 #include "comm/Loops.h"
97 #include "comm/TcpAcceptor.h"
98 #include "comm/Write.h"
99 #include "CommCalls.h"
100 #include "errorpage.h"
103 #include "fqdncache.h"
104 #include "FwdState.h"
107 #include "HttpHdrContRange.h"
108 #include "HttpHeaderTools.h"
109 #include "HttpReply.h"
110 #include "HttpRequest.h"
111 #include "ident/Config.h"
112 #include "ident/Ident.h"
113 #include "internal.h"
114 #include "ipc/FdNotes.h"
115 #include "ipc/StartListening.h"
116 #include "log/access_log.h"
119 #include "MemObject.h"
120 #include "mime_header.h"
121 #include "profiler/Profiler.h"
123 #include "SquidConfig.h"
124 #include "SquidTime.h"
125 #include "StatCounters.h"
126 #include "StatHist.h"
128 #include "TimeOrTag.h"
133 #include "auth/UserRequest.h"
136 #include "ClientInfo.h"
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"
157 #define comm_close comm_lingering_close
160 /// dials clientListenerConnectionOpened call
161 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
164 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
165 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
166 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
168 virtual void print(std::ostream
&os
) const {
170 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
173 virtual bool canDial(AsyncCall
&) const { return true; }
174 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
180 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
181 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
182 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
185 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
187 /* our socket-related context */
189 CBDATA_CLASS_INIT(ClientSocketContext
);
191 /* Local functions */
192 static IOCB clientWriteComplete
;
193 static IOCB clientWriteBodyComplete
;
194 static IOACB httpAccept
;
196 static IOACB httpsAccept
;
198 static CTCB clientLifetimeTimeout
;
199 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
200 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, Http::ProtocolVersion
*);
202 static IDCB clientIdentDone
;
204 static CSCB clientSocketRecipient
;
205 static CSD clientSocketDetach
;
206 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
207 static int clientIsContentLengthValid(HttpRequest
* r
);
208 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
210 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
211 static void clientUpdateStatCounters(LogTags logType
);
212 static void clientUpdateHierCounters(HierarchyLogEntry
*);
213 static bool clientPingHasFinished(ping_data
const *aPing
);
214 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
216 static bool connIsUsable(ConnStateData
* conn
);
218 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
219 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
220 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
222 char *skipLeadingSpace(char *aString
);
223 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
226 ClientSocketContext::getTail() const
228 if (http
->client_stream
.tail
)
229 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
235 ClientSocketContext::getClientReplyContext() const
237 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
241 * This routine should be called to grow the inbuf and then
245 ConnStateData::readSomeData()
250 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
252 if (!in
.maybeMakeSpaceAvailable())
255 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
256 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
257 comm_read(clientConnection
, in
.buf
, reader
);
261 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
263 ClientSocketContext::Pointer
*tempContextPointer
;
264 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
265 assert(conn
->getCurrentContext() != NULL
);
266 /* Unlink us from the connection request list */
267 tempContextPointer
= & conn
->currentobject
;
269 while (tempContextPointer
->getRaw()) {
270 if (*tempContextPointer
== this)
273 tempContextPointer
= &(*tempContextPointer
)->next
;
276 assert(tempContextPointer
->getRaw() != NULL
);
277 *tempContextPointer
= next
;
281 ClientSocketContext::~ClientSocketContext()
283 clientStreamNode
*node
= getTail();
286 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
289 /* We are *always* the tail - prevent recursive free */
290 assert(this == streamContext
);
296 deRegisterWithConn();
298 httpRequestFree(http
);
300 /* clean up connection links to us */
301 assert(this != next
.getRaw());
305 ClientSocketContext::registerWithConn()
307 assert (!connRegistered_
);
309 assert (http
->getConn() != NULL
);
310 connRegistered_
= true;
311 http
->getConn()->addContextToQueue(this);
315 ClientSocketContext::deRegisterWithConn()
317 assert (connRegistered_
);
318 removeFromConnectionList(http
->getConn());
319 connRegistered_
= false;
323 ClientSocketContext::connIsFinished()
326 assert (http
->getConn() != NULL
);
327 deRegisterWithConn();
328 /* we can't handle any more stream data - detach */
329 clientStreamDetach(getTail(), http
);
332 ClientSocketContext::ClientSocketContext(const Comm::ConnectionPointer
&aConn
, ClientHttpRequest
*aReq
) :
333 clientConnection(aConn
),
338 mayUseConnection_ (false),
339 connRegistered_ (false)
341 assert(http
!= NULL
);
342 memset (reqbuf
, '\0', sizeof (reqbuf
));
345 deferredparams
.node
= NULL
;
346 deferredparams
.rep
= NULL
;
350 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
352 const HttpReply::Pointer
rep(msg
.reply
);
355 // apply selected clientReplyContext::buildReplyHeader() mods
356 // it is not clear what headers are required for control messages
357 rep
->header
.removeHopByHopEntries();
358 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
359 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
361 // remember the callback
362 cbControlMsgSent
= msg
.cbSuccess
;
364 MemBuf
*mb
= rep
->pack();
366 debugs(11, 2, "HTTP Client " << clientConnection
);
367 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
369 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
370 CommIoCbPtrFun(&WroteControlMsg
, this));
371 Comm::Write(clientConnection
, mb
, call
);
376 /// called when we wrote the 1xx response
378 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
380 if (errflag
== COMM_ERR_CLOSING
)
383 if (errflag
== COMM_OK
) {
384 ScheduleCallHere(cbControlMsgSent
);
388 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
389 // no error notification: see HttpControlMsg.h for rationale and
390 // note that some errors are detected elsewhere (e.g., close handler)
392 // close on 1xx errors to be conservative and to simplify the code
393 // (if we do not close, we must notify the source of a failure!)
397 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
399 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
401 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
402 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
407 clientIdentDone(const char *ident
, void *data
)
409 ConnStateData
*conn
= (ConnStateData
*)data
;
410 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
415 clientUpdateStatCounters(LogTags logType
)
417 ++statCounter
.client_http
.requests
;
419 if (logTypeIsATcpHit(logType
))
420 ++statCounter
.client_http
.hits
;
422 if (logType
== LOG_TCP_HIT
)
423 ++statCounter
.client_http
.disk_hits
;
424 else if (logType
== LOG_TCP_MEM_HIT
)
425 ++statCounter
.client_http
.mem_hits
;
429 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
431 statCounter
.client_http
.allSvcTime
.count(svc_time
);
433 * The idea here is not to be complete, but to get service times
434 * for only well-defined types. For example, we don't include
435 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
436 * (we *tried* to validate it, but failed).
441 case LOG_TCP_REFRESH_UNMODIFIED
:
442 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
445 case LOG_TCP_IMS_HIT
:
446 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
451 case LOG_TCP_MEM_HIT
:
453 case LOG_TCP_OFFLINE_HIT
:
454 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
459 case LOG_TCP_CLIENT_REFRESH_MISS
:
460 statCounter
.client_http
.missSvcTime
.count(svc_time
);
464 /* make compiler warnings go away */
470 clientPingHasFinished(ping_data
const *aPing
)
472 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
479 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
483 switch (someEntry
->code
) {
484 #if USE_CACHE_DIGESTS
489 ++ statCounter
.cd
.times_used
;
497 case FIRST_PARENT_MISS
:
499 case CLOSEST_PARENT_MISS
:
500 ++ statCounter
.icp
.times_used
;
501 i
= &someEntry
->ping
;
503 if (clientPingHasFinished(i
))
504 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
507 ++ statCounter
.icp
.query_timeouts
;
514 ++ statCounter
.netdb
.times_used
;
524 ClientHttpRequest::updateCounters()
526 clientUpdateStatCounters(logType
);
528 if (request
->errType
!= ERR_NONE
)
529 ++ statCounter
.client_http
.errors
;
531 clientUpdateStatHistCounters(logType
,
532 tvSubMsec(al
->cache
.start_time
, current_time
));
534 clientUpdateHierCounters(&request
->hier
);
538 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
541 assert(aLogEntry
!= NULL
);
543 if (Config
.onoff
.log_mime_hdrs
) {
547 packerToMemInit(&p
, &mb
);
548 request
->header
.packInto(&p
);
549 //This is the request after adaptation or redirection
550 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
552 // the virgin request is saved to aLogEntry->request
553 if (aLogEntry
->request
) {
556 packerToMemInit(&p
, &mb
);
557 aLogEntry
->request
->header
.packInto(&p
);
558 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
562 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
566 packerToMemInit(&p
, &mb
);
567 ah
->lastMeta
.packInto(&p
);
568 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
577 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
579 aLogEntry
->icap
.processingTime
= ih
->processingTime();
582 aLogEntry
->http
.method
= request
->method
;
583 aLogEntry
->http
.version
= request
->http_ver
;
584 aLogEntry
->hier
= request
->hier
;
585 if (request
->content_length
> 0) // negative when no body or unknown length
586 aLogEntry
->http
.clientRequestSz
.payloadData
+= request
->content_length
; // XXX: actually adaptedRequest payload size ??
587 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
589 // Adapted request, if any, inherits and then collects all the stats, but
590 // the virgin request gets logged instead; copy the stats to log them.
591 // TODO: avoid losses by keeping these stats in a shared history object?
592 if (aLogEntry
->request
) {
593 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
594 aLogEntry
->request
->errType
= request
->errType
;
595 aLogEntry
->request
->errDetail
= request
->errDetail
;
600 ClientHttpRequest::logRequest()
602 if (!out
.size
&& !logType
)
603 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
605 al
->icp
.opcode
= ICP_INVALID
;
607 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
610 al
->http
.code
= al
->reply
->sline
.status();
611 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
612 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
613 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
614 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
617 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
619 if (loggingEntry() && loggingEntry()->mem_obj
)
620 al
->cache
.objectSize
= loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ?
622 al
->http
.clientRequestSz
.header
= req_sz
;
623 al
->http
.clientReplySz
.header
= out
.headers_sz
;
624 // XXX: calculate without payload encoding or headers !!
625 al
->http
.clientReplySz
.payloadData
= out
.size
- out
.headers_sz
; // pretend its all un-encoded data for now.
627 al
->cache
.highOffset
= out
.offset
;
629 al
->cache
.code
= logType
;
631 al
->cache
.msec
= tvSubMsec(al
->cache
.start_time
, current_time
);
634 prepareLogWithRequestDetails(request
, al
);
636 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
637 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
641 /* This is broken. Fails if the connection has been closed. Needs
642 * to snarf the ssl details some place earlier..
644 if (getConn() != NULL
)
645 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
650 // The al->notes and request->notes must point to the same object.
651 (void)SyncNotes(*al
, *request
);
652 typedef Notes::iterator ACAMLI
;
653 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
654 if (const char *value
= (*i
)->match(request
, al
->reply
, NULL
)) {
655 NotePairs
¬es
= SyncNotes(*al
, *request
);
656 notes
.add((*i
)->key
.termedBuf(), value
);
657 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
661 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
663 checklist
.reply
= al
->reply
;
664 HTTPMSGLOCK(checklist
.reply
);
668 al
->adapted_request
= request
;
669 HTTPMSGLOCK(al
->adapted_request
);
671 accessLogLog(al
, &checklist
);
673 bool updatePerformanceCounters
= true;
674 if (Config
.accessList
.stats_collection
) {
675 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
677 statsCheck
.reply
= al
->reply
;
678 HTTPMSGLOCK(statsCheck
.reply
);
680 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
683 if (updatePerformanceCounters
) {
687 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
688 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
693 ClientHttpRequest::freeResources()
697 safe_free(redirect
.location
);
698 range_iter
.boundary
.clean();
699 HTTPMSGUNLOCK(request
);
701 if (client_stream
.tail
)
702 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
706 httpRequestFree(void *data
)
708 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
709 assert(http
!= NULL
);
714 ConnStateData::areAllContextsForThisConnection() const
716 assert(this != NULL
);
717 ClientSocketContext::Pointer context
= getCurrentContext();
719 while (context
.getRaw()) {
720 if (context
->http
->getConn() != this)
723 context
= context
->next
;
730 ConnStateData::freeAllContexts()
732 ClientSocketContext::Pointer context
;
734 while ((context
= getCurrentContext()).getRaw() != NULL
) {
735 assert(getCurrentContext() !=
736 getCurrentContext()->next
);
737 context
->connIsFinished();
738 assert (context
!= currentobject
);
742 /// propagates abort event to all contexts
744 ConnStateData::notifyAllContexts(int xerrno
)
746 typedef ClientSocketContext::Pointer CSCP
;
747 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
748 c
->noteIoError(xerrno
);
751 /* This is a handler normally called by comm_close() */
752 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
754 deleteThis("ConnStateData::connStateClosed");
759 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
763 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
769 // clobered with self-pointer
770 // NP: something nasty is going on in Squid, but harmless.
772 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
777 * Connection-auth relies on a single set of credentials being preserved
778 * for all requests on a connection once they have been setup.
779 * There are several things which need to happen to preserve security
780 * when connection-auth credentials change unexpectedly or are unset.
782 * 1) auth helper released from any active state
784 * They can only be reserved by a handshake process which this
785 * connection can now never complete.
786 * This prevents helpers hanging when their connections close.
788 * 2) pinning is expected to be removed and server conn closed
790 * The upstream link is authenticated with the same credentials.
791 * Expecting the same level of consistency we should have received.
792 * This prevents upstream being faced with multiple or missing
793 * credentials after authentication.
794 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
795 * we just trigger that cleanup here via comm_reset_close() or
796 * ConnStateData::stopReceiving()
798 * 3) the connection needs to close.
800 * This prevents attackers injecting requests into a connection,
801 * or gateways wrongly multiplexing users into a single connection.
803 * When credentials are missing closure needs to follow an auth
804 * challenge for best recovery by the client.
806 * When credentials change there is nothing we can do but abort as
807 * fast as possible. Sending TCP RST instead of an HTTP response
808 * is the best-case action.
811 // clobbered with nul-pointer
813 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
814 auth_
->releaseAuthServer();
816 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
817 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
818 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
819 stopReceiving("connection-auth removed");
823 // clobbered with alternative credentials
825 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
826 auth_
->releaseAuthServer();
828 // this is a fatal type of problem.
829 // Close the connection immediately with TCP RST to abort all traffic flow
830 comm_reset_close(clientConnection
);
838 // cleans up before destructor is called
840 ConnStateData::swanSong()
842 debugs(33, 2, HERE
<< clientConnection
);
843 flags
.readMore
= false;
844 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
845 assert(areAllContextsForThisConnection());
850 if (Comm::IsConnOpen(clientConnection
))
851 clientConnection
->close();
854 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
855 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
858 BodyProducer::swanSong();
859 flags
.swanSang
= true;
863 ConnStateData::isOpen() const
865 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
866 Comm::IsConnOpen(clientConnection
) &&
867 !fd_table
[clientConnection
->fd
].closing();
870 ConnStateData::~ConnStateData()
872 assert(this != NULL
);
873 debugs(33, 3, HERE
<< clientConnection
);
876 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
879 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
881 cbdataReferenceDone(port
);
883 if (bodyPipe
!= NULL
)
884 stopProducingFor(bodyPipe
, false);
887 delete sslServerBump
;
892 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
893 * This is the client-side persistent connection flag. We need
894 * to set this relatively early in the request processing
895 * to handle hacks for broken servers and clients.
898 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
900 HttpRequest
*request
= http
->request
;
902 debugs(33, 3, "http_ver = " << request
->http_ver
);
903 debugs(33, 3, "method = " << request
->method
);
905 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
906 request
->flags
.proxyKeepalive
= request
->persistent();
910 clientIsContentLengthValid(HttpRequest
* r
)
912 switch (r
->method
.id()) {
914 case Http::METHOD_GET
:
916 case Http::METHOD_HEAD
:
917 /* We do not want to see a request entity on GET/HEAD requests */
918 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
921 /* For other types of requests we don't care */
929 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
931 if (Config
.maxRequestBodySize
&&
932 bodyLength
> Config
.maxRequestBodySize
)
933 return 1; /* too large */
940 connIsUsable(ConnStateData
* conn
)
942 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
950 // careful: the "current" context may be gone if we wrote an early response
951 ClientSocketContext::Pointer
952 ConnStateData::getCurrentContext() const
955 return currentobject
;
959 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
961 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
962 assert(flags
.deferred
== 0);
964 deferredparams
.node
= node
;
965 deferredparams
.rep
= rep
;
966 deferredparams
.queuedBuffer
= receivedData
;
971 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
973 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
980 ClientSocketContext::startOfOutput() const
982 return http
->out
.size
== 0;
986 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
988 /*the size of available range can always fit in a size_t type*/
989 size_t maximum
= (size_t)available
.size();
991 if (!http
->request
->range
)
994 assert (canPackMoreRanges());
996 if (http
->range_iter
.debt() == -1)
999 assert (http
->range_iter
.debt() > 0);
1001 /* TODO this + the last line could be a range intersection calculation */
1002 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
1005 return min(http
->range_iter
.debt(), (int64_t)maximum
);
1009 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
1011 http
->out
.offset
+= bytes
;
1013 if (!http
->request
->range
)
1016 if (http
->range_iter
.debt() != -1) {
1017 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
1018 assert (http
->range_iter
.debt() >= 0);
1021 /* debt() always stops at -1, below that is a bug */
1022 assert (http
->range_iter
.debt() >= -1);
1026 ClientHttpRequest::multipartRangeRequest() const
1028 return request
->multipartRangeRequest();
1032 ClientSocketContext::multipartRangeRequest() const
1034 return http
->multipartRangeRequest();
1038 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1040 assert(rep
== NULL
);
1042 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1043 size_t length
= lengthToSend(bodyData
.range());
1044 noteSentBodyBytes (length
);
1045 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1046 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1047 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1053 if (multipartRangeRequest())
1054 packRange(bodyData
, &mb
);
1056 packChunk(bodyData
, mb
);
1058 if (mb
.contentSize()) {
1060 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1061 CommIoCbPtrFun(clientWriteComplete
, this));
1062 Comm::Write(clientConnection
, &mb
, call
);
1064 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1068 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1069 * if bodyData is empty.
1072 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1074 const uint64_t length
=
1075 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1076 noteSentBodyBytes(length
);
1078 mb
.Printf("%" PRIX64
"\r\n", length
);
1079 mb
.append(bodyData
.data
, length
);
1083 /** put terminating boundary for multiparts */
1085 clientPackTermBound(String boundary
, MemBuf
* mb
)
1087 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1088 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1091 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1093 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1095 HttpHeader
hdr(hoReply
);
1101 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1102 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1103 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1105 /* stuff the header with required entries and pack it */
1107 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1108 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1110 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1112 packerToMemInit(&p
, mb
);
1120 /* append <crlf> (we packed a header, not a reply) */
1125 * extracts a "range" from *buf and appends them to mb, updating
1126 * all offsets and such.
1129 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1131 HttpHdrRangeIter
* i
= &http
->range_iter
;
1132 Range
<int64_t> available (source
.range());
1133 char const *buf
= source
.data
;
1135 while (i
->currentSpec() && available
.size()) {
1136 const size_t copy_sz
= lengthToSend(available
);
1140 * intersection of "have" and "need" ranges must not be empty
1142 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1143 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1146 * put boundary and headers at the beginning of a range in a
1150 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1151 assert(http
->memObject());
1153 http
->memObject()->getReply(), /* original reply */
1154 i
->currentSpec(), /* current range */
1155 i
->boundary
, /* boundary, the same for all */
1162 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1164 noteSentBodyBytes (copy_sz
);
1166 mb
->append(buf
, copy_sz
);
1171 available
.start
+= copy_sz
;
1177 if (!canPackMoreRanges()) {
1178 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1181 /* put terminating boundary for multiparts */
1182 clientPackTermBound(i
->boundary
, mb
);
1187 int64_t nextOffset
= getNextRangeOffset();
1189 assert (nextOffset
>= http
->out
.offset
);
1191 int64_t skip
= nextOffset
- http
->out
.offset
;
1193 /* adjust for not to be transmitted bytes */
1194 http
->out
.offset
= nextOffset
;
1196 if (available
.size() <= (uint64_t)skip
)
1199 available
.start
+= skip
;
1208 /** returns expected content length for multi-range replies
1209 * note: assumes that httpHdrRangeCanonize has already been called
1210 * warning: assumes that HTTP headers for individual ranges at the
1211 * time of the actuall assembly will be exactly the same as
1212 * the headers when clientMRangeCLen() is called */
1214 ClientHttpRequest::mRangeCLen()
1219 assert(memObject());
1222 HttpHdrRange::iterator pos
= request
->range
->begin();
1224 while (pos
!= request
->range
->end()) {
1225 /* account for headers for this range */
1227 clientPackRangeHdr(memObject()->getReply(),
1228 *pos
, range_iter
.boundary
, &mb
);
1231 /* account for range content */
1232 clen
+= (*pos
)->length
;
1234 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1238 /* account for the terminating boundary */
1241 clientPackTermBound(range_iter
.boundary
, &mb
);
1251 * returns true if If-Range specs match reply, false otherwise
1254 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1256 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1257 /* check for parsing falure */
1264 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1265 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1266 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1269 return 0; /* entity has no etag to compare with! */
1271 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1272 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1273 return 0; /* must use strong validator for sub-range requests */
1276 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1279 /* got modification time? */
1280 if (spec
.time
>= 0) {
1281 return http
->storeEntry()->lastmod
<= spec
.time
;
1284 assert(0); /* should not happen */
1289 * generates a "unique" boundary string for multipart responses
1290 * the caller is responsible for cleaning the string */
1292 ClientHttpRequest::rangeBoundaryStr() const
1296 String
b(APP_FULLNAME
);
1298 key
= storeEntry()->getMD5Text();
1299 b
.append(key
, strlen(key
));
1303 /** adds appropriate Range headers if needed */
1305 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1307 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1308 const char *range_err
= NULL
;
1309 HttpRequest
*request
= http
->request
;
1310 assert(request
->range
);
1311 /* check if we still want to do ranges */
1313 int64_t roffLimit
= request
->getRangeOffsetLimit();
1316 range_err
= "no [parse-able] reply";
1317 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1318 range_err
= "wrong status code";
1319 else if (hdr
->has(HDR_CONTENT_RANGE
))
1320 range_err
= "origin server does ranges";
1321 else if (rep
->content_length
< 0)
1322 range_err
= "unknown length";
1323 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1324 range_err
= "INCONSISTENT length"; /* a bug? */
1326 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1329 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1330 range_err
= "If-Range match failed";
1331 else if (!http
->request
->range
->canonize(rep
))
1332 range_err
= "canonization failed";
1333 else if (http
->request
->range
->isComplex())
1334 range_err
= "too complex range header";
1335 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1336 range_err
= "range outside range_offset_limit";
1338 /* get rid of our range specs on error */
1340 /* XXX We do this here because we need canonisation etc. However, this current
1341 * code will lead to incorrect store offset requests - the store will have the
1342 * offset data, but we won't be requesting it.
1343 * So, we can either re-request, or generate an error
1345 http
->request
->ignoreRange(range_err
);
1347 /* XXX: TODO: Review, this unconditional set may be wrong. */
1348 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1349 // web server responded with a valid, but unexpected range.
1350 // will (try-to) forward as-is.
1351 //TODO: we should cope with multirange request/responses
1352 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1353 request
->range
->contains(rep
->content_range
->spec
) :
1355 const int spec_count
= http
->request
->range
->specs
.size();
1356 int64_t actual_clen
= -1;
1358 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1359 spec_count
<< " virgin clen: " << rep
->content_length
);
1360 assert(spec_count
> 0);
1361 /* append appropriate header(s) */
1363 if (spec_count
== 1) {
1364 if (!replyMatchRequest
) {
1365 hdr
->delById(HDR_CONTENT_RANGE
);
1366 hdr
->putContRange(rep
->content_range
);
1367 actual_clen
= rep
->content_length
;
1368 //http->range_iter.pos = rep->content_range->spec.begin();
1369 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1370 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1373 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1375 /* append Content-Range */
1377 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1378 /* No content range, so this was a full object we are
1381 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1384 /* set new Content-Length to the actual number of bytes
1385 * transmitted in the message-body */
1386 actual_clen
= (*pos
)->length
;
1390 /* generate boundary string */
1391 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1392 /* delete old Content-Type, add ours */
1393 hdr
->delById(HDR_CONTENT_TYPE
);
1394 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1395 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1396 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1397 /* Content-Length is not required in multipart responses
1398 * but it is always nice to have one */
1399 actual_clen
= http
->mRangeCLen();
1400 /* http->out needs to start where we want data at */
1401 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1404 /* replace Content-Length header */
1405 assert(actual_clen
>= 0);
1407 hdr
->delById(HDR_CONTENT_LENGTH
);
1409 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1411 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1413 /* And start the range iter off */
1414 http
->range_iter
.updateSpec();
1419 ClientSocketContext::prepareReply(HttpReply
* rep
)
1423 if (http
->request
->range
)
1424 buildRangeHeader(rep
);
1428 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1432 MemBuf
*mb
= rep
->pack();
1434 // dump now, so we dont output any body.
1435 debugs(11, 2, "HTTP Client " << clientConnection
);
1436 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1438 /* Save length of headers for persistent conn checks */
1439 http
->out
.headers_sz
= mb
->contentSize();
1442 headersLog(0, 0, http
->request
->method
, rep
);
1445 if (bodyData
.data
&& bodyData
.length
) {
1446 if (multipartRangeRequest())
1447 packRange(bodyData
, mb
);
1448 else if (http
->request
->flags
.chunkedReply
) {
1449 packChunk(bodyData
, *mb
);
1451 size_t length
= lengthToSend(bodyData
.range());
1452 noteSentBodyBytes (length
);
1454 mb
->append(bodyData
.data
, length
);
1459 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1460 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1461 CommIoCbPtrFun(clientWriteComplete
, this));
1462 Comm::Write(clientConnection
, mb
, call
);
1467 * Write a chunk of data to a client socket. If the reply is present,
1468 * send the reply headers down the wire too, and clean them up when
1471 * The request is one backed by a connection, not an internal request.
1472 * data context is not NULL
1473 * There are no more entries in the stream chain.
1476 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1477 HttpReply
* rep
, StoreIOBuffer receivedData
)
1479 /* Test preconditions */
1480 assert(node
!= NULL
);
1481 PROF_start(clientSocketRecipient
);
1482 /* TODO: handle this rather than asserting
1483 * - it should only ever happen if we cause an abort and
1484 * the callback chain loops back to here, so we can simply return.
1485 * However, that itself shouldn't happen, so it stays as an assert for now.
1487 assert(cbdataReferenceValid(node
));
1488 assert(node
->node
.next
== NULL
);
1489 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1490 assert(context
!= NULL
);
1491 assert(connIsUsable(http
->getConn()));
1493 /* TODO: check offset is what we asked for */
1495 if (context
!= http
->getConn()->getCurrentContext()) {
1496 context
->deferRecipientForLater(node
, rep
, receivedData
);
1497 PROF_stop(clientSocketRecipient
);
1501 // After sending Transfer-Encoding: chunked (at least), always send
1502 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1503 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1504 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1505 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1506 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1507 PROF_stop(clientSocketRecipient
);
1511 if (!context
->startOfOutput())
1512 context
->sendBody(rep
, receivedData
);
1515 http
->al
->reply
= rep
;
1516 HTTPMSGLOCK(http
->al
->reply
);
1517 context
->sendStartOfMessage(rep
, receivedData
);
1520 PROF_stop(clientSocketRecipient
);
1524 * Called when a downstream node is no longer interested in
1525 * our data. As we are a terminal node, this means on aborts
1529 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1531 /* Test preconditions */
1532 assert(node
!= NULL
);
1533 /* TODO: handle this rather than asserting
1534 * - it should only ever happen if we cause an abort and
1535 * the callback chain loops back to here, so we can simply return.
1536 * However, that itself shouldn't happen, so it stays as an assert for now.
1538 assert(cbdataReferenceValid(node
));
1539 /* Set null by ContextFree */
1540 assert(node
->node
.next
== NULL
);
1541 /* this is the assert discussed above */
1542 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1543 /* We are only called when the client socket shutsdown.
1544 * Tell the prev pipeline member we're finished
1546 clientStreamDetach(node
, http
);
1550 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1552 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1553 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1557 ConnStateData::readNextRequest()
1559 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1561 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1563 * Set the timeout BEFORE calling readSomeData().
1565 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1566 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1567 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1568 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1571 /** Please don't do anything with the FD past here! */
1575 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1577 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1579 /** If the client stream is waiting on a socket write to occur, then */
1581 if (deferredRequest
->flags
.deferred
) {
1582 /** NO data is allowed to have been sent. */
1583 assert(deferredRequest
->http
->out
.size
== 0);
1585 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1586 deferredRequest
->http
,
1587 deferredRequest
->deferredparams
.rep
,
1588 deferredRequest
->deferredparams
.queuedBuffer
);
1591 /** otherwise, the request is still active in a callbacksomewhere,
1596 /// called when we have successfully finished writing the response
1598 ClientSocketContext::keepaliveNextRequest()
1600 ConnStateData
* conn
= http
->getConn();
1602 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1605 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1606 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1607 conn
->clientConnection
->close();
1612 * We are done with the response, and we are either still receiving request
1613 * body (early response!) or have already stopped receiving anything.
1615 * If we are still receiving, then clientParseRequest() below will fail.
1616 * (XXX: but then we will call readNextRequest() which may succeed and
1617 * execute a smuggled request as we are not done with the current request).
1619 * If we stopped because we got everything, then try the next request.
1621 * If we stopped receiving because of an error, then close now to avoid
1622 * getting stuck and to prevent accidental request smuggling.
1625 if (const char *reason
= conn
->stoppedReceiving()) {
1626 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1627 conn
->clientConnection
->close();
1632 * Attempt to parse a request from the request buffer.
1633 * If we've been fed a pipelined request it may already
1634 * be in our read buffer.
1637 * This needs to fall through - if we're unlucky and parse the _last_ request
1638 * from our read buffer we may never re-register for another client read.
1641 if (conn
->clientParseRequests()) {
1642 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1646 * Either we need to kick-start another read or, if we have
1647 * a half-closed connection, kill it after the last request.
1648 * This saves waiting for half-closed connections to finished being
1649 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1650 * the keepalive "Waiting for next request" state.
1652 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1653 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1654 conn
->clientConnection
->close();
1658 ClientSocketContext::Pointer deferredRequest
;
1661 * At this point we either have a parsed request (which we've
1662 * kicked off the processing for) or not. If we have a deferred
1663 * request (parsed but deferred for pipeling processing reasons)
1664 * then look at processing it. If not, simply kickstart
1668 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1669 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1670 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1671 } else if (conn
->flags
.readMore
) {
1672 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1673 conn
->readNextRequest();
1675 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1676 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1681 clientUpdateSocketStats(LogTags logType
, size_t size
)
1686 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1688 if (logTypeIsATcpHit(logType
))
1689 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1693 * increments iterator "i"
1694 * used by clientPackMoreRanges
1696 \retval true there is still data available to pack more ranges
1700 ClientSocketContext::canPackMoreRanges() const
1702 /** first update iterator "i" if needed */
1704 if (!http
->range_iter
.debt()) {
1705 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1707 if (http
->range_iter
.pos
!= http
->range_iter
.end
)
1708 ++http
->range_iter
.pos
;
1710 http
->range_iter
.updateSpec();
1713 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1715 /* paranoid sync condition */
1716 /* continue condition: need_more_data */
1717 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1718 return http
->range_iter
.currentSpec() ? true : false;
1722 ClientSocketContext::getNextRangeOffset() const
1724 debugs (33, 5, "range: " << http
->request
->range
<<
1725 "; http offset " << http
->out
.offset
<<
1726 "; reply " << reply
);
1728 // XXX: This method is called from many places, including pullData() which
1729 // may be called before prepareReply() [on some Squid-generated errors].
1730 // Hence, we may not even know yet whether we should honor/do ranges.
1732 if (http
->request
->range
) {
1733 /* offset in range specs does not count the prefix of an http msg */
1734 /* check: reply was parsed and range iterator was initialized */
1735 assert(http
->range_iter
.valid
);
1736 /* filter out data according to range specs */
1737 assert (canPackMoreRanges());
1739 int64_t start
; /* offset of still missing data */
1740 assert(http
->range_iter
.currentSpec());
1741 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1742 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1743 debugs(33, 3, "clientPackMoreRanges: out:"
1744 " start: " << start
<<
1745 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1746 " [" << http
->range_iter
.currentSpec()->offset
<<
1747 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1748 " len: " << http
->range_iter
.currentSpec()->length
<<
1749 " debt: " << http
->range_iter
.debt());
1750 if (http
->range_iter
.currentSpec()->length
!= -1)
1751 assert(http
->out
.offset
<= start
); /* we did not miss it */
1756 } else if (reply
&& reply
->content_range
) {
1757 /* request does not have ranges, but reply does */
1758 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1759 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1761 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1764 return http
->out
.offset
;
1768 ClientSocketContext::pullData()
1770 debugs(33, 5, reply
<< " written " << http
->out
.size
<< " into " << clientConnection
);
1772 /* More data will be coming from the stream. */
1773 StoreIOBuffer readBuffer
;
1774 /* XXX: Next requested byte in the range sequence */
1775 /* XXX: length = getmaximumrangelenfgth */
1776 readBuffer
.offset
= getNextRangeOffset();
1777 readBuffer
.length
= HTTP_REQBUF_SZ
;
1778 readBuffer
.data
= reqbuf
;
1779 /* we may note we have reached the end of the wanted ranges */
1780 clientStreamRead(getTail(), http
, readBuffer
);
1783 /** Adapt stream status to account for Range cases
1786 clientStream_status_t
1787 ClientSocketContext::socketState()
1789 switch (clientStreamStatus(getTail(), http
)) {
1792 /* check for range support ending */
1794 if (http
->request
->range
) {
1795 /* check: reply was parsed and range iterator was initialized */
1796 assert(http
->range_iter
.valid
);
1797 /* filter out data according to range specs */
1799 if (!canPackMoreRanges()) {
1800 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1801 "range sequence on " << clientConnection
);
1802 // we got everything we wanted from the store
1803 return STREAM_COMPLETE
;
1805 } else if (reply
&& reply
->content_range
) {
1806 /* reply has content-range, but Squid is not managing ranges */
1807 const int64_t &bytesSent
= http
->out
.offset
;
1808 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1810 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1811 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1812 reply
->content_range
->spec
.offset
<< ")");
1814 // did we get at least what we expected, based on range specs?
1816 if (bytesSent
== bytesExpected
) // got everything
1817 return STREAM_COMPLETE
;
1819 if (bytesSent
> bytesExpected
) // Error: Sent more than expected
1820 return STREAM_UNPLANNED_COMPLETE
;
1825 case STREAM_COMPLETE
:
1826 return STREAM_COMPLETE
;
1828 case STREAM_UNPLANNED_COMPLETE
:
1829 return STREAM_UNPLANNED_COMPLETE
;
1832 return STREAM_FAILED
;
1835 fatal ("unreachable code\n");
1840 * A write has just completed to the client, or we have just realised there is
1841 * no more data to send.
1844 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1846 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1847 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1850 /// remembers the abnormal connection termination for logging purposes
1852 ClientSocketContext::noteIoError(const int xerrno
)
1855 if (xerrno
== ETIMEDOUT
)
1856 http
->al
->http
.timedout
= true;
1857 else // even if xerrno is zero (which means read abort/eof)
1858 http
->al
->http
.aborted
= true;
1863 ClientSocketContext::doClose()
1865 clientConnection
->close();
1868 /// called when we encounter a response-related error
1870 ClientSocketContext::initiateClose(const char *reason
)
1872 http
->getConn()->stopSending(reason
); // closes ASAP
1876 ConnStateData::stopSending(const char *error
)
1878 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1879 "; old receiving error: " <<
1880 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1882 if (const char *oldError
= stoppedSending()) {
1883 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1884 return; // nothing has changed as far as this connection is concerned
1886 stoppedSending_
= error
;
1888 if (!stoppedReceiving()) {
1889 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1890 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1891 " request body bytes with " << in
.buf
.length() << " unused");
1892 return; // wait for the request receiver to finish reading
1896 clientConnection
->close();
1900 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1902 const StoreEntry
*entry
= http
->storeEntry();
1903 http
->out
.size
+= size
;
1904 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1905 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1906 (entry
? entry
->objectLen() : 0));
1907 clientUpdateSocketStats(http
->logType
, size
);
1909 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1911 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1914 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1915 initiateClose("failure or true request status");
1916 /* Do we leak here ? */
1920 switch (socketState()) {
1926 case STREAM_COMPLETE
:
1927 debugs(33, 5, conn
<< "Stream complete, keepalive is " << http
->request
->flags
.proxyKeepalive
);
1928 if (http
->request
->flags
.proxyKeepalive
)
1929 keepaliveNextRequest();
1931 initiateClose("STREAM_COMPLETE NOKEEPALIVE");
1934 case STREAM_UNPLANNED_COMPLETE
:
1935 initiateClose("STREAM_UNPLANNED_COMPLETE");
1939 initiateClose("STREAM_FAILED");
1943 fatal("Hit unreachable code in clientWriteComplete\n");
1947 SQUIDCEXTERN CSR clientGetMoreData
;
1948 SQUIDCEXTERN CSS clientReplyStatus
;
1949 SQUIDCEXTERN CSD clientReplyDetach
;
1951 static ClientSocketContext
*
1952 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1954 ClientHttpRequest
*http
;
1955 ClientSocketContext
*context
;
1956 StoreIOBuffer tempBuffer
;
1957 http
= new ClientHttpRequest(csd
);
1958 http
->req_sz
= csd
->in
.buf
.length();
1959 http
->uri
= xstrdup(uri
);
1960 setLogUri (http
, uri
);
1961 context
= new ClientSocketContext(csd
->clientConnection
, http
);
1962 tempBuffer
.data
= context
->reqbuf
;
1963 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1964 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1965 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1966 clientSocketDetach
, context
, tempBuffer
);
1971 skipLeadingSpace(char *aString
)
1973 char *result
= aString
;
1975 while (xisspace(*aString
))
1982 * 'end' defaults to NULL for backwards compatibility
1983 * remove default value if we ever get rid of NULL-terminated
1987 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1990 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1994 for (; end
> uriAndHTTPVersion
; --end
) {
1995 if (*end
== '\n' || *end
== '\r')
1998 if (xisspace(*end
)) {
1999 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2010 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2012 safe_free(http
->log_uri
);
2015 // The uri is already clean just dump it.
2016 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2019 switch (Config
.uri_whitespace
) {
2020 case URI_WHITESPACE_ALLOW
:
2021 flags
|= RFC1738_ESCAPE_NOSPACE
;
2023 case URI_WHITESPACE_ENCODE
:
2024 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2025 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2028 case URI_WHITESPACE_CHOP
: {
2029 flags
|= RFC1738_ESCAPE_NOSPACE
;
2030 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2031 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2032 int pos
= strcspn(http
->log_uri
, w_space
);
2033 http
->log_uri
[pos
] = '\0';
2037 case URI_WHITESPACE_DENY
:
2038 case URI_WHITESPACE_STRIP
:
2041 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2045 if (!xisspace(*t
)) {
2052 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2061 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2063 int vhost
= conn
->port
->vhost
;
2064 int vport
= conn
->port
->vport
;
2066 char ipbuf
[MAX_IPSTRLEN
];
2068 http
->flags
.accel
= true;
2070 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2072 if (strncasecmp(url
, "cache_object://", 15) == 0)
2073 return; /* already in good shape */
2076 if (conn
->port
->vhost
)
2077 return; /* already in good shape */
2079 /* else we need to ignore the host name */
2080 url
= strstr(url
, "//");
2082 #if SHOULD_REJECT_UNKNOWN_URLS
2085 hp
->request_parse_status
= Http::scBadRequest
;
2086 return parseHttpRequestAbort(conn
, "error:invalid-request");
2091 url
= strchr(url
+ 2, '/');
2098 vport
= http
->getConn()->clientConnection
->local
.port();
2100 const bool switchedToHttps
= conn
->switchedToHttps();
2101 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2102 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2103 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2108 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2109 strncpy(thost
, host
, (t
-host
));
2110 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2113 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2116 } // else nothing to alter port-wise.
2117 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2119 http
->uri
= (char *)xcalloc(url_sz
, 1);
2120 const char *protocol
= switchedToHttps
?
2121 "https" : AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str();
2122 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2123 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2124 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2125 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2126 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2127 strlen(conn
->port
->defaultsite
);
2128 http
->uri
= (char *)xcalloc(url_sz
, 1);
2132 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2134 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2135 AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(), conn
->port
->defaultsite
, vportStr
, url
);
2136 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2137 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2138 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2139 /* Put the local socket IP address as the hostname, with whatever vport we found */
2140 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2141 http
->uri
= (char *)xcalloc(url_sz
, 1);
2142 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2143 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2144 AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(),
2146 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2151 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2154 char ipbuf
[MAX_IPSTRLEN
];
2157 return; /* already in good shape */
2159 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2161 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2162 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2164 http
->uri
= (char *)xcalloc(url_sz
, 1);
2165 snprintf(http
->uri
, url_sz
, "%s://%s%s", AnyP::UriScheme(conn
->port
->transport
.protocol
).c_str(), host
, url
);
2166 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2168 /* Put the local socket IP address as the hostname. */
2169 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2170 http
->uri
= (char *)xcalloc(url_sz
, 1);
2171 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2172 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2173 AnyP::UriScheme(http
->getConn()->port
->transport
.protocol
).c_str(),
2174 ipbuf
, http
->getConn()->clientConnection
->local
.port(), url
);
2175 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2179 /** Parse an HTTP request
2181 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2182 * to 1 if the request was correctly parsed.
2183 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2184 * \param[in] hp an HttpParser
2185 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2186 * Pointed-to value will be set to Http::METHOD_NONE in case of
2188 * \param[out] http_ver will be set as a side-effect of the parsing
2189 * \return NULL on incomplete requests,
2190 * a ClientSocketContext structure on success or failure.
2192 static ClientSocketContext
*
2193 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2195 char *req_hdr
= NULL
;
2198 ClientHttpRequest
*http
;
2199 ClientSocketContext
*result
;
2200 StoreIOBuffer tempBuffer
;
2203 /* pre-set these values to make aborting simpler */
2204 *method_p
= Http::METHOD_NONE
;
2206 /* NP: don't be tempted to move this down or remove again.
2207 * It's the only DDoS protection old-String has against long URL */
2208 if ( hp
->bufsiz
<= 0) {
2209 debugs(33, 5, "Incomplete request, waiting for end of request line");
2211 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2212 debugs(33, 5, "parseHttpRequest: Too large request");
2213 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2214 return parseHttpRequestAbort(csd
, "error:request-too-large");
2217 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2218 r
= HttpParserParseReqLine(hp
);
2221 debugs(33, 5, "Incomplete request, waiting for end of request line");
2226 return parseHttpRequestAbort(csd
, "error:invalid-request");
2229 /* Request line is valid here .. */
2230 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2232 /* This call scans the entire request, not just the headers */
2233 if (hp
->req
.v_maj
> 0) {
2234 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2235 debugs(33, 5, "Incomplete request, waiting for end of headers");
2239 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2240 req_sz
= HttpParserReqSz(hp
);
2243 /* We know the whole request is in hp->buf now */
2245 assert(req_sz
<= (size_t) hp
->bufsiz
);
2247 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2248 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2251 hp
->hdr_end
= req_sz
- 1;
2253 hp
->hdr_start
= hp
->req
.end
+ 1;
2255 /* Enforce max_request_size */
2256 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2257 debugs(33, 5, "parseHttpRequest: Too large request");
2258 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2259 return parseHttpRequestAbort(csd
, "error:request-too-large");
2263 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2265 /* deny CONNECT via accelerated ports */
2266 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2267 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->transport
.protocol
<< " Accelerator port " << csd
->port
->s
.port());
2268 /* XXX need a way to say "this many character length string" */
2269 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2270 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2271 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2274 if (*method_p
== Http::METHOD_NONE
) {
2275 /* XXX need a way to say "this many character length string" */
2276 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2277 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2278 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2282 * Process headers after request line
2283 * TODO: Use httpRequestParse here.
2285 /* XXX this code should be modified to take a const char * later! */
2286 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2288 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2290 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2292 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2294 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2295 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2296 HttpParserReqSz(hp
));
2298 /* Ok, all headers are received */
2299 http
= new ClientHttpRequest(csd
);
2301 http
->req_sz
= HttpParserRequestLen(hp
);
2302 result
= new ClientSocketContext(csd
->clientConnection
, http
);
2303 tempBuffer
.data
= result
->reqbuf
;
2304 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2306 ClientStreamData newServer
= new clientReplyContext(http
);
2307 ClientStreamData newClient
= result
;
2308 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2309 clientReplyStatus
, newServer
, clientSocketRecipient
,
2310 clientSocketDetach
, newClient
, tempBuffer
);
2312 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2316 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2317 * below needs to be modified to not expect a mutable nul-terminated string.
2319 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2321 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2323 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2325 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2327 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2332 debugs(33,5, HERE
<< "repare absolute URL from " <<
2333 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2334 /* Rewrite the URL in transparent or accelerator mode */
2335 /* NP: there are several cases to traverse here:
2336 * - standard mode (forward proxy)
2337 * - transparent mode (TPROXY)
2338 * - transparent mode with failures
2339 * - intercept mode (NAT)
2340 * - intercept mode with failures
2341 * - accelerator mode (reverse proxy)
2343 * - mixed combos of the above with internal URL
2345 if (csd
->transparent()) {
2346 /* intercept or transparent mode, properly working with no failures */
2347 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2349 } else if (internalCheck(url
)) {
2350 /* internal URL mode */
2351 /* prepend our name & port */
2352 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2353 // We just re-wrote the URL. Must replace the Host: header.
2354 // But have not parsed there yet!! flag for local-only handling.
2355 http
->flags
.internal
= true;
2357 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2358 /* accelerator mode */
2359 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2363 /* No special rewrites have been applied above, use the
2364 * requested url. may be rewritten later, so make extra room */
2365 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2366 http
->uri
= (char *)xcalloc(url_sz
, 1);
2367 strcpy(http
->uri
, url
);
2370 debugs(33, 5, "parseHttpRequest: Complete request received");
2372 // XXX: crop this dump at the end of headers. No need for extras
2373 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2374 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2376 result
->flags
.parsed_ok
= 1;
2382 ConnStateData::In::maybeMakeSpaceAvailable()
2384 if (buf
.spaceSize() < 2) {
2385 const SBuf::size_type haveCapacity
= buf
.length() + buf
.spaceSize();
2386 if (haveCapacity
>= Config
.maxRequestBufferSize
) {
2387 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2390 const SBuf::size_type wantCapacity
= min(static_cast<SBuf::size_type
>(Config
.maxRequestBufferSize
), haveCapacity
*2);
2391 buf
.reserveCapacity(wantCapacity
);
2392 debugs(33, 2, "growing request buffer: available=" << buf
.spaceSize() << " used=" << buf
.length());
2394 return (buf
.spaceSize() >= 2);
2398 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2400 ClientSocketContext::Pointer
*S
;
2402 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2410 ConnStateData::getConcurrentRequestCount() const
2413 ClientSocketContext::Pointer
*T
;
2415 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2416 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2421 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2423 if (flag
!= COMM_OK
) {
2424 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2429 if (!ignoreErrno(xerrno
)) {
2430 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2432 } else if (in
.buf
.isEmpty()) {
2433 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2441 ConnStateData::connFinishedWithConn(int size
)
2444 if (getConcurrentRequestCount() == 0 && in
.buf
.isEmpty()) {
2445 /* no current or pending requests */
2446 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2448 } else if (!Config
.onoff
.half_closed_clients
) {
2449 /* admin doesn't want to support half-closed client sockets */
2450 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2451 notifyAllContexts(0); // no specific error implies abort
2460 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2462 assert(byteCount
> 0 && byteCount
<= conn
->in
.buf
.length());
2463 conn
->in
.buf
.consume(byteCount
);
2464 debugs(33, 5, "conn->in.buf has " << conn
->in
.buf
.length() << " bytes unused.");
2467 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2469 ConnStateData::checkHeaderLimits()
2471 if (in
.buf
.length() < Config
.maxRequestHeaderSize
)
2472 return; // can accumulte more header data
2474 debugs(33, 3, "Request header is too large (" << in
.buf
.length() << " > " <<
2475 Config
.maxRequestHeaderSize
<< " bytes)");
2477 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2478 clientStreamNode
*node
= context
->getClientReplyContext();
2479 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2480 assert (repContext
);
2481 repContext
->setReplyToError(ERR_TOO_BIG
,
2482 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2483 clientConnection
->remote
, NULL
, NULL
, NULL
);
2484 context
->registerWithConn();
2485 context
->pullData();
2489 ConnStateData::clientAfterReadingRequests()
2491 // Were we expecting to read more request body from half-closed connection?
2492 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2493 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2494 clientConnection
->close();
2503 ConnStateData::quitAfterError(HttpRequest
*request
)
2505 // From HTTP p.o.v., we do not have to close after every error detected
2506 // at the client-side, but many such errors do require closure and the
2507 // client-side code is bad at handling errors so we play it safe.
2509 request
->flags
.proxyKeepalive
= false;
2510 flags
.readMore
= false;
2511 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2515 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2517 ClientHttpRequest
*http
= context
->http
;
2522 assert(sslServerBump
->entry
);
2523 // Did we create an error entry while processing CONNECT?
2524 if (!sslServerBump
->entry
->isEmpty()) {
2525 quitAfterError(http
->request
);
2527 // Get the saved error entry and send it to the client by replacing the
2528 // ClientHttpRequest store entry with it.
2529 clientStreamNode
*node
= context
->getClientReplyContext();
2530 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2532 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2533 repContext
->setReplyToStoreEntry(sslServerBump
->entry
, "delayed SslBump error");
2535 // save the original request for logging purposes
2536 if (!context
->http
->al
->request
) {
2537 context
->http
->al
->request
= http
->request
;
2538 HTTPMSGLOCK(context
->http
->al
->request
);
2541 // Get error details from the fake certificate-peeking request.
2542 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2543 context
->pullData();
2547 // In bump-server-first mode, we have not necessarily seen the intended
2548 // server name at certificate-peeking time. Check for domain mismatch now,
2549 // when we can extract the intended name from the bumped HTTP request.
2550 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2551 HttpRequest
*request
= http
->request
;
2552 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2553 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2554 "does not match domainname " << request
->GetHost());
2556 bool allowDomainMismatch
= false;
2557 if (Config
.ssl_client
.cert_error
) {
2558 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2559 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2560 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2561 delete check
.sslErrors
;
2562 check
.sslErrors
= NULL
;
2565 if (!allowDomainMismatch
) {
2566 quitAfterError(request
);
2568 clientStreamNode
*node
= context
->getClientReplyContext();
2569 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2570 assert (repContext
);
2572 // Fill the server IP and hostname for error page generation.
2573 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2574 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2576 // Create an error object and fill it
2577 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2578 err
->src_addr
= clientConnection
->remote
;
2579 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2580 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2582 err
->detail
= errDetail
;
2583 // Save the original request for logging purposes.
2584 if (!context
->http
->al
->request
) {
2585 context
->http
->al
->request
= request
;
2586 HTTPMSGLOCK(context
->http
->al
->request
);
2588 repContext
->setReplyToError(request
->method
, err
);
2589 assert(context
->http
->out
.offset
== 0);
2590 context
->pullData();
2598 #endif // USE_OPENSSL
2601 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2603 ClientHttpRequest
*http
= context
->http
;
2604 HttpRequest::Pointer request
;
2605 bool notedUseOfBuffer
= false;
2606 bool chunked
= false;
2607 bool mustReplyToOptions
= false;
2608 bool unsupportedTe
= false;
2609 bool expectBody
= false;
2611 /* We have an initial client stream in place should it be needed */
2612 /* setup our private context */
2613 context
->registerWithConn();
2615 if (context
->flags
.parsed_ok
== 0) {
2616 clientStreamNode
*node
= context
->getClientReplyContext();
2617 debugs(33, 2, "clientProcessRequest: Invalid Request");
2618 conn
->quitAfterError(NULL
);
2619 // setLogUri should called before repContext->setReplyToError
2620 setLogUri(http
, http
->uri
, true);
2621 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2622 assert (repContext
);
2623 switch (hp
->request_parse_status
) {
2624 case Http::scHeaderTooLarge
:
2625 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
.c_str(), NULL
);
2627 case Http::scMethodNotAllowed
:
2628 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2629 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
.c_str(), NULL
);
2632 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2633 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
.c_str(), NULL
);
2635 assert(context
->http
->out
.offset
== 0);
2636 context
->pullData();
2640 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2641 clientStreamNode
*node
= context
->getClientReplyContext();
2642 debugs(33, 5, "Invalid URL: " << http
->uri
);
2643 conn
->quitAfterError(request
.getRaw());
2644 // setLogUri should called before repContext->setReplyToError
2645 setLogUri(http
, http
->uri
, true);
2646 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2647 assert (repContext
);
2648 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2649 assert(context
->http
->out
.offset
== 0);
2650 context
->pullData();
2654 /* RFC 2616 section 10.5.6 : handle unsupported HTTP major versions cleanly. */
2655 /* We currently only support 0.9, 1.0, 1.1 properly */
2656 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2657 (http_ver
.major
> 1) ) {
2659 clientStreamNode
*node
= context
->getClientReplyContext();
2660 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2661 conn
->quitAfterError(request
.getRaw());
2662 // setLogUri should called before repContext->setReplyToError
2663 setLogUri(http
, http
->uri
, true);
2664 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2665 assert (repContext
);
2666 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2667 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2668 assert(context
->http
->out
.offset
== 0);
2669 context
->pullData();
2673 /* compile headers */
2674 /* we should skip request line! */
2675 /* XXX should actually know the damned buffer size here */
2676 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2677 clientStreamNode
*node
= context
->getClientReplyContext();
2678 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2679 conn
->quitAfterError(request
.getRaw());
2680 // setLogUri should called before repContext->setReplyToError
2681 setLogUri(http
, http
->uri
, true);
2682 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2683 assert (repContext
);
2684 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2685 assert(context
->http
->out
.offset
== 0);
2686 context
->pullData();
2690 request
->clientConnectionManager
= conn
;
2692 request
->flags
.accelerated
= http
->flags
.accel
;
2693 request
->flags
.sslBumped
=conn
->switchedToHttps();
2694 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2695 // TODO: decouple http->flags.accel from request->flags.sslBumped
2696 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2697 !conn
->port
->allow_direct
: 0;
2699 if (request
->flags
.sslBumped
) {
2700 if (conn
->getAuth() != NULL
)
2701 request
->auth_user_request
= conn
->getAuth();
2706 * If transparent or interception mode is working clone the transparent and interception flags
2707 * from the port settings to the request.
2709 if (http
->clientConnection
!= NULL
) {
2710 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2711 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2712 if (request
->flags
.interceptTproxy
) {
2713 if (Config
.accessList
.spoof_client_ip
) {
2714 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2715 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2718 request
->flags
.spoofClientIp
= true;
2720 request
->flags
.spoofClientIp
= false;
2723 if (internalCheck(request
->urlpath
.termedBuf())) {
2724 if (internalHostnameIs(request
->GetHost()) && request
->port
== getMyPort()) {
2725 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2726 ':' << request
->port
);
2727 http
->flags
.internal
= true;
2728 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2729 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2730 ':' << request
->port
<< " (global_internal_static on)");
2731 request
->SetHost(internalHostname());
2732 request
->port
= getMyPort();
2733 http
->flags
.internal
= true;
2735 debugs(33, 2, "internal URL found: " << request
->url
.getScheme() << "://" << request
->GetHost() <<
2736 ':' << request
->port
<< " (not this proxy)");
2739 if (http
->flags
.internal
)
2740 request
->login
[0] = '\0';
2742 request
->flags
.internal
= http
->flags
.internal
;
2743 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2744 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2745 #if FOLLOW_X_FORWARDED_FOR
2746 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2747 // not a details about teh TCP connection itself
2748 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2749 #endif /* FOLLOW_X_FORWARDED_FOR */
2750 request
->my_addr
= conn
->clientConnection
->local
;
2751 request
->myportname
= conn
->port
->name
;
2752 request
->http_ver
= http_ver
;
2754 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2755 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2756 request
->clientConnectionManager
= conn
;
2758 if (request
->header
.chunked()) {
2760 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2761 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2762 // HTTP/1.1 requires chunking to be the last encoding if there is one
2763 unsupportedTe
= te
.size() && te
!= "identity";
2764 } // else implied identity coding
2766 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2767 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2768 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2769 clientStreamNode
*node
= context
->getClientReplyContext();
2770 conn
->quitAfterError(request
.getRaw());
2771 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2772 assert (repContext
);
2773 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2774 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2775 assert(context
->http
->out
.offset
== 0);
2776 context
->pullData();
2780 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2781 clientStreamNode
*node
= context
->getClientReplyContext();
2782 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2783 assert (repContext
);
2784 conn
->quitAfterError(request
.getRaw());
2785 repContext
->setReplyToError(ERR_INVALID_REQ
,
2786 Http::scLengthRequired
, request
->method
, NULL
,
2787 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2788 assert(context
->http
->out
.offset
== 0);
2789 context
->pullData();
2793 if (request
->header
.has(HDR_EXPECT
)) {
2794 const String expect
= request
->header
.getList(HDR_EXPECT
);
2795 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2796 if (!supportedExpect
) {
2797 clientStreamNode
*node
= context
->getClientReplyContext();
2798 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2799 assert (repContext
);
2800 conn
->quitAfterError(request
.getRaw());
2801 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2802 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2803 assert(context
->http
->out
.offset
== 0);
2804 context
->pullData();
2809 http
->request
= request
.getRaw();
2810 HTTPMSGLOCK(http
->request
);
2811 clientSetKeepaliveFlag(http
);
2813 // Let tunneling code be fully responsible for CONNECT requests
2814 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2815 context
->mayUseConnection(true);
2816 conn
->flags
.readMore
= false;
2818 // consume header early so that tunnel gets just the body
2819 connNoteUseOfBuffer(conn
, http
->req_sz
);
2820 notedUseOfBuffer
= true;
2824 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2828 /* Do we expect a request-body? */
2829 expectBody
= chunked
|| request
->content_length
> 0;
2830 if (!context
->mayUseConnection() && expectBody
) {
2831 request
->body_pipe
= conn
->expectRequestBody(
2832 chunked
? -1 : request
->content_length
);
2834 // consume header early so that body pipe gets just the body
2835 connNoteUseOfBuffer(conn
, http
->req_sz
);
2836 notedUseOfBuffer
= true;
2838 /* Is it too large? */
2839 if (!chunked
&& // if chunked, we will check as we accumulate
2840 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2841 clientStreamNode
*node
= context
->getClientReplyContext();
2842 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2843 assert (repContext
);
2844 conn
->quitAfterError(request
.getRaw());
2845 repContext
->setReplyToError(ERR_TOO_BIG
,
2846 Http::scPayloadTooLarge
, Http::METHOD_NONE
, NULL
,
2847 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2848 assert(context
->http
->out
.offset
== 0);
2849 context
->pullData();
2853 // We may stop producing, comm_close, and/or call setReplyToError()
2854 // below, so quit on errors to avoid http->doCallouts()
2855 if (!conn
->handleRequestBodyData())
2858 if (!request
->body_pipe
->productionEnded()) {
2859 debugs(33, 5, HERE
<< "need more request body");
2860 context
->mayUseConnection(true);
2861 assert(conn
->flags
.readMore
);
2865 http
->calloutContext
= new ClientRequestContext(http
);
2870 if (!notedUseOfBuffer
)
2871 connNoteUseOfBuffer(conn
, http
->req_sz
);
2875 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2876 * to here because calling comm_reset_close() causes http to
2877 * be freed and the above connNoteUseOfBuffer() would hit an
2878 * assertion, not to mention that we were accessing freed memory.
2880 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2881 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2882 conn
->flags
.readMore
= false;
2883 comm_reset_close(conn
->clientConnection
);
2888 connStripBufferWhitespace (ConnStateData
* conn
)
2890 // XXX: kill this whole function.
2891 while (!conn
->in
.buf
.isEmpty() && xisspace(conn
->in
.buf
.at(0))) {
2892 conn
->in
.buf
.consume(1);
2897 * Limit the number of concurrent requests.
2898 * \return true when there are available position(s) in the pipeline queue for another request.
2899 * \return false when the pipeline queue is full or disabled.
2902 ConnStateData::concurrentRequestQueueFilled() const
2904 const int existingRequestCount
= getConcurrentRequestCount();
2906 // default to the configured pipeline size.
2907 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
2908 const int concurrentRequestLimit
= Config
.pipeline_max_prefetch
+ 1;
2910 // when queue filled already we cant add more.
2911 if (existingRequestCount
>= concurrentRequestLimit
) {
2912 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
2913 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
2921 * Attempt to parse one or more requests from the input buffer.
2922 * If a request is successfully parsed, even if the next request
2923 * is only partially parsed, it will return TRUE.
2926 ConnStateData::clientParseRequests()
2928 HttpRequestMethod method
;
2929 bool parsed_req
= false;
2931 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2933 // Loop while we have read bytes that are not needed for producing the body
2934 // On errors, bodyPipe may become nil, but readMore will be cleared
2935 while (!in
.buf
.isEmpty() && !bodyPipe
&& flags
.readMore
) {
2936 connStripBufferWhitespace(this);
2938 /* Don't try to parse if the buffer is empty */
2939 if (in
.buf
.isEmpty())
2942 /* Limit the number of concurrent requests */
2943 if (concurrentRequestQueueFilled())
2946 /* Begin the parsing */
2947 PROF_start(parseHttpRequest
);
2948 HttpParserInit(&parser_
, in
.buf
.c_str(), in
.buf
.length());
2950 /* Process request */
2951 Http::ProtocolVersion http_ver
;
2952 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2953 PROF_stop(parseHttpRequest
);
2955 /* partial or incomplete request */
2957 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2958 // (which becomes context) but checkHeaderLimits cannot?
2959 checkHeaderLimits();
2963 /* status -1 or 1 */
2965 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2966 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2967 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2968 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2970 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2972 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2974 if (context
->mayUseConnection()) {
2975 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2981 /* XXX where to 'finish' the parsing pass? */
2986 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
2988 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
2992 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2994 if (io
.flag
== COMM_ERR_CLOSING
) {
2995 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
2999 assert(Comm::IsConnOpen(clientConnection
));
3000 assert(io
.conn
->fd
== clientConnection
->fd
);
3003 * Don't reset the timeout value here. The timeout value will be
3004 * set to Config.Timeout.request by httpAccept() and
3005 * clientWriteComplete(), and should apply to the request as a
3006 * whole, not individual read() calls. Plus, it breaks our
3007 * lame half-close detection
3009 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3010 notifyAllContexts(io
.xerrno
);
3015 if (io
.flag
== COMM_OK
) {
3017 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3019 // may comm_close or setReplyToError
3020 if (!handleReadData(io
.buf2
))
3023 } else if (io
.size
== 0) {
3024 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3026 if (connFinishedWithConn(io
.size
)) {
3027 clientConnection
->close();
3031 /* It might be half-closed, we can't tell */
3032 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3034 commMarkHalfClosed(io
.conn
->fd
);
3036 fd_note(io
.conn
->fd
, "half-closed");
3038 /* There is one more close check at the end, to detect aborted
3039 * (partial) requests. At this point we can't tell if the request
3042 /* Continue to process previously read data */
3046 /* Process next request */
3047 if (getConcurrentRequestCount() == 0)
3048 fd_note(io
.fd
, "Reading next request");
3050 if (!clientParseRequests()) {
3054 * If the client here is half closed and we failed
3055 * to parse a request, close the connection.
3056 * The above check with connFinishedWithConn() only
3057 * succeeds _if_ the buffer is empty which it won't
3058 * be if we have an incomplete request.
3059 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3061 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3062 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3063 clientConnection
->close();
3071 clientAfterReadingRequests();
3075 * called when new request data has been read from the socket
3077 * \retval false called comm_close or setReplyToError (the caller should bail)
3078 * \retval true we did not call comm_close or setReplyToError
3081 ConnStateData::handleReadData(SBuf
*buf
)
3083 assert(buf
== &in
.buf
); // XXX: make this abort the transaction if this fails
3085 // if we are reading a body, stuff data into the body pipe
3086 if (bodyPipe
!= NULL
)
3087 return handleRequestBodyData();
3092 * called when new request body data has been buffered in in.buf
3093 * may close the connection if we were closing and piped everything out
3095 * \retval false called comm_close or setReplyToError (the caller should bail)
3096 * \retval true we did not call comm_close or setReplyToError
3099 ConnStateData::handleRequestBodyData()
3101 assert(bodyPipe
!= NULL
);
3105 if (in
.bodyParser
) { // chunked encoding
3106 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3107 abortChunkedRequestBody(error
);
3110 } else { // identity encoding
3111 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3112 putSize
= bodyPipe
->putMoreData(in
.buf
.c_str(), in
.buf
.length());
3113 if (!bodyPipe
->mayNeedMoreData()) {
3114 // BodyPipe will clear us automagically when we produced everything
3120 connNoteUseOfBuffer(this, putSize
);
3123 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3125 if (const char *reason
= stoppedSending()) {
3126 /* we've finished reading like good clients,
3127 * now do the close that initiateClose initiated.
3129 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3130 clientConnection
->close();
3138 /// parses available chunked encoded body bytes, checks size, returns errors
3140 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3142 debugs(33, 7, "chunked from " << clientConnection
<< ": " << in
.buf
.length());
3144 try { // the parser will throw on errors
3146 if (in
.buf
.isEmpty()) // nothing to do
3149 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3150 // add one because MemBuf will assert if it cannot 0-terminate
3151 raw
.init(in
.buf
.length(), in
.buf
.length()+1);
3152 raw
.append(in
.buf
.c_str(), in
.buf
.length());
3154 const mb_size_t wasContentSize
= raw
.contentSize();
3155 BodyPipeCheckout
bpc(*bodyPipe
);
3156 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3158 putSize
= wasContentSize
- raw
.contentSize();
3160 // dechunk then check: the size limit applies to _dechunked_ content
3161 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3165 finishDechunkingRequest(true);
3167 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3170 // if chunk parser needs data, then the body pipe must need it too
3171 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3173 // if parser needs more space and we can consume nothing, we will stall
3174 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3175 } catch (...) { // TODO: be more specific
3176 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3177 return ERR_INVALID_REQ
;
3180 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3184 /// quit on errors related to chunked request body handling
3186 ConnStateData::abortChunkedRequestBody(const err_type error
)
3188 finishDechunkingRequest(false);
3190 // XXX: The code below works if we fail during initial request parsing,
3191 // but if we fail when the server-side works already, the server may send
3192 // us its response too, causing various assertions. How to prevent that?
3193 #if WE_KNOW_HOW_TO_SEND_ERRORS
3194 ClientSocketContext::Pointer context
= getCurrentContext();
3195 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3196 clientStreamNode
*node
= context
->getClientReplyContext();
3197 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3199 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3200 Http::scPayloadTooLarge
: HTTP_BAD_REQUEST
;
3201 repContext
->setReplyToError(error
, scode
,
3202 repContext
->http
->request
->method
,
3203 repContext
->http
->uri
,
3205 repContext
->http
->request
,
3207 context
->pullData();
3209 // close or otherwise we may get stuck as nobody will notice the error?
3210 comm_reset_close(clientConnection
);
3213 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3214 comm_reset_close(clientConnection
);
3216 flags
.readMore
= false;
3220 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3222 if (!handleRequestBodyData())
3225 // too late to read more body
3226 if (!isOpen() || stoppedReceiving())
3233 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3235 // request reader may get stuck waiting for space if nobody consumes body
3236 if (bodyPipe
!= NULL
)
3237 bodyPipe
->enableAutoConsumption();
3239 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3242 /** general lifetime handler for HTTP requests */
3244 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3247 * Just close the connection to not confuse browsers
3248 * using persistent connections. Some browsers open
3249 * a connection and then do not use it until much
3250 * later (presumeably because the request triggering
3251 * the open has already been completed on another
3254 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3259 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3261 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3262 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3263 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3264 http
->al
->http
.timedout
= true;
3265 if (Comm::IsConnOpen(io
.conn
))
3269 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
) :
3270 AsyncJob("ConnStateData"),
3272 sslBumpMode(Ssl::bumpEnd
),
3273 switchedToHttps_(false),
3274 sslServerBump(NULL
),
3276 stoppedSending_(NULL
),
3277 stoppedReceiving_(NULL
)
3279 pinning
.host
= NULL
;
3281 pinning
.pinned
= false;
3282 pinning
.auth
= false;
3283 pinning
.zeroReply
= false;
3284 pinning
.peer
= NULL
;
3286 // store the details required for creating more MasterXaction objects as new requests come in
3287 clientConnection
= xact
->tcpClient
;
3288 port
= cbdataReference(xact
->squidPort
.get());
3289 log_addr
= xact
->tcpClient
->remote
;
3290 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3292 in
.buf
.reserveCapacity(CLIENT_REQ_BUF_SZ
);
3294 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3295 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3296 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3297 int i
= IP_PMTUDISC_DONT
;
3298 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3299 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3301 static bool reported
= false;
3304 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3310 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3311 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3312 comm_add_close_handler(clientConnection
->fd
, call
);
3314 if (Config
.onoff
.log_fqdn
)
3315 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3318 if (Ident::TheConfig
.identLookup
) {
3319 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3320 identChecklist
.src_addr
= xact
->tcpClient
->remote
;
3321 identChecklist
.my_addr
= xact
->tcpClient
->local
;
3322 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3323 Ident::Start(xact
->tcpClient
, clientIdentDone
, this);
3327 clientdbEstablished(clientConnection
->remote
, 1);
3329 flags
.readMore
= true;
3332 /** Handle a new connection on HTTP socket. */
3334 httpAccept(const CommAcceptCbParams
¶ms
)
3336 MasterXaction::Pointer xact
= params
.xaction
;
3337 AnyP::PortCfgPointer s
= xact
->squidPort
;
3340 // it is possible the call or accept() was still queued when the port was reconfigured
3341 debugs(33, 2, "HTTP accept failure: port reconfigured.");
3345 if (params
.flag
!= COMM_OK
) {
3346 // Its possible the call was still queued when the client disconnected
3347 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3351 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3352 fd_note(params
.conn
->fd
, "client http connect");
3354 if (s
->tcp_keepalive
.enabled
) {
3355 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3358 ++ incoming_sockets_accepted
;
3360 // Socket is ready, setup the connection manager to start using it
3361 ConnStateData
*connState
= new ConnStateData(xact
);
3363 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3364 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3365 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3366 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3368 connState
->readSomeData();
3371 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3373 if (Config
.onoff
.client_db
) {
3374 /* it was said several times that client write limiter does not work if client_db is disabled */
3376 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3377 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3379 // TODO: we check early to limit error response bandwith but we
3380 // should recheck when we can honor delay_pool_uses_indirect
3381 // TODO: we should also pass the port details for myportname here.
3382 ch
.src_addr
= params
.conn
->remote
;
3383 ch
.my_addr
= params
.conn
->local
;
3385 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3387 /* pools require explicit 'allow' to assign a client into them */
3388 if (pools
[pool
].access
) {
3389 ch
.accessList
= pools
[pool
].access
;
3390 allow_t answer
= ch
.fastCheck();
3391 if (answer
== ACCESS_ALLOWED
) {
3393 /* request client information from db after we did all checks
3394 this will save hash lookup if client failed checks */
3395 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3398 /* put client info in FDE */
3399 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3401 /* setup write limiter for this request */
3402 const double burst
= floor(0.5 +
3403 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3404 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3407 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3417 /** Create SSL connection structure and update fd_table */
3419 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3421 if (SSL
*ssl
= Ssl::CreateServer(sslContext
, conn
->fd
, "client https start")) {
3422 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3431 Squid_SSL_accept(ConnStateData
*conn
, PF
*callback
)
3433 int fd
= conn
->clientConnection
->fd
;
3434 SSL
*ssl
= fd_table
[fd
].ssl
;
3437 if ((ret
= SSL_accept(ssl
)) <= 0) {
3438 int ssl_error
= SSL_get_error(ssl
, ret
);
3440 switch (ssl_error
) {
3442 case SSL_ERROR_WANT_READ
:
3443 Comm::SetSelect(fd
, COMM_SELECT_READ
, callback
, conn
, 0);
3446 case SSL_ERROR_WANT_WRITE
:
3447 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, callback
, conn
, 0);
3450 case SSL_ERROR_SYSCALL
:
3453 debugs(83, 2, "Error negotiating SSL connection on FD " << fd
<< ": Aborted by client: " << ssl_error
);
3459 if (errno
== ECONNRESET
)
3462 debugs(83, hard
? 1 : 2, "Error negotiating SSL connection on FD " <<
3463 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3470 case SSL_ERROR_ZERO_RETURN
:
3471 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3476 debugs(83, DBG_IMPORTANT
, "Error negotiating SSL connection on FD " <<
3477 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3478 " (" << ssl_error
<< "/" << ret
<< ")");
3488 /** negotiate an SSL connection */
3490 clientNegotiateSSL(int fd
, void *data
)
3492 ConnStateData
*conn
= (ConnStateData
*)data
;
3494 SSL
*ssl
= fd_table
[fd
].ssl
;
3496 if (!Squid_SSL_accept(conn
, clientNegotiateSSL
))
3499 if (SSL_session_reused(ssl
)) {
3500 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3501 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3503 if (do_debug(83, 4)) {
3504 /* Write out the SSL session details.. actually the call below, but
3505 * OpenSSL headers do strange typecasts confusing GCC.. */
3506 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3507 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3508 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
);
3510 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3512 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3513 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3514 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3515 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3516 * Because there are two possible usable cast, if you get an error here, try the other
3517 * commented line. */
3519 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3520 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3524 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3527 /* Note: This does not automatically fflush the log file.. */
3530 debugs(83, 2, "clientNegotiateSSL: New session " <<
3531 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3532 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3536 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3537 SSL_get_cipher(ssl
));
3539 client_cert
= SSL_get_peer_certificate(ssl
);
3541 if (client_cert
!= NULL
) {
3542 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3543 " client certificate: subject: " <<
3544 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3546 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3547 " client certificate: issuer: " <<
3548 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3550 X509_free(client_cert
);
3552 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3553 " has no certificate.");
3556 conn
->readSomeData();
3560 * If SSL_CTX is given, starts reading the SSL handshake.
3561 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3564 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3568 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3570 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3573 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3574 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3575 connState
, ConnStateData::requestTimeout
);
3576 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3579 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3581 char buf
[MAX_IPSTRLEN
];
3582 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3583 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3584 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3585 fakeRequest
->port
= details
->local
.port();
3586 fakeRequest
->clientConnectionManager
= connState
;
3587 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3588 #if FOLLOW_X_FORWARDED_FOR
3589 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3591 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3592 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3593 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3594 fakeRequest
->myportname
= connState
->port
->name
;
3595 if (fakeRequest
->flags
.interceptTproxy
) {
3596 if (Config
.accessList
.spoof_client_ip
) {
3597 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3598 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3600 fakeRequest
->flags
.spoofClientIp
= true;
3602 fakeRequest
->flags
.spoofClientIp
= false;
3603 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3604 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3609 * A callback function to use with the ACLFilledChecklist callback.
3610 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3611 * else reverts the connection to tunnel mode.
3614 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3616 ConnStateData
*connState
= (ConnStateData
*) data
;
3618 // if the connection is closed or closing, just return.
3619 if (!connState
->isOpen())
3622 // Require both a match and a positive bump mode to work around exceptional
3623 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3624 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3625 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3626 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3627 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3629 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3630 connState
->sslBumpMode
= Ssl::bumpNone
;
3632 // fake a CONNECT request to force connState to tunnel
3633 static char ip
[MAX_IPSTRLEN
];
3634 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3636 reqStr
.append("CONNECT ").append(ip
).append(" HTTP/1.1\r\nHost: ").append(ip
).append("\r\n\r\n");
3637 bool ret
= connState
->handleReadData(&reqStr
);
3639 ret
= connState
->clientParseRequests();
3642 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3643 connState
->clientConnection
->close();
3648 /** handle a new HTTPS connection */
3650 httpsAccept(const CommAcceptCbParams
¶ms
)
3652 MasterXaction::Pointer xact
= params
.xaction
;
3653 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3656 // it is possible the call or accept() was still queued when the port was reconfigured
3657 debugs(33, 2, "HTTPS accept failure: port reconfigured.");
3661 if (params
.flag
!= COMM_OK
) {
3662 // Its possible the call was still queued when the client disconnected
3663 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3667 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3668 fd_note(params
.conn
->fd
, "client https connect");
3670 if (s
->tcp_keepalive
.enabled
) {
3671 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3674 ++incoming_sockets_accepted
;
3676 // Socket is ready, setup the connection manager to start using it
3677 ConnStateData
*connState
= new ConnStateData(xact
);
3679 if (s
->flags
.tunnelSslBumping
) {
3680 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3682 if (!Config
.accessList
.ssl_bump
) {
3683 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3687 // Create a fake HTTP request for ssl_bump ACL check,
3688 // using tproxy/intercept provided destination IP and port.
3689 HttpRequest
*request
= new HttpRequest();
3690 static char ip
[MAX_IPSTRLEN
];
3691 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3692 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3693 request
->port
= params
.conn
->local
.port();
3694 request
->myportname
= s
->name
;
3696 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3697 acl_checklist
->src_addr
= params
.conn
->remote
;
3698 acl_checklist
->my_addr
= s
->s
;
3699 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3702 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3703 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3708 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3710 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3711 state_data
->sslCrtdHandleReply(reply
);
3715 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3717 if (reply
.result
== HelperReply::BrokenHelper
) {
3718 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3719 } else if (!reply
.other().hasContent()) {
3720 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3722 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3723 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3724 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3726 if (reply
.result
!= HelperReply::Okay
) {
3727 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3729 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3730 if (sslServerBump
&& sslServerBump
->mode
== Ssl::bumpPeekAndSplice
) {
3731 doPeekAndSpliceStep();
3732 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
3733 bool ret
= Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl
, reply_message
.getBody().c_str(), *port
);
3735 debugs(33, 5, HERE
<< "Failed to set certificates to ssl object for PeekAndSplice mode");
3737 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3738 getSslContextDone(ctx
, true);
3744 getSslContextDone(NULL
);
3747 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3749 certProperties
.commonName
= sslCommonName
.size() > 0 ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3751 // fake certificate adaptation requires bump-server-first mode
3752 if (!sslServerBump
) {
3753 assert(port
->signingCert
.get());
3754 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3755 if (port
->signPkey
.get())
3756 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3757 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3761 // In case of an error while connecting to the secure server, use a fake
3762 // trusted certificate, with no mimicked fields and no adaptation
3763 // algorithms. There is nothing we can mimic so we want to minimize the
3764 // number of warnings the user will have to see to get to the error page.
3765 assert(sslServerBump
->entry
);
3766 if (sslServerBump
->entry
->isEmpty()) {
3767 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3768 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3770 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
3771 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3772 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3774 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3775 // If the algorithm already set, then ignore it.
3776 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3777 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3778 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3781 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3782 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3783 const char *param
= ca
->param
;
3785 // For parameterless CN adaptation, use hostname from the
3787 if (ca
->alg
== Ssl::algSetCommonName
) {
3789 param
= sslConnectHostOrIp
.termedBuf();
3790 certProperties
.commonName
= param
;
3791 certProperties
.setCommonName
= true;
3792 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3793 certProperties
.setValidAfter
= true;
3794 else if (ca
->alg
== Ssl::algSetValidBefore
)
3795 certProperties
.setValidBefore
= true;
3797 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3798 alg
<< " param: " << (param
? param
: "-"));
3802 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3803 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3804 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3805 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3809 } else {// if (!sslServerBump->entry->isEmpty())
3810 // Use trusted certificate for a Squid-generated error
3811 // or the user would have to add a security exception
3812 // just to see the error page. We will close the connection
3813 // so that the trust is not extended to non-Squid content.
3814 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3817 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3819 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3820 assert(port
->untrustedSigningCert
.get());
3821 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3822 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3824 assert(port
->signingCert
.get());
3825 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3827 if (port
->signPkey
.get())
3828 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3830 signAlgorithm
= certProperties
.signAlgorithm
;
3834 ConnStateData::getSslContextStart()
3836 assert(areAllContextsForThisConnection());
3838 /* careful: freeAllContexts() above frees request, host, etc. */
3840 if (port
->generateHostCertificates
) {
3841 Ssl::CertificateProperties certProperties
;
3842 buildSslCertGenerationParams(certProperties
);
3843 sslBumpCertKey
= certProperties
.dbKey().c_str();
3844 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3846 // Disable caching for bumpPeekAndSplice mode
3847 if (!(sslServerBump
&& sslServerBump
->mode
== Ssl::bumpPeekAndSplice
)) {
3848 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3849 Ssl::LocalContextStorage
* ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3850 SSL_CTX
* dynCtx
= NULL
;
3851 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
? ssl_ctx_cache
->get(sslBumpCertKey
.termedBuf()) : NULL
;
3852 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3853 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3854 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3855 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3856 getSslContextDone(dynCtx
);
3859 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3861 ssl_ctx_cache
->del(sslBumpCertKey
.termedBuf());
3864 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3870 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3871 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3872 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3873 request_message
.composeRequest(certProperties
);
3874 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3875 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3877 } catch (const std::exception
&e
) {
3878 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3879 "request for " << certProperties
.commonName
<<
3880 " certificate: " << e
.what() << "; will now block to " <<
3881 "generate that certificate.");
3882 // fall through to do blocking in-process generation.
3884 #endif // USE_SSL_CRTD
3886 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3887 if (sslServerBump
&& sslServerBump
->mode
== Ssl::bumpPeekAndSplice
) {
3888 doPeekAndSpliceStep();
3889 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
3890 if (!Ssl::configureSSL(ssl
, certProperties
, *port
))
3891 debugs(33, 5, HERE
<< "Failed to set certificates to ssl object for PeekAndSplice mode");
3893 SSL_CTX
*dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3894 getSslContextDone(dynCtx
, true);
3898 getSslContextDone(NULL
);
3902 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3904 // Try to add generated ssl context to storage.
3905 if (port
->generateHostCertificates
&& isNew
) {
3907 if (signAlgorithm
== Ssl::algSignTrusted
) {
3908 // Add signing certificate to the certificates chain
3909 X509
*cert
= port
->signingCert
.get();
3910 if (SSL_CTX_add_extra_chain_cert(sslContext
, cert
)) {
3911 // increase the certificate lock
3912 CRYPTO_add(&(cert
->references
),1,CRYPTO_LOCK_X509
);
3914 const int ssl_error
= ERR_get_error();
3915 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error
, NULL
));
3917 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3919 //else it is self-signed or untrusted do not attrach any certificate
3921 Ssl::LocalContextStorage
*ssl_ctx_cache
= Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
);
3922 assert(sslBumpCertKey
.size() > 0 && sslBumpCertKey
[0] != '\0');
3924 if (!ssl_ctx_cache
|| !ssl_ctx_cache
->add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3925 // If it is not in storage delete after using. Else storage deleted it.
3926 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3929 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3933 // If generated ssl context = NULL, try to use static ssl context.
3935 if (!port
->staticSslContext
) {
3936 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3937 clientConnection
->close();
3940 debugs(33, 5, HERE
<< "Using static ssl context.");
3941 sslContext
= port
->staticSslContext
.get();
3945 if (!httpsCreate(clientConnection
, sslContext
))
3948 // commSetConnTimeout() was called for this request before we switched.
3950 // Disable the client read handler until CachePeer selection is complete
3951 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3952 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3953 switchedToHttps_
= true;
3957 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3959 assert(!switchedToHttps_
);
3961 sslConnectHostOrIp
= request
->GetHost();
3962 sslCommonName
= request
->GetHost();
3964 // We are going to read new request
3965 flags
.readMore
= true;
3966 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3968 // If sslServerBump is set, then we have decided to deny CONNECT
3969 // and now want to switch to SSL to send the error to the client
3970 // without even peeking at the origin server certificate.
3971 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3972 request
->flags
.sslPeek
= true;
3973 sslServerBump
= new Ssl::ServerBump(request
);
3975 // will call httpsPeeked() with certificate and connection, eventually
3976 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
3979 else if (bumpServerMode
== Ssl::bumpPeekAndSplice
) {
3980 request
->flags
.sslPeek
= true;
3981 sslServerBump
= new Ssl::ServerBump(request
, NULL
, Ssl::bumpPeekAndSplice
);
3982 startPeekAndSplice();
3986 // otherwise, use sslConnectHostOrIp
3987 getSslContextStart();
3990 /** negotiate an SSL connection */
3992 clientPeekAndSpliceSSL(int fd
, void *data
)
3994 ConnStateData
*conn
= (ConnStateData
*)data
;
3995 SSL
*ssl
= fd_table
[fd
].ssl
;
3997 debugs(83, 2, "Start peek and splice on" << fd
);
3999 if (!Squid_SSL_accept(conn
, clientPeekAndSpliceSSL
))
4000 debugs(83, 2, "SSL_accept failed.");
4002 BIO
*b
= SSL_get_rbio(ssl
);
4004 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4005 if (bio
->gotHello()) {
4006 debugs(83, 2, "I got hello. Start forwarding the request!!! ");
4007 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4008 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
4009 conn
->startPeekAndSpliceDone();
4014 void ConnStateData::startPeekAndSplice()
4016 // will call httpsPeeked() with certificate and connection, eventually
4017 SSL_CTX
*unConfiguredCTX
= Ssl::createSSLContext(port
->signingCert
, port
->signPkey
, *port
);
4018 fd_table
[clientConnection
->fd
].dynamicSslContext
= unConfiguredCTX
;
4020 if (!httpsCreate(clientConnection
, unConfiguredCTX
))
4023 // commSetConnTimeout() was called for this request before we switched.
4025 // Disable the client read handler until CachePeer selection is complete
4026 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4027 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientPeekAndSpliceSSL
, this, 0);
4028 switchedToHttps_
= true;
4030 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4031 BIO
*b
= SSL_get_rbio(ssl
);
4032 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4037 ConnStateData::startPeekAndSpliceDone()
4039 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4043 ConnStateData::doPeekAndSpliceStep()
4045 SSL
*ssl
= fd_table
[clientConnection
->fd
].ssl
;
4046 BIO
*b
= SSL_get_rbio(ssl
);
4048 Ssl::ClientBio
*bio
= static_cast<Ssl::ClientBio
*>(b
->ptr
);
4050 debugs(33, 5, HERE
<< "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl
));
4053 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, this, 0);
4054 switchedToHttps_
= true;
4058 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4060 Must(sslServerBump
!= NULL
);
4062 if (Comm::IsConnOpen(serverConnection
)) {
4063 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
4065 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
4066 assert(serverCert
.get() != NULL
);
4067 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4068 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4069 " bumped: " << *serverConnection
);
4071 pinConnection(serverConnection
, NULL
, NULL
, false);
4073 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4075 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4076 Ip::Address intendedDest
;
4077 intendedDest
= sslConnectHostOrIp
.termedBuf();
4078 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4080 // Squid serves its own error page and closes, so we want
4081 // a CN that causes no additional browser errors. Possible
4082 // only when bumping CONNECT with a user-typed address.
4083 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4084 sslCommonName
= sslConnectHostOrIp
;
4085 else if (sslServerBump
->serverCert
.get())
4086 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4088 // copy error detail from bump-server-first request to CONNECT request
4089 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4090 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4093 getSslContextStart();
4096 #endif /* USE_OPENSSL */
4098 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4100 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4102 if (!Comm::IsConnOpen(c
)) {
4103 Must(NHttpSockets
> 0); // we tried to open some
4104 --NHttpSockets
; // there will be fewer sockets than planned
4105 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4107 if (!NHttpSockets
) // we could not open any listen sockets at all
4108 fatalf("Unable to open %s",FdNote(portType
));
4115 /// find any unused HttpSockets[] slot and store fd there or return false
4117 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4120 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4121 if ((found
= HttpSockets
[i
] < 0))
4122 HttpSockets
[i
] = conn
->fd
;
4128 clientHttpConnectionsOpen(void)
4130 AnyP::PortCfg
*s
= NULL
;
4132 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4133 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4134 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4135 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4140 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4141 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4142 s
->flags
.tunnelSslBumping
= false;
4145 if (s
->flags
.tunnelSslBumping
&&
4146 !s
->staticSslContext
&&
4147 !s
->generateHostCertificates
) {
4148 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4149 s
->flags
.tunnelSslBumping
= false;
4151 if (s
->flags
.tunnelSslBumping
) {
4152 // Create ssl_ctx cache for this port.
4153 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4157 // Fill out a Comm::Connection which IPC will open as a listener for us
4158 // then pass back when active so we can start a TcpAcceptor subscription.
4159 s
->listenConn
= new Comm::Connection
;
4160 s
->listenConn
->local
= s
->s
;
4161 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4163 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4164 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4165 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4166 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4168 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4169 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4170 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4172 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4179 clientHttpsConnectionsOpen(void)
4183 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4184 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4185 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4186 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4190 if (!s
->staticSslContext
) {
4191 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4192 " due to SSL initialization failure.");
4196 // TODO: merge with similar code in clientHttpConnectionsOpen()
4197 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4198 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s
->transport
.protocol
) << "_port " << s
->s
);
4199 s
->flags
.tunnelSslBumping
= false;
4202 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4203 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4204 s
->flags
.tunnelSslBumping
= false;
4207 if (s
->flags
.tunnelSslBumping
) {
4208 // Create ssl_ctx cache for this port.
4209 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4212 // Fill out a Comm::Connection which IPC will open as a listener for us
4213 s
->listenConn
= new Comm::Connection
;
4214 s
->listenConn
->local
= s
->s
;
4215 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4216 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4218 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4219 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4220 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4221 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4223 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4224 ListeningStartedDialer(&clientListenerConnectionOpened
,
4225 s
, Ipc::fdnHttpsSocket
, sub
));
4226 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4227 HttpSockets
[NHttpSockets
] = -1;
4233 /// process clientHttpConnectionsOpen result
4235 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4237 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4241 Must(Comm::IsConnOpen(s
->listenConn
));
4243 // TCP: setup a job to handle accept() with subscribed handler
4244 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4246 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4247 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4248 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4249 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4250 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4251 << FdNote(portTypeNote
) << " connections at "
4254 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4258 clientOpenListenSockets(void)
4260 clientHttpConnectionsOpen();
4262 clientHttpsConnectionsOpen();
4265 if (NHttpSockets
< 1)
4266 fatal("No HTTP or HTTPS ports configured");
4270 clientHttpConnectionsClose(void)
4272 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4273 if (s
->listenConn
!= NULL
) {
4274 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4275 s
->listenConn
->close();
4276 s
->listenConn
= NULL
;
4281 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4282 if (s
->listenConn
!= NULL
) {
4283 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4284 s
->listenConn
->close();
4285 s
->listenConn
= NULL
;
4290 // TODO see if we can drop HttpSockets array entirely */
4291 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4292 HttpSockets
[i
] = -1;
4299 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4301 const char *vary
= request
->vary_headers
;
4302 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4303 #if X_ACCELERATOR_VARY
4306 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4309 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4311 /* Oops... something odd is going on here.. */
4312 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4313 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4314 safe_free(request
->vary_headers
);
4319 /* This is not a varying object */
4323 /* virtual "vary" object found. Calculate the vary key and
4324 * continue the search
4326 vary
= httpMakeVaryMark(request
, entry
->getReply());
4329 request
->vary_headers
= xstrdup(vary
);
4332 /* Ouch.. we cannot handle this kind of variance */
4333 /* XXX This cannot really happen, but just to be complete */
4338 vary
= httpMakeVaryMark(request
, entry
->getReply());
4341 request
->vary_headers
= xstrdup(vary
);
4345 /* Ouch.. we cannot handle this kind of variance */
4346 /* XXX This cannot really happen, but just to be complete */
4348 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4351 /* Oops.. we have already been here and still haven't
4352 * found the requested variant. Bail out
4354 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4355 entry
->mem_obj
->urlXXX() << "' '" << vary
<< "'");
4361 ACLFilledChecklist
*
4362 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4364 ConnStateData
* conn
= http
->getConn();
4365 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4366 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4369 * hack for ident ACL. It needs to get full addresses, and a place to store
4370 * the ident result on persistent connections...
4372 /* connection oriented auth also needs these two lines for it's operation. */
4376 CBDATA_CLASS_INIT(ConnStateData
);
4379 ConnStateData::transparent() const
4381 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4385 ConnStateData::reading() const
4387 return reader
!= NULL
;
4391 ConnStateData::stopReading()
4394 comm_read_cancel(clientConnection
->fd
, reader
);
4400 ConnStateData::expectRequestBody(int64_t size
)
4402 bodyPipe
= new BodyPipe(this);
4404 bodyPipe
->setBodySize(size
);
4406 startDechunkingRequest();
4411 ConnStateData::mayNeedToReadMoreBody() const
4414 return 0; // request without a body or read/produced all body bytes
4416 if (!bodyPipe
->bodySizeKnown())
4417 return -1; // probably need to read more, but we cannot be sure
4419 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4420 const int64_t haveAvailable
= static_cast<int64_t>(in
.buf
.length());
4422 if (needToProduce
<= haveAvailable
)
4423 return 0; // we have read what we need (but are waiting for pipe space)
4425 return needToProduce
- haveAvailable
;
4429 ConnStateData::stopReceiving(const char *error
)
4431 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4432 "; old sending error: " <<
4433 (stoppedSending() ? stoppedSending_
: "none"));
4435 if (const char *oldError
= stoppedReceiving()) {
4436 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4437 return; // nothing has changed as far as this connection is concerned
4440 stoppedReceiving_
= error
;
4442 if (const char *sendError
= stoppedSending()) {
4443 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4444 clientConnection
->close();
4449 ConnStateData::expectNoForwarding()
4451 if (bodyPipe
!= NULL
) {
4452 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4453 bodyPipe
->expectNoConsumption();
4457 /// initialize dechunking state
4459 ConnStateData::startDechunkingRequest()
4461 Must(bodyPipe
!= NULL
);
4462 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4463 assert(!in
.bodyParser
);
4464 in
.bodyParser
= new ChunkedCodingParser
;
4467 /// put parsed content into input buffer and clean up
4469 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4471 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4473 if (bodyPipe
!= NULL
) {
4474 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4475 BodyPipe::Pointer myPipe
= bodyPipe
;
4476 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4477 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4479 Must(myPipe
->bodySizeKnown());
4480 ClientSocketContext::Pointer context
= getCurrentContext();
4481 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4482 context
->http
->request
->setContentLength(myPipe
->bodySize());
4486 delete in
.bodyParser
;
4487 in
.bodyParser
= NULL
;
4490 ConnStateData::In::In() :
4495 ConnStateData::In::~In()
4497 delete bodyParser
; // TODO: pool
4501 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4504 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4508 ClientSocketContext::Pointer context
= getCurrentContext();
4509 if (context
!= NULL
) {
4510 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4514 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4515 clientConnection
->close();
4518 /// Our close handler called by Comm when the pinned connection is closed
4520 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4522 // FwdState might repin a failed connection sooner than this close
4523 // callback is called for the failed connection.
4524 assert(pinning
.serverConnection
== io
.conn
);
4525 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4526 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4528 if (sawZeroReply
&& clientConnection
!= NULL
) {
4529 debugs(33, 3, "Closing client connection on pinned zero reply.");
4530 clientConnection
->close();
4535 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4537 char desc
[FD_DESC_SZ
];
4539 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4540 if (pinning
.serverConnection
->fd
== pinServer
->fd
) {
4541 startPinnedConnectionMonitoring();
4546 unpinConnection(); // closes pinned connection, if any, and resets fields
4548 pinning
.serverConnection
= pinServer
;
4550 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4552 // when pinning an SSL bumped connection, the request may be NULL
4553 const char *pinnedHost
= "[unknown]";
4555 pinning
.host
= xstrdup(request
->GetHost());
4556 pinning
.port
= request
->port
;
4557 pinnedHost
= pinning
.host
;
4559 pinning
.port
= pinServer
->remote
.port();
4561 pinning
.pinned
= true;
4563 pinning
.peer
= cbdataReference(aPeer
);
4564 pinning
.auth
= auth
;
4565 char stmp
[MAX_IPSTRLEN
];
4566 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4567 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4568 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4569 clientConnection
->fd
);
4570 fd_note(pinning
.serverConnection
->fd
, desc
);
4572 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4573 pinning
.closeHandler
= JobCallback(33, 5,
4574 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4575 // remember the pinned connection so that cb does not unpin a fresher one
4576 typedef CommCloseCbParams Params
;
4577 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4578 params
.conn
= pinning
.serverConnection
;
4579 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4581 startPinnedConnectionMonitoring();
4584 /// Assign a read handler to an idle pinned connection so that we can detect connection closures.
4586 ConnStateData::startPinnedConnectionMonitoring()
4588 if (pinning
.readHandler
!= NULL
)
4589 return; // already monitoring
4591 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
4592 pinning
.readHandler
= JobCallback(33, 3,
4593 Dialer
, this, ConnStateData::clientPinnedConnectionRead
);
4594 static char unusedBuf
[8];
4595 comm_read(pinning
.serverConnection
, unusedBuf
, sizeof(unusedBuf
), pinning
.readHandler
);
4599 ConnStateData::stopPinnedConnectionMonitoring()
4601 if (pinning
.readHandler
!= NULL
) {
4602 comm_read_cancel(pinning
.serverConnection
->fd
, pinning
.readHandler
);
4603 pinning
.readHandler
= NULL
;
4607 /// Our read handler called by Comm when the server either closes an idle pinned connection or
4608 /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4610 ConnStateData::clientPinnedConnectionRead(const CommIoCbParams
&io
)
4612 pinning
.readHandler
= NULL
; // Comm unregisters handlers before calling
4614 if (io
.flag
== COMM_ERR_CLOSING
)
4615 return; // close handler will clean up
4617 // We could use getConcurrentRequestCount(), but this may be faster.
4618 const bool clientIsIdle
= !getCurrentContext();
4620 debugs(33, 3, "idle pinned " << pinning
.serverConnection
<< " read " <<
4621 io
.size
<< (clientIsIdle
? " with idle client" : ""));
4623 assert(pinning
.serverConnection
== io
.conn
);
4624 pinning
.serverConnection
->close();
4626 // If we are still sending data to the client, do not close now. When we are done sending,
4627 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4628 // However, if we are idle, then we must close to inform the idle client and minimize races.
4629 if (clientIsIdle
&& clientConnection
!= NULL
)
4630 clientConnection
->close();
4633 const Comm::ConnectionPointer
4634 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4636 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4639 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4641 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4643 else if (request
&& pinning
.port
!= request
->port
)
4645 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4647 else if (aPeer
!= pinning
.peer
)
4651 /* The pinning info is not safe, remove any pinning info */
4655 return pinning
.serverConnection
;
4659 ConnStateData::unpinConnection()
4661 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4664 cbdataReferenceDone(pinning
.peer
);
4666 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4667 if (pinning
.closeHandler
!= NULL
) {
4668 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4669 pinning
.closeHandler
= NULL
;
4671 /// also close the server side socket, we should not use it for any future requests...
4672 // TODO: do not close if called from our close handler?
4673 pinning
.serverConnection
->close();
4676 safe_free(pinning
.host
);
4678 pinning
.zeroReply
= false;
4680 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4681 * connection has gone away */