4 * DEBUG: section 33 Client-side Routines
5 * AUTHOR: Duane Wessels
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
36 \defgroup ClientSide Client-Side Logics
38 \section cserrors Errors and client side
40 \par Problem the first:
41 * the store entry is no longer authoritative on the
42 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
43 * of client_side_reply.c.
44 * Problem the second: resources are wasted if we delay in cleaning up.
45 * Problem the third we can't depend on a connection close to clean up.
47 \par Nice thing the first:
48 * Any step in the stream can callback with data
49 * representing an error.
50 * Nice thing the second: once you stop requesting reads from upstream,
51 * upstream can be stopped too.
54 * Error has a callback mechanism to hand over a membuf
55 * with the error content. The failing node pushes that back as the
56 * reply. Can this be generalised to reduce duplicate efforts?
57 * A: Possibly. For now, only one location uses this.
58 * How to deal with pre-stream errors?
59 * Tell client_side_reply that we *want* an error page before any
60 * stream calls occur. Then we simply read as normal.
63 \section pconn_logic Persistent connection logic:
66 * requests (httpClientRequest structs) get added to the connection
67 * list, with the current one being chr
70 * The request is *immediately* kicked off, and data flows through
71 * to clientSocketRecipient.
74 * If the data that arrives at clientSocketRecipient is not for the current
75 * request, clientSocketRecipient simply returns, without requesting more
76 * data, or sending it.
79 * ClientKeepAliveNextRequest will then detect the presence of data in
80 * the next ClientHttpRequest, and will send it, restablishing the
85 #include "acl/FilledChecklist.h"
86 #include "anyp/PortCfg.h"
87 #include "base/Subscription.h"
88 #include "base/TextException.h"
89 #include "ChunkedCodingParser.h"
90 #include "client_db.h"
91 #include "client_side_reply.h"
92 #include "client_side_request.h"
93 #include "client_side.h"
94 #include "ClientRequestContext.h"
95 #include "clientStream.h"
97 #include "comm/Connection.h"
98 #include "comm/Loops.h"
99 #include "comm/TcpAcceptor.h"
100 #include "comm/Write.h"
101 #include "CommCalls.h"
102 #include "errorpage.h"
103 #include "eui/Config.h"
107 #include "fqdncache.h"
109 #include "HttpHdrContRange.h"
110 #include "HttpHeaderTools.h"
111 #include "HttpReply.h"
112 #include "HttpRequest.h"
113 #include "ident/Config.h"
114 #include "ident/Ident.h"
115 #include "internal.h"
116 #include "ipc/FdNotes.h"
117 #include "ipc/StartListening.h"
118 #include "log/access_log.h"
121 #include "MemObject.h"
122 #include "profiler/Profiler.h"
125 #include "SquidTime.h"
126 #include "StatCounters.h"
127 #include "StatHist.h"
129 #include "TimeOrTag.h"
134 #include "auth/UserRequest.h"
137 #include "ClientInfo.h"
140 #include "ssl/context_storage.h"
141 #include "ssl/helper.h"
142 #include "ssl/ServerBump.h"
143 #include "ssl/support.h"
144 #include "ssl/gadgets.h"
147 #include "ssl/crtd_message.h"
148 #include "ssl/certificate_db.h"
162 #define comm_close comm_lingering_close
165 /// dials clientListenerConnectionOpened call
166 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
169 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
170 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
171 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
173 virtual void print(std::ostream
&os
) const {
175 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
178 virtual bool canDial(AsyncCall
&) const { return true; }
179 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
185 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
186 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
187 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
190 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
192 /* our socket-related context */
194 CBDATA_CLASS_INIT(ClientSocketContext
);
197 ClientSocketContext::operator new (size_t byteCount
)
199 /* derived classes with different sizes must implement their own new */
200 assert (byteCount
== sizeof (ClientSocketContext
));
201 CBDATA_INIT_TYPE(ClientSocketContext
);
202 return cbdataAlloc(ClientSocketContext
);
206 ClientSocketContext::operator delete (void *address
)
208 cbdataFree (address
);
211 /* Local functions */
212 /* ClientSocketContext */
213 static ClientSocketContext
*ClientSocketContextNew(const Comm::ConnectionPointer
&clientConn
, ClientHttpRequest
*);
215 static IOCB clientWriteComplete
;
216 static IOCB clientWriteBodyComplete
;
217 static IOACB httpAccept
;
219 static IOACB httpsAccept
;
221 static CTCB clientLifetimeTimeout
;
222 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
223 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, HttpVersion
*);
225 static IDCB clientIdentDone
;
227 static CSCB clientSocketRecipient
;
228 static CSD clientSocketDetach
;
229 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
230 static int clientIsContentLengthValid(HttpRequest
* r
);
231 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
233 static void clientUpdateStatHistCounters(log_type logType
, int svc_time
);
234 static void clientUpdateStatCounters(log_type logType
);
235 static void clientUpdateHierCounters(HierarchyLogEntry
*);
236 static bool clientPingHasFinished(ping_data
const *aPing
);
237 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
239 static bool connIsUsable(ConnStateData
* conn
);
241 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
242 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
243 static void clientUpdateSocketStats(log_type logType
, size_t size
);
245 char *skipLeadingSpace(char *aString
);
246 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
248 static ConnStateData
*connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
);
251 ClientSocketContext::getTail() const
253 if (http
->client_stream
.tail
)
254 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
260 ClientSocketContext::getClientReplyContext() const
262 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
266 * This routine should be called to grow the inbuf and then
270 ConnStateData::readSomeData()
275 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
277 if (!maybeMakeSpaceAvailable())
280 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
281 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
282 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
286 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
288 ClientSocketContext::Pointer
*tempContextPointer
;
289 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
290 assert(conn
->getCurrentContext() != NULL
);
291 /* Unlink us from the connection request list */
292 tempContextPointer
= & conn
->currentobject
;
294 while (tempContextPointer
->getRaw()) {
295 if (*tempContextPointer
== this)
298 tempContextPointer
= &(*tempContextPointer
)->next
;
301 assert(tempContextPointer
->getRaw() != NULL
);
302 *tempContextPointer
= next
;
306 ClientSocketContext::~ClientSocketContext()
308 clientStreamNode
*node
= getTail();
311 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
314 /* We are *always* the tail - prevent recursive free */
315 assert(this == streamContext
);
321 deRegisterWithConn();
323 httpRequestFree(http
);
325 /* clean up connection links to us */
326 assert(this != next
.getRaw());
330 ClientSocketContext::registerWithConn()
332 assert (!connRegistered_
);
334 assert (http
->getConn() != NULL
);
335 connRegistered_
= true;
336 http
->getConn()->addContextToQueue(this);
340 ClientSocketContext::deRegisterWithConn()
342 assert (connRegistered_
);
343 removeFromConnectionList(http
->getConn());
344 connRegistered_
= false;
348 ClientSocketContext::connIsFinished()
351 assert (http
->getConn() != NULL
);
352 deRegisterWithConn();
353 /* we can't handle any more stream data - detach */
354 clientStreamDetach(getTail(), http
);
357 ClientSocketContext::ClientSocketContext() : http(NULL
), reply(NULL
), next(NULL
),
359 mayUseConnection_ (false),
360 connRegistered_ (false)
362 memset (reqbuf
, '\0', sizeof (reqbuf
));
365 deferredparams
.node
= NULL
;
366 deferredparams
.rep
= NULL
;
369 ClientSocketContext
*
370 ClientSocketContextNew(const Comm::ConnectionPointer
&client
, ClientHttpRequest
* http
)
372 ClientSocketContext
*newContext
;
373 assert(http
!= NULL
);
374 newContext
= new ClientSocketContext
;
375 newContext
->http
= http
;
376 newContext
->clientConnection
= client
;
381 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
383 HttpReply
*rep
= msg
.reply
;
386 // apply selected clientReplyContext::buildReplyHeader() mods
387 // it is not clear what headers are required for control messages
388 rep
->header
.removeHopByHopEntries();
389 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
390 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
392 // remember the callback
393 cbControlMsgSent
= msg
.cbSuccess
;
395 MemBuf
*mb
= rep
->pack();
397 debugs(11, 2, "HTTP Client " << clientConnection
);
398 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
400 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
401 CommIoCbPtrFun(&WroteControlMsg
, this));
402 Comm::Write(clientConnection
, mb
, call
);
407 /// called when we wrote the 1xx response
409 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
411 if (errflag
== COMM_ERR_CLOSING
)
414 if (errflag
== COMM_OK
) {
415 ScheduleCallHere(cbControlMsgSent
);
419 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
420 // no error notification: see HttpControlMsg.h for rationale and
421 // note that some errors are detected elsewhere (e.g., close handler)
423 // close on 1xx errors to be conservative and to simplify the code
424 // (if we do not close, we must notify the source of a failure!)
428 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
430 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
432 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
433 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
438 clientIdentDone(const char *ident
, void *data
)
440 ConnStateData
*conn
= (ConnStateData
*)data
;
441 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
446 clientUpdateStatCounters(log_type logType
)
448 ++statCounter
.client_http
.requests
;
450 if (logTypeIsATcpHit(logType
))
451 ++statCounter
.client_http
.hits
;
453 if (logType
== LOG_TCP_HIT
)
454 ++statCounter
.client_http
.disk_hits
;
455 else if (logType
== LOG_TCP_MEM_HIT
)
456 ++statCounter
.client_http
.mem_hits
;
460 clientUpdateStatHistCounters(log_type logType
, int svc_time
)
462 statCounter
.client_http
.allSvcTime
.count(svc_time
);
464 * The idea here is not to be complete, but to get service times
465 * for only well-defined types. For example, we don't include
466 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
467 * (we *tried* to validate it, but failed).
472 case LOG_TCP_REFRESH_UNMODIFIED
:
473 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
476 case LOG_TCP_IMS_HIT
:
477 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
482 case LOG_TCP_MEM_HIT
:
484 case LOG_TCP_OFFLINE_HIT
:
485 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
490 case LOG_TCP_CLIENT_REFRESH_MISS
:
491 statCounter
.client_http
.missSvcTime
.count(svc_time
);
495 /* make compiler warnings go away */
501 clientPingHasFinished(ping_data
const *aPing
)
503 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
510 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
514 switch (someEntry
->code
) {
515 #if USE_CACHE_DIGESTS
520 ++ statCounter
.cd
.times_used
;
528 case FIRST_PARENT_MISS
:
530 case CLOSEST_PARENT_MISS
:
531 ++ statCounter
.icp
.times_used
;
532 i
= &someEntry
->ping
;
534 if (clientPingHasFinished(i
))
535 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
538 ++ statCounter
.icp
.query_timeouts
;
545 ++ statCounter
.netdb
.times_used
;
555 ClientHttpRequest::updateCounters()
557 clientUpdateStatCounters(logType
);
559 if (request
->errType
!= ERR_NONE
)
560 ++ statCounter
.client_http
.errors
;
562 clientUpdateStatHistCounters(logType
,
563 tvSubMsec(start_time
, current_time
));
565 clientUpdateHierCounters(&request
->hier
);
569 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
572 assert(aLogEntry
!= NULL
);
574 if (Config
.onoff
.log_mime_hdrs
) {
578 packerToMemInit(&p
, &mb
);
579 request
->header
.packInto(&p
);
580 //This is the request after adaptation or redirection
581 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
583 // the virgin request is saved to aLogEntry->request
584 if (aLogEntry
->request
) {
587 packerToMemInit(&p
, &mb
);
588 aLogEntry
->request
->header
.packInto(&p
);
589 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
593 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
597 packerToMemInit(&p
, &mb
);
598 ah
->lastMeta
.packInto(&p
);
599 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
608 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
610 aLogEntry
->icap
.processingTime
= ih
->processingTime();
613 aLogEntry
->http
.method
= request
->method
;
614 aLogEntry
->http
.version
= request
->http_ver
;
615 aLogEntry
->hier
= request
->hier
;
616 if (request
->content_length
> 0) // negative when no body or unknown length
617 aLogEntry
->cache
.requestSize
+= request
->content_length
;
618 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
621 if (request
->auth_user_request
!= NULL
) {
622 if (request
->auth_user_request
->username())
623 aLogEntry
->cache
.authuser
= xstrdup(request
->auth_user_request
->username());
627 // Adapted request, if any, inherits and then collects all the stats, but
628 // the virgin request gets logged instead; copy the stats to log them.
629 // TODO: avoid losses by keeping these stats in a shared history object?
630 if (aLogEntry
->request
) {
631 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
632 aLogEntry
->request
->errType
= request
->errType
;
633 aLogEntry
->request
->errDetail
= request
->errDetail
;
638 ClientHttpRequest::logRequest()
640 if (!out
.size
&& !logType
)
641 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
643 al
->icp
.opcode
= ICP_INVALID
;
645 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
648 al
->http
.code
= al
->reply
->sline
.status
;
649 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
650 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
651 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status
;
652 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
655 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
657 if (loggingEntry() && loggingEntry()->mem_obj
)
658 al
->cache
.objectSize
= loggingEntry()->contentLen();
660 al
->cache
.caddr
.SetNoAddr();
662 if (getConn() != NULL
) {
663 al
->cache
.caddr
= getConn()->log_addr
;
664 al
->cache
.port
= cbdataReference(getConn()->port
);
667 al
->cache
.requestSize
= req_sz
;
668 al
->cache
.requestHeadersSize
= req_sz
;
670 al
->cache
.replySize
= out
.size
;
671 al
->cache
.replyHeadersSize
= out
.headers_sz
;
673 al
->cache
.highOffset
= out
.offset
;
675 al
->cache
.code
= logType
;
677 al
->cache
.msec
= tvSubMsec(start_time
, current_time
);
680 prepareLogWithRequestDetails(request
, al
);
682 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
683 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
687 /* This is broken. Fails if the connection has been closed. Needs
688 * to snarf the ssl details some place earlier..
690 if (getConn() != NULL
)
691 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
695 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.log
, this);
698 checklist
->reply
= HTTPMSGLOCK(al
->reply
);
700 if (!Config
.accessList
.log
|| checklist
->fastCheck() == ACCESS_ALLOWED
) {
702 al
->adapted_request
= HTTPMSGLOCK(request
);
703 accessLogLog(al
, checklist
);
706 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
707 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
714 ClientHttpRequest::freeResources()
718 safe_free(redirect
.location
);
719 range_iter
.boundary
.clean();
720 HTTPMSGUNLOCK(request
);
722 if (client_stream
.tail
)
723 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
727 httpRequestFree(void *data
)
729 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
730 assert(http
!= NULL
);
735 ConnStateData::areAllContextsForThisConnection() const
737 assert(this != NULL
);
738 ClientSocketContext::Pointer context
= getCurrentContext();
740 while (context
.getRaw()) {
741 if (context
->http
->getConn() != this)
744 context
= context
->next
;
751 ConnStateData::freeAllContexts()
753 ClientSocketContext::Pointer context
;
755 while ((context
= getCurrentContext()).getRaw() != NULL
) {
756 assert(getCurrentContext() !=
757 getCurrentContext()->next
);
758 context
->connIsFinished();
759 assert (context
!= currentobject
);
763 /// propagates abort event to all contexts
765 ConnStateData::notifyAllContexts(int xerrno
)
767 typedef ClientSocketContext::Pointer CSCP
;
768 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
769 c
->noteIoError(xerrno
);
772 /* This is a handler normally called by comm_close() */
773 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
775 deleteThis("ConnStateData::connStateClosed");
778 // cleans up before destructor is called
780 ConnStateData::swanSong()
782 debugs(33, 2, HERE
<< clientConnection
);
783 flags
.readMore
= false;
784 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
785 assert(areAllContextsForThisConnection());
788 if (auth_user_request
!= NULL
) {
789 debugs(33, 4, "ConnStateData::swanSong: freeing auth_user_request '" << auth_user_request
<< "' (this is '" << this << "')");
790 auth_user_request
->onConnectionClose(this);
794 if (Comm::IsConnOpen(pinning
.serverConnection
))
795 pinning
.serverConnection
->close();
796 pinning
.serverConnection
= NULL
;
798 if (Comm::IsConnOpen(clientConnection
))
799 clientConnection
->close();
800 clientConnection
= NULL
;
802 BodyProducer::swanSong();
803 flags
.swanSang
= true;
807 ConnStateData::isOpen() const
809 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
810 Comm::IsConnOpen(clientConnection
) &&
811 !fd_table
[clientConnection
->fd
].closing();
814 ConnStateData::~ConnStateData()
816 assert(this != NULL
);
817 debugs(33, 3, HERE
<< clientConnection
);
820 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
823 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
825 cbdataReferenceDone(port
);
827 if (bodyPipe
!= NULL
)
828 stopProducingFor(bodyPipe
, false);
831 delete sslServerBump
;
836 * clientSetKeepaliveFlag() sets request->flags.proxy_keepalive.
837 * This is the client-side persistent connection flag. We need
838 * to set this relatively early in the request processing
839 * to handle hacks for broken servers and clients.
842 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
844 HttpRequest
*request
= http
->request
;
846 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
847 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
848 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
849 RequestMethodStr(request
->method
));
851 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
852 request
->flags
.proxy_keepalive
= request
->persistent() ? 1 : 0;
856 clientIsContentLengthValid(HttpRequest
* r
)
858 switch (r
->method
.id()) {
863 /* We do not want to see a request entity on GET/HEAD requests */
864 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
867 /* For other types of requests we don't care */
875 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
877 if (Config
.maxRequestBodySize
&&
878 bodyLength
> Config
.maxRequestBodySize
)
879 return 1; /* too large */
886 connIsUsable(ConnStateData
* conn
)
888 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
896 // careful: the "current" context may be gone if we wrote an early response
897 ClientSocketContext::Pointer
898 ConnStateData::getCurrentContext() const
901 return currentobject
;
905 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
907 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
908 assert(flags
.deferred
== 0);
910 deferredparams
.node
= node
;
911 deferredparams
.rep
= rep
;
912 deferredparams
.queuedBuffer
= receivedData
;
917 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
919 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
926 ClientSocketContext::startOfOutput() const
928 return http
->out
.size
== 0;
932 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
934 /*the size of available range can always fit in a size_t type*/
935 size_t maximum
= (size_t)available
.size();
937 if (!http
->request
->range
)
940 assert (canPackMoreRanges());
942 if (http
->range_iter
.debt() == -1)
945 assert (http
->range_iter
.debt() > 0);
947 /* TODO this + the last line could be a range intersection calculation */
948 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
951 return min(http
->range_iter
.debt(), (int64_t)maximum
);
955 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
957 http
->out
.offset
+= bytes
;
959 if (!http
->request
->range
)
962 if (http
->range_iter
.debt() != -1) {
963 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
964 assert (http
->range_iter
.debt() >= 0);
967 /* debt() always stops at -1, below that is a bug */
968 assert (http
->range_iter
.debt() >= -1);
972 ClientHttpRequest::multipartRangeRequest() const
974 return request
->multipartRangeRequest();
978 ClientSocketContext::multipartRangeRequest() const
980 return http
->multipartRangeRequest();
984 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
988 if (!multipartRangeRequest() && !http
->request
->flags
.chunked_reply
) {
989 size_t length
= lengthToSend(bodyData
.range());
990 noteSentBodyBytes (length
);
991 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
992 CommIoCbPtrFun(clientWriteBodyComplete
, this));
993 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
999 if (multipartRangeRequest())
1000 packRange(bodyData
, &mb
);
1002 packChunk(bodyData
, mb
);
1004 if (mb
.contentSize()) {
1006 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1007 CommIoCbPtrFun(clientWriteComplete
, this));
1008 Comm::Write(clientConnection
, &mb
, call
);
1010 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1014 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1015 * if bodyData is empty.
1018 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1020 const uint64_t length
=
1021 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1022 noteSentBodyBytes(length
);
1024 mb
.Printf("%" PRIX64
"\r\n", length
);
1025 mb
.append(bodyData
.data
, length
);
1029 /** put terminating boundary for multiparts */
1031 clientPackTermBound(String boundary
, MemBuf
* mb
)
1033 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1034 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1037 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1039 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1041 HttpHeader
hdr(hoReply
);
1047 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1048 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1049 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1051 /* stuff the header with required entries and pack it */
1053 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1054 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1056 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1058 packerToMemInit(&p
, mb
);
1066 /* append <crlf> (we packed a header, not a reply) */
1071 * extracts a "range" from *buf and appends them to mb, updating
1072 * all offsets and such.
1075 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1077 HttpHdrRangeIter
* i
= &http
->range_iter
;
1078 Range
<int64_t> available (source
.range());
1079 char const *buf
= source
.data
;
1081 while (i
->currentSpec() && available
.size()) {
1082 const size_t copy_sz
= lengthToSend(available
);
1086 * intersection of "have" and "need" ranges must not be empty
1088 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1089 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1092 * put boundary and headers at the beginning of a range in a
1096 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1097 assert(http
->memObject());
1099 http
->memObject()->getReply(), /* original reply */
1100 i
->currentSpec(), /* current range */
1101 i
->boundary
, /* boundary, the same for all */
1108 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1110 noteSentBodyBytes (copy_sz
);
1112 mb
->append(buf
, copy_sz
);
1117 available
.start
+= copy_sz
;
1123 if (!canPackMoreRanges()) {
1124 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1127 /* put terminating boundary for multiparts */
1128 clientPackTermBound(i
->boundary
, mb
);
1133 int64_t nextOffset
= getNextRangeOffset();
1135 assert (nextOffset
>= http
->out
.offset
);
1137 int64_t skip
= nextOffset
- http
->out
.offset
;
1139 /* adjust for not to be transmitted bytes */
1140 http
->out
.offset
= nextOffset
;
1142 if (available
.size() <= (uint64_t)skip
)
1145 available
.start
+= skip
;
1154 /** returns expected content length for multi-range replies
1155 * note: assumes that httpHdrRangeCanonize has already been called
1156 * warning: assumes that HTTP headers for individual ranges at the
1157 * time of the actuall assembly will be exactly the same as
1158 * the headers when clientMRangeCLen() is called */
1160 ClientHttpRequest::mRangeCLen()
1165 assert(memObject());
1168 HttpHdrRange::iterator pos
= request
->range
->begin();
1170 while (pos
!= request
->range
->end()) {
1171 /* account for headers for this range */
1173 clientPackRangeHdr(memObject()->getReply(),
1174 *pos
, range_iter
.boundary
, &mb
);
1177 /* account for range content */
1178 clen
+= (*pos
)->length
;
1180 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1184 /* account for the terminating boundary */
1187 clientPackTermBound(range_iter
.boundary
, &mb
);
1197 * returns true if If-Range specs match reply, false otherwise
1200 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1202 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1203 /* check for parsing falure */
1210 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1211 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1212 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1215 return 0; /* entity has no etag to compare with! */
1217 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1218 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1219 return 0; /* must use strong validator for sub-range requests */
1222 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1225 /* got modification time? */
1226 if (spec
.time
>= 0) {
1227 return http
->storeEntry()->lastmod
<= spec
.time
;
1230 assert(0); /* should not happen */
1235 * generates a "unique" boundary string for multipart responses
1236 * the caller is responsible for cleaning the string */
1238 ClientHttpRequest::rangeBoundaryStr() const
1242 String
b(APP_FULLNAME
);
1244 key
= storeEntry()->getMD5Text();
1245 b
.append(key
, strlen(key
));
1249 /** adds appropriate Range headers if needed */
1251 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1253 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1254 const char *range_err
= NULL
;
1255 HttpRequest
*request
= http
->request
;
1256 assert(request
->range
);
1257 /* check if we still want to do ranges */
1259 int64_t roffLimit
= request
->getRangeOffsetLimit();
1262 range_err
= "no [parse-able] reply";
1263 else if ((rep
->sline
.status
!= HTTP_OK
) && (rep
->sline
.status
!= HTTP_PARTIAL_CONTENT
))
1264 range_err
= "wrong status code";
1265 else if (hdr
->has(HDR_CONTENT_RANGE
))
1266 range_err
= "origin server does ranges";
1267 else if (rep
->content_length
< 0)
1268 range_err
= "unknown length";
1269 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1270 range_err
= "INCONSISTENT length"; /* a bug? */
1272 /* hits only - upstream peer determines correct behaviour on misses, and client_side_reply determines
1275 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1276 range_err
= "If-Range match failed";
1277 else if (!http
->request
->range
->canonize(rep
))
1278 range_err
= "canonization failed";
1279 else if (http
->request
->range
->isComplex())
1280 range_err
= "too complex range header";
1281 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1282 range_err
= "range outside range_offset_limit";
1284 /* get rid of our range specs on error */
1286 /* XXX We do this here because we need canonisation etc. However, this current
1287 * code will lead to incorrect store offset requests - the store will have the
1288 * offset data, but we won't be requesting it.
1289 * So, we can either re-request, or generate an error
1291 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1292 delete http
->request
->range
;
1293 http
->request
->range
= NULL
;
1295 /* XXX: TODO: Review, this unconditional set may be wrong. - TODO: review. */
1296 httpStatusLineSet(&rep
->sline
, rep
->sline
.version
,
1297 HTTP_PARTIAL_CONTENT
, NULL
);
1298 // web server responded with a valid, but unexpected range.
1299 // will (try-to) forward as-is.
1300 //TODO: we should cope with multirange request/responses
1301 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1302 request
->range
->contains(rep
->content_range
->spec
) :
1304 const int spec_count
= http
->request
->range
->specs
.count
;
1305 int64_t actual_clen
= -1;
1307 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1308 spec_count
<< " virgin clen: " << rep
->content_length
);
1309 assert(spec_count
> 0);
1310 /* append appropriate header(s) */
1312 if (spec_count
== 1) {
1313 if (!replyMatchRequest
) {
1314 hdr
->delById(HDR_CONTENT_RANGE
);
1315 hdr
->putContRange(rep
->content_range
);
1316 actual_clen
= rep
->content_length
;
1317 //http->range_iter.pos = rep->content_range->spec.begin();
1318 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1319 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1322 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1324 /* append Content-Range */
1326 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1327 /* No content range, so this was a full object we are
1330 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1333 /* set new Content-Length to the actual number of bytes
1334 * transmitted in the message-body */
1335 actual_clen
= (*pos
)->length
;
1339 /* generate boundary string */
1340 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1341 /* delete old Content-Type, add ours */
1342 hdr
->delById(HDR_CONTENT_TYPE
);
1343 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1344 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1345 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1346 /* Content-Length is not required in multipart responses
1347 * but it is always nice to have one */
1348 actual_clen
= http
->mRangeCLen();
1349 /* http->out needs to start where we want data at */
1350 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1353 /* replace Content-Length header */
1354 assert(actual_clen
>= 0);
1356 hdr
->delById(HDR_CONTENT_LENGTH
);
1358 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1360 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1362 /* And start the range iter off */
1363 http
->range_iter
.updateSpec();
1368 ClientSocketContext::prepareReply(HttpReply
* rep
)
1372 if (http
->request
->range
)
1373 buildRangeHeader(rep
);
1377 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1381 MemBuf
*mb
= rep
->pack();
1383 // dump now, so we dont output any body.
1384 debugs(11, 2, "HTTP Client " << clientConnection
);
1385 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1387 /* Save length of headers for persistent conn checks */
1388 http
->out
.headers_sz
= mb
->contentSize();
1391 headersLog(0, 0, http
->request
->method
, rep
);
1394 if (bodyData
.data
&& bodyData
.length
) {
1395 if (multipartRangeRequest())
1396 packRange(bodyData
, mb
);
1397 else if (http
->request
->flags
.chunked_reply
) {
1398 packChunk(bodyData
, *mb
);
1400 size_t length
= lengthToSend(bodyData
.range());
1401 noteSentBodyBytes (length
);
1403 mb
->append(bodyData
.data
, length
);
1408 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1409 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1410 CommIoCbPtrFun(clientWriteComplete
, this));
1411 Comm::Write(clientConnection
, mb
, call
);
1416 * Write a chunk of data to a client socket. If the reply is present,
1417 * send the reply headers down the wire too, and clean them up when
1420 * The request is one backed by a connection, not an internal request.
1421 * data context is not NULL
1422 * There are no more entries in the stream chain.
1425 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1426 HttpReply
* rep
, StoreIOBuffer receivedData
)
1428 /* Test preconditions */
1429 assert(node
!= NULL
);
1430 PROF_start(clientSocketRecipient
);
1431 /* TODO: handle this rather than asserting
1432 * - it should only ever happen if we cause an abort and
1433 * the callback chain loops back to here, so we can simply return.
1434 * However, that itself shouldn't happen, so it stays as an assert for now.
1436 assert(cbdataReferenceValid(node
));
1437 assert(node
->node
.next
== NULL
);
1438 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1439 assert(context
!= NULL
);
1440 assert(connIsUsable(http
->getConn()));
1442 /* TODO: check offset is what we asked for */
1444 if (context
!= http
->getConn()->getCurrentContext()) {
1445 context
->deferRecipientForLater(node
, rep
, receivedData
);
1446 PROF_stop(clientSocketRecipient
);
1450 // After sending Transfer-Encoding: chunked (at least), always send
1451 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1452 const bool mustSendLastChunk
= http
->request
->flags
.chunked_reply
&&
1453 !http
->request
->flags
.stream_error
&& !context
->startOfOutput();
1454 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1455 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1456 PROF_stop(clientSocketRecipient
);
1460 if (!context
->startOfOutput())
1461 context
->sendBody(rep
, receivedData
);
1464 http
->al
->reply
= HTTPMSGLOCK(rep
);
1465 context
->sendStartOfMessage(rep
, receivedData
);
1468 PROF_stop(clientSocketRecipient
);
1472 * Called when a downstream node is no longer interested in
1473 * our data. As we are a terminal node, this means on aborts
1477 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1479 /* Test preconditions */
1480 assert(node
!= NULL
);
1481 /* TODO: handle this rather than asserting
1482 * - it should only ever happen if we cause an abort and
1483 * the callback chain loops back to here, so we can simply return.
1484 * However, that itself shouldn't happen, so it stays as an assert for now.
1486 assert(cbdataReferenceValid(node
));
1487 /* Set null by ContextFree */
1488 assert(node
->node
.next
== NULL
);
1489 /* this is the assert discussed above */
1490 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1491 /* We are only called when the client socket shutsdown.
1492 * Tell the prev pipeline member we're finished
1494 clientStreamDetach(node
, http
);
1498 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1500 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1501 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1505 ConnStateData::readNextRequest()
1507 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1509 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1511 * Set the timeout BEFORE calling clientReadRequest().
1513 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1514 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1515 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1516 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1519 /** Please don't do anything with the FD past here! */
1523 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1525 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1527 /** If the client stream is waiting on a socket write to occur, then */
1529 if (deferredRequest
->flags
.deferred
) {
1530 /** NO data is allowed to have been sent. */
1531 assert(deferredRequest
->http
->out
.size
== 0);
1533 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1534 deferredRequest
->http
,
1535 deferredRequest
->deferredparams
.rep
,
1536 deferredRequest
->deferredparams
.queuedBuffer
);
1539 /** otherwise, the request is still active in a callbacksomewhere,
1544 /// called when we have successfully finished writing the response
1546 ClientSocketContext::keepaliveNextRequest()
1548 ConnStateData
* conn
= http
->getConn();
1550 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1553 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1554 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1555 conn
->clientConnection
->close();
1560 * We are done with the response, and we are either still receiving request
1561 * body (early response!) or have already stopped receiving anything.
1563 * If we are still receiving, then clientParseRequest() below will fail.
1564 * (XXX: but then we will call readNextRequest() which may succeed and
1565 * execute a smuggled request as we are not done with the current request).
1567 * If we stopped because we got everything, then try the next request.
1569 * If we stopped receiving because of an error, then close now to avoid
1570 * getting stuck and to prevent accidental request smuggling.
1573 if (const char *reason
= conn
->stoppedReceiving()) {
1574 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1575 conn
->clientConnection
->close();
1580 * Attempt to parse a request from the request buffer.
1581 * If we've been fed a pipelined request it may already
1582 * be in our read buffer.
1585 * This needs to fall through - if we're unlucky and parse the _last_ request
1586 * from our read buffer we may never re-register for another client read.
1589 if (conn
->clientParseRequests()) {
1590 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1594 * Either we need to kick-start another read or, if we have
1595 * a half-closed connection, kill it after the last request.
1596 * This saves waiting for half-closed connections to finished being
1597 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1598 * the keepalive "Waiting for next request" state.
1600 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1601 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1602 conn
->clientConnection
->close();
1606 ClientSocketContext::Pointer deferredRequest
;
1609 * At this point we either have a parsed request (which we've
1610 * kicked off the processing for) or not. If we have a deferred
1611 * request (parsed but deferred for pipeling processing reasons)
1612 * then look at processing it. If not, simply kickstart
1616 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1617 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1618 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1619 } else if (conn
->flags
.readMore
) {
1620 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1621 conn
->readNextRequest();
1623 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1624 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1629 clientUpdateSocketStats(log_type logType
, size_t size
)
1634 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1636 if (logTypeIsATcpHit(logType
))
1637 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1641 * increments iterator "i"
1642 * used by clientPackMoreRanges
1644 \retval true there is still data available to pack more ranges
1648 ClientSocketContext::canPackMoreRanges() const
1650 /** first update iterator "i" if needed */
1652 if (!http
->range_iter
.debt()) {
1653 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1655 if (http
->range_iter
.pos
.incrementable())
1656 ++http
->range_iter
.pos
;
1658 http
->range_iter
.updateSpec();
1661 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1663 /* paranoid sync condition */
1664 /* continue condition: need_more_data */
1665 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1666 return http
->range_iter
.currentSpec() ? true : false;
1670 ClientSocketContext::getNextRangeOffset() const
1672 if (http
->request
->range
) {
1673 /* offset in range specs does not count the prefix of an http msg */
1674 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1675 /* check: reply was parsed and range iterator was initialized */
1676 assert(http
->range_iter
.valid
);
1677 /* filter out data according to range specs */
1678 assert (canPackMoreRanges());
1680 int64_t start
; /* offset of still missing data */
1681 assert(http
->range_iter
.currentSpec());
1682 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1683 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1684 debugs(33, 3, "clientPackMoreRanges: out:"
1685 " start: " << start
<<
1686 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1687 " [" << http
->range_iter
.currentSpec()->offset
<<
1688 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1689 " len: " << http
->range_iter
.currentSpec()->length
<<
1690 " debt: " << http
->range_iter
.debt());
1691 if (http
->range_iter
.currentSpec()->length
!= -1)
1692 assert(http
->out
.offset
<= start
); /* we did not miss it */
1697 } else if (reply
&& reply
->content_range
) {
1698 /* request does not have ranges, but reply does */
1699 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1700 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1702 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1705 return http
->out
.offset
;
1709 ClientSocketContext::pullData()
1711 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1713 /* More data will be coming from the stream. */
1714 StoreIOBuffer readBuffer
;
1715 /* XXX: Next requested byte in the range sequence */
1716 /* XXX: length = getmaximumrangelenfgth */
1717 readBuffer
.offset
= getNextRangeOffset();
1718 readBuffer
.length
= HTTP_REQBUF_SZ
;
1719 readBuffer
.data
= reqbuf
;
1720 /* we may note we have reached the end of the wanted ranges */
1721 clientStreamRead(getTail(), http
, readBuffer
);
1724 clientStream_status_t
1725 ClientSocketContext::socketState()
1727 switch (clientStreamStatus(getTail(), http
)) {
1730 /* check for range support ending */
1732 if (http
->request
->range
) {
1733 /* check: reply was parsed and range iterator was initialized */
1734 assert(http
->range_iter
.valid
);
1735 /* filter out data according to range specs */
1737 if (!canPackMoreRanges()) {
1738 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1739 "range sequence on " << clientConnection
);
1741 if (http
->request
->flags
.proxy_keepalive
)
1742 return STREAM_COMPLETE
;
1744 return STREAM_UNPLANNED_COMPLETE
;
1746 } else if (reply
&& reply
->content_range
) {
1747 /* reply has content-range, but Squid is not managing ranges */
1748 const int64_t &bytesSent
= http
->out
.offset
;
1749 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1751 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1752 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1753 reply
->content_range
->spec
.offset
<< ")");
1755 // did we get at least what we expected, based on range specs?
1757 if (bytesSent
== bytesExpected
) { // got everything
1758 if (http
->request
->flags
.proxy_keepalive
)
1759 return STREAM_COMPLETE
;
1761 return STREAM_UNPLANNED_COMPLETE
;
1764 // The logic below is not clear: If we got more than we
1765 // expected why would persistency matter? Should not this
1766 // always be an error?
1767 if (bytesSent
> bytesExpected
) { // got extra
1768 if (http
->request
->flags
.proxy_keepalive
)
1769 return STREAM_COMPLETE
;
1771 return STREAM_UNPLANNED_COMPLETE
;
1774 // did not get enough yet, expecting more
1779 case STREAM_COMPLETE
:
1780 return STREAM_COMPLETE
;
1782 case STREAM_UNPLANNED_COMPLETE
:
1783 return STREAM_UNPLANNED_COMPLETE
;
1786 return STREAM_FAILED
;
1789 fatal ("unreachable code\n");
1794 * A write has just completed to the client, or we have just realised there is
1795 * no more data to send.
1798 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1800 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1801 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1804 /// remembers the abnormal connection termination for logging purposes
1806 ClientSocketContext::noteIoError(const int xerrno
)
1809 if (xerrno
== ETIMEDOUT
)
1810 http
->al
->http
.timedout
= true;
1811 else // even if xerrno is zero (which means read abort/eof)
1812 http
->al
->http
.aborted
= true;
1817 ClientSocketContext::doClose()
1819 clientConnection
->close();
1822 /// called when we encounter a response-related error
1824 ClientSocketContext::initiateClose(const char *reason
)
1826 http
->getConn()->stopSending(reason
); // closes ASAP
1830 ConnStateData::stopSending(const char *error
)
1832 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1833 "; old receiving error: " <<
1834 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1836 if (const char *oldError
= stoppedSending()) {
1837 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1838 return; // nothing has changed as far as this connection is concerned
1840 stoppedSending_
= error
;
1842 if (!stoppedReceiving()) {
1843 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1844 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1845 " request body bytes with " << in
.notYetUsed
<< " unused");
1846 return; // wait for the request receiver to finish reading
1850 clientConnection
->close();
1854 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1856 const StoreEntry
*entry
= http
->storeEntry();
1857 http
->out
.size
+= size
;
1858 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1859 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1860 (entry
? entry
->objectLen() : 0));
1861 clientUpdateSocketStats(http
->logType
, size
);
1863 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1865 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1868 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1869 initiateClose("failure or true request status");
1870 /* Do we leak here ? */
1874 switch (socketState()) {
1880 case STREAM_COMPLETE
:
1881 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1882 keepaliveNextRequest();
1885 case STREAM_UNPLANNED_COMPLETE
:
1886 initiateClose("STREAM_UNPLANNED_COMPLETE");
1890 initiateClose("STREAM_FAILED");
1894 fatal("Hit unreachable code in clientWriteComplete\n");
1898 extern "C" CSR clientGetMoreData
;
1899 extern "C" CSS clientReplyStatus
;
1900 extern "C" CSD clientReplyDetach
;
1902 static ClientSocketContext
*
1903 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1905 ClientHttpRequest
*http
;
1906 ClientSocketContext
*context
;
1907 StoreIOBuffer tempBuffer
;
1908 http
= new ClientHttpRequest(csd
);
1909 http
->req_sz
= csd
->in
.notYetUsed
;
1910 http
->uri
= xstrdup(uri
);
1911 setLogUri (http
, uri
);
1912 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
1913 tempBuffer
.data
= context
->reqbuf
;
1914 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1915 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1916 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1917 clientSocketDetach
, context
, tempBuffer
);
1922 skipLeadingSpace(char *aString
)
1924 char *result
= aString
;
1926 while (xisspace(*aString
))
1933 * 'end' defaults to NULL for backwards compatibility
1934 * remove default value if we ever get rid of NULL-terminated
1938 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1941 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1945 for (; end
> uriAndHTTPVersion
; --end
) {
1946 if (*end
== '\n' || *end
== '\r')
1949 if (xisspace(*end
)) {
1950 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1961 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1963 safe_free(http
->log_uri
);
1966 // The uri is already clean just dump it.
1967 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1970 switch (Config
.uri_whitespace
) {
1971 case URI_WHITESPACE_ALLOW
:
1972 flags
|= RFC1738_ESCAPE_NOSPACE
;
1974 case URI_WHITESPACE_ENCODE
:
1975 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1976 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1979 case URI_WHITESPACE_CHOP
: {
1980 flags
|= RFC1738_ESCAPE_NOSPACE
;
1981 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1982 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1983 int pos
= strcspn(http
->log_uri
, w_space
);
1984 http
->log_uri
[pos
] = '\0';
1988 case URI_WHITESPACE_DENY
:
1989 case URI_WHITESPACE_STRIP
:
1992 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
1996 if (!xisspace(*t
)) {
2003 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2012 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2014 int vhost
= conn
->port
->vhost
;
2015 int vport
= conn
->port
->vport
;
2017 char ipbuf
[MAX_IPSTRLEN
];
2019 http
->flags
.accel
= 1;
2021 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2023 if (strncasecmp(url
, "cache_object://", 15) == 0)
2024 return; /* already in good shape */
2027 if (conn
->port
->vhost
)
2028 return; /* already in good shape */
2030 /* else we need to ignore the host name */
2031 url
= strstr(url
, "//");
2033 #if SHOULD_REJECT_UNKNOWN_URLS
2036 hp
->request_parse_status
= HTTP_BAD_REQUEST
;
2037 return parseHttpRequestAbort(conn
, "error:invalid-request");
2042 url
= strchr(url
+ 2, '/');
2049 vport
= http
->getConn()->clientConnection
->local
.GetPort();
2051 const bool switchedToHttps
= conn
->switchedToHttps();
2052 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2053 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2054 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2059 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2060 strncpy(thost
, host
, (t
-host
));
2061 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2064 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2067 } // else nothing to alter port-wise.
2068 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2070 http
->uri
= (char *)xcalloc(url_sz
, 1);
2071 const char *protocol
= switchedToHttps
?
2072 "https" : conn
->port
->protocol
;
2073 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2074 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2075 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2076 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2077 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2078 strlen(conn
->port
->defaultsite
);
2079 http
->uri
= (char *)xcalloc(url_sz
, 1);
2083 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2085 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2086 conn
->port
->protocol
, conn
->port
->defaultsite
, vportStr
, url
);
2087 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2088 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2089 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2090 /* Put the local socket IP address as the hostname, with whatever vport we found */
2091 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2092 http
->uri
= (char *)xcalloc(url_sz
, 1);
2093 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2094 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2095 http
->getConn()->port
->protocol
,
2097 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2102 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2105 char ipbuf
[MAX_IPSTRLEN
];
2108 return; /* already in good shape */
2110 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2112 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2113 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2115 http
->uri
= (char *)xcalloc(url_sz
, 1);
2116 snprintf(http
->uri
, url_sz
, "%s://%s%s", conn
->port
->protocol
, host
, url
);
2117 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2119 /* Put the local socket IP address as the hostname. */
2120 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2121 http
->uri
= (char *)xcalloc(url_sz
, 1);
2122 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2123 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2124 http
->getConn()->port
->protocol
,
2125 ipbuf
, http
->getConn()->clientConnection
->local
.GetPort(), url
);
2126 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2131 * parseHttpRequest()
2134 * NULL on incomplete requests
2135 * a ClientSocketContext structure on success or failure.
2136 * Sets result->flags.parsed_ok to 0 if failed to parse the request.
2137 * Sets result->flags.parsed_ok to 1 if we have a good request.
2139 static ClientSocketContext
*
2140 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, HttpVersion
*http_ver
)
2142 char *req_hdr
= NULL
;
2145 ClientHttpRequest
*http
;
2146 ClientSocketContext
*result
;
2147 StoreIOBuffer tempBuffer
;
2150 /* pre-set these values to make aborting simpler */
2151 *method_p
= METHOD_NONE
;
2153 /* NP: don't be tempted to move this down or remove again.
2154 * It's the only DDoS protection old-String has against long URL */
2155 if ( hp
->bufsiz
<= 0) {
2156 debugs(33, 5, "Incomplete request, waiting for end of request line");
2158 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2159 debugs(33, 5, "parseHttpRequest: Too large request");
2160 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2161 return parseHttpRequestAbort(csd
, "error:request-too-large");
2164 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2165 r
= HttpParserParseReqLine(hp
);
2168 debugs(33, 5, "Incomplete request, waiting for end of request line");
2173 return parseHttpRequestAbort(csd
, "error:invalid-request");
2176 /* Request line is valid here .. */
2177 *http_ver
= HttpVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2179 /* This call scans the entire request, not just the headers */
2180 if (hp
->req
.v_maj
> 0) {
2181 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2182 debugs(33, 5, "Incomplete request, waiting for end of headers");
2186 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2187 req_sz
= HttpParserReqSz(hp
);
2190 /* We know the whole request is in hp->buf now */
2192 assert(req_sz
<= (size_t) hp
->bufsiz
);
2194 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2195 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2198 hp
->hdr_end
= req_sz
- 1;
2200 hp
->hdr_start
= hp
->req
.end
+ 1;
2202 /* Enforce max_request_size */
2203 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2204 debugs(33, 5, "parseHttpRequest: Too large request");
2205 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2206 return parseHttpRequestAbort(csd
, "error:request-too-large");
2210 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2212 /* deny CONNECT via accelerated ports */
2213 if (*method_p
== METHOD_CONNECT
&& csd
&& csd
->port
&& csd
->port
->accel
) {
2214 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->protocol
<< " Accelerator port " << csd
->port
->s
.GetPort() );
2215 /* XXX need a way to say "this many character length string" */
2216 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2217 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2218 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2221 if (*method_p
== METHOD_NONE
) {
2222 /* XXX need a way to say "this many character length string" */
2223 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2224 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2225 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2229 * Process headers after request line
2230 * TODO: Use httpRequestParse here.
2232 /* XXX this code should be modified to take a const char * later! */
2233 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2235 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2237 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2239 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2241 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2242 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2243 HttpParserReqSz(hp
));
2245 /* Ok, all headers are received */
2246 http
= new ClientHttpRequest(csd
);
2248 http
->req_sz
= HttpParserRequestLen(hp
);
2249 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2250 tempBuffer
.data
= result
->reqbuf
;
2251 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2253 ClientStreamData newServer
= new clientReplyContext(http
);
2254 ClientStreamData newClient
= result
;
2255 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2256 clientReplyStatus
, newServer
, clientSocketRecipient
,
2257 clientSocketDetach
, newClient
, tempBuffer
);
2259 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2263 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2264 * below needs to be modified to not expect a mutable nul-terminated string.
2266 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2268 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2270 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2272 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2274 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2279 debugs(33,5, HERE
<< "repare absolute URL from " << (csd
->transparent()?"intercept":(csd
->port
->accel
? "accel":"")));
2280 /* Rewrite the URL in transparent or accelerator mode */
2281 /* NP: there are several cases to traverse here:
2282 * - standard mode (forward proxy)
2283 * - transparent mode (TPROXY)
2284 * - transparent mode with failures
2285 * - intercept mode (NAT)
2286 * - intercept mode with failures
2287 * - accelerator mode (reverse proxy)
2289 * - mixed combos of the above with internal URL
2291 if (csd
->transparent()) {
2292 /* intercept or transparent mode, properly working with no failures */
2293 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2295 } else if (internalCheck(url
)) {
2296 /* internal URL mode */
2297 /* prepend our name & port */
2298 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2299 // We just re-wrote the URL. Must replace the Host: header.
2300 // But have not parsed there yet!! flag for local-only handling.
2301 http
->flags
.internal
= 1;
2303 } else if (csd
->port
->accel
|| csd
->switchedToHttps()) {
2304 /* accelerator mode */
2305 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2309 /* No special rewrites have been applied above, use the
2310 * requested url. may be rewritten later, so make extra room */
2311 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2312 http
->uri
= (char *)xcalloc(url_sz
, 1);
2313 strcpy(http
->uri
, url
);
2316 debugs(33, 5, "parseHttpRequest: Complete request received");
2318 // XXX: crop this dump at the end of headers. No need for extras
2319 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2320 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2322 result
->flags
.parsed_ok
= 1;
2328 ConnStateData::getAvailableBufferLength() const
2330 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2331 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2332 // huge request_header_max_size may lead to more than INT_MAX unused space
2333 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2338 ConnStateData::maybeMakeSpaceAvailable()
2340 if (getAvailableBufferLength() < 2) {
2342 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2343 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2346 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2347 newSize
=Config
.maxRequestBufferSize
;
2349 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2350 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2356 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2358 ClientSocketContext::Pointer
*S
;
2360 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2368 ConnStateData::getConcurrentRequestCount() const
2371 ClientSocketContext::Pointer
*T
;
2373 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2374 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2379 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2381 if (flag
!= COMM_OK
) {
2382 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2387 if (!ignoreErrno(xerrno
)) {
2388 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2390 } else if (in
.notYetUsed
== 0) {
2391 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2399 ConnStateData::connFinishedWithConn(int size
)
2402 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2403 /* no current or pending requests */
2404 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2406 } else if (!Config
.onoff
.half_closed_clients
) {
2407 /* admin doesn't want to support half-closed client sockets */
2408 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2409 notifyAllContexts(0); // no specific error implies abort
2418 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2420 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2421 conn
->in
.notYetUsed
-= byteCount
;
2422 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2424 * If there is still data that will be used,
2425 * move it to the beginning.
2428 if (conn
->in
.notYetUsed
> 0)
2429 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2432 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2434 ConnStateData::checkHeaderLimits()
2436 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2437 return; // can accumulte more header data
2439 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2440 Config
.maxRequestHeaderSize
<< " bytes)");
2442 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2443 clientStreamNode
*node
= context
->getClientReplyContext();
2444 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2445 assert (repContext
);
2446 repContext
->setReplyToError(ERR_TOO_BIG
,
2447 HTTP_BAD_REQUEST
, METHOD_NONE
, NULL
,
2448 clientConnection
->remote
, NULL
, NULL
, NULL
);
2449 context
->registerWithConn();
2450 context
->pullData();
2454 ConnStateData::clientAfterReadingRequests()
2456 // Were we expecting to read more request body from half-closed connection?
2457 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2458 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2459 clientConnection
->close();
2468 ConnStateData::quitAfterError(HttpRequest
*request
)
2470 // From HTTP p.o.v., we do not have to close after every error detected
2471 // at the client-side, but many such errors do require closure and the
2472 // client-side code is bad at handling errors so we play it safe.
2474 request
->flags
.proxy_keepalive
= 0;
2475 flags
.readMore
= false;
2476 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2480 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2482 ClientHttpRequest
*http
= context
->http
;
2487 assert(sslServerBump
->entry
);
2488 // Did we create an error entry while processing CONNECT?
2489 if (!sslServerBump
->entry
->isEmpty()) {
2490 quitAfterError(http
->request
);
2492 // Get the saved error entry and send it to the client by replacing the
2493 // ClientHttpRequest store entry with it.
2494 clientStreamNode
*node
= context
->getClientReplyContext();
2495 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2497 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2498 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2500 // save the original request for logging purposes
2501 if (!context
->http
->al
->request
)
2502 context
->http
->al
->request
= HTTPMSGLOCK(http
->request
);
2504 // Get error details from the fake certificate-peeking request.
2505 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2506 context
->pullData();
2510 // In bump-server-first mode, we have not necessarily seen the intended
2511 // server name at certificate-peeking time. Check for domain mismatch now,
2512 // when we can extract the intended name from the bumped HTTP request.
2513 if (sslServerBump
->serverCert
.get()) {
2514 HttpRequest
*request
= http
->request
;
2515 if (!Ssl::checkX509ServerValidity(sslServerBump
->serverCert
.get(), request
->GetHost())) {
2516 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2517 "does not match domainname " << request
->GetHost());
2519 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2520 check
.sslErrors
= new Ssl::Errors(SQUID_X509_V_ERR_DOMAIN_MISMATCH
);
2521 if (Comm::IsConnOpen(pinning
.serverConnection
))
2522 check
.fd(pinning
.serverConnection
->fd
);
2523 const bool allowDomainMismatch
=
2524 check
.fastCheck() == ACCESS_ALLOWED
;
2525 delete check
.sslErrors
;
2526 check
.sslErrors
= NULL
;
2528 if (!allowDomainMismatch
) {
2529 quitAfterError(request
);
2531 clientStreamNode
*node
= context
->getClientReplyContext();
2532 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2533 assert (repContext
);
2535 // Fill the server IP and hostname for error page generation.
2536 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2537 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2539 // Create an error object and fill it
2540 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, HTTP_SERVICE_UNAVAILABLE
, request
);
2541 err
->src_addr
= clientConnection
->remote
;
2542 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2543 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2544 sslServerBump
->serverCert
.get(), NULL
);
2545 err
->detail
= errDetail
;
2546 // Save the original request for logging purposes.
2547 if (!context
->http
->al
->request
)
2548 context
->http
->al
->request
= HTTPMSGLOCK(request
);
2549 repContext
->setReplyToError(request
->method
, err
);
2550 assert(context
->http
->out
.offset
== 0);
2551 context
->pullData();
2562 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, HttpVersion http_ver
)
2564 ClientHttpRequest
*http
= context
->http
;
2565 HttpRequest
*request
= NULL
;
2566 bool notedUseOfBuffer
= false;
2567 bool chunked
= false;
2568 bool mustReplyToOptions
= false;
2569 bool unsupportedTe
= false;
2570 bool expectBody
= false;
2572 /* We have an initial client stream in place should it be needed */
2573 /* setup our private context */
2574 context
->registerWithConn();
2576 if (context
->flags
.parsed_ok
== 0) {
2577 clientStreamNode
*node
= context
->getClientReplyContext();
2578 debugs(33, 2, "clientProcessRequest: Invalid Request");
2579 conn
->quitAfterError(NULL
);
2580 // setLogUri should called before repContext->setReplyToError
2581 setLogUri(http
, http
->uri
, true);
2582 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2583 assert (repContext
);
2584 switch (hp
->request_parse_status
) {
2585 case HTTP_HEADER_TOO_LARGE
:
2586 repContext
->setReplyToError(ERR_TOO_BIG
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2588 case HTTP_METHOD_NOT_ALLOWED
:
2589 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_METHOD_NOT_ALLOWED
, method
, http
->uri
,
2590 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2593 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2594 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2596 assert(context
->http
->out
.offset
== 0);
2597 context
->pullData();
2601 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2602 clientStreamNode
*node
= context
->getClientReplyContext();
2603 debugs(33, 5, "Invalid URL: " << http
->uri
);
2604 conn
->quitAfterError(request
);
2605 // setLogUri should called before repContext->setReplyToError
2606 setLogUri(http
, http
->uri
, true);
2607 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2608 assert (repContext
);
2609 repContext
->setReplyToError(ERR_INVALID_URL
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2610 assert(context
->http
->out
.offset
== 0);
2611 context
->pullData();
2615 /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */
2616 /* We currently only accept 0.9, 1.0, 1.1 */
2617 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2618 (http_ver
.major
== 1 && http_ver
.minor
> 1 ) ||
2619 (http_ver
.major
> 1) ) {
2621 clientStreamNode
*node
= context
->getClientReplyContext();
2622 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2623 conn
->quitAfterError(request
);
2624 // setLogUri should called before repContext->setReplyToError
2625 setLogUri(http
, http
->uri
, true);
2626 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2627 assert (repContext
);
2628 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, HTTP_HTTP_VERSION_NOT_SUPPORTED
, method
, http
->uri
,
2629 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2630 assert(context
->http
->out
.offset
== 0);
2631 context
->pullData();
2635 /* compile headers */
2636 /* we should skip request line! */
2637 /* XXX should actually know the damned buffer size here */
2638 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2639 clientStreamNode
*node
= context
->getClientReplyContext();
2640 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2641 conn
->quitAfterError(request
);
2642 // setLogUri should called before repContext->setReplyToError
2643 setLogUri(http
, http
->uri
, true);
2644 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2645 assert (repContext
);
2646 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2647 assert(context
->http
->out
.offset
== 0);
2648 context
->pullData();
2652 request
->clientConnectionManager
= conn
;
2654 request
->flags
.accelerated
= http
->flags
.accel
;
2655 request
->flags
.sslBumped
= conn
->switchedToHttps();
2656 request
->flags
.canRePin
= request
->flags
.sslBumped
&& conn
->pinning
.pinned
;
2657 request
->flags
.ignore_cc
= conn
->port
->ignore_cc
;
2658 // TODO: decouple http->flags.accel from request->flags.sslBumped
2659 request
->flags
.no_direct
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2660 !conn
->port
->allow_direct
: 0;
2662 if (request
->flags
.sslBumped
) {
2663 if (conn
->auth_user_request
!= NULL
)
2664 request
->auth_user_request
= conn
->auth_user_request
;
2669 * If transparent or interception mode is working clone the transparent and interception flags
2670 * from the port settings to the request.
2672 if (http
->clientConnection
!= NULL
) {
2673 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2674 request
->flags
.spoof_client_ip
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2677 if (internalCheck(request
->urlpath
.termedBuf())) {
2678 if (internalHostnameIs(request
->GetHost()) &&
2679 request
->port
== getMyPort()) {
2680 http
->flags
.internal
= 1;
2681 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2682 request
->SetHost(internalHostname());
2683 request
->port
= getMyPort();
2684 http
->flags
.internal
= 1;
2688 if (http
->flags
.internal
) {
2689 request
->protocol
= AnyP::PROTO_HTTP
;
2690 request
->login
[0] = '\0';
2693 request
->flags
.internal
= http
->flags
.internal
;
2694 setLogUri (http
, urlCanonicalClean(request
));
2695 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2696 #if FOLLOW_X_FORWARDED_FOR
2697 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2698 // not a details about teh TCP connection itself
2699 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2700 #endif /* FOLLOW_X_FORWARDED_FOR */
2701 request
->my_addr
= conn
->clientConnection
->local
;
2702 request
->myportname
= conn
->port
->name
;
2703 request
->http_ver
= http_ver
;
2705 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2706 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2707 request
->clientConnectionManager
= conn
;
2709 if (request
->header
.chunked()) {
2711 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2712 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2713 // HTTP/1.1 requires chunking to be the last encoding if there is one
2714 unsupportedTe
= te
.size() && te
!= "identity";
2715 } // else implied identity coding
2717 mustReplyToOptions
= (method
== METHOD_OPTIONS
) &&
2718 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2719 if (!urlCheckRequest(request
) || mustReplyToOptions
|| unsupportedTe
) {
2720 clientStreamNode
*node
= context
->getClientReplyContext();
2721 conn
->quitAfterError(request
);
2722 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2723 assert (repContext
);
2724 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_NOT_IMPLEMENTED
, request
->method
, NULL
,
2725 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2726 assert(context
->http
->out
.offset
== 0);
2727 context
->pullData();
2731 if (!chunked
&& !clientIsContentLengthValid(request
)) {
2732 clientStreamNode
*node
= context
->getClientReplyContext();
2733 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2734 assert (repContext
);
2735 conn
->quitAfterError(request
);
2736 repContext
->setReplyToError(ERR_INVALID_REQ
,
2737 HTTP_LENGTH_REQUIRED
, request
->method
, NULL
,
2738 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2739 assert(context
->http
->out
.offset
== 0);
2740 context
->pullData();
2744 if (request
->header
.has(HDR_EXPECT
)) {
2745 const String expect
= request
->header
.getList(HDR_EXPECT
);
2746 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2747 if (!supportedExpect
) {
2748 clientStreamNode
*node
= context
->getClientReplyContext();
2749 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2750 assert (repContext
);
2751 conn
->quitAfterError(request
);
2752 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_EXPECTATION_FAILED
, request
->method
, http
->uri
,
2753 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2754 assert(context
->http
->out
.offset
== 0);
2755 context
->pullData();
2760 http
->request
= HTTPMSGLOCK(request
);
2761 clientSetKeepaliveFlag(http
);
2763 // Let tunneling code be fully responsible for CONNECT requests
2764 if (http
->request
->method
== METHOD_CONNECT
) {
2765 context
->mayUseConnection(true);
2766 conn
->flags
.readMore
= false;
2770 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2774 /* Do we expect a request-body? */
2775 expectBody
= chunked
|| request
->content_length
> 0;
2776 if (!context
->mayUseConnection() && expectBody
) {
2777 request
->body_pipe
= conn
->expectRequestBody(
2778 chunked
? -1 : request
->content_length
);
2780 // consume header early so that body pipe gets just the body
2781 connNoteUseOfBuffer(conn
, http
->req_sz
);
2782 notedUseOfBuffer
= true;
2784 /* Is it too large? */
2785 if (!chunked
&& // if chunked, we will check as we accumulate
2786 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2787 clientStreamNode
*node
= context
->getClientReplyContext();
2788 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2789 assert (repContext
);
2790 conn
->quitAfterError(request
);
2791 repContext
->setReplyToError(ERR_TOO_BIG
,
2792 HTTP_REQUEST_ENTITY_TOO_LARGE
, METHOD_NONE
, NULL
,
2793 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2794 assert(context
->http
->out
.offset
== 0);
2795 context
->pullData();
2799 // We may stop producing, comm_close, and/or call setReplyToError()
2800 // below, so quit on errors to avoid http->doCallouts()
2801 if (!conn
->handleRequestBodyData())
2804 if (!request
->body_pipe
->productionEnded()) {
2805 debugs(33, 5, HERE
<< "need more request body");
2806 context
->mayUseConnection(true);
2807 assert(conn
->flags
.readMore
);
2811 http
->calloutContext
= new ClientRequestContext(http
);
2816 if (!notedUseOfBuffer
)
2817 connNoteUseOfBuffer(conn
, http
->req_sz
);
2821 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2822 * to here because calling comm_reset_close() causes http to
2823 * be freed and the above connNoteUseOfBuffer() would hit an
2824 * assertion, not to mention that we were accessing freed memory.
2826 if (request
&& request
->flags
.resetTCP() && Comm::IsConnOpen(conn
->clientConnection
)) {
2827 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2828 conn
->flags
.readMore
= false;
2829 comm_reset_close(conn
->clientConnection
);
2834 connStripBufferWhitespace (ConnStateData
* conn
)
2836 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2837 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2838 -- conn
->in
.notYetUsed
;
2843 connOkToAddRequest(ConnStateData
* conn
)
2845 int result
= conn
->getConcurrentRequestCount() < (Config
.onoff
.pipeline_prefetch
? 2 : 1);
2848 debugs(33, 3, HERE
<< conn
->clientConnection
<< " max concurrent requests reached");
2849 debugs(33, 5, HERE
<< conn
->clientConnection
<< " defering new request until one is done");
2856 * Attempt to parse one or more requests from the input buffer.
2857 * If a request is successfully parsed, even if the next request
2858 * is only partially parsed, it will return TRUE.
2861 ConnStateData::clientParseRequests()
2863 HttpRequestMethod method
;
2864 bool parsed_req
= false;
2865 HttpVersion http_ver
;
2867 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2869 // Loop while we have read bytes that are not needed for producing the body
2870 // On errors, bodyPipe may become nil, but readMore will be cleared
2871 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2872 connStripBufferWhitespace(this);
2874 /* Don't try to parse if the buffer is empty */
2875 if (in
.notYetUsed
== 0)
2878 /* Limit the number of concurrent requests to 2 */
2879 if (!connOkToAddRequest(this)) {
2883 /* Should not be needed anymore */
2884 /* Terminate the string */
2885 in
.buf
[in
.notYetUsed
] = '\0';
2887 /* Begin the parsing */
2888 PROF_start(parseHttpRequest
);
2889 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
2891 /* Process request */
2892 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2893 PROF_stop(parseHttpRequest
);
2895 /* partial or incomplete request */
2897 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2898 // (which becomes context) but checkHeaderLimits cannot?
2899 checkHeaderLimits();
2903 /* status -1 or 1 */
2905 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2906 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2907 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2908 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2910 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2912 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2914 if (context
->mayUseConnection()) {
2915 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2921 /* XXX where to 'finish' the parsing pass? */
2926 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
2928 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
2932 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2934 if (io
.flag
== COMM_ERR_CLOSING
) {
2935 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
2939 assert(Comm::IsConnOpen(clientConnection
));
2940 assert(io
.conn
->fd
== clientConnection
->fd
);
2943 * Don't reset the timeout value here. The timeout value will be
2944 * set to Config.Timeout.request by httpAccept() and
2945 * clientWriteComplete(), and should apply to the request as a
2946 * whole, not individual read() calls. Plus, it breaks our
2947 * lame half-close detection
2949 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
2950 notifyAllContexts(io
.xerrno
);
2955 if (io
.flag
== COMM_OK
) {
2957 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
2959 // may comm_close or setReplyToError
2960 if (!handleReadData(io
.buf
, io
.size
))
2963 } else if (io
.size
== 0) {
2964 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
2966 if (connFinishedWithConn(io
.size
)) {
2967 clientConnection
->close();
2971 /* It might be half-closed, we can't tell */
2972 fd_table
[io
.conn
->fd
].flags
.socket_eof
= 1;
2974 commMarkHalfClosed(io
.conn
->fd
);
2976 fd_note(io
.conn
->fd
, "half-closed");
2978 /* There is one more close check at the end, to detect aborted
2979 * (partial) requests. At this point we can't tell if the request
2982 /* Continue to process previously read data */
2986 /* Process next request */
2987 if (getConcurrentRequestCount() == 0)
2988 fd_note(io
.fd
, "Reading next request");
2990 if (!clientParseRequests()) {
2994 * If the client here is half closed and we failed
2995 * to parse a request, close the connection.
2996 * The above check with connFinishedWithConn() only
2997 * succeeds _if_ the buffer is empty which it won't
2998 * be if we have an incomplete request.
2999 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3001 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3002 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3003 clientConnection
->close();
3011 clientAfterReadingRequests();
3015 * called when new request data has been read from the socket
3017 * \retval false called comm_close or setReplyToError (the caller should bail)
3018 * \retval true we did not call comm_close or setReplyToError
3021 ConnStateData::handleReadData(char *buf
, size_t size
)
3023 char *current_buf
= in
.addressToReadInto();
3025 if (buf
!= current_buf
)
3026 memmove(current_buf
, buf
, size
);
3028 in
.notYetUsed
+= size
;
3030 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3032 // if we are reading a body, stuff data into the body pipe
3033 if (bodyPipe
!= NULL
)
3034 return handleRequestBodyData();
3039 * called when new request body data has been buffered in in.buf
3040 * may close the connection if we were closing and piped everything out
3042 * \retval false called comm_close or setReplyToError (the caller should bail)
3043 * \retval true we did not call comm_close or setReplyToError
3046 ConnStateData::handleRequestBodyData()
3048 assert(bodyPipe
!= NULL
);
3052 if (in
.bodyParser
) { // chunked encoding
3053 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3054 abortChunkedRequestBody(error
);
3057 } else { // identity encoding
3058 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3059 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3060 if (!bodyPipe
->mayNeedMoreData()) {
3061 // BodyPipe will clear us automagically when we produced everything
3067 connNoteUseOfBuffer(this, putSize
);
3070 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3072 if (const char *reason
= stoppedSending()) {
3073 /* we've finished reading like good clients,
3074 * now do the close that initiateClose initiated.
3076 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3077 clientConnection
->close();
3085 /// parses available chunked encoded body bytes, checks size, returns errors
3087 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3089 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3091 try { // the parser will throw on errors
3093 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3096 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3097 // add one because MemBuf will assert if it cannot 0-terminate
3098 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3099 raw
.append(in
.buf
, in
.notYetUsed
);
3101 const mb_size_t wasContentSize
= raw
.contentSize();
3102 BodyPipeCheckout
bpc(*bodyPipe
);
3103 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3105 putSize
= wasContentSize
- raw
.contentSize();
3107 // dechunk then check: the size limit applies to _dechunked_ content
3108 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3112 finishDechunkingRequest(true);
3114 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3117 // if chunk parser needs data, then the body pipe must need it too
3118 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3120 // if parser needs more space and we can consume nothing, we will stall
3121 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3122 } catch (...) { // TODO: be more specific
3123 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3124 return ERR_INVALID_REQ
;
3127 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3131 /// quit on errors related to chunked request body handling
3133 ConnStateData::abortChunkedRequestBody(const err_type error
)
3135 finishDechunkingRequest(false);
3137 // XXX: The code below works if we fail during initial request parsing,
3138 // but if we fail when the server-side works already, the server may send
3139 // us its response too, causing various assertions. How to prevent that?
3140 #if WE_KNOW_HOW_TO_SEND_ERRORS
3141 ClientSocketContext::Pointer context
= getCurrentContext();
3142 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3143 clientStreamNode
*node
= context
->getClientReplyContext();
3144 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3146 const http_status scode
= (error
== ERR_TOO_BIG
) ?
3147 HTTP_REQUEST_ENTITY_TOO_LARGE
: HTTP_BAD_REQUEST
;
3148 repContext
->setReplyToError(error
, scode
,
3149 repContext
->http
->request
->method
,
3150 repContext
->http
->uri
,
3152 repContext
->http
->request
,
3154 context
->pullData();
3156 // close or otherwise we may get stuck as nobody will notice the error?
3157 comm_reset_close(clientConnection
);
3160 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3161 comm_reset_close(clientConnection
);
3163 flags
.readMore
= false;
3167 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3169 if (!handleRequestBodyData())
3172 // too late to read more body
3173 if (!isOpen() || stoppedReceiving())
3180 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3182 // request reader may get stuck waiting for space if nobody consumes body
3183 if (bodyPipe
!= NULL
)
3184 bodyPipe
->enableAutoConsumption();
3186 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3189 /** general lifetime handler for HTTP requests */
3191 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3193 #if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS
3194 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3196 if (COMMIO_FD_WRITECB(io
.fd
)->active
) {
3197 /* FIXME: If this code is reinstated, check the conn counters,
3198 * not the fd table state
3201 * Some data has been sent to the client, just close the FD
3203 clientConnection
->close();
3204 } else if (nrequests
) {
3206 * assume its a persistent connection; just close it
3208 clientConnection
->close();
3213 ClientHttpRequest
**H
;
3214 clientStreamNode
*node
;
3215 ClientHttpRequest
*http
= parseHttpRequestAbort(this, "error:Connection%20lifetime%20expired");
3216 node
= http
->client_stream
.tail
->prev
->data
;
3217 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3218 assert (repContext
);
3219 repContext
->setReplyToError(ERR_LIFETIME_EXP
,
3220 HTTP_REQUEST_TIMEOUT
, METHOD_NONE
, "N/A", &peer
.sin_addr
,
3222 /* No requests can be outstanded */
3223 assert(chr
== NULL
);
3224 /* add to the client request queue */
3226 for (H
= &chr
; *H
; H
= &(*H
)->next
);
3229 clientStreamRead(http
->client_stream
.tail
->data
, http
, 0,
3230 HTTP_REQBUF_SZ
, context
->reqbuf
);
3233 * if we don't close() here, we still need a timeout handler!
3235 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3236 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3237 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3238 commSetConnTimeout(io
.conn
, 30, timeoutCall
);
3241 * Aha, but we don't want a read handler!
3243 Comm::SetSelect(io
.fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3248 * Just close the connection to not confuse browsers
3249 * using persistent connections. Some browsers opens
3250 * an connection and then does not use it until much
3251 * later (presumeably because the request triggering
3252 * the open has already been completed on another
3255 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3261 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3263 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3264 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3265 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3266 http
->al
->http
.timedout
= true;
3267 if (Comm::IsConnOpen(io
.conn
))
3272 connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
)
3274 ConnStateData
*result
= new ConnStateData
;
3276 result
->clientConnection
= client
;
3277 result
->log_addr
= client
->remote
;
3278 result
->log_addr
.ApplyMask(Config
.Addrs
.client_netmask
);
3279 result
->in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &result
->in
.allocatedSize
);
3280 result
->port
= cbdataReference(port
);
3282 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3283 (result
->transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3284 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3285 int i
= IP_PMTUDISC_DONT
;
3286 setsockopt(client
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof i
);
3288 static int reported
= 0;
3291 debugs(33, DBG_IMPORTANT
, "Notice: httpd_accel_no_pmtu_disc not supported on your platform");
3297 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3298 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, result
, ConnStateData::connStateClosed
);
3299 comm_add_close_handler(client
->fd
, call
);
3301 if (Config
.onoff
.log_fqdn
)
3302 fqdncache_gethostbyaddr(client
->remote
, FQDN_LOOKUP_IF_MISS
);
3305 if (Ident::TheConfig
.identLookup
) {
3306 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3307 identChecklist
.src_addr
= client
->remote
;
3308 identChecklist
.my_addr
= client
->local
;
3309 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3310 Ident::Start(client
, clientIdentDone
, result
);
3315 if (Eui::TheConfig
.euiLookup
) {
3316 if (client
->remote
.IsIPv4()) {
3317 result
->clientConnection
->remoteEui48
.lookup(client
->remote
);
3318 } else if (client
->remote
.IsIPv6()) {
3319 result
->clientConnection
->remoteEui64
.lookup(client
->remote
);
3324 clientdbEstablished(client
->remote
, 1);
3326 result
->flags
.readMore
= true;
3330 /** Handle a new connection on HTTP socket. */
3332 httpAccept(const CommAcceptCbParams
¶ms
)
3334 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3336 if (params
.flag
!= COMM_OK
) {
3337 // Its possible the call was still queued when the client disconnected
3338 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3342 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3343 fd_note(params
.conn
->fd
, "client http connect");
3345 if (s
->tcp_keepalive
.enabled
) {
3346 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3349 ++ incoming_sockets_accepted
;
3351 // Socket is ready, setup the connection manager to start using it
3352 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3354 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3355 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3356 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3357 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3359 connState
->readSomeData();
3362 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3364 if (Config
.onoff
.client_db
) {
3365 /* it was said several times that client write limiter does not work if client_db is disabled */
3367 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3368 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3370 // TODO: we check early to limit error response bandwith but we
3371 // should recheck when we can honor delay_pool_uses_indirect
3372 // TODO: we should also pass the port details for myportname here.
3373 ch
.src_addr
= params
.conn
->remote
;
3374 ch
.my_addr
= params
.conn
->local
;
3376 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3378 /* pools require explicit 'allow' to assign a client into them */
3379 if (pools
[pool
].access
) {
3380 ch
.accessList
= pools
[pool
].access
;
3381 allow_t answer
= ch
.fastCheck();
3382 if (answer
== ACCESS_ALLOWED
) {
3384 /* request client information from db after we did all checks
3385 this will save hash lookup if client failed checks */
3386 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3389 /* put client info in FDE */
3390 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3392 /* setup write limiter for this request */
3393 const double burst
= floor(0.5 +
3394 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3395 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3398 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3408 /** Create SSL connection structure and update fd_table */
3410 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3412 SSL
*ssl
= SSL_new(sslContext
);
3415 const int ssl_error
= ERR_get_error();
3416 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3421 SSL_set_fd(ssl
, conn
->fd
);
3422 fd_table
[conn
->fd
].ssl
= ssl
;
3423 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3424 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3426 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3427 fd_note(conn
->fd
, "client https start");
3432 /** negotiate an SSL connection */
3434 clientNegotiateSSL(int fd
, void *data
)
3436 ConnStateData
*conn
= (ConnStateData
*)data
;
3438 SSL
*ssl
= fd_table
[fd
].ssl
;
3441 if ((ret
= SSL_accept(ssl
)) <= 0) {
3442 int ssl_error
= SSL_get_error(ssl
, ret
);
3444 switch (ssl_error
) {
3446 case SSL_ERROR_WANT_READ
:
3447 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3450 case SSL_ERROR_WANT_WRITE
:
3451 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3454 case SSL_ERROR_SYSCALL
:
3457 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3463 if (errno
== ECONNRESET
)
3466 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3467 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3474 case SSL_ERROR_ZERO_RETURN
:
3475 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3480 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3481 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3482 " (" << ssl_error
<< "/" << ret
<< ")");
3490 if (SSL_session_reused(ssl
)) {
3491 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3492 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3494 if (do_debug(83, 4)) {
3495 /* Write out the SSL session details.. actually the call below, but
3496 * OpenSSL headers do strange typecasts confusing GCC.. */
3497 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3498 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3499 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
);
3501 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3503 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3504 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3505 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3506 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3507 * Because there are two possible usable cast, if you get an error here, try the other
3508 * commented line. */
3510 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3511 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3515 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3518 /* Note: This does not automatically fflush the log file.. */
3521 debugs(83, 2, "clientNegotiateSSL: New session " <<
3522 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3523 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3527 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3528 SSL_get_cipher(ssl
));
3530 client_cert
= SSL_get_peer_certificate(ssl
);
3532 if (client_cert
!= NULL
) {
3533 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3534 " client certificate: subject: " <<
3535 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3537 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3538 " client certificate: issuer: " <<
3539 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3541 X509_free(client_cert
);
3543 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3544 " has no certificate.");
3547 conn
->readSomeData();
3551 * If SSL_CTX is given, starts reading the SSL handshake.
3552 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3555 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3559 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3561 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3564 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3565 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3566 connState
, ConnStateData::requestTimeout
);
3567 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3570 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3572 char buf
[MAX_IPSTRLEN
];
3573 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3574 HttpRequest
*fakeRequest
= new HttpRequest
;
3575 fakeRequest
->SetHost(details
->local
.NtoA(buf
, sizeof(buf
)));
3576 fakeRequest
->port
= details
->local
.GetPort();
3577 fakeRequest
->clientConnectionManager
= connState
;
3578 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3579 #if FOLLOW_X_FORWARDED_FOR
3580 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3582 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3583 fakeRequest
->flags
.spoof_client_ip
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3584 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3585 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3586 connState
->switchToHttps(fakeRequest
, bumpMode
);
3591 * A callback function to use with the ACLFilledChecklist callback.
3592 * In the case of ACCES_ALLOWED answer initializes a bumped SSL connection,
3593 * else reverts the connection to tunnel mode.
3596 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3598 ConnStateData
*connState
= (ConnStateData
*) data
;
3600 // if the connection is closed or closing, just return.
3601 if (!connState
->isOpen())
3604 // Require both a match and a positive bump mode to work around exceptional
3605 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3606 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3607 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3608 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3609 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3611 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3612 connState
->sslBumpMode
= Ssl::bumpNone
;
3614 // fake a CONNECT request to force connState to tunnel
3615 static char ip
[MAX_IPSTRLEN
];
3616 static char reqStr
[MAX_IPSTRLEN
+ 80];
3617 connState
->clientConnection
->local
.NtoA(ip
, sizeof(ip
));
3618 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s:%d HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, connState
->clientConnection
->local
.GetPort(), ip
);
3619 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3621 ret
= connState
->clientParseRequests();
3624 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3625 connState
->clientConnection
->close();
3630 /** handle a new HTTPS connection */
3632 httpsAccept(const CommAcceptCbParams
¶ms
)
3634 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3636 if (params
.flag
!= COMM_OK
) {
3637 // Its possible the call was still queued when the client disconnected
3638 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3642 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3643 fd_note(params
.conn
->fd
, "client https connect");
3645 if (s
->tcp_keepalive
.enabled
) {
3646 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3649 ++incoming_sockets_accepted
;
3651 // Socket is ready, setup the connection manager to start using it
3652 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3655 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3657 if (!Config
.accessList
.ssl_bump
) {
3658 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3662 // Create a fake HTTP request for ssl_bump ACL check,
3663 // using tproxy/intercept provided destination IP and port.
3664 HttpRequest
*request
= new HttpRequest();
3665 static char ip
[MAX_IPSTRLEN
];
3666 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3667 request
->SetHost(params
.conn
->local
.NtoA(ip
, sizeof(ip
)));
3668 request
->port
= params
.conn
->local
.GetPort();
3669 request
->myportname
= s
->name
;
3671 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3672 acl_checklist
->src_addr
= params
.conn
->remote
;
3673 acl_checklist
->my_addr
= s
->s
;
3674 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3677 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3678 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3683 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, char *reply
)
3685 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3686 state_data
->sslCrtdHandleReply(reply
);
3690 ConnStateData::sslCrtdHandleReply(const char * reply
)
3693 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper return <NULL> reply");
3695 Ssl::CrtdMessage reply_message
;
3696 if (reply_message
.parse(reply
, strlen(reply
)) != Ssl::CrtdMessage::OK
) {
3697 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3699 if (reply_message
.getCode() != "OK") {
3700 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3702 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3703 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str());
3704 getSslContextDone(ctx
, true);
3709 getSslContextDone(NULL
);
3712 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3714 certProperties
.commonName
= sslCommonName
.defined() ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3716 // fake certificate adaptation requires bump-server-first mode
3717 if (!sslServerBump
) {
3718 assert(port
->signingCert
.get());
3719 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3720 if (port
->signPkey
.get())
3721 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3722 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3726 // In case of an error while connecting to the secure server, use a fake
3727 // trusted certificate, with no mimicked fields and no adaptation
3728 // algorithms. There is nothing we can mimic so we want to minimize the
3729 // number of warnings the user will have to see to get to the error page.
3730 assert(sslServerBump
->entry
);
3731 if (sslServerBump
->entry
->isEmpty()) {
3732 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3733 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3735 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
,
3736 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3737 checklist
.conn(this);
3738 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3740 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3741 // If the algorithm already set, then ignore it.
3742 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3743 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3744 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3747 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3748 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3749 const char *param
= ca
->param
;
3751 // For parameterless CN adaptation, use hostname from the
3753 if (ca
->alg
== Ssl::algSetCommonName
) {
3755 param
= sslConnectHostOrIp
.termedBuf();
3756 certProperties
.commonName
= param
;
3757 certProperties
.setCommonName
= true;
3758 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3759 certProperties
.setValidAfter
= true;
3760 else if (ca
->alg
== Ssl::algSetValidBefore
)
3761 certProperties
.setValidBefore
= true;
3763 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3764 alg
<< " param: " << (param
? param
: "-"));
3768 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3769 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3770 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3771 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3775 } else {// if (!sslServerBump->entry->isEmpty())
3776 // Use trusted certificate for a Squid-generated error
3777 // or the user would have to add a security exception
3778 // just to see the error page. We will close the connection
3779 // so that the trust is not extended to non-Squid content.
3780 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3783 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3785 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3786 assert(port
->untrustedSigningCert
.get());
3787 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3788 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3790 assert(port
->signingCert
.get());
3791 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3793 if (port
->signPkey
.get())
3794 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3796 signAlgorithm
= certProperties
.signAlgorithm
;
3800 ConnStateData::getSslContextStart()
3802 assert(areAllContextsForThisConnection());
3804 /* careful: freeAllContexts() above frees request, host, etc. */
3806 if (port
->generateHostCertificates
) {
3807 Ssl::CertificateProperties certProperties
;
3808 buildSslCertGenerationParams(certProperties
);
3809 sslBumpCertKey
= certProperties
.dbKey().c_str();
3810 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3812 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3813 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3814 SSL_CTX
* dynCtx
= ssl_ctx_cache
.find(sslBumpCertKey
.termedBuf());
3816 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3817 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3818 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3819 getSslContextDone(dynCtx
);
3822 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3823 ssl_ctx_cache
.remove(sslBumpCertKey
.termedBuf());
3826 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3831 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3832 Ssl::CrtdMessage request_message
;
3833 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3834 request_message
.composeRequest(certProperties
);
3835 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3836 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3838 } catch (const std::exception
&e
) {
3839 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3840 "request for " << certProperties
.commonName
<<
3841 " certificate: " << e
.what() << "; will now block to " <<
3842 "generate that certificate.");
3843 // fall through to do blocking in-process generation.
3845 #endif // USE_SSL_CRTD
3847 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3848 dynCtx
= Ssl::generateSslContext(certProperties
);
3849 getSslContextDone(dynCtx
, true);
3852 getSslContextDone(NULL
);
3856 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3858 // Try to add generated ssl context to storage.
3859 if (port
->generateHostCertificates
&& isNew
) {
3861 if (signAlgorithm
== Ssl::algSignTrusted
)
3862 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3863 //else it is self-signed or untrusted do not attrach any certificate
3865 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3866 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3868 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), sslContext
)) {
3869 // If it is not in storage delete after using. Else storage deleted it.
3870 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3873 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3877 // If generated ssl context = NULL, try to use static ssl context.
3879 if (!port
->staticSslContext
) {
3880 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3881 clientConnection
->close();
3884 debugs(33, 5, HERE
<< "Using static ssl context.");
3885 sslContext
= port
->staticSslContext
.get();
3890 if (!(ssl
= httpsCreate(clientConnection
, sslContext
)))
3893 // commSetConnTimeout() was called for this request before we switched.
3895 // Disable the client read handler until peer selection is complete
3896 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3897 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3898 switchedToHttps_
= true;
3902 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3904 assert(!switchedToHttps_
);
3906 sslConnectHostOrIp
= request
->GetHost();
3907 sslCommonName
= request
->GetHost();
3909 // We are going to read new request
3910 flags
.readMore
= true;
3911 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3913 // If sslServerBump is set, then we have decided to deny CONNECT
3914 // and now want to switch to SSL to send the error to the client
3915 // without even peeking at the origin server certificate.
3916 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3917 request
->flags
.sslPeek
= 1;
3918 sslServerBump
= new Ssl::ServerBump(request
);
3920 // will call httpsPeeked() with certificate and connection, eventually
3921 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
);
3925 // otherwise, use sslConnectHostOrIp
3926 getSslContextStart();
3930 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3932 Must(sslServerBump
!= NULL
);
3934 if (Comm::IsConnOpen(serverConnection
)) {
3935 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3937 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3938 assert(serverCert
.get() != NULL
);
3939 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
3940 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
3941 " bumped: " << *serverConnection
);
3943 pinConnection(serverConnection
, NULL
, NULL
, false);
3945 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3947 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3948 Ip::Address intendedDest
;
3949 intendedDest
= sslConnectHostOrIp
.termedBuf();
3950 const bool isConnectRequest
= !port
->spoof_client_ip
&& !port
->intercepted
;
3952 // Squid serves its own error page and closes, so we want
3953 // a CN that causes no additional browser errors. Possible
3954 // only when bumping CONNECT with a user-typed address.
3955 if (intendedDest
.IsAnyAddr() || isConnectRequest
)
3956 sslCommonName
= sslConnectHostOrIp
;
3957 else if (sslServerBump
->serverCert
.get())
3958 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
3960 // copy error detail from bump-server-first request to CONNECT request
3961 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
3962 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3965 getSslContextStart();
3968 #endif /* USE_SSL */
3970 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3972 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3974 if (!Comm::IsConnOpen(c
)) {
3975 Must(NHttpSockets
> 0); // we tried to open some
3976 --NHttpSockets
; // there will be fewer sockets than planned
3977 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3979 if (!NHttpSockets
) // we could not open any listen sockets at all
3980 fatalf("Unable to open %s",FdNote(portType
));
3987 /// find any unused HttpSockets[] slot and store fd there or return false
3989 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
3992 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
3993 if ((found
= HttpSockets
[i
] < 0))
3994 HttpSockets
[i
] = conn
->fd
;
4000 clientHttpConnectionsOpen(void)
4002 AnyP::PortCfg
*s
= NULL
;
4004 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4005 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4006 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4007 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4012 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4013 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4017 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4018 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4022 // Create ssl_ctx cache for this port.
4023 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4027 // Fill out a Comm::Connection which IPC will open as a listener for us
4028 // then pass back when active so we can start a TcpAcceptor subscription.
4029 s
->listenConn
= new Comm::Connection
;
4030 s
->listenConn
->local
= s
->s
;
4031 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) | (s
->intercepted
? COMM_INTERCEPTION
: 0);
4033 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4034 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4035 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4036 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4038 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4039 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4040 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4042 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4049 clientHttpsConnectionsOpen(void)
4053 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4054 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4055 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4056 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4060 if (!s
->staticSslContext
) {
4061 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4062 " due to SSL initialization failure.");
4066 // TODO: merge with similar code in clientHttpConnectionsOpen()
4067 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4068 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4072 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4073 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4078 // Create ssl_ctx cache for this port.
4079 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4082 // Fill out a Comm::Connection which IPC will open as a listener for us
4083 s
->listenConn
= new Comm::Connection
;
4084 s
->listenConn
->local
= s
->s
;
4085 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) |
4086 (s
->intercepted
? COMM_INTERCEPTION
: 0);
4088 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4089 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4090 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4091 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4093 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4094 ListeningStartedDialer(&clientListenerConnectionOpened
,
4095 s
, Ipc::fdnHttpsSocket
, sub
));
4096 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4097 HttpSockets
[NHttpSockets
] = -1;
4103 /// process clientHttpConnectionsOpen result
4105 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4107 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4111 Must(Comm::IsConnOpen(s
->listenConn
));
4113 // TCP: setup a job to handle accept() with subscribed handler
4114 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4116 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4117 (s
->intercepted
? "NAT intercepted " : "") <<
4118 (s
->spoof_client_ip
? "TPROXY spoofing " : "") <<
4119 (s
->sslBump
? "SSL bumped " : "") <<
4120 (s
->accel
? "reverse-proxy " : "")
4121 << FdNote(portTypeNote
) << " connections at "
4124 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4128 clientOpenListenSockets(void)
4130 clientHttpConnectionsOpen();
4132 clientHttpsConnectionsOpen();
4135 if (NHttpSockets
< 1)
4136 fatal("No HTTP or HTTPS ports configured");
4140 clientHttpConnectionsClose(void)
4142 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4143 if (s
->listenConn
!= NULL
) {
4144 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4145 s
->listenConn
->close();
4146 s
->listenConn
= NULL
;
4151 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4152 if (s
->listenConn
!= NULL
) {
4153 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4154 s
->listenConn
->close();
4155 s
->listenConn
= NULL
;
4160 // TODO see if we can drop HttpSockets array entirely */
4161 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4162 HttpSockets
[i
] = -1;
4169 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4171 const char *vary
= request
->vary_headers
;
4172 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4173 #if X_ACCELERATOR_VARY
4176 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4179 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4181 /* Oops... something odd is going on here.. */
4182 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4183 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4184 safe_free(request
->vary_headers
);
4189 /* This is not a varying object */
4193 /* virtual "vary" object found. Calculate the vary key and
4194 * continue the search
4196 vary
= httpMakeVaryMark(request
, entry
->getReply());
4199 request
->vary_headers
= xstrdup(vary
);
4202 /* Ouch.. we cannot handle this kind of variance */
4203 /* XXX This cannot really happen, but just to be complete */
4208 vary
= httpMakeVaryMark(request
, entry
->getReply());
4211 request
->vary_headers
= xstrdup(vary
);
4215 /* Ouch.. we cannot handle this kind of variance */
4216 /* XXX This cannot really happen, but just to be complete */
4218 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4221 /* Oops.. we have already been here and still haven't
4222 * found the requested variant. Bail out
4224 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4225 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4231 ACLFilledChecklist
*
4232 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4234 ConnStateData
* conn
= http
->getConn();
4235 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4236 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4239 * hack for ident ACL. It needs to get full addresses, and a place to store
4240 * the ident result on persistent connections...
4242 /* connection oriented auth also needs these two lines for it's operation. */
4244 * Internal requests do not have a connection reference, because: A) their
4245 * byte count may be transformed before being applied to an outbound
4246 * connection B) they are internal - any limiting on them should be done on
4251 ch
->conn(conn
); /* unreferenced in FilledCheckList.cc */
4256 CBDATA_CLASS_INIT(ConnStateData
);
4258 ConnStateData::ConnStateData() :
4259 AsyncJob("ConnStateData"),
4261 sslBumpMode(Ssl::bumpEnd
),
4262 switchedToHttps_(false),
4263 sslServerBump(NULL
),
4265 stoppedSending_(NULL
),
4266 stoppedReceiving_(NULL
)
4268 pinning
.pinned
= false;
4269 pinning
.auth
= false;
4273 ConnStateData::transparent() const
4275 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4279 ConnStateData::reading() const
4281 return reader
!= NULL
;
4285 ConnStateData::stopReading()
4288 comm_read_cancel(clientConnection
->fd
, reader
);
4294 ConnStateData::expectRequestBody(int64_t size
)
4296 bodyPipe
= new BodyPipe(this);
4298 bodyPipe
->setBodySize(size
);
4300 startDechunkingRequest();
4305 ConnStateData::mayNeedToReadMoreBody() const
4308 return 0; // request without a body or read/produced all body bytes
4310 if (!bodyPipe
->bodySizeKnown())
4311 return -1; // probably need to read more, but we cannot be sure
4313 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4314 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4316 if (needToProduce
<= haveAvailable
)
4317 return 0; // we have read what we need (but are waiting for pipe space)
4319 return needToProduce
- haveAvailable
;
4323 ConnStateData::stopReceiving(const char *error
)
4325 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4326 "; old sending error: " <<
4327 (stoppedSending() ? stoppedSending_
: "none"));
4329 if (const char *oldError
= stoppedReceiving()) {
4330 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4331 return; // nothing has changed as far as this connection is concerned
4334 stoppedReceiving_
= error
;
4336 if (const char *sendError
= stoppedSending()) {
4337 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4338 clientConnection
->close();
4343 ConnStateData::expectNoForwarding()
4345 if (bodyPipe
!= NULL
) {
4346 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4347 bodyPipe
->expectNoConsumption();
4351 /// initialize dechunking state
4353 ConnStateData::startDechunkingRequest()
4355 Must(bodyPipe
!= NULL
);
4356 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4357 assert(!in
.bodyParser
);
4358 in
.bodyParser
= new ChunkedCodingParser
;
4361 /// put parsed content into input buffer and clean up
4363 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4365 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4367 if (bodyPipe
!= NULL
) {
4368 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4369 BodyPipe::Pointer myPipe
= bodyPipe
;
4370 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4371 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4373 Must(myPipe
->bodySizeKnown());
4374 ClientSocketContext::Pointer context
= getCurrentContext();
4375 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4376 context
->http
->request
->setContentLength(myPipe
->bodySize());
4380 delete in
.bodyParser
;
4381 in
.bodyParser
= NULL
;
4385 ConnStateData::In::addressToReadInto() const
4387 return buf
+ notYetUsed
;
4390 ConnStateData::In::In() : bodyParser(NULL
),
4391 buf (NULL
), notYetUsed (0), allocatedSize (0)
4394 ConnStateData::In::~In()
4397 memFreeBuf(allocatedSize
, buf
);
4398 delete bodyParser
; // TODO: pool
4402 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4405 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4409 ClientSocketContext::Pointer context
= getCurrentContext();
4410 if (context
!= NULL
) {
4411 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4415 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4416 clientConnection
->close();
4419 /// Our close handler called by Comm when the pinned connection is closed
4421 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4423 // FwdState might repin a failed connection sooner than this close
4424 // callback is called for the failed connection.
4425 if (pinning
.serverConnection
== io
.conn
) {
4426 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4432 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, struct peer
*aPeer
, bool auth
)
4434 char desc
[FD_DESC_SZ
];
4436 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4437 if (pinning
.serverConnection
->fd
== pinServer
->fd
)
4441 unpinConnection(); // closes pinned connection, if any, and resets fields
4443 pinning
.serverConnection
= pinServer
;
4445 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4447 // when pinning an SSL bumped connection, the request may be NULL
4448 const char *pinnedHost
= "[unknown]";
4450 pinning
.host
= xstrdup(request
->GetHost());
4451 pinning
.port
= request
->port
;
4452 pinnedHost
= pinning
.host
;
4454 pinning
.port
= pinServer
->remote
.GetPort();
4456 pinning
.pinned
= true;
4458 pinning
.peer
= cbdataReference(aPeer
);
4459 pinning
.auth
= auth
;
4460 char stmp
[MAX_IPSTRLEN
];
4461 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4462 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4463 clientConnection
->remote
.ToURL(stmp
,MAX_IPSTRLEN
),
4464 clientConnection
->fd
);
4465 fd_note(pinning
.serverConnection
->fd
, desc
);
4467 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4468 pinning
.closeHandler
= JobCallback(33, 5,
4469 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4470 // remember the pinned connection so that cb does not unpin a fresher one
4471 typedef CommCloseCbParams Params
;
4472 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4473 params
.conn
= pinning
.serverConnection
;
4474 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4477 const Comm::ConnectionPointer
4478 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const struct peer
*aPeer
)
4480 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4483 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4485 if (pinning
.auth
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0) {
4488 if (request
&& pinning
.port
!= request
->port
) {
4491 if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
)) {
4494 if (aPeer
!= pinning
.peer
) {
4499 /* The pinning info is not safe, remove any pinning info */
4503 return pinning
.serverConnection
;
4507 ConnStateData::unpinConnection()
4509 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4512 cbdataReferenceDone(pinning
.peer
);
4514 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4515 if (pinning
.closeHandler
!= NULL
) {
4516 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4517 pinning
.closeHandler
= NULL
;
4519 /// also close the server side socket, we should not use it for any future requests...
4520 // TODO: do not close if called from our close handler?
4521 pinning
.serverConnection
->close();
4524 safe_free(pinning
.host
);
4526 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4527 * connection has gone away */