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 "ChunkedCodingParser.h"
87 #include "client_db.h"
88 #include "client_side_reply.h"
89 #include "client_side_request.h"
90 #include "client_side.h"
91 #include "ClientRequestContext.h"
92 #include "clientStream.h"
94 #include "comm/Connection.h"
95 #include "comm/Loops.h"
96 #include "comm/TcpAcceptor.h"
97 #include "comm/Write.h"
98 #include "CommCalls.h"
99 #include "errorpage.h"
100 #include "eui/Config.h"
104 #include "fqdncache.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 "SquidTime.h"
124 #include "StatCounters.h"
125 #include "StatHist.h"
127 #include "TimeOrTag.h"
132 #include "auth/UserRequest.h"
135 #include "ClientInfo.h"
138 #include "ssl/context_storage.h"
139 #include "ssl/helper.h"
140 #include "ssl/ServerBump.h"
141 #include "ssl/support.h"
142 #include "ssl/gadgets.h"
145 #include "ssl/crtd_message.h"
146 #include "ssl/certificate_db.h"
160 #define comm_close comm_lingering_close
163 /// dials clientListenerConnectionOpened call
164 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
167 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
168 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
169 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
171 virtual void print(std::ostream
&os
) const {
173 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
176 virtual bool canDial(AsyncCall
&) const { return true; }
177 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
183 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
184 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
185 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
188 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
190 /* our socket-related context */
192 CBDATA_CLASS_INIT(ClientSocketContext
);
195 ClientSocketContext::operator new (size_t byteCount
)
197 /* derived classes with different sizes must implement their own new */
198 assert (byteCount
== sizeof (ClientSocketContext
));
199 CBDATA_INIT_TYPE(ClientSocketContext
);
200 return cbdataAlloc(ClientSocketContext
);
204 ClientSocketContext::operator delete (void *address
)
206 cbdataFree (address
);
209 /* Local functions */
210 /* ClientSocketContext */
211 static ClientSocketContext
*ClientSocketContextNew(const Comm::ConnectionPointer
&clientConn
, ClientHttpRequest
*);
213 static IOCB clientWriteComplete
;
214 static IOCB clientWriteBodyComplete
;
215 static IOACB httpAccept
;
217 static IOACB httpsAccept
;
219 static CTCB clientLifetimeTimeout
;
220 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
221 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, HttpVersion
*);
223 static IDCB clientIdentDone
;
225 static CSCB clientSocketRecipient
;
226 static CSD clientSocketDetach
;
227 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
228 static int clientIsContentLengthValid(HttpRequest
* r
);
229 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
231 static void clientUpdateStatHistCounters(log_type logType
, int svc_time
);
232 static void clientUpdateStatCounters(log_type logType
);
233 static void clientUpdateHierCounters(HierarchyLogEntry
*);
234 static bool clientPingHasFinished(ping_data
const *aPing
);
235 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
237 static bool connIsUsable(ConnStateData
* conn
);
239 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
240 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
241 static void clientUpdateSocketStats(log_type logType
, size_t size
);
243 char *skipLeadingSpace(char *aString
);
244 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
246 static ConnStateData
*connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
);
249 ClientSocketContext::getTail() const
251 if (http
->client_stream
.tail
)
252 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
258 ClientSocketContext::getClientReplyContext() const
260 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
264 * This routine should be called to grow the inbuf and then
268 ConnStateData::readSomeData()
273 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
275 if (!maybeMakeSpaceAvailable())
278 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
279 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
280 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
284 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
286 ClientSocketContext::Pointer
*tempContextPointer
;
287 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
288 assert(conn
->getCurrentContext() != NULL
);
289 /* Unlink us from the connection request list */
290 tempContextPointer
= & conn
->currentobject
;
292 while (tempContextPointer
->getRaw()) {
293 if (*tempContextPointer
== this)
296 tempContextPointer
= &(*tempContextPointer
)->next
;
299 assert(tempContextPointer
->getRaw() != NULL
);
300 *tempContextPointer
= next
;
304 ClientSocketContext::~ClientSocketContext()
306 clientStreamNode
*node
= getTail();
309 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
312 /* We are *always* the tail - prevent recursive free */
313 assert(this == streamContext
);
319 deRegisterWithConn();
321 httpRequestFree(http
);
323 /* clean up connection links to us */
324 assert(this != next
.getRaw());
328 ClientSocketContext::registerWithConn()
330 assert (!connRegistered_
);
332 assert (http
->getConn() != NULL
);
333 connRegistered_
= true;
334 http
->getConn()->addContextToQueue(this);
338 ClientSocketContext::deRegisterWithConn()
340 assert (connRegistered_
);
341 removeFromConnectionList(http
->getConn());
342 connRegistered_
= false;
346 ClientSocketContext::connIsFinished()
349 assert (http
->getConn() != NULL
);
350 deRegisterWithConn();
351 /* we can't handle any more stream data - detach */
352 clientStreamDetach(getTail(), http
);
355 ClientSocketContext::ClientSocketContext() : http(NULL
), reply(NULL
), next(NULL
),
357 mayUseConnection_ (false),
358 connRegistered_ (false)
360 memset (reqbuf
, '\0', sizeof (reqbuf
));
363 deferredparams
.node
= NULL
;
364 deferredparams
.rep
= NULL
;
367 ClientSocketContext
*
368 ClientSocketContextNew(const Comm::ConnectionPointer
&client
, ClientHttpRequest
* http
)
370 ClientSocketContext
*newContext
;
371 assert(http
!= NULL
);
372 newContext
= new ClientSocketContext
;
373 newContext
->http
= http
;
374 newContext
->clientConnection
= client
;
379 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
381 HttpReply
*rep
= msg
.reply
;
384 // apply selected clientReplyContext::buildReplyHeader() mods
385 // it is not clear what headers are required for control messages
386 rep
->header
.removeHopByHopEntries();
387 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
388 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
390 // remember the callback
391 cbControlMsgSent
= msg
.cbSuccess
;
393 MemBuf
*mb
= rep
->pack();
395 debugs(11, 2, "HTTP Client " << clientConnection
);
396 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
398 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
399 CommIoCbPtrFun(&WroteControlMsg
, this));
400 Comm::Write(clientConnection
, mb
, call
);
405 /// called when we wrote the 1xx response
407 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
409 if (errflag
== COMM_ERR_CLOSING
)
412 if (errflag
== COMM_OK
) {
413 ScheduleCallHere(cbControlMsgSent
);
417 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
418 // no error notification: see HttpControlMsg.h for rationale and
419 // note that some errors are detected elsewhere (e.g., close handler)
421 // close on 1xx errors to be conservative and to simplify the code
422 // (if we do not close, we must notify the source of a failure!)
426 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
428 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
430 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
431 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
436 clientIdentDone(const char *ident
, void *data
)
438 ConnStateData
*conn
= (ConnStateData
*)data
;
439 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
444 clientUpdateStatCounters(log_type logType
)
446 ++statCounter
.client_http
.requests
;
448 if (logTypeIsATcpHit(logType
))
449 ++statCounter
.client_http
.hits
;
451 if (logType
== LOG_TCP_HIT
)
452 ++statCounter
.client_http
.disk_hits
;
453 else if (logType
== LOG_TCP_MEM_HIT
)
454 ++statCounter
.client_http
.mem_hits
;
458 clientUpdateStatHistCounters(log_type logType
, int svc_time
)
460 statCounter
.client_http
.allSvcTime
.count(svc_time
);
462 * The idea here is not to be complete, but to get service times
463 * for only well-defined types. For example, we don't include
464 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
465 * (we *tried* to validate it, but failed).
470 case LOG_TCP_REFRESH_UNMODIFIED
:
471 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
474 case LOG_TCP_IMS_HIT
:
475 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
480 case LOG_TCP_MEM_HIT
:
482 case LOG_TCP_OFFLINE_HIT
:
483 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
488 case LOG_TCP_CLIENT_REFRESH_MISS
:
489 statCounter
.client_http
.missSvcTime
.count(svc_time
);
493 /* make compiler warnings go away */
499 clientPingHasFinished(ping_data
const *aPing
)
501 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
508 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
512 switch (someEntry
->code
) {
513 #if USE_CACHE_DIGESTS
518 ++ statCounter
.cd
.times_used
;
526 case FIRST_PARENT_MISS
:
528 case CLOSEST_PARENT_MISS
:
529 ++ statCounter
.icp
.times_used
;
530 i
= &someEntry
->ping
;
532 if (clientPingHasFinished(i
))
533 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
536 ++ statCounter
.icp
.query_timeouts
;
543 ++ statCounter
.netdb
.times_used
;
553 ClientHttpRequest::updateCounters()
555 clientUpdateStatCounters(logType
);
557 if (request
->errType
!= ERR_NONE
)
558 ++ statCounter
.client_http
.errors
;
560 clientUpdateStatHistCounters(logType
,
561 tvSubMsec(start_time
, current_time
));
563 clientUpdateHierCounters(&request
->hier
);
567 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
570 assert(aLogEntry
!= NULL
);
572 if (Config
.onoff
.log_mime_hdrs
) {
576 packerToMemInit(&p
, &mb
);
577 request
->header
.packInto(&p
);
578 //This is the request after adaptation or redirection
579 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
581 // the virgin request is saved to aLogEntry->request
582 if (aLogEntry
->request
) {
585 packerToMemInit(&p
, &mb
);
586 aLogEntry
->request
->header
.packInto(&p
);
587 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
591 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
595 packerToMemInit(&p
, &mb
);
596 ah
->lastMeta
.packInto(&p
);
597 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
606 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
608 aLogEntry
->icap
.processingTime
= ih
->processingTime();
611 aLogEntry
->http
.method
= request
->method
;
612 aLogEntry
->http
.version
= request
->http_ver
;
613 aLogEntry
->hier
= request
->hier
;
614 if (request
->content_length
> 0) // negative when no body or unknown length
615 aLogEntry
->cache
.requestSize
+= request
->content_length
;
616 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
619 if (request
->auth_user_request
!= NULL
) {
620 if (request
->auth_user_request
->username())
621 aLogEntry
->cache
.authuser
= xstrdup(request
->auth_user_request
->username());
625 // Adapted request, if any, inherits and then collects all the stats, but
626 // the virgin request gets logged instead; copy the stats to log them.
627 // TODO: avoid losses by keeping these stats in a shared history object?
628 if (aLogEntry
->request
) {
629 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
630 aLogEntry
->request
->errType
= request
->errType
;
631 aLogEntry
->request
->errDetail
= request
->errDetail
;
636 ClientHttpRequest::logRequest()
638 if (!out
.size
&& !logType
)
639 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
641 al
->icp
.opcode
= ICP_INVALID
;
643 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
646 al
->http
.code
= al
->reply
->sline
.status
;
647 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
648 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
649 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status
;
650 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
653 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
655 if (loggingEntry() && loggingEntry()->mem_obj
)
656 al
->cache
.objectSize
= loggingEntry()->contentLen();
658 al
->cache
.caddr
.SetNoAddr();
660 if (getConn() != NULL
) {
661 al
->cache
.caddr
= getConn()->log_addr
;
662 al
->cache
.port
= cbdataReference(getConn()->port
);
665 al
->cache
.requestSize
= req_sz
;
666 al
->cache
.requestHeadersSize
= req_sz
;
668 al
->cache
.replySize
= out
.size
;
669 al
->cache
.replyHeadersSize
= out
.headers_sz
;
671 al
->cache
.highOffset
= out
.offset
;
673 al
->cache
.code
= logType
;
675 al
->cache
.msec
= tvSubMsec(start_time
, current_time
);
678 prepareLogWithRequestDetails(request
, al
);
680 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
681 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
685 /* This is broken. Fails if the connection has been closed. Needs
686 * to snarf the ssl details some place earlier..
688 if (getConn() != NULL
)
689 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
693 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.log
, this);
696 checklist
->reply
= HTTPMSGLOCK(al
->reply
);
698 if (!Config
.accessList
.log
|| checklist
->fastCheck() == ACCESS_ALLOWED
) {
700 al
->adapted_request
= HTTPMSGLOCK(request
);
701 accessLogLog(al
, checklist
);
704 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
705 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
712 ClientHttpRequest::freeResources()
716 safe_free(redirect
.location
);
717 range_iter
.boundary
.clean();
718 HTTPMSGUNLOCK(request
);
720 if (client_stream
.tail
)
721 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
725 httpRequestFree(void *data
)
727 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
728 assert(http
!= NULL
);
733 ConnStateData::areAllContextsForThisConnection() const
735 assert(this != NULL
);
736 ClientSocketContext::Pointer context
= getCurrentContext();
738 while (context
.getRaw()) {
739 if (context
->http
->getConn() != this)
742 context
= context
->next
;
749 ConnStateData::freeAllContexts()
751 ClientSocketContext::Pointer context
;
753 while ((context
= getCurrentContext()).getRaw() != NULL
) {
754 assert(getCurrentContext() !=
755 getCurrentContext()->next
);
756 context
->connIsFinished();
757 assert (context
!= currentobject
);
761 /// propagates abort event to all contexts
763 ConnStateData::notifyAllContexts(int xerrno
)
765 typedef ClientSocketContext::Pointer CSCP
;
766 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
767 c
->noteIoError(xerrno
);
770 /* This is a handler normally called by comm_close() */
771 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
773 deleteThis("ConnStateData::connStateClosed");
776 // cleans up before destructor is called
778 ConnStateData::swanSong()
780 debugs(33, 2, HERE
<< clientConnection
);
781 flags
.readMore
= false;
782 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
783 assert(areAllContextsForThisConnection());
786 if (auth_user_request
!= NULL
) {
787 debugs(33, 4, "ConnStateData::swanSong: freeing auth_user_request '" << auth_user_request
<< "' (this is '" << this << "')");
788 auth_user_request
->onConnectionClose(this);
792 if (Comm::IsConnOpen(pinning
.serverConnection
))
793 pinning
.serverConnection
->close();
794 pinning
.serverConnection
= NULL
;
796 if (Comm::IsConnOpen(clientConnection
))
797 clientConnection
->close();
798 clientConnection
= NULL
;
800 BodyProducer::swanSong();
801 flags
.swanSang
= true;
805 ConnStateData::isOpen() const
807 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
808 Comm::IsConnOpen(clientConnection
) &&
809 !fd_table
[clientConnection
->fd
].closing();
812 ConnStateData::~ConnStateData()
814 assert(this != NULL
);
815 debugs(33, 3, HERE
<< clientConnection
);
818 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
821 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
823 cbdataReferenceDone(port
);
825 if (bodyPipe
!= NULL
)
826 stopProducingFor(bodyPipe
, false);
829 delete sslServerBump
;
834 * clientSetKeepaliveFlag() sets request->flags.proxy_keepalive.
835 * This is the client-side persistent connection flag. We need
836 * to set this relatively early in the request processing
837 * to handle hacks for broken servers and clients.
840 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
842 HttpRequest
*request
= http
->request
;
844 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
845 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
846 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
847 RequestMethodStr(request
->method
));
849 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
850 request
->flags
.proxy_keepalive
= request
->persistent() ? 1 : 0;
854 clientIsContentLengthValid(HttpRequest
* r
)
856 switch (r
->method
.id()) {
861 /* We do not want to see a request entity on GET/HEAD requests */
862 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
865 /* For other types of requests we don't care */
873 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
875 if (Config
.maxRequestBodySize
&&
876 bodyLength
> Config
.maxRequestBodySize
)
877 return 1; /* too large */
884 connIsUsable(ConnStateData
* conn
)
886 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
894 // careful: the "current" context may be gone if we wrote an early response
895 ClientSocketContext::Pointer
896 ConnStateData::getCurrentContext() const
899 return currentobject
;
903 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
905 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
906 assert(flags
.deferred
== 0);
908 deferredparams
.node
= node
;
909 deferredparams
.rep
= rep
;
910 deferredparams
.queuedBuffer
= receivedData
;
915 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
917 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
924 ClientSocketContext::startOfOutput() const
926 return http
->out
.size
== 0;
930 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
932 /*the size of available range can always fit in a size_t type*/
933 size_t maximum
= (size_t)available
.size();
935 if (!http
->request
->range
)
938 assert (canPackMoreRanges());
940 if (http
->range_iter
.debt() == -1)
943 assert (http
->range_iter
.debt() > 0);
945 /* TODO this + the last line could be a range intersection calculation */
946 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
949 return min(http
->range_iter
.debt(), (int64_t)maximum
);
953 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
955 http
->out
.offset
+= bytes
;
957 if (!http
->request
->range
)
960 if (http
->range_iter
.debt() != -1) {
961 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
962 assert (http
->range_iter
.debt() >= 0);
965 /* debt() always stops at -1, below that is a bug */
966 assert (http
->range_iter
.debt() >= -1);
970 ClientHttpRequest::multipartRangeRequest() const
972 return request
->multipartRangeRequest();
976 ClientSocketContext::multipartRangeRequest() const
978 return http
->multipartRangeRequest();
982 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
986 if (!multipartRangeRequest() && !http
->request
->flags
.chunked_reply
) {
987 size_t length
= lengthToSend(bodyData
.range());
988 noteSentBodyBytes (length
);
989 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
990 CommIoCbPtrFun(clientWriteBodyComplete
, this));
991 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
997 if (multipartRangeRequest())
998 packRange(bodyData
, &mb
);
1000 packChunk(bodyData
, mb
);
1002 if (mb
.contentSize()) {
1004 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1005 CommIoCbPtrFun(clientWriteComplete
, this));
1006 Comm::Write(clientConnection
, &mb
, call
);
1008 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1012 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1013 * if bodyData is empty.
1016 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1018 const uint64_t length
=
1019 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1020 noteSentBodyBytes(length
);
1022 mb
.Printf("%" PRIX64
"\r\n", length
);
1023 mb
.append(bodyData
.data
, length
);
1027 /** put terminating boundary for multiparts */
1029 clientPackTermBound(String boundary
, MemBuf
* mb
)
1031 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1032 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1035 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1037 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1039 HttpHeader
hdr(hoReply
);
1045 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1046 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1047 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1049 /* stuff the header with required entries and pack it */
1051 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1052 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1054 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1056 packerToMemInit(&p
, mb
);
1064 /* append <crlf> (we packed a header, not a reply) */
1069 * extracts a "range" from *buf and appends them to mb, updating
1070 * all offsets and such.
1073 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1075 HttpHdrRangeIter
* i
= &http
->range_iter
;
1076 Range
<int64_t> available (source
.range());
1077 char const *buf
= source
.data
;
1079 while (i
->currentSpec() && available
.size()) {
1080 const size_t copy_sz
= lengthToSend(available
);
1084 * intersection of "have" and "need" ranges must not be empty
1086 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1087 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1090 * put boundary and headers at the beginning of a range in a
1094 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1095 assert(http
->memObject());
1097 http
->memObject()->getReply(), /* original reply */
1098 i
->currentSpec(), /* current range */
1099 i
->boundary
, /* boundary, the same for all */
1106 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1108 noteSentBodyBytes (copy_sz
);
1110 mb
->append(buf
, copy_sz
);
1115 available
.start
+= copy_sz
;
1121 if (!canPackMoreRanges()) {
1122 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1125 /* put terminating boundary for multiparts */
1126 clientPackTermBound(i
->boundary
, mb
);
1131 int64_t nextOffset
= getNextRangeOffset();
1133 assert (nextOffset
>= http
->out
.offset
);
1135 int64_t skip
= nextOffset
- http
->out
.offset
;
1137 /* adjust for not to be transmitted bytes */
1138 http
->out
.offset
= nextOffset
;
1140 if (available
.size() <= (uint64_t)skip
)
1143 available
.start
+= skip
;
1152 /** returns expected content length for multi-range replies
1153 * note: assumes that httpHdrRangeCanonize has already been called
1154 * warning: assumes that HTTP headers for individual ranges at the
1155 * time of the actuall assembly will be exactly the same as
1156 * the headers when clientMRangeCLen() is called */
1158 ClientHttpRequest::mRangeCLen()
1163 assert(memObject());
1166 HttpHdrRange::iterator pos
= request
->range
->begin();
1168 while (pos
!= request
->range
->end()) {
1169 /* account for headers for this range */
1171 clientPackRangeHdr(memObject()->getReply(),
1172 *pos
, range_iter
.boundary
, &mb
);
1175 /* account for range content */
1176 clen
+= (*pos
)->length
;
1178 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1182 /* account for the terminating boundary */
1185 clientPackTermBound(range_iter
.boundary
, &mb
);
1195 * returns true if If-Range specs match reply, false otherwise
1198 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1200 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1201 /* check for parsing falure */
1208 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1209 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1210 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1213 return 0; /* entity has no etag to compare with! */
1215 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1216 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1217 return 0; /* must use strong validator for sub-range requests */
1220 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1223 /* got modification time? */
1224 if (spec
.time
>= 0) {
1225 return http
->storeEntry()->lastmod
<= spec
.time
;
1228 assert(0); /* should not happen */
1233 * generates a "unique" boundary string for multipart responses
1234 * the caller is responsible for cleaning the string */
1236 ClientHttpRequest::rangeBoundaryStr() const
1240 String
b(APP_FULLNAME
);
1242 key
= storeEntry()->getMD5Text();
1243 b
.append(key
, strlen(key
));
1247 /** adds appropriate Range headers if needed */
1249 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1251 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1252 const char *range_err
= NULL
;
1253 HttpRequest
*request
= http
->request
;
1254 assert(request
->range
);
1255 /* check if we still want to do ranges */
1257 int64_t roffLimit
= request
->getRangeOffsetLimit();
1260 range_err
= "no [parse-able] reply";
1261 else if ((rep
->sline
.status
!= HTTP_OK
) && (rep
->sline
.status
!= HTTP_PARTIAL_CONTENT
))
1262 range_err
= "wrong status code";
1263 else if (hdr
->has(HDR_CONTENT_RANGE
))
1264 range_err
= "origin server does ranges";
1265 else if (rep
->content_length
< 0)
1266 range_err
= "unknown length";
1267 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1268 range_err
= "INCONSISTENT length"; /* a bug? */
1270 /* hits only - upstream peer determines correct behaviour on misses, and client_side_reply determines
1273 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1274 range_err
= "If-Range match failed";
1275 else if (!http
->request
->range
->canonize(rep
))
1276 range_err
= "canonization failed";
1277 else if (http
->request
->range
->isComplex())
1278 range_err
= "too complex range header";
1279 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1280 range_err
= "range outside range_offset_limit";
1282 /* get rid of our range specs on error */
1284 /* XXX We do this here because we need canonisation etc. However, this current
1285 * code will lead to incorrect store offset requests - the store will have the
1286 * offset data, but we won't be requesting it.
1287 * So, we can either re-request, or generate an error
1289 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1290 delete http
->request
->range
;
1291 http
->request
->range
= NULL
;
1293 /* XXX: TODO: Review, this unconditional set may be wrong. - TODO: review. */
1294 httpStatusLineSet(&rep
->sline
, rep
->sline
.version
,
1295 HTTP_PARTIAL_CONTENT
, NULL
);
1296 // web server responded with a valid, but unexpected range.
1297 // will (try-to) forward as-is.
1298 //TODO: we should cope with multirange request/responses
1299 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1300 request
->range
->contains(rep
->content_range
->spec
) :
1302 const int spec_count
= http
->request
->range
->specs
.count
;
1303 int64_t actual_clen
= -1;
1305 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1306 spec_count
<< " virgin clen: " << rep
->content_length
);
1307 assert(spec_count
> 0);
1308 /* append appropriate header(s) */
1310 if (spec_count
== 1) {
1311 if (!replyMatchRequest
) {
1312 hdr
->delById(HDR_CONTENT_RANGE
);
1313 hdr
->putContRange(rep
->content_range
);
1314 actual_clen
= rep
->content_length
;
1315 //http->range_iter.pos = rep->content_range->spec.begin();
1316 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1317 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1320 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1322 /* append Content-Range */
1324 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1325 /* No content range, so this was a full object we are
1328 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1331 /* set new Content-Length to the actual number of bytes
1332 * transmitted in the message-body */
1333 actual_clen
= (*pos
)->length
;
1337 /* generate boundary string */
1338 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1339 /* delete old Content-Type, add ours */
1340 hdr
->delById(HDR_CONTENT_TYPE
);
1341 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1342 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1343 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1344 /* Content-Length is not required in multipart responses
1345 * but it is always nice to have one */
1346 actual_clen
= http
->mRangeCLen();
1347 /* http->out needs to start where we want data at */
1348 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1351 /* replace Content-Length header */
1352 assert(actual_clen
>= 0);
1354 hdr
->delById(HDR_CONTENT_LENGTH
);
1356 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1358 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1360 /* And start the range iter off */
1361 http
->range_iter
.updateSpec();
1366 ClientSocketContext::prepareReply(HttpReply
* rep
)
1370 if (http
->request
->range
)
1371 buildRangeHeader(rep
);
1375 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1379 MemBuf
*mb
= rep
->pack();
1381 // dump now, so we dont output any body.
1382 debugs(11, 2, "HTTP Client " << clientConnection
);
1383 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1385 /* Save length of headers for persistent conn checks */
1386 http
->out
.headers_sz
= mb
->contentSize();
1389 headersLog(0, 0, http
->request
->method
, rep
);
1392 if (bodyData
.data
&& bodyData
.length
) {
1393 if (multipartRangeRequest())
1394 packRange(bodyData
, mb
);
1395 else if (http
->request
->flags
.chunked_reply
) {
1396 packChunk(bodyData
, *mb
);
1398 size_t length
= lengthToSend(bodyData
.range());
1399 noteSentBodyBytes (length
);
1401 mb
->append(bodyData
.data
, length
);
1406 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1407 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1408 CommIoCbPtrFun(clientWriteComplete
, this));
1409 Comm::Write(clientConnection
, mb
, call
);
1414 * Write a chunk of data to a client socket. If the reply is present,
1415 * send the reply headers down the wire too, and clean them up when
1418 * The request is one backed by a connection, not an internal request.
1419 * data context is not NULL
1420 * There are no more entries in the stream chain.
1423 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1424 HttpReply
* rep
, StoreIOBuffer receivedData
)
1426 /* Test preconditions */
1427 assert(node
!= NULL
);
1428 PROF_start(clientSocketRecipient
);
1429 /* TODO: handle this rather than asserting
1430 * - it should only ever happen if we cause an abort and
1431 * the callback chain loops back to here, so we can simply return.
1432 * However, that itself shouldn't happen, so it stays as an assert for now.
1434 assert(cbdataReferenceValid(node
));
1435 assert(node
->node
.next
== NULL
);
1436 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1437 assert(context
!= NULL
);
1438 assert(connIsUsable(http
->getConn()));
1440 /* TODO: check offset is what we asked for */
1442 if (context
!= http
->getConn()->getCurrentContext()) {
1443 context
->deferRecipientForLater(node
, rep
, receivedData
);
1444 PROF_stop(clientSocketRecipient
);
1448 // After sending Transfer-Encoding: chunked (at least), always send
1449 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1450 const bool mustSendLastChunk
= http
->request
->flags
.chunked_reply
&&
1451 !http
->request
->flags
.stream_error
&& !context
->startOfOutput();
1452 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1453 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1454 PROF_stop(clientSocketRecipient
);
1458 if (!context
->startOfOutput())
1459 context
->sendBody(rep
, receivedData
);
1462 http
->al
->reply
= HTTPMSGLOCK(rep
);
1463 context
->sendStartOfMessage(rep
, receivedData
);
1466 PROF_stop(clientSocketRecipient
);
1470 * Called when a downstream node is no longer interested in
1471 * our data. As we are a terminal node, this means on aborts
1475 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1477 /* Test preconditions */
1478 assert(node
!= NULL
);
1479 /* TODO: handle this rather than asserting
1480 * - it should only ever happen if we cause an abort and
1481 * the callback chain loops back to here, so we can simply return.
1482 * However, that itself shouldn't happen, so it stays as an assert for now.
1484 assert(cbdataReferenceValid(node
));
1485 /* Set null by ContextFree */
1486 assert(node
->node
.next
== NULL
);
1487 /* this is the assert discussed above */
1488 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1489 /* We are only called when the client socket shutsdown.
1490 * Tell the prev pipeline member we're finished
1492 clientStreamDetach(node
, http
);
1496 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1498 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1499 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1503 ConnStateData::readNextRequest()
1505 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1507 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1509 * Set the timeout BEFORE calling clientReadRequest().
1511 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1512 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1513 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1514 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1517 /** Please don't do anything with the FD past here! */
1521 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1523 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1525 /** If the client stream is waiting on a socket write to occur, then */
1527 if (deferredRequest
->flags
.deferred
) {
1528 /** NO data is allowed to have been sent. */
1529 assert(deferredRequest
->http
->out
.size
== 0);
1531 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1532 deferredRequest
->http
,
1533 deferredRequest
->deferredparams
.rep
,
1534 deferredRequest
->deferredparams
.queuedBuffer
);
1537 /** otherwise, the request is still active in a callbacksomewhere,
1542 /// called when we have successfully finished writing the response
1544 ClientSocketContext::keepaliveNextRequest()
1546 ConnStateData
* conn
= http
->getConn();
1548 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1551 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1552 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1553 conn
->clientConnection
->close();
1558 * We are done with the response, and we are either still receiving request
1559 * body (early response!) or have already stopped receiving anything.
1561 * If we are still receiving, then clientParseRequest() below will fail.
1562 * (XXX: but then we will call readNextRequest() which may succeed and
1563 * execute a smuggled request as we are not done with the current request).
1565 * If we stopped because we got everything, then try the next request.
1567 * If we stopped receiving because of an error, then close now to avoid
1568 * getting stuck and to prevent accidental request smuggling.
1571 if (const char *reason
= conn
->stoppedReceiving()) {
1572 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1573 conn
->clientConnection
->close();
1578 * Attempt to parse a request from the request buffer.
1579 * If we've been fed a pipelined request it may already
1580 * be in our read buffer.
1583 * This needs to fall through - if we're unlucky and parse the _last_ request
1584 * from our read buffer we may never re-register for another client read.
1587 if (conn
->clientParseRequests()) {
1588 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1592 * Either we need to kick-start another read or, if we have
1593 * a half-closed connection, kill it after the last request.
1594 * This saves waiting for half-closed connections to finished being
1595 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1596 * the keepalive "Waiting for next request" state.
1598 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1599 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1600 conn
->clientConnection
->close();
1604 ClientSocketContext::Pointer deferredRequest
;
1607 * At this point we either have a parsed request (which we've
1608 * kicked off the processing for) or not. If we have a deferred
1609 * request (parsed but deferred for pipeling processing reasons)
1610 * then look at processing it. If not, simply kickstart
1614 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1615 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1616 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1617 } else if (conn
->flags
.readMore
) {
1618 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1619 conn
->readNextRequest();
1621 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1622 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1627 clientUpdateSocketStats(log_type logType
, size_t size
)
1632 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1634 if (logTypeIsATcpHit(logType
))
1635 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1639 * increments iterator "i"
1640 * used by clientPackMoreRanges
1642 \retval true there is still data available to pack more ranges
1646 ClientSocketContext::canPackMoreRanges() const
1648 /** first update iterator "i" if needed */
1650 if (!http
->range_iter
.debt()) {
1651 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1653 if (http
->range_iter
.pos
.incrementable())
1654 ++http
->range_iter
.pos
;
1656 http
->range_iter
.updateSpec();
1659 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1661 /* paranoid sync condition */
1662 /* continue condition: need_more_data */
1663 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1664 return http
->range_iter
.currentSpec() ? true : false;
1668 ClientSocketContext::getNextRangeOffset() const
1670 if (http
->request
->range
) {
1671 /* offset in range specs does not count the prefix of an http msg */
1672 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1673 /* check: reply was parsed and range iterator was initialized */
1674 assert(http
->range_iter
.valid
);
1675 /* filter out data according to range specs */
1676 assert (canPackMoreRanges());
1678 int64_t start
; /* offset of still missing data */
1679 assert(http
->range_iter
.currentSpec());
1680 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1681 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1682 debugs(33, 3, "clientPackMoreRanges: out:"
1683 " start: " << start
<<
1684 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1685 " [" << http
->range_iter
.currentSpec()->offset
<<
1686 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1687 " len: " << http
->range_iter
.currentSpec()->length
<<
1688 " debt: " << http
->range_iter
.debt());
1689 if (http
->range_iter
.currentSpec()->length
!= -1)
1690 assert(http
->out
.offset
<= start
); /* we did not miss it */
1695 } else if (reply
&& reply
->content_range
) {
1696 /* request does not have ranges, but reply does */
1697 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1698 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1700 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1703 return http
->out
.offset
;
1707 ClientSocketContext::pullData()
1709 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1711 /* More data will be coming from the stream. */
1712 StoreIOBuffer readBuffer
;
1713 /* XXX: Next requested byte in the range sequence */
1714 /* XXX: length = getmaximumrangelenfgth */
1715 readBuffer
.offset
= getNextRangeOffset();
1716 readBuffer
.length
= HTTP_REQBUF_SZ
;
1717 readBuffer
.data
= reqbuf
;
1718 /* we may note we have reached the end of the wanted ranges */
1719 clientStreamRead(getTail(), http
, readBuffer
);
1722 clientStream_status_t
1723 ClientSocketContext::socketState()
1725 switch (clientStreamStatus(getTail(), http
)) {
1728 /* check for range support ending */
1730 if (http
->request
->range
) {
1731 /* check: reply was parsed and range iterator was initialized */
1732 assert(http
->range_iter
.valid
);
1733 /* filter out data according to range specs */
1735 if (!canPackMoreRanges()) {
1736 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1737 "range sequence on " << clientConnection
);
1739 if (http
->request
->flags
.proxy_keepalive
)
1740 return STREAM_COMPLETE
;
1742 return STREAM_UNPLANNED_COMPLETE
;
1744 } else if (reply
&& reply
->content_range
) {
1745 /* reply has content-range, but Squid is not managing ranges */
1746 const int64_t &bytesSent
= http
->out
.offset
;
1747 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1749 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1750 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1751 reply
->content_range
->spec
.offset
<< ")");
1753 // did we get at least what we expected, based on range specs?
1755 if (bytesSent
== bytesExpected
) { // got everything
1756 if (http
->request
->flags
.proxy_keepalive
)
1757 return STREAM_COMPLETE
;
1759 return STREAM_UNPLANNED_COMPLETE
;
1762 // The logic below is not clear: If we got more than we
1763 // expected why would persistency matter? Should not this
1764 // always be an error?
1765 if (bytesSent
> bytesExpected
) { // got extra
1766 if (http
->request
->flags
.proxy_keepalive
)
1767 return STREAM_COMPLETE
;
1769 return STREAM_UNPLANNED_COMPLETE
;
1772 // did not get enough yet, expecting more
1777 case STREAM_COMPLETE
:
1778 return STREAM_COMPLETE
;
1780 case STREAM_UNPLANNED_COMPLETE
:
1781 return STREAM_UNPLANNED_COMPLETE
;
1784 return STREAM_FAILED
;
1787 fatal ("unreachable code\n");
1792 * A write has just completed to the client, or we have just realised there is
1793 * no more data to send.
1796 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1798 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1799 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1802 /// remembers the abnormal connection termination for logging purposes
1804 ClientSocketContext::noteIoError(const int xerrno
)
1807 if (xerrno
== ETIMEDOUT
)
1808 http
->al
->http
.timedout
= true;
1809 else // even if xerrno is zero (which means read abort/eof)
1810 http
->al
->http
.aborted
= true;
1815 ClientSocketContext::doClose()
1817 clientConnection
->close();
1820 /// called when we encounter a response-related error
1822 ClientSocketContext::initiateClose(const char *reason
)
1824 http
->getConn()->stopSending(reason
); // closes ASAP
1828 ConnStateData::stopSending(const char *error
)
1830 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1831 "; old receiving error: " <<
1832 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1834 if (const char *oldError
= stoppedSending()) {
1835 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1836 return; // nothing has changed as far as this connection is concerned
1838 stoppedSending_
= error
;
1840 if (!stoppedReceiving()) {
1841 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1842 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1843 " request body bytes with " << in
.notYetUsed
<< " unused");
1844 return; // wait for the request receiver to finish reading
1848 clientConnection
->close();
1852 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1854 const StoreEntry
*entry
= http
->storeEntry();
1855 http
->out
.size
+= size
;
1856 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1857 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1858 (entry
? entry
->objectLen() : 0));
1859 clientUpdateSocketStats(http
->logType
, size
);
1861 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1863 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1866 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1867 initiateClose("failure or true request status");
1868 /* Do we leak here ? */
1872 switch (socketState()) {
1878 case STREAM_COMPLETE
:
1879 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1880 keepaliveNextRequest();
1883 case STREAM_UNPLANNED_COMPLETE
:
1884 initiateClose("STREAM_UNPLANNED_COMPLETE");
1888 initiateClose("STREAM_FAILED");
1892 fatal("Hit unreachable code in clientWriteComplete\n");
1896 extern "C" CSR clientGetMoreData
;
1897 extern "C" CSS clientReplyStatus
;
1898 extern "C" CSD clientReplyDetach
;
1900 static ClientSocketContext
*
1901 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1903 ClientHttpRequest
*http
;
1904 ClientSocketContext
*context
;
1905 StoreIOBuffer tempBuffer
;
1906 http
= new ClientHttpRequest(csd
);
1907 http
->req_sz
= csd
->in
.notYetUsed
;
1908 http
->uri
= xstrdup(uri
);
1909 setLogUri (http
, uri
);
1910 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
1911 tempBuffer
.data
= context
->reqbuf
;
1912 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1913 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1914 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1915 clientSocketDetach
, context
, tempBuffer
);
1920 skipLeadingSpace(char *aString
)
1922 char *result
= aString
;
1924 while (xisspace(*aString
))
1931 * 'end' defaults to NULL for backwards compatibility
1932 * remove default value if we ever get rid of NULL-terminated
1936 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1939 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1943 for (; end
> uriAndHTTPVersion
; --end
) {
1944 if (*end
== '\n' || *end
== '\r')
1947 if (xisspace(*end
)) {
1948 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1959 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1961 safe_free(http
->log_uri
);
1964 // The uri is already clean just dump it.
1965 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1968 switch (Config
.uri_whitespace
) {
1969 case URI_WHITESPACE_ALLOW
:
1970 flags
|= RFC1738_ESCAPE_NOSPACE
;
1972 case URI_WHITESPACE_ENCODE
:
1973 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1974 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1977 case URI_WHITESPACE_CHOP
: {
1978 flags
|= RFC1738_ESCAPE_NOSPACE
;
1979 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1980 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1981 int pos
= strcspn(http
->log_uri
, w_space
);
1982 http
->log_uri
[pos
] = '\0';
1986 case URI_WHITESPACE_DENY
:
1987 case URI_WHITESPACE_STRIP
:
1990 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1994 if (!xisspace(*t
)) {
2001 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2010 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2012 int vhost
= conn
->port
->vhost
;
2013 int vport
= conn
->port
->vport
;
2015 char ipbuf
[MAX_IPSTRLEN
];
2017 http
->flags
.accel
= 1;
2019 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2021 if (strncasecmp(url
, "cache_object://", 15) == 0)
2022 return; /* already in good shape */
2025 if (conn
->port
->vhost
)
2026 return; /* already in good shape */
2028 /* else we need to ignore the host name */
2029 url
= strstr(url
, "//");
2031 #if SHOULD_REJECT_UNKNOWN_URLS
2034 hp
->request_parse_status
= HTTP_BAD_REQUEST
;
2035 return parseHttpRequestAbort(conn
, "error:invalid-request");
2040 url
= strchr(url
+ 2, '/');
2047 vport
= http
->getConn()->clientConnection
->local
.GetPort();
2049 const bool switchedToHttps
= conn
->switchedToHttps();
2050 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2051 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2052 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2057 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2058 strncpy(thost
, host
, (t
-host
));
2059 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2062 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2065 } // else nothing to alter port-wise.
2066 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2068 http
->uri
= (char *)xcalloc(url_sz
, 1);
2069 const char *protocol
= switchedToHttps
?
2070 "https" : conn
->port
->protocol
;
2071 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2072 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2073 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2074 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2075 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2076 strlen(conn
->port
->defaultsite
);
2077 http
->uri
= (char *)xcalloc(url_sz
, 1);
2081 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2083 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2084 conn
->port
->protocol
, conn
->port
->defaultsite
, vportStr
, url
);
2085 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2086 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2087 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2088 /* Put the local socket IP address as the hostname, with whatever vport we found */
2089 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2090 http
->uri
= (char *)xcalloc(url_sz
, 1);
2091 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2092 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2093 http
->getConn()->port
->protocol
,
2095 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2100 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2103 char ipbuf
[MAX_IPSTRLEN
];
2106 return; /* already in good shape */
2108 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2110 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2111 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2113 http
->uri
= (char *)xcalloc(url_sz
, 1);
2114 snprintf(http
->uri
, url_sz
, "%s://%s%s", conn
->port
->protocol
, host
, url
);
2115 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2117 /* Put the local socket IP address as the hostname. */
2118 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2119 http
->uri
= (char *)xcalloc(url_sz
, 1);
2120 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2121 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2122 http
->getConn()->port
->protocol
,
2123 ipbuf
, http
->getConn()->clientConnection
->local
.GetPort(), url
);
2124 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2129 * parseHttpRequest()
2132 * NULL on incomplete requests
2133 * a ClientSocketContext structure on success or failure.
2134 * Sets result->flags.parsed_ok to 0 if failed to parse the request.
2135 * Sets result->flags.parsed_ok to 1 if we have a good request.
2137 static ClientSocketContext
*
2138 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, HttpVersion
*http_ver
)
2140 char *req_hdr
= NULL
;
2143 ClientHttpRequest
*http
;
2144 ClientSocketContext
*result
;
2145 StoreIOBuffer tempBuffer
;
2148 /* pre-set these values to make aborting simpler */
2149 *method_p
= METHOD_NONE
;
2151 /* NP: don't be tempted to move this down or remove again.
2152 * It's the only DDoS protection old-String has against long URL */
2153 if ( hp
->bufsiz
<= 0) {
2154 debugs(33, 5, "Incomplete request, waiting for end of request line");
2156 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2157 debugs(33, 5, "parseHttpRequest: Too large request");
2158 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2159 return parseHttpRequestAbort(csd
, "error:request-too-large");
2162 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2163 r
= HttpParserParseReqLine(hp
);
2166 debugs(33, 5, "Incomplete request, waiting for end of request line");
2171 return parseHttpRequestAbort(csd
, "error:invalid-request");
2174 /* Request line is valid here .. */
2175 *http_ver
= HttpVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2177 /* This call scans the entire request, not just the headers */
2178 if (hp
->req
.v_maj
> 0) {
2179 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2180 debugs(33, 5, "Incomplete request, waiting for end of headers");
2184 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2185 req_sz
= HttpParserReqSz(hp
);
2188 /* We know the whole request is in hp->buf now */
2190 assert(req_sz
<= (size_t) hp
->bufsiz
);
2192 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2193 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2196 hp
->hdr_end
= req_sz
- 1;
2198 hp
->hdr_start
= hp
->req
.end
+ 1;
2200 /* Enforce max_request_size */
2201 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2202 debugs(33, 5, "parseHttpRequest: Too large request");
2203 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2204 return parseHttpRequestAbort(csd
, "error:request-too-large");
2208 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2210 /* deny CONNECT via accelerated ports */
2211 if (*method_p
== METHOD_CONNECT
&& csd
&& csd
->port
&& csd
->port
->accel
) {
2212 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->protocol
<< " Accelerator port " << csd
->port
->s
.GetPort() );
2213 /* XXX need a way to say "this many character length string" */
2214 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2215 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2216 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2219 if (*method_p
== METHOD_NONE
) {
2220 /* XXX need a way to say "this many character length string" */
2221 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2222 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2223 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2227 * Process headers after request line
2228 * TODO: Use httpRequestParse here.
2230 /* XXX this code should be modified to take a const char * later! */
2231 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2233 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2235 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2237 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2239 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2240 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2241 HttpParserReqSz(hp
));
2243 /* Ok, all headers are received */
2244 http
= new ClientHttpRequest(csd
);
2246 http
->req_sz
= HttpParserRequestLen(hp
);
2247 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2248 tempBuffer
.data
= result
->reqbuf
;
2249 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2251 ClientStreamData newServer
= new clientReplyContext(http
);
2252 ClientStreamData newClient
= result
;
2253 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2254 clientReplyStatus
, newServer
, clientSocketRecipient
,
2255 clientSocketDetach
, newClient
, tempBuffer
);
2257 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2261 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2262 * below needs to be modified to not expect a mutable nul-terminated string.
2264 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2266 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2268 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2270 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2272 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2277 debugs(33,5, HERE
<< "repare absolute URL from " << (csd
->transparent()?"intercept":(csd
->port
->accel
? "accel":"")));
2278 /* Rewrite the URL in transparent or accelerator mode */
2279 /* NP: there are several cases to traverse here:
2280 * - standard mode (forward proxy)
2281 * - transparent mode (TPROXY)
2282 * - transparent mode with failures
2283 * - intercept mode (NAT)
2284 * - intercept mode with failures
2285 * - accelerator mode (reverse proxy)
2287 * - mixed combos of the above with internal URL
2289 if (csd
->transparent()) {
2290 /* intercept or transparent mode, properly working with no failures */
2291 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2293 } else if (internalCheck(url
)) {
2294 /* internal URL mode */
2295 /* prepend our name & port */
2296 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2297 // We just re-wrote the URL. Must replace the Host: header.
2298 // But have not parsed there yet!! flag for local-only handling.
2299 http
->flags
.internal
= 1;
2301 } else if (csd
->port
->accel
|| csd
->switchedToHttps()) {
2302 /* accelerator mode */
2303 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2307 /* No special rewrites have been applied above, use the
2308 * requested url. may be rewritten later, so make extra room */
2309 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2310 http
->uri
= (char *)xcalloc(url_sz
, 1);
2311 strcpy(http
->uri
, url
);
2314 debugs(33, 5, "parseHttpRequest: Complete request received");
2316 // XXX: crop this dump at the end of headers. No need for extras
2317 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2318 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2320 result
->flags
.parsed_ok
= 1;
2326 ConnStateData::getAvailableBufferLength() const
2328 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2329 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2330 // huge request_header_max_size may lead to more than INT_MAX unused space
2331 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2336 ConnStateData::maybeMakeSpaceAvailable()
2338 if (getAvailableBufferLength() < 2) {
2340 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2341 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2344 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2345 newSize
=Config
.maxRequestBufferSize
;
2347 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2348 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2354 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2356 ClientSocketContext::Pointer
*S
;
2358 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2366 ConnStateData::getConcurrentRequestCount() const
2369 ClientSocketContext::Pointer
*T
;
2371 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2372 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2377 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2379 if (flag
!= COMM_OK
) {
2380 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2385 if (!ignoreErrno(xerrno
)) {
2386 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2388 } else if (in
.notYetUsed
== 0) {
2389 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2397 ConnStateData::connFinishedWithConn(int size
)
2400 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2401 /* no current or pending requests */
2402 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2404 } else if (!Config
.onoff
.half_closed_clients
) {
2405 /* admin doesn't want to support half-closed client sockets */
2406 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2407 notifyAllContexts(0); // no specific error implies abort
2416 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2418 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2419 conn
->in
.notYetUsed
-= byteCount
;
2420 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2422 * If there is still data that will be used,
2423 * move it to the beginning.
2426 if (conn
->in
.notYetUsed
> 0)
2427 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2430 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2432 ConnStateData::checkHeaderLimits()
2434 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2435 return; // can accumulte more header data
2437 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2438 Config
.maxRequestHeaderSize
<< " bytes)");
2440 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2441 clientStreamNode
*node
= context
->getClientReplyContext();
2442 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2443 assert (repContext
);
2444 repContext
->setReplyToError(ERR_TOO_BIG
,
2445 HTTP_BAD_REQUEST
, METHOD_NONE
, NULL
,
2446 clientConnection
->remote
, NULL
, NULL
, NULL
);
2447 context
->registerWithConn();
2448 context
->pullData();
2452 ConnStateData::clientAfterReadingRequests()
2454 // Were we expecting to read more request body from half-closed connection?
2455 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2456 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2457 clientConnection
->close();
2466 ConnStateData::quitAfterError(HttpRequest
*request
)
2468 // From HTTP p.o.v., we do not have to close after every error detected
2469 // at the client-side, but many such errors do require closure and the
2470 // client-side code is bad at handling errors so we play it safe.
2472 request
->flags
.proxy_keepalive
= 0;
2473 flags
.readMore
= false;
2474 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2478 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2480 ClientHttpRequest
*http
= context
->http
;
2485 assert(sslServerBump
->entry
);
2486 // Did we create an error entry while processing CONNECT?
2487 if (!sslServerBump
->entry
->isEmpty()) {
2488 quitAfterError(http
->request
);
2490 // Get the saved error entry and send it to the client by replacing the
2491 // ClientHttpRequest store entry with it.
2492 clientStreamNode
*node
= context
->getClientReplyContext();
2493 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2495 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2496 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2498 // save the original request for logging purposes
2499 if (!context
->http
->al
->request
)
2500 context
->http
->al
->request
= HTTPMSGLOCK(http
->request
);
2502 // Get error details from the fake certificate-peeking request.
2503 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2504 context
->pullData();
2508 // In bump-server-first mode, we have not necessarily seen the intended
2509 // server name at certificate-peeking time. Check for domain mismatch now,
2510 // when we can extract the intended name from the bumped HTTP request.
2511 if (sslServerBump
->serverCert
.get()) {
2512 HttpRequest
*request
= http
->request
;
2513 if (!Ssl::checkX509ServerValidity(sslServerBump
->serverCert
.get(), request
->GetHost())) {
2514 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2515 "does not match domainname " << request
->GetHost());
2517 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2518 check
.sslErrors
= new Ssl::Errors(SQUID_X509_V_ERR_DOMAIN_MISMATCH
);
2519 if (Comm::IsConnOpen(pinning
.serverConnection
))
2520 check
.fd(pinning
.serverConnection
->fd
);
2521 const bool allowDomainMismatch
=
2522 check
.fastCheck() == ACCESS_ALLOWED
;
2523 delete check
.sslErrors
;
2524 check
.sslErrors
= NULL
;
2526 if (!allowDomainMismatch
) {
2527 quitAfterError(request
);
2529 clientStreamNode
*node
= context
->getClientReplyContext();
2530 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2531 assert (repContext
);
2533 // Fill the server IP and hostname for error page generation.
2534 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2535 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2537 // Create an error object and fill it
2538 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, HTTP_SERVICE_UNAVAILABLE
, request
);
2539 err
->src_addr
= clientConnection
->remote
;
2540 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2541 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2542 sslServerBump
->serverCert
.get(), NULL
);
2543 err
->detail
= errDetail
;
2544 // Save the original request for logging purposes.
2545 if (!context
->http
->al
->request
)
2546 context
->http
->al
->request
= HTTPMSGLOCK(request
);
2547 repContext
->setReplyToError(request
->method
, err
);
2548 assert(context
->http
->out
.offset
== 0);
2549 context
->pullData();
2560 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, HttpVersion http_ver
)
2562 ClientHttpRequest
*http
= context
->http
;
2563 HttpRequest
*request
= NULL
;
2564 bool notedUseOfBuffer
= false;
2565 bool chunked
= false;
2566 bool mustReplyToOptions
= false;
2567 bool unsupportedTe
= false;
2568 bool expectBody
= false;
2570 /* We have an initial client stream in place should it be needed */
2571 /* setup our private context */
2572 context
->registerWithConn();
2574 if (context
->flags
.parsed_ok
== 0) {
2575 clientStreamNode
*node
= context
->getClientReplyContext();
2576 debugs(33, 2, "clientProcessRequest: Invalid Request");
2577 conn
->quitAfterError(NULL
);
2578 // setLogUri should called before repContext->setReplyToError
2579 setLogUri(http
, http
->uri
, true);
2580 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2581 assert (repContext
);
2582 switch (hp
->request_parse_status
) {
2583 case HTTP_HEADER_TOO_LARGE
:
2584 repContext
->setReplyToError(ERR_TOO_BIG
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2586 case HTTP_METHOD_NOT_ALLOWED
:
2587 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_METHOD_NOT_ALLOWED
, method
, http
->uri
,
2588 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2591 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2592 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2594 assert(context
->http
->out
.offset
== 0);
2595 context
->pullData();
2599 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2600 clientStreamNode
*node
= context
->getClientReplyContext();
2601 debugs(33, 5, "Invalid URL: " << http
->uri
);
2602 conn
->quitAfterError(request
);
2603 // setLogUri should called before repContext->setReplyToError
2604 setLogUri(http
, http
->uri
, true);
2605 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2606 assert (repContext
);
2607 repContext
->setReplyToError(ERR_INVALID_URL
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2608 assert(context
->http
->out
.offset
== 0);
2609 context
->pullData();
2613 /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */
2614 /* We currently only accept 0.9, 1.0, 1.1 */
2615 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2616 (http_ver
.major
== 1 && http_ver
.minor
> 1 ) ||
2617 (http_ver
.major
> 1) ) {
2619 clientStreamNode
*node
= context
->getClientReplyContext();
2620 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2621 conn
->quitAfterError(request
);
2622 // setLogUri should called before repContext->setReplyToError
2623 setLogUri(http
, http
->uri
, true);
2624 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2625 assert (repContext
);
2626 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, HTTP_HTTP_VERSION_NOT_SUPPORTED
, method
, http
->uri
,
2627 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2628 assert(context
->http
->out
.offset
== 0);
2629 context
->pullData();
2633 /* compile headers */
2634 /* we should skip request line! */
2635 /* XXX should actually know the damned buffer size here */
2636 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2637 clientStreamNode
*node
= context
->getClientReplyContext();
2638 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2639 conn
->quitAfterError(request
);
2640 // setLogUri should called before repContext->setReplyToError
2641 setLogUri(http
, http
->uri
, true);
2642 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2643 assert (repContext
);
2644 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2645 assert(context
->http
->out
.offset
== 0);
2646 context
->pullData();
2650 request
->clientConnectionManager
= conn
;
2652 request
->flags
.accelerated
= http
->flags
.accel
;
2653 request
->flags
.sslBumped
= conn
->switchedToHttps();
2654 request
->flags
.canRePin
= request
->flags
.sslBumped
&& conn
->pinning
.pinned
;
2655 request
->flags
.ignore_cc
= conn
->port
->ignore_cc
;
2656 // TODO: decouple http->flags.accel from request->flags.sslBumped
2657 request
->flags
.no_direct
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2658 !conn
->port
->allow_direct
: 0;
2660 if (request
->flags
.sslBumped
) {
2661 if (conn
->auth_user_request
!= NULL
)
2662 request
->auth_user_request
= conn
->auth_user_request
;
2667 * If transparent or interception mode is working clone the transparent and interception flags
2668 * from the port settings to the request.
2670 if (http
->clientConnection
!= NULL
) {
2671 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2672 request
->flags
.spoof_client_ip
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2675 if (internalCheck(request
->urlpath
.termedBuf())) {
2676 if (internalHostnameIs(request
->GetHost()) &&
2677 request
->port
== getMyPort()) {
2678 http
->flags
.internal
= 1;
2679 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2680 request
->SetHost(internalHostname());
2681 request
->port
= getMyPort();
2682 http
->flags
.internal
= 1;
2686 if (http
->flags
.internal
) {
2687 request
->protocol
= AnyP::PROTO_HTTP
;
2688 request
->login
[0] = '\0';
2691 request
->flags
.internal
= http
->flags
.internal
;
2692 setLogUri (http
, urlCanonicalClean(request
));
2693 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2694 #if FOLLOW_X_FORWARDED_FOR
2695 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2696 // not a details about teh TCP connection itself
2697 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2698 #endif /* FOLLOW_X_FORWARDED_FOR */
2699 request
->my_addr
= conn
->clientConnection
->local
;
2700 request
->myportname
= conn
->port
->name
;
2701 request
->http_ver
= http_ver
;
2703 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2704 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2705 request
->clientConnectionManager
= conn
;
2707 if (request
->header
.chunked()) {
2709 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2710 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2711 // HTTP/1.1 requires chunking to be the last encoding if there is one
2712 unsupportedTe
= te
.size() && te
!= "identity";
2713 } // else implied identity coding
2715 mustReplyToOptions
= (method
== METHOD_OPTIONS
) &&
2716 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2717 if (!urlCheckRequest(request
) || mustReplyToOptions
|| unsupportedTe
) {
2718 clientStreamNode
*node
= context
->getClientReplyContext();
2719 conn
->quitAfterError(request
);
2720 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2721 assert (repContext
);
2722 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_NOT_IMPLEMENTED
, request
->method
, NULL
,
2723 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2724 assert(context
->http
->out
.offset
== 0);
2725 context
->pullData();
2729 if (!chunked
&& !clientIsContentLengthValid(request
)) {
2730 clientStreamNode
*node
= context
->getClientReplyContext();
2731 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2732 assert (repContext
);
2733 conn
->quitAfterError(request
);
2734 repContext
->setReplyToError(ERR_INVALID_REQ
,
2735 HTTP_LENGTH_REQUIRED
, request
->method
, NULL
,
2736 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2737 assert(context
->http
->out
.offset
== 0);
2738 context
->pullData();
2742 if (request
->header
.has(HDR_EXPECT
)) {
2743 const String expect
= request
->header
.getList(HDR_EXPECT
);
2744 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2745 if (!supportedExpect
) {
2746 clientStreamNode
*node
= context
->getClientReplyContext();
2747 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2748 assert (repContext
);
2749 conn
->quitAfterError(request
);
2750 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_EXPECTATION_FAILED
, request
->method
, http
->uri
,
2751 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2752 assert(context
->http
->out
.offset
== 0);
2753 context
->pullData();
2758 http
->request
= HTTPMSGLOCK(request
);
2759 clientSetKeepaliveFlag(http
);
2761 // Let tunneling code be fully responsible for CONNECT requests
2762 if (http
->request
->method
== METHOD_CONNECT
) {
2763 context
->mayUseConnection(true);
2764 conn
->flags
.readMore
= false;
2768 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2772 /* Do we expect a request-body? */
2773 expectBody
= chunked
|| request
->content_length
> 0;
2774 if (!context
->mayUseConnection() && expectBody
) {
2775 request
->body_pipe
= conn
->expectRequestBody(
2776 chunked
? -1 : request
->content_length
);
2778 // consume header early so that body pipe gets just the body
2779 connNoteUseOfBuffer(conn
, http
->req_sz
);
2780 notedUseOfBuffer
= true;
2782 /* Is it too large? */
2783 if (!chunked
&& // if chunked, we will check as we accumulate
2784 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2785 clientStreamNode
*node
= context
->getClientReplyContext();
2786 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2787 assert (repContext
);
2788 conn
->quitAfterError(request
);
2789 repContext
->setReplyToError(ERR_TOO_BIG
,
2790 HTTP_REQUEST_ENTITY_TOO_LARGE
, METHOD_NONE
, NULL
,
2791 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2792 assert(context
->http
->out
.offset
== 0);
2793 context
->pullData();
2797 // We may stop producing, comm_close, and/or call setReplyToError()
2798 // below, so quit on errors to avoid http->doCallouts()
2799 if (!conn
->handleRequestBodyData())
2802 if (!request
->body_pipe
->productionEnded()) {
2803 debugs(33, 5, HERE
<< "need more request body");
2804 context
->mayUseConnection(true);
2805 assert(conn
->flags
.readMore
);
2809 http
->calloutContext
= new ClientRequestContext(http
);
2814 if (!notedUseOfBuffer
)
2815 connNoteUseOfBuffer(conn
, http
->req_sz
);
2819 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2820 * to here because calling comm_reset_close() causes http to
2821 * be freed and the above connNoteUseOfBuffer() would hit an
2822 * assertion, not to mention that we were accessing freed memory.
2824 if (request
&& request
->flags
.resetTCP() && Comm::IsConnOpen(conn
->clientConnection
)) {
2825 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2826 conn
->flags
.readMore
= false;
2827 comm_reset_close(conn
->clientConnection
);
2832 connStripBufferWhitespace (ConnStateData
* conn
)
2834 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2835 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2836 -- conn
->in
.notYetUsed
;
2841 connOkToAddRequest(ConnStateData
* conn
)
2843 int result
= conn
->getConcurrentRequestCount() < (Config
.onoff
.pipeline_prefetch
? 2 : 1);
2846 debugs(33, 3, HERE
<< conn
->clientConnection
<< " max concurrent requests reached");
2847 debugs(33, 5, HERE
<< conn
->clientConnection
<< " defering new request until one is done");
2854 * Attempt to parse one or more requests from the input buffer.
2855 * If a request is successfully parsed, even if the next request
2856 * is only partially parsed, it will return TRUE.
2859 ConnStateData::clientParseRequests()
2861 HttpRequestMethod method
;
2862 bool parsed_req
= false;
2863 HttpVersion http_ver
;
2865 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2867 // Loop while we have read bytes that are not needed for producing the body
2868 // On errors, bodyPipe may become nil, but readMore will be cleared
2869 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2870 connStripBufferWhitespace(this);
2872 /* Don't try to parse if the buffer is empty */
2873 if (in
.notYetUsed
== 0)
2876 /* Limit the number of concurrent requests to 2 */
2877 if (!connOkToAddRequest(this)) {
2881 /* Should not be needed anymore */
2882 /* Terminate the string */
2883 in
.buf
[in
.notYetUsed
] = '\0';
2885 /* Begin the parsing */
2886 PROF_start(parseHttpRequest
);
2887 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
2889 /* Process request */
2890 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2891 PROF_stop(parseHttpRequest
);
2893 /* partial or incomplete request */
2895 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2896 // (which becomes context) but checkHeaderLimits cannot?
2897 checkHeaderLimits();
2901 /* status -1 or 1 */
2903 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2904 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2905 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2906 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2908 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2910 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2912 if (context
->mayUseConnection()) {
2913 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2919 /* XXX where to 'finish' the parsing pass? */
2924 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
2926 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
2930 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2932 if (io
.flag
== COMM_ERR_CLOSING
) {
2933 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
2937 assert(Comm::IsConnOpen(clientConnection
));
2938 assert(io
.conn
->fd
== clientConnection
->fd
);
2941 * Don't reset the timeout value here. The timeout value will be
2942 * set to Config.Timeout.request by httpAccept() and
2943 * clientWriteComplete(), and should apply to the request as a
2944 * whole, not individual read() calls. Plus, it breaks our
2945 * lame half-close detection
2947 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
2948 notifyAllContexts(io
.xerrno
);
2953 if (io
.flag
== COMM_OK
) {
2955 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
2957 // may comm_close or setReplyToError
2958 if (!handleReadData(io
.buf
, io
.size
))
2961 } else if (io
.size
== 0) {
2962 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
2964 if (connFinishedWithConn(io
.size
)) {
2965 clientConnection
->close();
2969 /* It might be half-closed, we can't tell */
2970 fd_table
[io
.conn
->fd
].flags
.socket_eof
= 1;
2972 commMarkHalfClosed(io
.conn
->fd
);
2974 fd_note(io
.conn
->fd
, "half-closed");
2976 /* There is one more close check at the end, to detect aborted
2977 * (partial) requests. At this point we can't tell if the request
2980 /* Continue to process previously read data */
2984 /* Process next request */
2985 if (getConcurrentRequestCount() == 0)
2986 fd_note(io
.fd
, "Reading next request");
2988 if (!clientParseRequests()) {
2992 * If the client here is half closed and we failed
2993 * to parse a request, close the connection.
2994 * The above check with connFinishedWithConn() only
2995 * succeeds _if_ the buffer is empty which it won't
2996 * be if we have an incomplete request.
2997 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
2999 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3000 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3001 clientConnection
->close();
3009 clientAfterReadingRequests();
3013 * called when new request data has been read from the socket
3015 * \retval false called comm_close or setReplyToError (the caller should bail)
3016 * \retval true we did not call comm_close or setReplyToError
3019 ConnStateData::handleReadData(char *buf
, size_t size
)
3021 char *current_buf
= in
.addressToReadInto();
3023 if (buf
!= current_buf
)
3024 memmove(current_buf
, buf
, size
);
3026 in
.notYetUsed
+= size
;
3028 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3030 // if we are reading a body, stuff data into the body pipe
3031 if (bodyPipe
!= NULL
)
3032 return handleRequestBodyData();
3037 * called when new request body data has been buffered in in.buf
3038 * may close the connection if we were closing and piped everything out
3040 * \retval false called comm_close or setReplyToError (the caller should bail)
3041 * \retval true we did not call comm_close or setReplyToError
3044 ConnStateData::handleRequestBodyData()
3046 assert(bodyPipe
!= NULL
);
3050 if (in
.bodyParser
) { // chunked encoding
3051 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3052 abortChunkedRequestBody(error
);
3055 } else { // identity encoding
3056 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3057 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3058 if (!bodyPipe
->mayNeedMoreData()) {
3059 // BodyPipe will clear us automagically when we produced everything
3065 connNoteUseOfBuffer(this, putSize
);
3068 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3070 if (const char *reason
= stoppedSending()) {
3071 /* we've finished reading like good clients,
3072 * now do the close that initiateClose initiated.
3074 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3075 clientConnection
->close();
3083 /// parses available chunked encoded body bytes, checks size, returns errors
3085 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3087 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3089 try { // the parser will throw on errors
3091 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3094 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3095 // add one because MemBuf will assert if it cannot 0-terminate
3096 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3097 raw
.append(in
.buf
, in
.notYetUsed
);
3099 const mb_size_t wasContentSize
= raw
.contentSize();
3100 BodyPipeCheckout
bpc(*bodyPipe
);
3101 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3103 putSize
= wasContentSize
- raw
.contentSize();
3105 // dechunk then check: the size limit applies to _dechunked_ content
3106 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3110 finishDechunkingRequest(true);
3112 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3115 // if chunk parser needs data, then the body pipe must need it too
3116 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3118 // if parser needs more space and we can consume nothing, we will stall
3119 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3120 } catch (...) { // TODO: be more specific
3121 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3122 return ERR_INVALID_REQ
;
3125 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3129 /// quit on errors related to chunked request body handling
3131 ConnStateData::abortChunkedRequestBody(const err_type error
)
3133 finishDechunkingRequest(false);
3135 // XXX: The code below works if we fail during initial request parsing,
3136 // but if we fail when the server-side works already, the server may send
3137 // us its response too, causing various assertions. How to prevent that?
3138 #if WE_KNOW_HOW_TO_SEND_ERRORS
3139 ClientSocketContext::Pointer context
= getCurrentContext();
3140 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3141 clientStreamNode
*node
= context
->getClientReplyContext();
3142 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3144 const http_status scode
= (error
== ERR_TOO_BIG
) ?
3145 HTTP_REQUEST_ENTITY_TOO_LARGE
: HTTP_BAD_REQUEST
;
3146 repContext
->setReplyToError(error
, scode
,
3147 repContext
->http
->request
->method
,
3148 repContext
->http
->uri
,
3150 repContext
->http
->request
,
3152 context
->pullData();
3154 // close or otherwise we may get stuck as nobody will notice the error?
3155 comm_reset_close(clientConnection
);
3158 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3159 comm_reset_close(clientConnection
);
3161 flags
.readMore
= false;
3165 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3167 if (!handleRequestBodyData())
3170 // too late to read more body
3171 if (!isOpen() || stoppedReceiving())
3178 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3180 // request reader may get stuck waiting for space if nobody consumes body
3181 if (bodyPipe
!= NULL
)
3182 bodyPipe
->enableAutoConsumption();
3184 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3187 /** general lifetime handler for HTTP requests */
3189 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3191 #if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS
3192 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3194 if (COMMIO_FD_WRITECB(io
.fd
)->active
) {
3195 /* FIXME: If this code is reinstated, check the conn counters,
3196 * not the fd table state
3199 * Some data has been sent to the client, just close the FD
3201 clientConnection
->close();
3202 } else if (nrequests
) {
3204 * assume its a persistent connection; just close it
3206 clientConnection
->close();
3211 ClientHttpRequest
**H
;
3212 clientStreamNode
*node
;
3213 ClientHttpRequest
*http
= parseHttpRequestAbort(this, "error:Connection%20lifetime%20expired");
3214 node
= http
->client_stream
.tail
->prev
->data
;
3215 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3216 assert (repContext
);
3217 repContext
->setReplyToError(ERR_LIFETIME_EXP
,
3218 HTTP_REQUEST_TIMEOUT
, METHOD_NONE
, "N/A", &peer
.sin_addr
,
3220 /* No requests can be outstanded */
3221 assert(chr
== NULL
);
3222 /* add to the client request queue */
3224 for (H
= &chr
; *H
; H
= &(*H
)->next
);
3227 clientStreamRead(http
->client_stream
.tail
->data
, http
, 0,
3228 HTTP_REQBUF_SZ
, context
->reqbuf
);
3231 * if we don't close() here, we still need a timeout handler!
3233 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3234 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3235 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3236 commSetConnTimeout(io
.conn
, 30, timeoutCall
);
3239 * Aha, but we don't want a read handler!
3241 Comm::SetSelect(io
.fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3246 * Just close the connection to not confuse browsers
3247 * using persistent connections. Some browsers opens
3248 * an connection and then does not use it until much
3249 * later (presumeably because the request triggering
3250 * the open has already been completed on another
3253 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
))
3270 connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
)
3272 ConnStateData
*result
= new ConnStateData
;
3274 result
->clientConnection
= client
;
3275 result
->log_addr
= client
->remote
;
3276 result
->log_addr
.ApplyMask(Config
.Addrs
.client_netmask
);
3277 result
->in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &result
->in
.allocatedSize
);
3278 result
->port
= cbdataReference(port
);
3280 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3281 (result
->transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3282 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3283 int i
= IP_PMTUDISC_DONT
;
3284 setsockopt(client
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof i
);
3286 static int reported
= 0;
3289 debugs(33, DBG_IMPORTANT
, "Notice: httpd_accel_no_pmtu_disc not supported on your platform");
3295 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3296 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, result
, ConnStateData::connStateClosed
);
3297 comm_add_close_handler(client
->fd
, call
);
3299 if (Config
.onoff
.log_fqdn
)
3300 fqdncache_gethostbyaddr(client
->remote
, FQDN_LOOKUP_IF_MISS
);
3303 if (Ident::TheConfig
.identLookup
) {
3304 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3305 identChecklist
.src_addr
= client
->remote
;
3306 identChecklist
.my_addr
= client
->local
;
3307 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3308 Ident::Start(client
, clientIdentDone
, result
);
3313 if (Eui::TheConfig
.euiLookup
) {
3314 if (client
->remote
.IsIPv4()) {
3315 result
->clientConnection
->remoteEui48
.lookup(client
->remote
);
3316 } else if (client
->remote
.IsIPv6()) {
3317 result
->clientConnection
->remoteEui64
.lookup(client
->remote
);
3322 clientdbEstablished(client
->remote
, 1);
3324 result
->flags
.readMore
= true;
3328 /** Handle a new connection on HTTP socket. */
3330 httpAccept(const CommAcceptCbParams
¶ms
)
3332 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3334 if (params
.flag
!= COMM_OK
) {
3335 // Its possible the call was still queued when the client disconnected
3336 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3340 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3341 fd_note(params
.conn
->fd
, "client http connect");
3343 if (s
->tcp_keepalive
.enabled
) {
3344 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3347 ++ incoming_sockets_accepted
;
3349 // Socket is ready, setup the connection manager to start using it
3350 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3352 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3353 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3354 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3355 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3357 connState
->readSomeData();
3360 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3362 if (Config
.onoff
.client_db
) {
3363 /* it was said several times that client write limiter does not work if client_db is disabled */
3365 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3366 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3368 // TODO: we check early to limit error response bandwith but we
3369 // should recheck when we can honor delay_pool_uses_indirect
3370 // TODO: we should also pass the port details for myportname here.
3371 ch
.src_addr
= params
.conn
->remote
;
3372 ch
.my_addr
= params
.conn
->local
;
3374 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3376 /* pools require explicit 'allow' to assign a client into them */
3377 if (pools
[pool
].access
) {
3378 ch
.accessList
= pools
[pool
].access
;
3379 allow_t answer
= ch
.fastCheck();
3380 if (answer
== ACCESS_ALLOWED
) {
3382 /* request client information from db after we did all checks
3383 this will save hash lookup if client failed checks */
3384 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3387 /* put client info in FDE */
3388 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3390 /* setup write limiter for this request */
3391 const double burst
= floor(0.5 +
3392 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3393 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3396 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3406 /** Create SSL connection structure and update fd_table */
3408 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3410 SSL
*ssl
= SSL_new(sslContext
);
3413 const int ssl_error
= ERR_get_error();
3414 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3419 SSL_set_fd(ssl
, conn
->fd
);
3420 fd_table
[conn
->fd
].ssl
= ssl
;
3421 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3422 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3424 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3425 fd_note(conn
->fd
, "client https start");
3430 /** negotiate an SSL connection */
3432 clientNegotiateSSL(int fd
, void *data
)
3434 ConnStateData
*conn
= (ConnStateData
*)data
;
3436 SSL
*ssl
= fd_table
[fd
].ssl
;
3439 if ((ret
= SSL_accept(ssl
)) <= 0) {
3440 int ssl_error
= SSL_get_error(ssl
, ret
);
3442 switch (ssl_error
) {
3444 case SSL_ERROR_WANT_READ
:
3445 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3448 case SSL_ERROR_WANT_WRITE
:
3449 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3452 case SSL_ERROR_SYSCALL
:
3455 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3461 if (errno
== ECONNRESET
)
3464 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3465 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3472 case SSL_ERROR_ZERO_RETURN
:
3473 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3478 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3479 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3480 " (" << ssl_error
<< "/" << ret
<< ")");
3488 if (SSL_session_reused(ssl
)) {
3489 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3490 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3492 if (do_debug(83, 4)) {
3493 /* Write out the SSL session details.. actually the call below, but
3494 * OpenSSL headers do strange typecasts confusing GCC.. */
3495 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3496 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3497 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
);
3499 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3501 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3502 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3503 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3504 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3505 * Because there are two possible usable cast, if you get an error here, try the other
3506 * commented line. */
3508 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3509 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3513 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3516 /* Note: This does not automatically fflush the log file.. */
3519 debugs(83, 2, "clientNegotiateSSL: New session " <<
3520 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3521 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3525 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3526 SSL_get_cipher(ssl
));
3528 client_cert
= SSL_get_peer_certificate(ssl
);
3530 if (client_cert
!= NULL
) {
3531 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3532 " client certificate: subject: " <<
3533 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3535 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3536 " client certificate: issuer: " <<
3537 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3539 X509_free(client_cert
);
3541 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3542 " has no certificate.");
3545 conn
->readSomeData();
3549 * If SSL_CTX is given, starts reading the SSL handshake.
3550 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3553 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3557 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3559 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3562 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3563 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3564 connState
, ConnStateData::requestTimeout
);
3565 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3568 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3570 char buf
[MAX_IPSTRLEN
];
3571 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3572 HttpRequest
*fakeRequest
= new HttpRequest
;
3573 fakeRequest
->SetHost(details
->local
.NtoA(buf
, sizeof(buf
)));
3574 fakeRequest
->port
= details
->local
.GetPort();
3575 fakeRequest
->clientConnectionManager
= connState
;
3576 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3577 #if FOLLOW_X_FORWARDED_FOR
3578 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3580 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3581 fakeRequest
->flags
.spoof_client_ip
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3582 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3583 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3584 connState
->switchToHttps(fakeRequest
, bumpMode
);
3589 * A callback function to use with the ACLFilledChecklist callback.
3590 * In the case of ACCES_ALLOWED answer initializes a bumped SSL connection,
3591 * else reverts the connection to tunnel mode.
3594 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3596 ConnStateData
*connState
= (ConnStateData
*) data
;
3598 // if the connection is closed or closing, just return.
3599 if (!connState
->isOpen())
3602 // Require both a match and a positive bump mode to work around exceptional
3603 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3604 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3605 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3606 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3607 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3609 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3610 connState
->sslBumpMode
= Ssl::bumpNone
;
3612 // fake a CONNECT request to force connState to tunnel
3613 static char ip
[MAX_IPSTRLEN
];
3614 static char reqStr
[MAX_IPSTRLEN
+ 80];
3615 connState
->clientConnection
->local
.NtoA(ip
, sizeof(ip
));
3616 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s:%d HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, connState
->clientConnection
->local
.GetPort(), ip
);
3617 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3619 ret
= connState
->clientParseRequests();
3622 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3623 connState
->clientConnection
->close();
3628 /** handle a new HTTPS connection */
3630 httpsAccept(const CommAcceptCbParams
¶ms
)
3632 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3634 if (params
.flag
!= COMM_OK
) {
3635 // Its possible the call was still queued when the client disconnected
3636 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3640 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3641 fd_note(params
.conn
->fd
, "client https connect");
3643 if (s
->tcp_keepalive
.enabled
) {
3644 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3647 ++incoming_sockets_accepted
;
3649 // Socket is ready, setup the connection manager to start using it
3650 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3653 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3655 if (!Config
.accessList
.ssl_bump
) {
3656 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3660 // Create a fake HTTP request for ssl_bump ACL check,
3661 // using tproxy/intercept provided destination IP and port.
3662 HttpRequest
*request
= new HttpRequest();
3663 static char ip
[MAX_IPSTRLEN
];
3664 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3665 request
->SetHost(params
.conn
->local
.NtoA(ip
, sizeof(ip
)));
3666 request
->port
= params
.conn
->local
.GetPort();
3667 request
->myportname
= s
->name
;
3669 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3670 acl_checklist
->src_addr
= params
.conn
->remote
;
3671 acl_checklist
->my_addr
= s
->s
;
3672 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3675 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3676 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3681 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, char *reply
)
3683 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3684 state_data
->sslCrtdHandleReply(reply
);
3688 ConnStateData::sslCrtdHandleReply(const char * reply
)
3691 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper return <NULL> reply");
3693 Ssl::CrtdMessage reply_message
;
3694 if (reply_message
.parse(reply
, strlen(reply
)) != Ssl::CrtdMessage::OK
) {
3695 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3697 if (reply_message
.getCode() != "OK") {
3698 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3700 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3701 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3702 getSslContextDone(ctx
, true);
3707 getSslContextDone(NULL
);
3710 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3712 certProperties
.commonName
= sslCommonName
.defined() ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3714 // fake certificate adaptation requires bump-server-first mode
3715 if (!sslServerBump
) {
3716 assert(port
->signingCert
.get());
3717 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3718 if (port
->signPkey
.get())
3719 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3720 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3724 // In case of an error while connecting to the secure server, use a fake
3725 // trusted certificate, with no mimicked fields and no adaptation
3726 // algorithms. There is nothing we can mimic so we want to minimize the
3727 // number of warnings the user will have to see to get to the error page.
3728 assert(sslServerBump
->entry
);
3729 if (sslServerBump
->entry
->isEmpty()) {
3730 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3731 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3733 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
,
3734 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3735 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3737 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3738 // If the algorithm already set, then ignore it.
3739 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3740 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3741 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3744 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3745 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3746 const char *param
= ca
->param
;
3748 // For parameterless CN adaptation, use hostname from the
3750 if (ca
->alg
== Ssl::algSetCommonName
) {
3752 param
= sslConnectHostOrIp
.termedBuf();
3753 certProperties
.commonName
= param
;
3754 certProperties
.setCommonName
= true;
3755 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3756 certProperties
.setValidAfter
= true;
3757 else if (ca
->alg
== Ssl::algSetValidBefore
)
3758 certProperties
.setValidBefore
= true;
3760 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3761 alg
<< " param: " << (param
? param
: "-"));
3765 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3766 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3767 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3768 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3772 } else {// if (!sslServerBump->entry->isEmpty())
3773 // Use trusted certificate for a Squid-generated error
3774 // or the user would have to add a security exception
3775 // just to see the error page. We will close the connection
3776 // so that the trust is not extended to non-Squid content.
3777 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3780 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3782 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3783 assert(port
->untrustedSigningCert
.get());
3784 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3785 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3787 assert(port
->signingCert
.get());
3788 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3790 if (port
->signPkey
.get())
3791 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3793 signAlgorithm
= certProperties
.signAlgorithm
;
3797 ConnStateData::getSslContextStart()
3799 assert(areAllContextsForThisConnection());
3801 /* careful: freeAllContexts() above frees request, host, etc. */
3803 if (port
->generateHostCertificates
) {
3804 Ssl::CertificateProperties certProperties
;
3805 buildSslCertGenerationParams(certProperties
);
3806 sslBumpCertKey
= certProperties
.dbKey().c_str();
3807 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3809 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3810 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3811 SSL_CTX
* dynCtx
= ssl_ctx_cache
.find(sslBumpCertKey
.termedBuf());
3813 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3814 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3815 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3816 getSslContextDone(dynCtx
);
3819 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3820 ssl_ctx_cache
.remove(sslBumpCertKey
.termedBuf());
3823 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3828 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3829 Ssl::CrtdMessage request_message
;
3830 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3831 request_message
.composeRequest(certProperties
);
3832 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3833 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3835 } catch (const std::exception
&e
) {
3836 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3837 "request for " << certProperties
.commonName
<<
3838 " certificate: " << e
.what() << "; will now block to " <<
3839 "generate that certificate.");
3840 // fall through to do blocking in-process generation.
3842 #endif // USE_SSL_CRTD
3844 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3845 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3846 getSslContextDone(dynCtx
, true);
3849 getSslContextDone(NULL
);
3853 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3855 // Try to add generated ssl context to storage.
3856 if (port
->generateHostCertificates
&& isNew
) {
3858 if (signAlgorithm
== Ssl::algSignTrusted
)
3859 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3860 //else it is self-signed or untrusted do not attrach any certificate
3862 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3863 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3865 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), sslContext
)) {
3866 // If it is not in storage delete after using. Else storage deleted it.
3867 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3870 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3874 // If generated ssl context = NULL, try to use static ssl context.
3876 if (!port
->staticSslContext
) {
3877 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3878 clientConnection
->close();
3881 debugs(33, 5, HERE
<< "Using static ssl context.");
3882 sslContext
= port
->staticSslContext
.get();
3887 if (!(ssl
= httpsCreate(clientConnection
, sslContext
)))
3890 // commSetConnTimeout() was called for this request before we switched.
3892 // Disable the client read handler until peer selection is complete
3893 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3894 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3895 switchedToHttps_
= true;
3899 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3901 assert(!switchedToHttps_
);
3903 sslConnectHostOrIp
= request
->GetHost();
3904 sslCommonName
= request
->GetHost();
3906 // We are going to read new request
3907 flags
.readMore
= true;
3908 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3910 // If sslServerBump is set, then we have decided to deny CONNECT
3911 // and now want to switch to SSL to send the error to the client
3912 // without even peeking at the origin server certificate.
3913 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3914 request
->flags
.sslPeek
= 1;
3915 sslServerBump
= new Ssl::ServerBump(request
);
3917 // will call httpsPeeked() with certificate and connection, eventually
3918 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
);
3922 // otherwise, use sslConnectHostOrIp
3923 getSslContextStart();
3927 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3929 Must(sslServerBump
!= NULL
);
3931 if (Comm::IsConnOpen(serverConnection
)) {
3932 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3934 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3935 assert(serverCert
.get() != NULL
);
3936 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
3937 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
3938 " bumped: " << *serverConnection
);
3940 pinConnection(serverConnection
, NULL
, NULL
, false);
3942 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3944 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3945 Ip::Address intendedDest
;
3946 intendedDest
= sslConnectHostOrIp
.termedBuf();
3947 const bool isConnectRequest
= !port
->spoof_client_ip
&& !port
->intercepted
;
3949 // Squid serves its own error page and closes, so we want
3950 // a CN that causes no additional browser errors. Possible
3951 // only when bumping CONNECT with a user-typed address.
3952 if (intendedDest
.IsAnyAddr() || isConnectRequest
)
3953 sslCommonName
= sslConnectHostOrIp
;
3954 else if (sslServerBump
->serverCert
.get())
3955 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
3957 // copy error detail from bump-server-first request to CONNECT request
3958 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
3959 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3962 getSslContextStart();
3965 #endif /* USE_SSL */
3967 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3969 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3971 if (!Comm::IsConnOpen(c
)) {
3972 Must(NHttpSockets
> 0); // we tried to open some
3973 --NHttpSockets
; // there will be fewer sockets than planned
3974 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3976 if (!NHttpSockets
) // we could not open any listen sockets at all
3977 fatalf("Unable to open %s",FdNote(portType
));
3984 /// find any unused HttpSockets[] slot and store fd there or return false
3986 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
3989 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
3990 if ((found
= HttpSockets
[i
] < 0))
3991 HttpSockets
[i
] = conn
->fd
;
3997 clientHttpConnectionsOpen(void)
3999 AnyP::PortCfg
*s
= NULL
;
4001 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4002 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4003 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4004 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4009 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4010 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4014 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4015 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4019 // Create ssl_ctx cache for this port.
4020 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4024 // Fill out a Comm::Connection which IPC will open as a listener for us
4025 // then pass back when active so we can start a TcpAcceptor subscription.
4026 s
->listenConn
= new Comm::Connection
;
4027 s
->listenConn
->local
= s
->s
;
4028 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) | (s
->intercepted
? COMM_INTERCEPTION
: 0);
4030 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4031 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4032 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4033 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4035 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4036 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4037 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4039 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4046 clientHttpsConnectionsOpen(void)
4050 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4051 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4052 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4053 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4057 if (!s
->staticSslContext
) {
4058 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4059 " due to SSL initialization failure.");
4063 // TODO: merge with similar code in clientHttpConnectionsOpen()
4064 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4065 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4069 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4070 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4075 // Create ssl_ctx cache for this port.
4076 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4079 // Fill out a Comm::Connection which IPC will open as a listener for us
4080 s
->listenConn
= new Comm::Connection
;
4081 s
->listenConn
->local
= s
->s
;
4082 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) |
4083 (s
->intercepted
? COMM_INTERCEPTION
: 0);
4085 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4086 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4087 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4088 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4090 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4091 ListeningStartedDialer(&clientListenerConnectionOpened
,
4092 s
, Ipc::fdnHttpsSocket
, sub
));
4093 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4094 HttpSockets
[NHttpSockets
] = -1;
4100 /// process clientHttpConnectionsOpen result
4102 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4104 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4108 Must(Comm::IsConnOpen(s
->listenConn
));
4110 // TCP: setup a job to handle accept() with subscribed handler
4111 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4113 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4114 (s
->intercepted
? "NAT intercepted " : "") <<
4115 (s
->spoof_client_ip
? "TPROXY spoofing " : "") <<
4116 (s
->sslBump
? "SSL bumped " : "") <<
4117 (s
->accel
? "reverse-proxy " : "")
4118 << FdNote(portTypeNote
) << " connections at "
4121 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4125 clientOpenListenSockets(void)
4127 clientHttpConnectionsOpen();
4129 clientHttpsConnectionsOpen();
4132 if (NHttpSockets
< 1)
4133 fatal("No HTTP or HTTPS ports configured");
4137 clientHttpConnectionsClose(void)
4139 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4140 if (s
->listenConn
!= NULL
) {
4141 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4142 s
->listenConn
->close();
4143 s
->listenConn
= NULL
;
4148 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4149 if (s
->listenConn
!= NULL
) {
4150 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4151 s
->listenConn
->close();
4152 s
->listenConn
= NULL
;
4157 // TODO see if we can drop HttpSockets array entirely */
4158 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4159 HttpSockets
[i
] = -1;
4166 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4168 const char *vary
= request
->vary_headers
;
4169 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4170 #if X_ACCELERATOR_VARY
4173 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4176 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4178 /* Oops... something odd is going on here.. */
4179 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4180 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4181 safe_free(request
->vary_headers
);
4186 /* This is not a varying object */
4190 /* virtual "vary" object found. Calculate the vary key and
4191 * continue the search
4193 vary
= httpMakeVaryMark(request
, entry
->getReply());
4196 request
->vary_headers
= xstrdup(vary
);
4199 /* Ouch.. we cannot handle this kind of variance */
4200 /* XXX This cannot really happen, but just to be complete */
4205 vary
= httpMakeVaryMark(request
, entry
->getReply());
4208 request
->vary_headers
= xstrdup(vary
);
4212 /* Ouch.. we cannot handle this kind of variance */
4213 /* XXX This cannot really happen, but just to be complete */
4215 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4218 /* Oops.. we have already been here and still haven't
4219 * found the requested variant. Bail out
4221 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4222 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4228 ACLFilledChecklist
*
4229 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4231 ConnStateData
* conn
= http
->getConn();
4232 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4233 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4236 * hack for ident ACL. It needs to get full addresses, and a place to store
4237 * the ident result on persistent connections...
4239 /* connection oriented auth also needs these two lines for it's operation. */
4243 CBDATA_CLASS_INIT(ConnStateData
);
4245 ConnStateData::ConnStateData() :
4246 AsyncJob("ConnStateData"),
4248 sslBumpMode(Ssl::bumpEnd
),
4249 switchedToHttps_(false),
4250 sslServerBump(NULL
),
4252 stoppedSending_(NULL
),
4253 stoppedReceiving_(NULL
)
4255 pinning
.pinned
= false;
4256 pinning
.auth
= false;
4260 ConnStateData::transparent() const
4262 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4266 ConnStateData::reading() const
4268 return reader
!= NULL
;
4272 ConnStateData::stopReading()
4275 comm_read_cancel(clientConnection
->fd
, reader
);
4281 ConnStateData::expectRequestBody(int64_t size
)
4283 bodyPipe
= new BodyPipe(this);
4285 bodyPipe
->setBodySize(size
);
4287 startDechunkingRequest();
4292 ConnStateData::mayNeedToReadMoreBody() const
4295 return 0; // request without a body or read/produced all body bytes
4297 if (!bodyPipe
->bodySizeKnown())
4298 return -1; // probably need to read more, but we cannot be sure
4300 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4301 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4303 if (needToProduce
<= haveAvailable
)
4304 return 0; // we have read what we need (but are waiting for pipe space)
4306 return needToProduce
- haveAvailable
;
4310 ConnStateData::stopReceiving(const char *error
)
4312 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4313 "; old sending error: " <<
4314 (stoppedSending() ? stoppedSending_
: "none"));
4316 if (const char *oldError
= stoppedReceiving()) {
4317 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4318 return; // nothing has changed as far as this connection is concerned
4321 stoppedReceiving_
= error
;
4323 if (const char *sendError
= stoppedSending()) {
4324 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4325 clientConnection
->close();
4330 ConnStateData::expectNoForwarding()
4332 if (bodyPipe
!= NULL
) {
4333 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4334 bodyPipe
->expectNoConsumption();
4338 /// initialize dechunking state
4340 ConnStateData::startDechunkingRequest()
4342 Must(bodyPipe
!= NULL
);
4343 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4344 assert(!in
.bodyParser
);
4345 in
.bodyParser
= new ChunkedCodingParser
;
4348 /// put parsed content into input buffer and clean up
4350 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4352 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4354 if (bodyPipe
!= NULL
) {
4355 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4356 BodyPipe::Pointer myPipe
= bodyPipe
;
4357 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4358 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4360 Must(myPipe
->bodySizeKnown());
4361 ClientSocketContext::Pointer context
= getCurrentContext();
4362 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4363 context
->http
->request
->setContentLength(myPipe
->bodySize());
4367 delete in
.bodyParser
;
4368 in
.bodyParser
= NULL
;
4372 ConnStateData::In::addressToReadInto() const
4374 return buf
+ notYetUsed
;
4377 ConnStateData::In::In() : bodyParser(NULL
),
4378 buf (NULL
), notYetUsed (0), allocatedSize (0)
4381 ConnStateData::In::~In()
4384 memFreeBuf(allocatedSize
, buf
);
4385 delete bodyParser
; // TODO: pool
4389 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4392 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4396 ClientSocketContext::Pointer context
= getCurrentContext();
4397 if (context
!= NULL
) {
4398 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4402 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4403 clientConnection
->close();
4406 /// Our close handler called by Comm when the pinned connection is closed
4408 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4410 // FwdState might repin a failed connection sooner than this close
4411 // callback is called for the failed connection.
4412 if (pinning
.serverConnection
== io
.conn
) {
4413 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4419 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, struct peer
*aPeer
, bool auth
)
4421 char desc
[FD_DESC_SZ
];
4423 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4424 if (pinning
.serverConnection
->fd
== pinServer
->fd
)
4428 unpinConnection(); // closes pinned connection, if any, and resets fields
4430 pinning
.serverConnection
= pinServer
;
4432 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4434 // when pinning an SSL bumped connection, the request may be NULL
4435 const char *pinnedHost
= "[unknown]";
4437 pinning
.host
= xstrdup(request
->GetHost());
4438 pinning
.port
= request
->port
;
4439 pinnedHost
= pinning
.host
;
4441 pinning
.port
= pinServer
->remote
.GetPort();
4443 pinning
.pinned
= true;
4445 pinning
.peer
= cbdataReference(aPeer
);
4446 pinning
.auth
= auth
;
4447 char stmp
[MAX_IPSTRLEN
];
4448 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4449 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4450 clientConnection
->remote
.ToURL(stmp
,MAX_IPSTRLEN
),
4451 clientConnection
->fd
);
4452 fd_note(pinning
.serverConnection
->fd
, desc
);
4454 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4455 pinning
.closeHandler
= JobCallback(33, 5,
4456 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4457 // remember the pinned connection so that cb does not unpin a fresher one
4458 typedef CommCloseCbParams Params
;
4459 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4460 params
.conn
= pinning
.serverConnection
;
4461 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4464 const Comm::ConnectionPointer
4465 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const struct peer
*aPeer
)
4467 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4470 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4472 if (pinning
.auth
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0) {
4475 if (request
&& pinning
.port
!= request
->port
) {
4478 if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
)) {
4481 if (aPeer
!= pinning
.peer
) {
4486 /* The pinning info is not safe, remove any pinning info */
4490 return pinning
.serverConnection
;
4494 ConnStateData::unpinConnection()
4496 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4499 cbdataReferenceDone(pinning
.peer
);
4501 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4502 if (pinning
.closeHandler
!= NULL
) {
4503 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4504 pinning
.closeHandler
= NULL
;
4506 /// also close the server side socket, we should not use it for any future requests...
4507 // TODO: do not close if called from our close handler?
4508 pinning
.serverConnection
->close();
4511 safe_free(pinning
.host
);
4513 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4514 * connection has gone away */