2 * DEBUG: section 33 Client-side Routines
3 * AUTHOR: Duane Wessels
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 \defgroup ClientSide Client-Side Logics
35 \section cserrors Errors and client side
37 \par Problem the first:
38 * the store entry is no longer authoritative on the
39 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
40 * of client_side_reply.c.
41 * Problem the second: resources are wasted if we delay in cleaning up.
42 * Problem the third we can't depend on a connection close to clean up.
44 \par Nice thing the first:
45 * Any step in the stream can callback with data
46 * representing an error.
47 * Nice thing the second: once you stop requesting reads from upstream,
48 * upstream can be stopped too.
51 * Error has a callback mechanism to hand over a membuf
52 * with the error content. The failing node pushes that back as the
53 * reply. Can this be generalised to reduce duplicate efforts?
54 * A: Possibly. For now, only one location uses this.
55 * How to deal with pre-stream errors?
56 * Tell client_side_reply that we *want* an error page before any
57 * stream calls occur. Then we simply read as normal.
60 \section pconn_logic Persistent connection logic:
63 * requests (httpClientRequest structs) get added to the connection
64 * list, with the current one being chr
67 * The request is *immediately* kicked off, and data flows through
68 * to clientSocketRecipient.
71 * If the data that arrives at clientSocketRecipient is not for the current
72 * request, clientSocketRecipient simply returns, without requesting more
73 * data, or sending it.
76 * ClientKeepAliveNextRequest will then detect the presence of data in
77 * the next ClientHttpRequest, and will send it, restablishing the
82 #include "acl/FilledChecklist.h"
83 #include "anyp/PortCfg.h"
84 #include "base/Subscription.h"
85 #include "base/TextException.h"
86 #include "CachePeer.h"
87 #include "ChunkedCodingParser.h"
88 #include "client_db.h"
89 #include "client_side_reply.h"
90 #include "client_side_request.h"
91 #include "client_side.h"
92 #include "ClientRequestContext.h"
93 #include "clientStream.h"
95 #include "comm/Connection.h"
96 #include "comm/Loops.h"
97 #include "comm/TcpAcceptor.h"
98 #include "comm/Write.h"
99 #include "CommCalls.h"
100 #include "errorpage.h"
101 #include "eui/Config.h"
105 #include "fqdncache.h"
108 #include "HttpHdrContRange.h"
109 #include "HttpHeaderTools.h"
110 #include "HttpReply.h"
111 #include "HttpRequest.h"
112 #include "ident/Config.h"
113 #include "ident/Ident.h"
114 #include "internal.h"
115 #include "ipc/FdNotes.h"
116 #include "ipc/StartListening.h"
117 #include "log/access_log.h"
120 #include "MemObject.h"
121 #include "mime_header.h"
122 #include "profiler/Profiler.h"
124 #include "SquidConfig.h"
125 #include "SquidTime.h"
126 #include "StatCounters.h"
127 #include "StatHist.h"
129 #include "TimeOrTag.h"
134 #include "auth/UserRequest.h"
137 #include "ClientInfo.h"
140 #include "ssl/ProxyCerts.h"
141 #include "ssl/context_storage.h"
142 #include "ssl/helper.h"
143 #include "ssl/ServerBump.h"
144 #include "ssl/support.h"
145 #include "ssl/gadgets.h"
148 #include "ssl/crtd_message.h"
149 #include "ssl/certificate_db.h"
163 #define comm_close comm_lingering_close
166 /// dials clientListenerConnectionOpened call
167 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
170 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
171 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
172 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
174 virtual void print(std::ostream
&os
) const {
176 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
179 virtual bool canDial(AsyncCall
&) const { return true; }
180 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
186 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
187 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
188 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
191 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
193 /* our socket-related context */
195 CBDATA_CLASS_INIT(ClientSocketContext
);
198 ClientSocketContext::operator new (size_t byteCount
)
200 /* derived classes with different sizes must implement their own new */
201 assert (byteCount
== sizeof (ClientSocketContext
));
202 CBDATA_INIT_TYPE(ClientSocketContext
);
203 return cbdataAlloc(ClientSocketContext
);
207 ClientSocketContext::operator delete (void *address
)
209 cbdataFree (address
);
212 /* Local functions */
213 /* ClientSocketContext */
214 static ClientSocketContext
*ClientSocketContextNew(const Comm::ConnectionPointer
&clientConn
, ClientHttpRequest
*);
216 static IOCB clientWriteComplete
;
217 static IOCB clientWriteBodyComplete
;
218 static IOACB httpAccept
;
220 static IOACB httpsAccept
;
222 static CTCB clientLifetimeTimeout
;
223 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
224 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, HttpVersion
*);
226 static IDCB clientIdentDone
;
228 static CSCB clientSocketRecipient
;
229 static CSD clientSocketDetach
;
230 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
231 static int clientIsContentLengthValid(HttpRequest
* r
);
232 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
234 static void clientUpdateStatHistCounters(log_type logType
, int svc_time
);
235 static void clientUpdateStatCounters(log_type logType
);
236 static void clientUpdateHierCounters(HierarchyLogEntry
*);
237 static bool clientPingHasFinished(ping_data
const *aPing
);
238 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
240 static bool connIsUsable(ConnStateData
* conn
);
242 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
243 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
244 static void clientUpdateSocketStats(log_type logType
, size_t size
);
246 char *skipLeadingSpace(char *aString
);
247 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
249 static ConnStateData
*connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
);
252 ClientSocketContext::getTail() const
254 if (http
->client_stream
.tail
)
255 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
261 ClientSocketContext::getClientReplyContext() const
263 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
267 * This routine should be called to grow the inbuf and then
271 ConnStateData::readSomeData()
276 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
278 if (!maybeMakeSpaceAvailable())
281 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
282 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
283 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
287 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
289 ClientSocketContext::Pointer
*tempContextPointer
;
290 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
291 assert(conn
->getCurrentContext() != NULL
);
292 /* Unlink us from the connection request list */
293 tempContextPointer
= & conn
->currentobject
;
295 while (tempContextPointer
->getRaw()) {
296 if (*tempContextPointer
== this)
299 tempContextPointer
= &(*tempContextPointer
)->next
;
302 assert(tempContextPointer
->getRaw() != NULL
);
303 *tempContextPointer
= next
;
307 ClientSocketContext::~ClientSocketContext()
309 clientStreamNode
*node
= getTail();
312 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
315 /* We are *always* the tail - prevent recursive free */
316 assert(this == streamContext
);
322 deRegisterWithConn();
324 httpRequestFree(http
);
326 /* clean up connection links to us */
327 assert(this != next
.getRaw());
331 ClientSocketContext::registerWithConn()
333 assert (!connRegistered_
);
335 assert (http
->getConn() != NULL
);
336 connRegistered_
= true;
337 http
->getConn()->addContextToQueue(this);
341 ClientSocketContext::deRegisterWithConn()
343 assert (connRegistered_
);
344 removeFromConnectionList(http
->getConn());
345 connRegistered_
= false;
349 ClientSocketContext::connIsFinished()
352 assert (http
->getConn() != NULL
);
353 deRegisterWithConn();
354 /* we can't handle any more stream data - detach */
355 clientStreamDetach(getTail(), http
);
358 ClientSocketContext::ClientSocketContext() : http(NULL
), reply(NULL
), next(NULL
),
360 mayUseConnection_ (false),
361 connRegistered_ (false)
363 memset (reqbuf
, '\0', sizeof (reqbuf
));
366 deferredparams
.node
= NULL
;
367 deferredparams
.rep
= NULL
;
370 ClientSocketContext
*
371 ClientSocketContextNew(const Comm::ConnectionPointer
&client
, ClientHttpRequest
* http
)
373 ClientSocketContext
*newContext
;
374 assert(http
!= NULL
);
375 newContext
= new ClientSocketContext
;
376 newContext
->http
= http
;
377 newContext
->clientConnection
= client
;
382 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
384 HttpReply
*rep
= msg
.reply
;
387 // apply selected clientReplyContext::buildReplyHeader() mods
388 // it is not clear what headers are required for control messages
389 rep
->header
.removeHopByHopEntries();
390 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
391 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
393 // remember the callback
394 cbControlMsgSent
= msg
.cbSuccess
;
396 MemBuf
*mb
= rep
->pack();
398 debugs(11, 2, "HTTP Client " << clientConnection
);
399 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
401 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
402 CommIoCbPtrFun(&WroteControlMsg
, this));
403 Comm::Write(clientConnection
, mb
, call
);
408 /// called when we wrote the 1xx response
410 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
412 if (errflag
== COMM_ERR_CLOSING
)
415 if (errflag
== COMM_OK
) {
416 ScheduleCallHere(cbControlMsgSent
);
420 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
421 // no error notification: see HttpControlMsg.h for rationale and
422 // note that some errors are detected elsewhere (e.g., close handler)
424 // close on 1xx errors to be conservative and to simplify the code
425 // (if we do not close, we must notify the source of a failure!)
429 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
431 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
433 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
434 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
439 clientIdentDone(const char *ident
, void *data
)
441 ConnStateData
*conn
= (ConnStateData
*)data
;
442 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
447 clientUpdateStatCounters(log_type logType
)
449 ++statCounter
.client_http
.requests
;
451 if (logTypeIsATcpHit(logType
))
452 ++statCounter
.client_http
.hits
;
454 if (logType
== LOG_TCP_HIT
)
455 ++statCounter
.client_http
.disk_hits
;
456 else if (logType
== LOG_TCP_MEM_HIT
)
457 ++statCounter
.client_http
.mem_hits
;
461 clientUpdateStatHistCounters(log_type logType
, int svc_time
)
463 statCounter
.client_http
.allSvcTime
.count(svc_time
);
465 * The idea here is not to be complete, but to get service times
466 * for only well-defined types. For example, we don't include
467 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
468 * (we *tried* to validate it, but failed).
473 case LOG_TCP_REFRESH_UNMODIFIED
:
474 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
477 case LOG_TCP_IMS_HIT
:
478 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
483 case LOG_TCP_MEM_HIT
:
485 case LOG_TCP_OFFLINE_HIT
:
486 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
491 case LOG_TCP_CLIENT_REFRESH_MISS
:
492 statCounter
.client_http
.missSvcTime
.count(svc_time
);
496 /* make compiler warnings go away */
502 clientPingHasFinished(ping_data
const *aPing
)
504 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
511 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
515 switch (someEntry
->code
) {
516 #if USE_CACHE_DIGESTS
521 ++ statCounter
.cd
.times_used
;
529 case FIRST_PARENT_MISS
:
531 case CLOSEST_PARENT_MISS
:
532 ++ statCounter
.icp
.times_used
;
533 i
= &someEntry
->ping
;
535 if (clientPingHasFinished(i
))
536 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
539 ++ statCounter
.icp
.query_timeouts
;
546 ++ statCounter
.netdb
.times_used
;
556 ClientHttpRequest::updateCounters()
558 clientUpdateStatCounters(logType
);
560 if (request
->errType
!= ERR_NONE
)
561 ++ statCounter
.client_http
.errors
;
563 clientUpdateStatHistCounters(logType
,
564 tvSubMsec(start_time
, current_time
));
566 clientUpdateHierCounters(&request
->hier
);
570 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
573 assert(aLogEntry
!= NULL
);
575 if (Config
.onoff
.log_mime_hdrs
) {
579 packerToMemInit(&p
, &mb
);
580 request
->header
.packInto(&p
);
581 //This is the request after adaptation or redirection
582 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
584 // the virgin request is saved to aLogEntry->request
585 if (aLogEntry
->request
) {
588 packerToMemInit(&p
, &mb
);
589 aLogEntry
->request
->header
.packInto(&p
);
590 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
594 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
598 packerToMemInit(&p
, &mb
);
599 ah
->lastMeta
.packInto(&p
);
600 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
601 aLogEntry
->notes
.append(&ah
->metaHeaders
);
610 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
612 aLogEntry
->icap
.processingTime
= ih
->processingTime();
615 aLogEntry
->http
.method
= request
->method
;
616 aLogEntry
->http
.version
= request
->http_ver
;
617 aLogEntry
->hier
= request
->hier
;
618 if (request
->helperNotes
)
619 aLogEntry
->notes
.append(request
->helperNotes
->notes
);
620 if (request
->content_length
> 0) // negative when no body or unknown length
621 aLogEntry
->cache
.requestSize
+= request
->content_length
;
622 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
625 if (request
->auth_user_request
!= NULL
) {
626 if (request
->auth_user_request
->username())
627 aLogEntry
->cache
.authuser
= xstrdup(request
->auth_user_request
->username());
631 // Adapted request, if any, inherits and then collects all the stats, but
632 // the virgin request gets logged instead; copy the stats to log them.
633 // TODO: avoid losses by keeping these stats in a shared history object?
634 if (aLogEntry
->request
) {
635 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
636 aLogEntry
->request
->errType
= request
->errType
;
637 aLogEntry
->request
->errDetail
= request
->errDetail
;
642 ClientHttpRequest::logRequest()
644 if (!out
.size
&& !logType
)
645 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
647 al
->icp
.opcode
= ICP_INVALID
;
649 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
652 al
->http
.code
= al
->reply
->sline
.status
;
653 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
654 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
655 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status
;
656 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
659 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
661 if (loggingEntry() && loggingEntry()->mem_obj
)
662 al
->cache
.objectSize
= loggingEntry()->contentLen();
664 al
->cache
.caddr
.SetNoAddr();
666 if (getConn() != NULL
) {
667 al
->cache
.caddr
= getConn()->log_addr
;
668 al
->cache
.port
= cbdataReference(getConn()->port
);
671 al
->cache
.requestSize
= req_sz
;
672 al
->cache
.requestHeadersSize
= req_sz
;
674 al
->cache
.replySize
= out
.size
;
675 al
->cache
.replyHeadersSize
= out
.headers_sz
;
677 al
->cache
.highOffset
= out
.offset
;
679 al
->cache
.code
= logType
;
681 al
->cache
.msec
= tvSubMsec(start_time
, current_time
);
684 prepareLogWithRequestDetails(request
, al
);
686 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
687 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
691 /* This is broken. Fails if the connection has been closed. Needs
692 * to snarf the ssl details some place earlier..
694 if (getConn() != NULL
)
695 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
700 typedef Notes::iterator ACAMLI
;
701 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
702 if (const char *value
= (*i
)->match(request
, al
->reply
)) {
703 al
->notes
.addEntry(new HttpHeaderEntry(HDR_OTHER
, (*i
)->key
.termedBuf(), value
));
704 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
708 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.log
, this);
711 checklist
->reply
= HTTPMSGLOCK(al
->reply
);
713 if (!Config
.accessList
.log
|| checklist
->fastCheck() == ACCESS_ALLOWED
) {
715 al
->adapted_request
= HTTPMSGLOCK(request
);
716 accessLogLog(al
, checklist
);
720 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
721 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
728 ClientHttpRequest::freeResources()
732 safe_free(redirect
.location
);
733 range_iter
.boundary
.clean();
734 HTTPMSGUNLOCK(request
);
736 if (client_stream
.tail
)
737 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
741 httpRequestFree(void *data
)
743 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
744 assert(http
!= NULL
);
749 ConnStateData::areAllContextsForThisConnection() const
751 assert(this != NULL
);
752 ClientSocketContext::Pointer context
= getCurrentContext();
754 while (context
.getRaw()) {
755 if (context
->http
->getConn() != this)
758 context
= context
->next
;
765 ConnStateData::freeAllContexts()
767 ClientSocketContext::Pointer context
;
769 while ((context
= getCurrentContext()).getRaw() != NULL
) {
770 assert(getCurrentContext() !=
771 getCurrentContext()->next
);
772 context
->connIsFinished();
773 assert (context
!= currentobject
);
777 /// propagates abort event to all contexts
779 ConnStateData::notifyAllContexts(int xerrno
)
781 typedef ClientSocketContext::Pointer CSCP
;
782 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
783 c
->noteIoError(xerrno
);
786 /* This is a handler normally called by comm_close() */
787 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
789 deleteThis("ConnStateData::connStateClosed");
792 // cleans up before destructor is called
794 ConnStateData::swanSong()
796 debugs(33, 2, HERE
<< clientConnection
);
797 flags
.readMore
= false;
798 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
799 assert(areAllContextsForThisConnection());
802 if (auth_user_request
!= NULL
) {
803 debugs(33, 4, "ConnStateData::swanSong: freeing auth_user_request '" << auth_user_request
<< "' (this is '" << this << "')");
804 auth_user_request
->onConnectionClose(this);
808 if (Comm::IsConnOpen(pinning
.serverConnection
))
809 pinning
.serverConnection
->close();
810 pinning
.serverConnection
= NULL
;
812 if (Comm::IsConnOpen(clientConnection
))
813 clientConnection
->close();
814 clientConnection
= NULL
;
816 BodyProducer::swanSong();
817 flags
.swanSang
= true;
821 ConnStateData::isOpen() const
823 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
824 Comm::IsConnOpen(clientConnection
) &&
825 !fd_table
[clientConnection
->fd
].closing();
828 ConnStateData::~ConnStateData()
830 assert(this != NULL
);
831 debugs(33, 3, HERE
<< clientConnection
);
834 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
837 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
839 cbdataReferenceDone(port
);
841 if (bodyPipe
!= NULL
)
842 stopProducingFor(bodyPipe
, false);
845 delete sslServerBump
;
850 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
851 * This is the client-side persistent connection flag. We need
852 * to set this relatively early in the request processing
853 * to handle hacks for broken servers and clients.
856 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
858 HttpRequest
*request
= http
->request
;
860 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
861 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
862 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
863 RequestMethodStr(request
->method
));
865 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
866 request
->flags
.proxyKeepalive
= request
->persistent() ? 1 : 0;
870 clientIsContentLengthValid(HttpRequest
* r
)
872 switch (r
->method
.id()) {
874 case Http::METHOD_GET
:
876 case Http::METHOD_HEAD
:
877 /* We do not want to see a request entity on GET/HEAD requests */
878 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
881 /* For other types of requests we don't care */
889 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
891 if (Config
.maxRequestBodySize
&&
892 bodyLength
> Config
.maxRequestBodySize
)
893 return 1; /* too large */
900 connIsUsable(ConnStateData
* conn
)
902 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
910 // careful: the "current" context may be gone if we wrote an early response
911 ClientSocketContext::Pointer
912 ConnStateData::getCurrentContext() const
915 return currentobject
;
919 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
921 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
922 assert(flags
.deferred
== 0);
924 deferredparams
.node
= node
;
925 deferredparams
.rep
= rep
;
926 deferredparams
.queuedBuffer
= receivedData
;
931 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
933 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
940 ClientSocketContext::startOfOutput() const
942 return http
->out
.size
== 0;
946 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
948 /*the size of available range can always fit in a size_t type*/
949 size_t maximum
= (size_t)available
.size();
951 if (!http
->request
->range
)
954 assert (canPackMoreRanges());
956 if (http
->range_iter
.debt() == -1)
959 assert (http
->range_iter
.debt() > 0);
961 /* TODO this + the last line could be a range intersection calculation */
962 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
965 return min(http
->range_iter
.debt(), (int64_t)maximum
);
969 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
971 http
->out
.offset
+= bytes
;
973 if (!http
->request
->range
)
976 if (http
->range_iter
.debt() != -1) {
977 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
978 assert (http
->range_iter
.debt() >= 0);
981 /* debt() always stops at -1, below that is a bug */
982 assert (http
->range_iter
.debt() >= -1);
986 ClientHttpRequest::multipartRangeRequest() const
988 return request
->multipartRangeRequest();
992 ClientSocketContext::multipartRangeRequest() const
994 return http
->multipartRangeRequest();
998 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1000 assert(rep
== NULL
);
1002 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1003 size_t length
= lengthToSend(bodyData
.range());
1004 noteSentBodyBytes (length
);
1005 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1006 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1007 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1013 if (multipartRangeRequest())
1014 packRange(bodyData
, &mb
);
1016 packChunk(bodyData
, mb
);
1018 if (mb
.contentSize()) {
1020 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1021 CommIoCbPtrFun(clientWriteComplete
, this));
1022 Comm::Write(clientConnection
, &mb
, call
);
1024 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1028 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1029 * if bodyData is empty.
1032 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1034 const uint64_t length
=
1035 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1036 noteSentBodyBytes(length
);
1038 mb
.Printf("%" PRIX64
"\r\n", length
);
1039 mb
.append(bodyData
.data
, length
);
1043 /** put terminating boundary for multiparts */
1045 clientPackTermBound(String boundary
, MemBuf
* mb
)
1047 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1048 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1051 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1053 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1055 HttpHeader
hdr(hoReply
);
1061 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1062 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1063 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1065 /* stuff the header with required entries and pack it */
1067 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1068 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1070 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1072 packerToMemInit(&p
, mb
);
1080 /* append <crlf> (we packed a header, not a reply) */
1085 * extracts a "range" from *buf and appends them to mb, updating
1086 * all offsets and such.
1089 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1091 HttpHdrRangeIter
* i
= &http
->range_iter
;
1092 Range
<int64_t> available (source
.range());
1093 char const *buf
= source
.data
;
1095 while (i
->currentSpec() && available
.size()) {
1096 const size_t copy_sz
= lengthToSend(available
);
1100 * intersection of "have" and "need" ranges must not be empty
1102 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1103 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1106 * put boundary and headers at the beginning of a range in a
1110 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1111 assert(http
->memObject());
1113 http
->memObject()->getReply(), /* original reply */
1114 i
->currentSpec(), /* current range */
1115 i
->boundary
, /* boundary, the same for all */
1122 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1124 noteSentBodyBytes (copy_sz
);
1126 mb
->append(buf
, copy_sz
);
1131 available
.start
+= copy_sz
;
1137 if (!canPackMoreRanges()) {
1138 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1141 /* put terminating boundary for multiparts */
1142 clientPackTermBound(i
->boundary
, mb
);
1147 int64_t nextOffset
= getNextRangeOffset();
1149 assert (nextOffset
>= http
->out
.offset
);
1151 int64_t skip
= nextOffset
- http
->out
.offset
;
1153 /* adjust for not to be transmitted bytes */
1154 http
->out
.offset
= nextOffset
;
1156 if (available
.size() <= (uint64_t)skip
)
1159 available
.start
+= skip
;
1168 /** returns expected content length for multi-range replies
1169 * note: assumes that httpHdrRangeCanonize has already been called
1170 * warning: assumes that HTTP headers for individual ranges at the
1171 * time of the actuall assembly will be exactly the same as
1172 * the headers when clientMRangeCLen() is called */
1174 ClientHttpRequest::mRangeCLen()
1179 assert(memObject());
1182 HttpHdrRange::iterator pos
= request
->range
->begin();
1184 while (pos
!= request
->range
->end()) {
1185 /* account for headers for this range */
1187 clientPackRangeHdr(memObject()->getReply(),
1188 *pos
, range_iter
.boundary
, &mb
);
1191 /* account for range content */
1192 clen
+= (*pos
)->length
;
1194 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1198 /* account for the terminating boundary */
1201 clientPackTermBound(range_iter
.boundary
, &mb
);
1211 * returns true if If-Range specs match reply, false otherwise
1214 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1216 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1217 /* check for parsing falure */
1224 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1225 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1226 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1229 return 0; /* entity has no etag to compare with! */
1231 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1232 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1233 return 0; /* must use strong validator for sub-range requests */
1236 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1239 /* got modification time? */
1240 if (spec
.time
>= 0) {
1241 return http
->storeEntry()->lastmod
<= spec
.time
;
1244 assert(0); /* should not happen */
1249 * generates a "unique" boundary string for multipart responses
1250 * the caller is responsible for cleaning the string */
1252 ClientHttpRequest::rangeBoundaryStr() const
1256 String
b(APP_FULLNAME
);
1258 key
= storeEntry()->getMD5Text();
1259 b
.append(key
, strlen(key
));
1263 /** adds appropriate Range headers if needed */
1265 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1267 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1268 const char *range_err
= NULL
;
1269 HttpRequest
*request
= http
->request
;
1270 assert(request
->range
);
1271 /* check if we still want to do ranges */
1273 int64_t roffLimit
= request
->getRangeOffsetLimit();
1276 range_err
= "no [parse-able] reply";
1277 else if ((rep
->sline
.status
!= HTTP_OK
) && (rep
->sline
.status
!= HTTP_PARTIAL_CONTENT
))
1278 range_err
= "wrong status code";
1279 else if (hdr
->has(HDR_CONTENT_RANGE
))
1280 range_err
= "origin server does ranges";
1281 else if (rep
->content_length
< 0)
1282 range_err
= "unknown length";
1283 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1284 range_err
= "INCONSISTENT length"; /* a bug? */
1286 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1289 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1290 range_err
= "If-Range match failed";
1291 else if (!http
->request
->range
->canonize(rep
))
1292 range_err
= "canonization failed";
1293 else if (http
->request
->range
->isComplex())
1294 range_err
= "too complex range header";
1295 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1296 range_err
= "range outside range_offset_limit";
1298 /* get rid of our range specs on error */
1300 /* XXX We do this here because we need canonisation etc. However, this current
1301 * code will lead to incorrect store offset requests - the store will have the
1302 * offset data, but we won't be requesting it.
1303 * So, we can either re-request, or generate an error
1305 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1306 delete http
->request
->range
;
1307 http
->request
->range
= NULL
;
1309 /* XXX: TODO: Review, this unconditional set may be wrong. - TODO: review. */
1310 httpStatusLineSet(&rep
->sline
, rep
->sline
.version
,
1311 HTTP_PARTIAL_CONTENT
, NULL
);
1312 // web server responded with a valid, but unexpected range.
1313 // will (try-to) forward as-is.
1314 //TODO: we should cope with multirange request/responses
1315 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1316 request
->range
->contains(rep
->content_range
->spec
) :
1318 const int spec_count
= http
->request
->range
->specs
.count
;
1319 int64_t actual_clen
= -1;
1321 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1322 spec_count
<< " virgin clen: " << rep
->content_length
);
1323 assert(spec_count
> 0);
1324 /* append appropriate header(s) */
1326 if (spec_count
== 1) {
1327 if (!replyMatchRequest
) {
1328 hdr
->delById(HDR_CONTENT_RANGE
);
1329 hdr
->putContRange(rep
->content_range
);
1330 actual_clen
= rep
->content_length
;
1331 //http->range_iter.pos = rep->content_range->spec.begin();
1332 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1333 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1336 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1338 /* append Content-Range */
1340 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1341 /* No content range, so this was a full object we are
1344 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1347 /* set new Content-Length to the actual number of bytes
1348 * transmitted in the message-body */
1349 actual_clen
= (*pos
)->length
;
1353 /* generate boundary string */
1354 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1355 /* delete old Content-Type, add ours */
1356 hdr
->delById(HDR_CONTENT_TYPE
);
1357 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1358 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1359 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1360 /* Content-Length is not required in multipart responses
1361 * but it is always nice to have one */
1362 actual_clen
= http
->mRangeCLen();
1363 /* http->out needs to start where we want data at */
1364 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1367 /* replace Content-Length header */
1368 assert(actual_clen
>= 0);
1370 hdr
->delById(HDR_CONTENT_LENGTH
);
1372 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1374 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1376 /* And start the range iter off */
1377 http
->range_iter
.updateSpec();
1382 ClientSocketContext::prepareReply(HttpReply
* rep
)
1386 if (http
->request
->range
)
1387 buildRangeHeader(rep
);
1391 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1395 MemBuf
*mb
= rep
->pack();
1397 // dump now, so we dont output any body.
1398 debugs(11, 2, "HTTP Client " << clientConnection
);
1399 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1401 /* Save length of headers for persistent conn checks */
1402 http
->out
.headers_sz
= mb
->contentSize();
1405 headersLog(0, 0, http
->request
->method
, rep
);
1408 if (bodyData
.data
&& bodyData
.length
) {
1409 if (multipartRangeRequest())
1410 packRange(bodyData
, mb
);
1411 else if (http
->request
->flags
.chunkedReply
) {
1412 packChunk(bodyData
, *mb
);
1414 size_t length
= lengthToSend(bodyData
.range());
1415 noteSentBodyBytes (length
);
1417 mb
->append(bodyData
.data
, length
);
1422 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1423 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1424 CommIoCbPtrFun(clientWriteComplete
, this));
1425 Comm::Write(clientConnection
, mb
, call
);
1430 * Write a chunk of data to a client socket. If the reply is present,
1431 * send the reply headers down the wire too, and clean them up when
1434 * The request is one backed by a connection, not an internal request.
1435 * data context is not NULL
1436 * There are no more entries in the stream chain.
1439 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1440 HttpReply
* rep
, StoreIOBuffer receivedData
)
1442 /* Test preconditions */
1443 assert(node
!= NULL
);
1444 PROF_start(clientSocketRecipient
);
1445 /* TODO: handle this rather than asserting
1446 * - it should only ever happen if we cause an abort and
1447 * the callback chain loops back to here, so we can simply return.
1448 * However, that itself shouldn't happen, so it stays as an assert for now.
1450 assert(cbdataReferenceValid(node
));
1451 assert(node
->node
.next
== NULL
);
1452 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1453 assert(context
!= NULL
);
1454 assert(connIsUsable(http
->getConn()));
1456 /* TODO: check offset is what we asked for */
1458 if (context
!= http
->getConn()->getCurrentContext()) {
1459 context
->deferRecipientForLater(node
, rep
, receivedData
);
1460 PROF_stop(clientSocketRecipient
);
1464 // After sending Transfer-Encoding: chunked (at least), always send
1465 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1466 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1467 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1468 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1469 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1470 PROF_stop(clientSocketRecipient
);
1474 if (!context
->startOfOutput())
1475 context
->sendBody(rep
, receivedData
);
1478 http
->al
->reply
= HTTPMSGLOCK(rep
);
1479 context
->sendStartOfMessage(rep
, receivedData
);
1482 PROF_stop(clientSocketRecipient
);
1486 * Called when a downstream node is no longer interested in
1487 * our data. As we are a terminal node, this means on aborts
1491 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1493 /* Test preconditions */
1494 assert(node
!= NULL
);
1495 /* TODO: handle this rather than asserting
1496 * - it should only ever happen if we cause an abort and
1497 * the callback chain loops back to here, so we can simply return.
1498 * However, that itself shouldn't happen, so it stays as an assert for now.
1500 assert(cbdataReferenceValid(node
));
1501 /* Set null by ContextFree */
1502 assert(node
->node
.next
== NULL
);
1503 /* this is the assert discussed above */
1504 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1505 /* We are only called when the client socket shutsdown.
1506 * Tell the prev pipeline member we're finished
1508 clientStreamDetach(node
, http
);
1512 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1514 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1515 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1519 ConnStateData::readNextRequest()
1521 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1523 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1525 * Set the timeout BEFORE calling clientReadRequest().
1527 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1528 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1529 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1530 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1533 /** Please don't do anything with the FD past here! */
1537 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1539 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1541 /** If the client stream is waiting on a socket write to occur, then */
1543 if (deferredRequest
->flags
.deferred
) {
1544 /** NO data is allowed to have been sent. */
1545 assert(deferredRequest
->http
->out
.size
== 0);
1547 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1548 deferredRequest
->http
,
1549 deferredRequest
->deferredparams
.rep
,
1550 deferredRequest
->deferredparams
.queuedBuffer
);
1553 /** otherwise, the request is still active in a callbacksomewhere,
1558 /// called when we have successfully finished writing the response
1560 ClientSocketContext::keepaliveNextRequest()
1562 ConnStateData
* conn
= http
->getConn();
1564 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1567 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1568 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1569 conn
->clientConnection
->close();
1574 * We are done with the response, and we are either still receiving request
1575 * body (early response!) or have already stopped receiving anything.
1577 * If we are still receiving, then clientParseRequest() below will fail.
1578 * (XXX: but then we will call readNextRequest() which may succeed and
1579 * execute a smuggled request as we are not done with the current request).
1581 * If we stopped because we got everything, then try the next request.
1583 * If we stopped receiving because of an error, then close now to avoid
1584 * getting stuck and to prevent accidental request smuggling.
1587 if (const char *reason
= conn
->stoppedReceiving()) {
1588 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1589 conn
->clientConnection
->close();
1594 * Attempt to parse a request from the request buffer.
1595 * If we've been fed a pipelined request it may already
1596 * be in our read buffer.
1599 * This needs to fall through - if we're unlucky and parse the _last_ request
1600 * from our read buffer we may never re-register for another client read.
1603 if (conn
->clientParseRequests()) {
1604 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1608 * Either we need to kick-start another read or, if we have
1609 * a half-closed connection, kill it after the last request.
1610 * This saves waiting for half-closed connections to finished being
1611 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1612 * the keepalive "Waiting for next request" state.
1614 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1615 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1616 conn
->clientConnection
->close();
1620 ClientSocketContext::Pointer deferredRequest
;
1623 * At this point we either have a parsed request (which we've
1624 * kicked off the processing for) or not. If we have a deferred
1625 * request (parsed but deferred for pipeling processing reasons)
1626 * then look at processing it. If not, simply kickstart
1630 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1631 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1632 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1633 } else if (conn
->flags
.readMore
) {
1634 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1635 conn
->readNextRequest();
1637 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1638 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1643 clientUpdateSocketStats(log_type logType
, size_t size
)
1648 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1650 if (logTypeIsATcpHit(logType
))
1651 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1655 * increments iterator "i"
1656 * used by clientPackMoreRanges
1658 \retval true there is still data available to pack more ranges
1662 ClientSocketContext::canPackMoreRanges() const
1664 /** first update iterator "i" if needed */
1666 if (!http
->range_iter
.debt()) {
1667 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1669 if (http
->range_iter
.pos
.incrementable())
1670 ++http
->range_iter
.pos
;
1672 http
->range_iter
.updateSpec();
1675 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1677 /* paranoid sync condition */
1678 /* continue condition: need_more_data */
1679 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1680 return http
->range_iter
.currentSpec() ? true : false;
1684 ClientSocketContext::getNextRangeOffset() const
1686 if (http
->request
->range
) {
1687 /* offset in range specs does not count the prefix of an http msg */
1688 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1689 /* check: reply was parsed and range iterator was initialized */
1690 assert(http
->range_iter
.valid
);
1691 /* filter out data according to range specs */
1692 assert (canPackMoreRanges());
1694 int64_t start
; /* offset of still missing data */
1695 assert(http
->range_iter
.currentSpec());
1696 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1697 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1698 debugs(33, 3, "clientPackMoreRanges: out:"
1699 " start: " << start
<<
1700 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1701 " [" << http
->range_iter
.currentSpec()->offset
<<
1702 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1703 " len: " << http
->range_iter
.currentSpec()->length
<<
1704 " debt: " << http
->range_iter
.debt());
1705 if (http
->range_iter
.currentSpec()->length
!= -1)
1706 assert(http
->out
.offset
<= start
); /* we did not miss it */
1711 } else if (reply
&& reply
->content_range
) {
1712 /* request does not have ranges, but reply does */
1713 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1714 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1716 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1719 return http
->out
.offset
;
1723 ClientSocketContext::pullData()
1725 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1727 /* More data will be coming from the stream. */
1728 StoreIOBuffer readBuffer
;
1729 /* XXX: Next requested byte in the range sequence */
1730 /* XXX: length = getmaximumrangelenfgth */
1731 readBuffer
.offset
= getNextRangeOffset();
1732 readBuffer
.length
= HTTP_REQBUF_SZ
;
1733 readBuffer
.data
= reqbuf
;
1734 /* we may note we have reached the end of the wanted ranges */
1735 clientStreamRead(getTail(), http
, readBuffer
);
1738 clientStream_status_t
1739 ClientSocketContext::socketState()
1741 switch (clientStreamStatus(getTail(), http
)) {
1744 /* check for range support ending */
1746 if (http
->request
->range
) {
1747 /* check: reply was parsed and range iterator was initialized */
1748 assert(http
->range_iter
.valid
);
1749 /* filter out data according to range specs */
1751 if (!canPackMoreRanges()) {
1752 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1753 "range sequence on " << clientConnection
);
1755 if (http
->request
->flags
.proxyKeepalive
)
1756 return STREAM_COMPLETE
;
1758 return STREAM_UNPLANNED_COMPLETE
;
1760 } else if (reply
&& reply
->content_range
) {
1761 /* reply has content-range, but Squid is not managing ranges */
1762 const int64_t &bytesSent
= http
->out
.offset
;
1763 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1765 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1766 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1767 reply
->content_range
->spec
.offset
<< ")");
1769 // did we get at least what we expected, based on range specs?
1771 if (bytesSent
== bytesExpected
) { // got everything
1772 if (http
->request
->flags
.proxyKeepalive
)
1773 return STREAM_COMPLETE
;
1775 return STREAM_UNPLANNED_COMPLETE
;
1778 // The logic below is not clear: If we got more than we
1779 // expected why would persistency matter? Should not this
1780 // always be an error?
1781 if (bytesSent
> bytesExpected
) { // got extra
1782 if (http
->request
->flags
.proxyKeepalive
)
1783 return STREAM_COMPLETE
;
1785 return STREAM_UNPLANNED_COMPLETE
;
1788 // did not get enough yet, expecting more
1793 case STREAM_COMPLETE
:
1794 return STREAM_COMPLETE
;
1796 case STREAM_UNPLANNED_COMPLETE
:
1797 return STREAM_UNPLANNED_COMPLETE
;
1800 return STREAM_FAILED
;
1803 fatal ("unreachable code\n");
1808 * A write has just completed to the client, or we have just realised there is
1809 * no more data to send.
1812 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1814 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1815 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1818 /// remembers the abnormal connection termination for logging purposes
1820 ClientSocketContext::noteIoError(const int xerrno
)
1823 if (xerrno
== ETIMEDOUT
)
1824 http
->al
->http
.timedout
= true;
1825 else // even if xerrno is zero (which means read abort/eof)
1826 http
->al
->http
.aborted
= true;
1831 ClientSocketContext::doClose()
1833 clientConnection
->close();
1836 /// called when we encounter a response-related error
1838 ClientSocketContext::initiateClose(const char *reason
)
1840 http
->getConn()->stopSending(reason
); // closes ASAP
1844 ConnStateData::stopSending(const char *error
)
1846 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1847 "; old receiving error: " <<
1848 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1850 if (const char *oldError
= stoppedSending()) {
1851 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1852 return; // nothing has changed as far as this connection is concerned
1854 stoppedSending_
= error
;
1856 if (!stoppedReceiving()) {
1857 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1858 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1859 " request body bytes with " << in
.notYetUsed
<< " unused");
1860 return; // wait for the request receiver to finish reading
1864 clientConnection
->close();
1868 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1870 const StoreEntry
*entry
= http
->storeEntry();
1871 http
->out
.size
+= size
;
1872 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1873 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1874 (entry
? entry
->objectLen() : 0));
1875 clientUpdateSocketStats(http
->logType
, size
);
1877 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1879 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1882 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1883 initiateClose("failure or true request status");
1884 /* Do we leak here ? */
1888 switch (socketState()) {
1894 case STREAM_COMPLETE
:
1895 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1896 keepaliveNextRequest();
1899 case STREAM_UNPLANNED_COMPLETE
:
1900 initiateClose("STREAM_UNPLANNED_COMPLETE");
1904 initiateClose("STREAM_FAILED");
1908 fatal("Hit unreachable code in clientWriteComplete\n");
1912 SQUIDCEXTERN CSR clientGetMoreData
;
1913 SQUIDCEXTERN CSS clientReplyStatus
;
1914 SQUIDCEXTERN CSD clientReplyDetach
;
1916 static ClientSocketContext
*
1917 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1919 ClientHttpRequest
*http
;
1920 ClientSocketContext
*context
;
1921 StoreIOBuffer tempBuffer
;
1922 http
= new ClientHttpRequest(csd
);
1923 http
->req_sz
= csd
->in
.notYetUsed
;
1924 http
->uri
= xstrdup(uri
);
1925 setLogUri (http
, uri
);
1926 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
1927 tempBuffer
.data
= context
->reqbuf
;
1928 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1929 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1930 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1931 clientSocketDetach
, context
, tempBuffer
);
1936 skipLeadingSpace(char *aString
)
1938 char *result
= aString
;
1940 while (xisspace(*aString
))
1947 * 'end' defaults to NULL for backwards compatibility
1948 * remove default value if we ever get rid of NULL-terminated
1952 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1955 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1959 for (; end
> uriAndHTTPVersion
; --end
) {
1960 if (*end
== '\n' || *end
== '\r')
1963 if (xisspace(*end
)) {
1964 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1975 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1977 safe_free(http
->log_uri
);
1980 // The uri is already clean just dump it.
1981 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1984 switch (Config
.uri_whitespace
) {
1985 case URI_WHITESPACE_ALLOW
:
1986 flags
|= RFC1738_ESCAPE_NOSPACE
;
1988 case URI_WHITESPACE_ENCODE
:
1989 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1990 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1993 case URI_WHITESPACE_CHOP
: {
1994 flags
|= RFC1738_ESCAPE_NOSPACE
;
1995 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1996 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1997 int pos
= strcspn(http
->log_uri
, w_space
);
1998 http
->log_uri
[pos
] = '\0';
2002 case URI_WHITESPACE_DENY
:
2003 case URI_WHITESPACE_STRIP
:
2006 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2010 if (!xisspace(*t
)) {
2017 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2026 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2028 int vhost
= conn
->port
->vhost
;
2029 int vport
= conn
->port
->vport
;
2031 char ipbuf
[MAX_IPSTRLEN
];
2033 http
->flags
.accel
= 1;
2035 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2037 if (strncasecmp(url
, "cache_object://", 15) == 0)
2038 return; /* already in good shape */
2041 if (conn
->port
->vhost
)
2042 return; /* already in good shape */
2044 /* else we need to ignore the host name */
2045 url
= strstr(url
, "//");
2047 #if SHOULD_REJECT_UNKNOWN_URLS
2050 hp
->request_parse_status
= HTTP_BAD_REQUEST
;
2051 return parseHttpRequestAbort(conn
, "error:invalid-request");
2056 url
= strchr(url
+ 2, '/');
2063 vport
= http
->getConn()->clientConnection
->local
.GetPort();
2065 const bool switchedToHttps
= conn
->switchedToHttps();
2066 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2067 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2068 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2073 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2074 strncpy(thost
, host
, (t
-host
));
2075 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2078 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2081 } // else nothing to alter port-wise.
2082 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2084 http
->uri
= (char *)xcalloc(url_sz
, 1);
2085 const char *protocol
= switchedToHttps
?
2086 "https" : conn
->port
->protocol
;
2087 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2088 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2089 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2090 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2091 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2092 strlen(conn
->port
->defaultsite
);
2093 http
->uri
= (char *)xcalloc(url_sz
, 1);
2097 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2099 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2100 conn
->port
->protocol
, conn
->port
->defaultsite
, vportStr
, url
);
2101 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2102 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2103 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2104 /* Put the local socket IP address as the hostname, with whatever vport we found */
2105 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2106 http
->uri
= (char *)xcalloc(url_sz
, 1);
2107 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2108 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2109 http
->getConn()->port
->protocol
,
2111 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2116 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2119 char ipbuf
[MAX_IPSTRLEN
];
2122 return; /* already in good shape */
2124 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2126 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2127 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2129 http
->uri
= (char *)xcalloc(url_sz
, 1);
2130 snprintf(http
->uri
, url_sz
, "%s://%s%s", conn
->port
->protocol
, host
, url
);
2131 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2133 /* Put the local socket IP address as the hostname. */
2134 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2135 http
->uri
= (char *)xcalloc(url_sz
, 1);
2136 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2137 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2138 http
->getConn()->port
->protocol
,
2139 ipbuf
, http
->getConn()->clientConnection
->local
.GetPort(), url
);
2140 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2144 /** Parse an HTTP request
2146 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2147 * to 1 if the request was correctly parsed.
2148 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2149 * \param[in] hp an HttpParser
2150 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2151 * Pointed-to value will be set to Http::METHOD_NONE in case of
2153 * \param[out] http_ver will be set as a side-effect of the parsing
2154 * \return NULL on incomplete requests,
2155 * a ClientSocketContext structure on success or failure.
2157 static ClientSocketContext
*
2158 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, HttpVersion
*http_ver
)
2160 char *req_hdr
= NULL
;
2163 ClientHttpRequest
*http
;
2164 ClientSocketContext
*result
;
2165 StoreIOBuffer tempBuffer
;
2168 /* pre-set these values to make aborting simpler */
2169 *method_p
= Http::METHOD_NONE
;
2171 /* NP: don't be tempted to move this down or remove again.
2172 * It's the only DDoS protection old-String has against long URL */
2173 if ( hp
->bufsiz
<= 0) {
2174 debugs(33, 5, "Incomplete request, waiting for end of request line");
2176 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2177 debugs(33, 5, "parseHttpRequest: Too large request");
2178 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2179 return parseHttpRequestAbort(csd
, "error:request-too-large");
2182 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2183 r
= HttpParserParseReqLine(hp
);
2186 debugs(33, 5, "Incomplete request, waiting for end of request line");
2191 return parseHttpRequestAbort(csd
, "error:invalid-request");
2194 /* Request line is valid here .. */
2195 *http_ver
= HttpVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2197 /* This call scans the entire request, not just the headers */
2198 if (hp
->req
.v_maj
> 0) {
2199 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2200 debugs(33, 5, "Incomplete request, waiting for end of headers");
2204 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2205 req_sz
= HttpParserReqSz(hp
);
2208 /* We know the whole request is in hp->buf now */
2210 assert(req_sz
<= (size_t) hp
->bufsiz
);
2212 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2213 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2216 hp
->hdr_end
= req_sz
- 1;
2218 hp
->hdr_start
= hp
->req
.end
+ 1;
2220 /* Enforce max_request_size */
2221 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2222 debugs(33, 5, "parseHttpRequest: Too large request");
2223 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2224 return parseHttpRequestAbort(csd
, "error:request-too-large");
2228 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2230 /* deny CONNECT via accelerated ports */
2231 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->accel
) {
2232 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->protocol
<< " Accelerator port " << csd
->port
->s
.GetPort() );
2233 /* XXX need a way to say "this many character length string" */
2234 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2235 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2236 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2239 if (*method_p
== Http::METHOD_NONE
) {
2240 /* XXX need a way to say "this many character length string" */
2241 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2242 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2243 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2247 * Process headers after request line
2248 * TODO: Use httpRequestParse here.
2250 /* XXX this code should be modified to take a const char * later! */
2251 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2253 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2255 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2257 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2259 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2260 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2261 HttpParserReqSz(hp
));
2263 /* Ok, all headers are received */
2264 http
= new ClientHttpRequest(csd
);
2266 http
->req_sz
= HttpParserRequestLen(hp
);
2267 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2268 tempBuffer
.data
= result
->reqbuf
;
2269 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2271 ClientStreamData newServer
= new clientReplyContext(http
);
2272 ClientStreamData newClient
= result
;
2273 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2274 clientReplyStatus
, newServer
, clientSocketRecipient
,
2275 clientSocketDetach
, newClient
, tempBuffer
);
2277 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2281 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2282 * below needs to be modified to not expect a mutable nul-terminated string.
2284 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2286 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2288 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2290 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2292 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2297 debugs(33,5, HERE
<< "repare absolute URL from " << (csd
->transparent()?"intercept":(csd
->port
->accel
? "accel":"")));
2298 /* Rewrite the URL in transparent or accelerator mode */
2299 /* NP: there are several cases to traverse here:
2300 * - standard mode (forward proxy)
2301 * - transparent mode (TPROXY)
2302 * - transparent mode with failures
2303 * - intercept mode (NAT)
2304 * - intercept mode with failures
2305 * - accelerator mode (reverse proxy)
2307 * - mixed combos of the above with internal URL
2309 if (csd
->transparent()) {
2310 /* intercept or transparent mode, properly working with no failures */
2311 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2313 } else if (internalCheck(url
)) {
2314 /* internal URL mode */
2315 /* prepend our name & port */
2316 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2317 // We just re-wrote the URL. Must replace the Host: header.
2318 // But have not parsed there yet!! flag for local-only handling.
2319 http
->flags
.internal
= 1;
2321 } else if (csd
->port
->accel
|| csd
->switchedToHttps()) {
2322 /* accelerator mode */
2323 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2327 /* No special rewrites have been applied above, use the
2328 * requested url. may be rewritten later, so make extra room */
2329 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2330 http
->uri
= (char *)xcalloc(url_sz
, 1);
2331 strcpy(http
->uri
, url
);
2334 debugs(33, 5, "parseHttpRequest: Complete request received");
2336 // XXX: crop this dump at the end of headers. No need for extras
2337 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2338 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2340 result
->flags
.parsed_ok
= 1;
2346 ConnStateData::getAvailableBufferLength() const
2348 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2349 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2350 // huge request_header_max_size may lead to more than INT_MAX unused space
2351 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2356 ConnStateData::maybeMakeSpaceAvailable()
2358 if (getAvailableBufferLength() < 2) {
2360 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2361 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2364 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2365 newSize
=Config
.maxRequestBufferSize
;
2367 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2368 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2374 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2376 ClientSocketContext::Pointer
*S
;
2378 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2386 ConnStateData::getConcurrentRequestCount() const
2389 ClientSocketContext::Pointer
*T
;
2391 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2392 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2397 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2399 if (flag
!= COMM_OK
) {
2400 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2405 if (!ignoreErrno(xerrno
)) {
2406 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2408 } else if (in
.notYetUsed
== 0) {
2409 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2417 ConnStateData::connFinishedWithConn(int size
)
2420 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2421 /* no current or pending requests */
2422 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2424 } else if (!Config
.onoff
.half_closed_clients
) {
2425 /* admin doesn't want to support half-closed client sockets */
2426 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2427 notifyAllContexts(0); // no specific error implies abort
2436 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2438 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2439 conn
->in
.notYetUsed
-= byteCount
;
2440 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2442 * If there is still data that will be used,
2443 * move it to the beginning.
2446 if (conn
->in
.notYetUsed
> 0)
2447 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2450 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2452 ConnStateData::checkHeaderLimits()
2454 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2455 return; // can accumulte more header data
2457 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2458 Config
.maxRequestHeaderSize
<< " bytes)");
2460 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2461 clientStreamNode
*node
= context
->getClientReplyContext();
2462 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2463 assert (repContext
);
2464 repContext
->setReplyToError(ERR_TOO_BIG
,
2465 HTTP_BAD_REQUEST
, Http::METHOD_NONE
, NULL
,
2466 clientConnection
->remote
, NULL
, NULL
, NULL
);
2467 context
->registerWithConn();
2468 context
->pullData();
2472 ConnStateData::clientAfterReadingRequests()
2474 // Were we expecting to read more request body from half-closed connection?
2475 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2476 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2477 clientConnection
->close();
2486 ConnStateData::quitAfterError(HttpRequest
*request
)
2488 // From HTTP p.o.v., we do not have to close after every error detected
2489 // at the client-side, but many such errors do require closure and the
2490 // client-side code is bad at handling errors so we play it safe.
2492 request
->flags
.proxyKeepalive
= 0;
2493 flags
.readMore
= false;
2494 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2498 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2500 ClientHttpRequest
*http
= context
->http
;
2505 assert(sslServerBump
->entry
);
2506 // Did we create an error entry while processing CONNECT?
2507 if (!sslServerBump
->entry
->isEmpty()) {
2508 quitAfterError(http
->request
);
2510 // Get the saved error entry and send it to the client by replacing the
2511 // ClientHttpRequest store entry with it.
2512 clientStreamNode
*node
= context
->getClientReplyContext();
2513 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2515 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2516 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2518 // save the original request for logging purposes
2519 if (!context
->http
->al
->request
)
2520 context
->http
->al
->request
= HTTPMSGLOCK(http
->request
);
2522 // Get error details from the fake certificate-peeking request.
2523 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2524 context
->pullData();
2528 // In bump-server-first mode, we have not necessarily seen the intended
2529 // server name at certificate-peeking time. Check for domain mismatch now,
2530 // when we can extract the intended name from the bumped HTTP request.
2531 if (sslServerBump
->serverCert
.get()) {
2532 HttpRequest
*request
= http
->request
;
2533 if (!Ssl::checkX509ServerValidity(sslServerBump
->serverCert
.get(), request
->GetHost())) {
2534 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2535 "does not match domainname " << request
->GetHost());
2537 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2538 check
.sslErrors
= new Ssl::Errors(SQUID_X509_V_ERR_DOMAIN_MISMATCH
);
2539 const bool allowDomainMismatch
=
2540 check
.fastCheck() == ACCESS_ALLOWED
;
2541 delete check
.sslErrors
;
2542 check
.sslErrors
= NULL
;
2544 if (!allowDomainMismatch
) {
2545 quitAfterError(request
);
2547 clientStreamNode
*node
= context
->getClientReplyContext();
2548 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2549 assert (repContext
);
2551 // Fill the server IP and hostname for error page generation.
2552 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2553 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2555 // Create an error object and fill it
2556 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, HTTP_SERVICE_UNAVAILABLE
, request
);
2557 err
->src_addr
= clientConnection
->remote
;
2558 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2559 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2560 sslServerBump
->serverCert
.get(), NULL
);
2561 err
->detail
= errDetail
;
2562 // Save the original request for logging purposes.
2563 if (!context
->http
->al
->request
)
2564 context
->http
->al
->request
= HTTPMSGLOCK(request
);
2565 repContext
->setReplyToError(request
->method
, err
);
2566 assert(context
->http
->out
.offset
== 0);
2567 context
->pullData();
2578 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, HttpVersion http_ver
)
2580 ClientHttpRequest
*http
= context
->http
;
2581 HttpRequest::Pointer request
;
2582 bool notedUseOfBuffer
= false;
2583 bool chunked
= false;
2584 bool mustReplyToOptions
= false;
2585 bool unsupportedTe
= false;
2586 bool expectBody
= false;
2588 /* We have an initial client stream in place should it be needed */
2589 /* setup our private context */
2590 context
->registerWithConn();
2592 if (context
->flags
.parsed_ok
== 0) {
2593 clientStreamNode
*node
= context
->getClientReplyContext();
2594 debugs(33, 2, "clientProcessRequest: Invalid Request");
2595 conn
->quitAfterError(NULL
);
2596 // setLogUri should called before repContext->setReplyToError
2597 setLogUri(http
, http
->uri
, true);
2598 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2599 assert (repContext
);
2600 switch (hp
->request_parse_status
) {
2601 case HTTP_HEADER_TOO_LARGE
:
2602 repContext
->setReplyToError(ERR_TOO_BIG
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2604 case HTTP_METHOD_NOT_ALLOWED
:
2605 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_METHOD_NOT_ALLOWED
, method
, http
->uri
,
2606 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2609 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2610 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2612 assert(context
->http
->out
.offset
== 0);
2613 context
->pullData();
2617 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2618 clientStreamNode
*node
= context
->getClientReplyContext();
2619 debugs(33, 5, "Invalid URL: " << http
->uri
);
2620 conn
->quitAfterError(request
);
2621 // setLogUri should called before repContext->setReplyToError
2622 setLogUri(http
, http
->uri
, true);
2623 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2624 assert (repContext
);
2625 repContext
->setReplyToError(ERR_INVALID_URL
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2626 assert(context
->http
->out
.offset
== 0);
2627 context
->pullData();
2631 /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */
2632 /* We currently only accept 0.9, 1.0, 1.1 */
2633 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2634 (http_ver
.major
== 1 && http_ver
.minor
> 1 ) ||
2635 (http_ver
.major
> 1) ) {
2637 clientStreamNode
*node
= context
->getClientReplyContext();
2638 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2639 conn
->quitAfterError(request
);
2640 // setLogUri should called before repContext->setReplyToError
2641 setLogUri(http
, http
->uri
, true);
2642 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2643 assert (repContext
);
2644 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, HTTP_HTTP_VERSION_NOT_SUPPORTED
, method
, http
->uri
,
2645 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2646 assert(context
->http
->out
.offset
== 0);
2647 context
->pullData();
2651 /* compile headers */
2652 /* we should skip request line! */
2653 /* XXX should actually know the damned buffer size here */
2654 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2655 clientStreamNode
*node
= context
->getClientReplyContext();
2656 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2657 conn
->quitAfterError(request
);
2658 // setLogUri should called before repContext->setReplyToError
2659 setLogUri(http
, http
->uri
, true);
2660 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2661 assert (repContext
);
2662 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2663 assert(context
->http
->out
.offset
== 0);
2664 context
->pullData();
2668 request
->clientConnectionManager
= conn
;
2670 request
->flags
.accelerated
= http
->flags
.accel
;
2671 request
->flags
.sslBumped
=conn
->switchedToHttps();
2672 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2673 // TODO: decouple http->flags.accel from request->flags.sslBumped
2674 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2675 !conn
->port
->allow_direct
: 0;
2677 if (request
->flags
.sslBumped
) {
2678 if (conn
->auth_user_request
!= NULL
)
2679 request
->auth_user_request
= conn
->auth_user_request
;
2684 * If transparent or interception mode is working clone the transparent and interception flags
2685 * from the port settings to the request.
2687 if (http
->clientConnection
!= NULL
) {
2688 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2689 request
->flags
.spoofClientIp
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2692 if (internalCheck(request
->urlpath
.termedBuf())) {
2693 if (internalHostnameIs(request
->GetHost()) &&
2694 request
->port
== getMyPort()) {
2695 http
->flags
.internal
= 1;
2696 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2697 request
->SetHost(internalHostname());
2698 request
->port
= getMyPort();
2699 http
->flags
.internal
= 1;
2703 if (http
->flags
.internal
) {
2704 request
->protocol
= AnyP::PROTO_HTTP
;
2705 request
->login
[0] = '\0';
2708 request
->flags
.internal
= http
->flags
.internal
;
2709 setLogUri (http
, urlCanonicalClean(request
));
2710 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2711 #if FOLLOW_X_FORWARDED_FOR
2712 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2713 // not a details about teh TCP connection itself
2714 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2715 #endif /* FOLLOW_X_FORWARDED_FOR */
2716 request
->my_addr
= conn
->clientConnection
->local
;
2717 request
->myportname
= conn
->port
->name
;
2718 request
->http_ver
= http_ver
;
2720 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2721 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2722 request
->clientConnectionManager
= conn
;
2724 if (request
->header
.chunked()) {
2726 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2727 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2728 // HTTP/1.1 requires chunking to be the last encoding if there is one
2729 unsupportedTe
= te
.size() && te
!= "identity";
2730 } // else implied identity coding
2732 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2733 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2734 if (!urlCheckRequest(request
) || mustReplyToOptions
|| unsupportedTe
) {
2735 clientStreamNode
*node
= context
->getClientReplyContext();
2736 conn
->quitAfterError(request
);
2737 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2738 assert (repContext
);
2739 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_NOT_IMPLEMENTED
, request
->method
, NULL
,
2740 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2741 assert(context
->http
->out
.offset
== 0);
2742 context
->pullData();
2746 if (!chunked
&& !clientIsContentLengthValid(request
)) {
2747 clientStreamNode
*node
= context
->getClientReplyContext();
2748 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2749 assert (repContext
);
2750 conn
->quitAfterError(request
);
2751 repContext
->setReplyToError(ERR_INVALID_REQ
,
2752 HTTP_LENGTH_REQUIRED
, request
->method
, NULL
,
2753 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2754 assert(context
->http
->out
.offset
== 0);
2755 context
->pullData();
2759 if (request
->header
.has(HDR_EXPECT
)) {
2760 const String expect
= request
->header
.getList(HDR_EXPECT
);
2761 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2762 if (!supportedExpect
) {
2763 clientStreamNode
*node
= context
->getClientReplyContext();
2764 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2765 assert (repContext
);
2766 conn
->quitAfterError(request
);
2767 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_EXPECTATION_FAILED
, request
->method
, http
->uri
,
2768 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2769 assert(context
->http
->out
.offset
== 0);
2770 context
->pullData();
2775 http
->request
= HTTPMSGLOCK(request
);
2776 clientSetKeepaliveFlag(http
);
2778 // Let tunneling code be fully responsible for CONNECT requests
2779 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2780 context
->mayUseConnection(true);
2781 conn
->flags
.readMore
= false;
2785 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2789 /* Do we expect a request-body? */
2790 expectBody
= chunked
|| request
->content_length
> 0;
2791 if (!context
->mayUseConnection() && expectBody
) {
2792 request
->body_pipe
= conn
->expectRequestBody(
2793 chunked
? -1 : request
->content_length
);
2795 // consume header early so that body pipe gets just the body
2796 connNoteUseOfBuffer(conn
, http
->req_sz
);
2797 notedUseOfBuffer
= true;
2799 /* Is it too large? */
2800 if (!chunked
&& // if chunked, we will check as we accumulate
2801 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2802 clientStreamNode
*node
= context
->getClientReplyContext();
2803 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2804 assert (repContext
);
2805 conn
->quitAfterError(request
);
2806 repContext
->setReplyToError(ERR_TOO_BIG
,
2807 HTTP_REQUEST_ENTITY_TOO_LARGE
, Http::METHOD_NONE
, NULL
,
2808 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2809 assert(context
->http
->out
.offset
== 0);
2810 context
->pullData();
2814 // We may stop producing, comm_close, and/or call setReplyToError()
2815 // below, so quit on errors to avoid http->doCallouts()
2816 if (!conn
->handleRequestBodyData())
2819 if (!request
->body_pipe
->productionEnded()) {
2820 debugs(33, 5, HERE
<< "need more request body");
2821 context
->mayUseConnection(true);
2822 assert(conn
->flags
.readMore
);
2826 http
->calloutContext
= new ClientRequestContext(http
);
2831 if (!notedUseOfBuffer
)
2832 connNoteUseOfBuffer(conn
, http
->req_sz
);
2836 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2837 * to here because calling comm_reset_close() causes http to
2838 * be freed and the above connNoteUseOfBuffer() would hit an
2839 * assertion, not to mention that we were accessing freed memory.
2841 if (request
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2842 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2843 conn
->flags
.readMore
= false;
2844 comm_reset_close(conn
->clientConnection
);
2849 connStripBufferWhitespace (ConnStateData
* conn
)
2851 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2852 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2853 -- conn
->in
.notYetUsed
;
2858 connOkToAddRequest(ConnStateData
* conn
)
2860 int result
= conn
->getConcurrentRequestCount() < (Config
.onoff
.pipeline_prefetch
? 2 : 1);
2863 debugs(33, 3, HERE
<< conn
->clientConnection
<< " max concurrent requests reached");
2864 debugs(33, 5, HERE
<< conn
->clientConnection
<< " defering new request until one is done");
2871 * Attempt to parse one or more requests from the input buffer.
2872 * If a request is successfully parsed, even if the next request
2873 * is only partially parsed, it will return TRUE.
2876 ConnStateData::clientParseRequests()
2878 HttpRequestMethod method
;
2879 bool parsed_req
= false;
2880 HttpVersion http_ver
;
2882 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2884 // Loop while we have read bytes that are not needed for producing the body
2885 // On errors, bodyPipe may become nil, but readMore will be cleared
2886 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2887 connStripBufferWhitespace(this);
2889 /* Don't try to parse if the buffer is empty */
2890 if (in
.notYetUsed
== 0)
2893 /* Limit the number of concurrent requests to 2 */
2894 if (!connOkToAddRequest(this)) {
2898 /* Should not be needed anymore */
2899 /* Terminate the string */
2900 in
.buf
[in
.notYetUsed
] = '\0';
2902 /* Begin the parsing */
2903 PROF_start(parseHttpRequest
);
2904 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
2906 /* Process request */
2907 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2908 PROF_stop(parseHttpRequest
);
2910 /* partial or incomplete request */
2912 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2913 // (which becomes context) but checkHeaderLimits cannot?
2914 checkHeaderLimits();
2918 /* status -1 or 1 */
2920 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2921 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2922 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2923 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2925 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2927 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2929 if (context
->mayUseConnection()) {
2930 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2936 /* XXX where to 'finish' the parsing pass? */
2941 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
2943 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
2947 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2949 if (io
.flag
== COMM_ERR_CLOSING
) {
2950 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
2954 assert(Comm::IsConnOpen(clientConnection
));
2955 assert(io
.conn
->fd
== clientConnection
->fd
);
2958 * Don't reset the timeout value here. The timeout value will be
2959 * set to Config.Timeout.request by httpAccept() and
2960 * clientWriteComplete(), and should apply to the request as a
2961 * whole, not individual read() calls. Plus, it breaks our
2962 * lame half-close detection
2964 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
2965 notifyAllContexts(io
.xerrno
);
2970 if (io
.flag
== COMM_OK
) {
2972 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
2974 // may comm_close or setReplyToError
2975 if (!handleReadData(io
.buf
, io
.size
))
2978 } else if (io
.size
== 0) {
2979 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
2981 if (connFinishedWithConn(io
.size
)) {
2982 clientConnection
->close();
2986 /* It might be half-closed, we can't tell */
2987 fd_table
[io
.conn
->fd
].flags
.socket_eof
= 1;
2989 commMarkHalfClosed(io
.conn
->fd
);
2991 fd_note(io
.conn
->fd
, "half-closed");
2993 /* There is one more close check at the end, to detect aborted
2994 * (partial) requests. At this point we can't tell if the request
2997 /* Continue to process previously read data */
3001 /* Process next request */
3002 if (getConcurrentRequestCount() == 0)
3003 fd_note(io
.fd
, "Reading next request");
3005 if (!clientParseRequests()) {
3009 * If the client here is half closed and we failed
3010 * to parse a request, close the connection.
3011 * The above check with connFinishedWithConn() only
3012 * succeeds _if_ the buffer is empty which it won't
3013 * be if we have an incomplete request.
3014 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3016 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3017 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3018 clientConnection
->close();
3026 clientAfterReadingRequests();
3030 * called when new request data has been read from the socket
3032 * \retval false called comm_close or setReplyToError (the caller should bail)
3033 * \retval true we did not call comm_close or setReplyToError
3036 ConnStateData::handleReadData(char *buf
, size_t size
)
3038 char *current_buf
= in
.addressToReadInto();
3040 if (buf
!= current_buf
)
3041 memmove(current_buf
, buf
, size
);
3043 in
.notYetUsed
+= size
;
3045 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3047 // if we are reading a body, stuff data into the body pipe
3048 if (bodyPipe
!= NULL
)
3049 return handleRequestBodyData();
3054 * called when new request body data has been buffered in in.buf
3055 * may close the connection if we were closing and piped everything out
3057 * \retval false called comm_close or setReplyToError (the caller should bail)
3058 * \retval true we did not call comm_close or setReplyToError
3061 ConnStateData::handleRequestBodyData()
3063 assert(bodyPipe
!= NULL
);
3067 if (in
.bodyParser
) { // chunked encoding
3068 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3069 abortChunkedRequestBody(error
);
3072 } else { // identity encoding
3073 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3074 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3075 if (!bodyPipe
->mayNeedMoreData()) {
3076 // BodyPipe will clear us automagically when we produced everything
3082 connNoteUseOfBuffer(this, putSize
);
3085 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3087 if (const char *reason
= stoppedSending()) {
3088 /* we've finished reading like good clients,
3089 * now do the close that initiateClose initiated.
3091 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3092 clientConnection
->close();
3100 /// parses available chunked encoded body bytes, checks size, returns errors
3102 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3104 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3106 try { // the parser will throw on errors
3108 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3111 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3112 // add one because MemBuf will assert if it cannot 0-terminate
3113 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3114 raw
.append(in
.buf
, in
.notYetUsed
);
3116 const mb_size_t wasContentSize
= raw
.contentSize();
3117 BodyPipeCheckout
bpc(*bodyPipe
);
3118 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3120 putSize
= wasContentSize
- raw
.contentSize();
3122 // dechunk then check: the size limit applies to _dechunked_ content
3123 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3127 finishDechunkingRequest(true);
3129 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3132 // if chunk parser needs data, then the body pipe must need it too
3133 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3135 // if parser needs more space and we can consume nothing, we will stall
3136 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3137 } catch (...) { // TODO: be more specific
3138 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3139 return ERR_INVALID_REQ
;
3142 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3146 /// quit on errors related to chunked request body handling
3148 ConnStateData::abortChunkedRequestBody(const err_type error
)
3150 finishDechunkingRequest(false);
3152 // XXX: The code below works if we fail during initial request parsing,
3153 // but if we fail when the server-side works already, the server may send
3154 // us its response too, causing various assertions. How to prevent that?
3155 #if WE_KNOW_HOW_TO_SEND_ERRORS
3156 ClientSocketContext::Pointer context
= getCurrentContext();
3157 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3158 clientStreamNode
*node
= context
->getClientReplyContext();
3159 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3161 const http_status scode
= (error
== ERR_TOO_BIG
) ?
3162 HTTP_REQUEST_ENTITY_TOO_LARGE
: HTTP_BAD_REQUEST
;
3163 repContext
->setReplyToError(error
, scode
,
3164 repContext
->http
->request
->method
,
3165 repContext
->http
->uri
,
3167 repContext
->http
->request
,
3169 context
->pullData();
3171 // close or otherwise we may get stuck as nobody will notice the error?
3172 comm_reset_close(clientConnection
);
3175 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3176 comm_reset_close(clientConnection
);
3178 flags
.readMore
= false;
3182 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3184 if (!handleRequestBodyData())
3187 // too late to read more body
3188 if (!isOpen() || stoppedReceiving())
3195 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3197 // request reader may get stuck waiting for space if nobody consumes body
3198 if (bodyPipe
!= NULL
)
3199 bodyPipe
->enableAutoConsumption();
3201 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3204 /** general lifetime handler for HTTP requests */
3206 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3208 #if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS
3209 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3211 if (COMMIO_FD_WRITECB(io
.fd
)->active
) {
3212 /* FIXME: If this code is reinstated, check the conn counters,
3213 * not the fd table state
3216 * Some data has been sent to the client, just close the FD
3218 clientConnection
->close();
3219 } else if (nrequests
) {
3221 * assume its a persistent connection; just close it
3223 clientConnection
->close();
3228 ClientHttpRequest
**H
;
3229 clientStreamNode
*node
;
3230 ClientHttpRequest
*http
= parseHttpRequestAbort(this, "error:Connection%20lifetime%20expired");
3231 node
= http
->client_stream
.tail
->prev
->data
;
3232 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3233 assert (repContext
);
3234 repContext
->setReplyToError(ERR_LIFETIME_EXP
,
3235 HTTP_REQUEST_TIMEOUT
, Http::METHOD_NONE
, "N/A", &CachePeer
.sin_addr
,
3237 /* No requests can be outstanded */
3238 assert(chr
== NULL
);
3239 /* add to the client request queue */
3241 for (H
= &chr
; *H
; H
= &(*H
)->next
);
3244 clientStreamRead(http
->client_stream
.tail
->data
, http
, 0,
3245 HTTP_REQBUF_SZ
, context
->reqbuf
);
3248 * if we don't close() here, we still need a timeout handler!
3250 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3251 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3252 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3253 commSetConnTimeout(io
.conn
, 30, timeoutCall
);
3256 * Aha, but we don't want a read handler!
3258 Comm::SetSelect(io
.fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3263 * Just close the connection to not confuse browsers
3264 * using persistent connections. Some browsers opens
3265 * an connection and then does not use it until much
3266 * later (presumeably because the request triggering
3267 * the open has already been completed on another
3270 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3276 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3278 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3279 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3280 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3281 http
->al
->http
.timedout
= true;
3282 if (Comm::IsConnOpen(io
.conn
))
3287 connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
)
3289 ConnStateData
*result
= new ConnStateData
;
3291 result
->clientConnection
= client
;
3292 result
->log_addr
= client
->remote
;
3293 result
->log_addr
.ApplyMask(Config
.Addrs
.client_netmask
);
3294 result
->in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &result
->in
.allocatedSize
);
3295 result
->port
= cbdataReference(port
);
3297 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3298 (result
->transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3299 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3300 int i
= IP_PMTUDISC_DONT
;
3301 if (setsockopt(client
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3302 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << client
<< " : " << xstrerror());
3304 static bool reported
= false;
3307 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3313 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3314 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, result
, ConnStateData::connStateClosed
);
3315 comm_add_close_handler(client
->fd
, call
);
3317 if (Config
.onoff
.log_fqdn
)
3318 fqdncache_gethostbyaddr(client
->remote
, FQDN_LOOKUP_IF_MISS
);
3321 if (Ident::TheConfig
.identLookup
) {
3322 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3323 identChecklist
.src_addr
= client
->remote
;
3324 identChecklist
.my_addr
= client
->local
;
3325 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3326 Ident::Start(client
, clientIdentDone
, result
);
3331 if (Eui::TheConfig
.euiLookup
) {
3332 if (client
->remote
.IsIPv4()) {
3333 result
->clientConnection
->remoteEui48
.lookup(client
->remote
);
3334 } else if (client
->remote
.IsIPv6()) {
3335 result
->clientConnection
->remoteEui64
.lookup(client
->remote
);
3340 clientdbEstablished(client
->remote
, 1);
3342 result
->flags
.readMore
= true;
3346 /** Handle a new connection on HTTP socket. */
3348 httpAccept(const CommAcceptCbParams
¶ms
)
3350 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3352 if (params
.flag
!= COMM_OK
) {
3353 // Its possible the call was still queued when the client disconnected
3354 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3358 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3359 fd_note(params
.conn
->fd
, "client http connect");
3361 if (s
->tcp_keepalive
.enabled
) {
3362 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3365 ++ incoming_sockets_accepted
;
3367 // Socket is ready, setup the connection manager to start using it
3368 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3370 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3371 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3372 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3373 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3375 connState
->readSomeData();
3378 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3380 if (Config
.onoff
.client_db
) {
3381 /* it was said several times that client write limiter does not work if client_db is disabled */
3383 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3384 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3386 // TODO: we check early to limit error response bandwith but we
3387 // should recheck when we can honor delay_pool_uses_indirect
3388 // TODO: we should also pass the port details for myportname here.
3389 ch
.src_addr
= params
.conn
->remote
;
3390 ch
.my_addr
= params
.conn
->local
;
3392 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3394 /* pools require explicit 'allow' to assign a client into them */
3395 if (pools
[pool
].access
) {
3396 ch
.accessList
= pools
[pool
].access
;
3397 allow_t answer
= ch
.fastCheck();
3398 if (answer
== ACCESS_ALLOWED
) {
3400 /* request client information from db after we did all checks
3401 this will save hash lookup if client failed checks */
3402 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3405 /* put client info in FDE */
3406 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3408 /* setup write limiter for this request */
3409 const double burst
= floor(0.5 +
3410 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3411 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3414 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3424 /** Create SSL connection structure and update fd_table */
3426 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3428 SSL
*ssl
= SSL_new(sslContext
);
3431 const int ssl_error
= ERR_get_error();
3432 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3437 SSL_set_fd(ssl
, conn
->fd
);
3438 fd_table
[conn
->fd
].ssl
= ssl
;
3439 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3440 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3442 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3443 fd_note(conn
->fd
, "client https start");
3448 /** negotiate an SSL connection */
3450 clientNegotiateSSL(int fd
, void *data
)
3452 ConnStateData
*conn
= (ConnStateData
*)data
;
3454 SSL
*ssl
= fd_table
[fd
].ssl
;
3457 if ((ret
= SSL_accept(ssl
)) <= 0) {
3458 int ssl_error
= SSL_get_error(ssl
, ret
);
3460 switch (ssl_error
) {
3462 case SSL_ERROR_WANT_READ
:
3463 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3466 case SSL_ERROR_WANT_WRITE
:
3467 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3470 case SSL_ERROR_SYSCALL
:
3473 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3479 if (errno
== ECONNRESET
)
3482 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3483 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3490 case SSL_ERROR_ZERO_RETURN
:
3491 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3496 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3497 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3498 " (" << ssl_error
<< "/" << ret
<< ")");
3506 if (SSL_session_reused(ssl
)) {
3507 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3508 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3510 if (do_debug(83, 4)) {
3511 /* Write out the SSL session details.. actually the call below, but
3512 * OpenSSL headers do strange typecasts confusing GCC.. */
3513 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3514 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3515 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
);
3517 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3519 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3520 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3521 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3522 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3523 * Because there are two possible usable cast, if you get an error here, try the other
3524 * commented line. */
3526 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3527 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3531 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3534 /* Note: This does not automatically fflush the log file.. */
3537 debugs(83, 2, "clientNegotiateSSL: New session " <<
3538 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3539 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3543 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3544 SSL_get_cipher(ssl
));
3546 client_cert
= SSL_get_peer_certificate(ssl
);
3548 if (client_cert
!= NULL
) {
3549 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3550 " client certificate: subject: " <<
3551 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3553 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3554 " client certificate: issuer: " <<
3555 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3557 X509_free(client_cert
);
3559 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3560 " has no certificate.");
3563 conn
->readSomeData();
3567 * If SSL_CTX is given, starts reading the SSL handshake.
3568 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3571 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3575 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3577 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3580 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3581 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3582 connState
, ConnStateData::requestTimeout
);
3583 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3586 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3588 char buf
[MAX_IPSTRLEN
];
3589 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3590 HttpRequest
*fakeRequest
= new HttpRequest
;
3591 fakeRequest
->SetHost(details
->local
.NtoA(buf
, sizeof(buf
)));
3592 fakeRequest
->port
= details
->local
.GetPort();
3593 fakeRequest
->clientConnectionManager
= connState
;
3594 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3595 #if FOLLOW_X_FORWARDED_FOR
3596 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3598 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3599 fakeRequest
->flags
.spoofClientIp
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3600 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3601 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3602 connState
->switchToHttps(fakeRequest
, bumpMode
);
3607 * A callback function to use with the ACLFilledChecklist callback.
3608 * In the case of ACCES_ALLOWED answer initializes a bumped SSL connection,
3609 * else reverts the connection to tunnel mode.
3612 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3614 ConnStateData
*connState
= (ConnStateData
*) data
;
3616 // if the connection is closed or closing, just return.
3617 if (!connState
->isOpen())
3620 // Require both a match and a positive bump mode to work around exceptional
3621 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3622 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3623 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3624 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3625 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3627 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3628 connState
->sslBumpMode
= Ssl::bumpNone
;
3630 // fake a CONNECT request to force connState to tunnel
3631 static char ip
[MAX_IPSTRLEN
];
3632 static char reqStr
[MAX_IPSTRLEN
+ 80];
3633 connState
->clientConnection
->local
.NtoA(ip
, sizeof(ip
));
3634 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s:%d HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, connState
->clientConnection
->local
.GetPort(), ip
);
3635 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3637 ret
= connState
->clientParseRequests();
3640 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3641 connState
->clientConnection
->close();
3646 /** handle a new HTTPS connection */
3648 httpsAccept(const CommAcceptCbParams
¶ms
)
3650 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3652 if (params
.flag
!= COMM_OK
) {
3653 // Its possible the call was still queued when the client disconnected
3654 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3658 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3659 fd_note(params
.conn
->fd
, "client https connect");
3661 if (s
->tcp_keepalive
.enabled
) {
3662 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3665 ++incoming_sockets_accepted
;
3667 // Socket is ready, setup the connection manager to start using it
3668 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3671 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3673 if (!Config
.accessList
.ssl_bump
) {
3674 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3678 // Create a fake HTTP request for ssl_bump ACL check,
3679 // using tproxy/intercept provided destination IP and port.
3680 HttpRequest
*request
= new HttpRequest();
3681 static char ip
[MAX_IPSTRLEN
];
3682 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3683 request
->SetHost(params
.conn
->local
.NtoA(ip
, sizeof(ip
)));
3684 request
->port
= params
.conn
->local
.GetPort();
3685 request
->myportname
= s
->name
;
3687 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3688 acl_checklist
->src_addr
= params
.conn
->remote
;
3689 acl_checklist
->my_addr
= s
->s
;
3690 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3693 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3694 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3699 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3701 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3702 state_data
->sslCrtdHandleReply(reply
);
3706 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3708 if (reply
.result
== HelperReply::BrokenHelper
) {
3709 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3710 } else if (!reply
.other().hasContent()) {
3711 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3713 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3714 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3715 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3717 if (reply
.result
!= HelperReply::Okay
) {
3718 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3720 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3721 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3722 getSslContextDone(ctx
, true);
3727 getSslContextDone(NULL
);
3730 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3732 certProperties
.commonName
= sslCommonName
.defined() ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3734 // fake certificate adaptation requires bump-server-first mode
3735 if (!sslServerBump
) {
3736 assert(port
->signingCert
.get());
3737 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3738 if (port
->signPkey
.get())
3739 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3740 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3744 // In case of an error while connecting to the secure server, use a fake
3745 // trusted certificate, with no mimicked fields and no adaptation
3746 // algorithms. There is nothing we can mimic so we want to minimize the
3747 // number of warnings the user will have to see to get to the error page.
3748 assert(sslServerBump
->entry
);
3749 if (sslServerBump
->entry
->isEmpty()) {
3750 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3751 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3753 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
,
3754 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3755 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3757 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3758 // If the algorithm already set, then ignore it.
3759 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3760 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3761 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3764 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3765 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3766 const char *param
= ca
->param
;
3768 // For parameterless CN adaptation, use hostname from the
3770 if (ca
->alg
== Ssl::algSetCommonName
) {
3772 param
= sslConnectHostOrIp
.termedBuf();
3773 certProperties
.commonName
= param
;
3774 certProperties
.setCommonName
= true;
3775 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3776 certProperties
.setValidAfter
= true;
3777 else if (ca
->alg
== Ssl::algSetValidBefore
)
3778 certProperties
.setValidBefore
= true;
3780 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3781 alg
<< " param: " << (param
? param
: "-"));
3785 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3786 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3787 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3788 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3792 } else {// if (!sslServerBump->entry->isEmpty())
3793 // Use trusted certificate for a Squid-generated error
3794 // or the user would have to add a security exception
3795 // just to see the error page. We will close the connection
3796 // so that the trust is not extended to non-Squid content.
3797 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3800 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3802 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3803 assert(port
->untrustedSigningCert
.get());
3804 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3805 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3807 assert(port
->signingCert
.get());
3808 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3810 if (port
->signPkey
.get())
3811 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3813 signAlgorithm
= certProperties
.signAlgorithm
;
3817 ConnStateData::getSslContextStart()
3819 assert(areAllContextsForThisConnection());
3821 /* careful: freeAllContexts() above frees request, host, etc. */
3823 if (port
->generateHostCertificates
) {
3824 Ssl::CertificateProperties certProperties
;
3825 buildSslCertGenerationParams(certProperties
);
3826 sslBumpCertKey
= certProperties
.dbKey().c_str();
3827 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3829 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3830 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3831 SSL_CTX
* dynCtx
= NULL
;
3832 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
.get(sslBumpCertKey
.termedBuf());
3833 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
3834 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3835 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3836 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3837 getSslContextDone(dynCtx
);
3840 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3841 ssl_ctx_cache
.del(sslBumpCertKey
.termedBuf());
3844 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3849 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3850 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3851 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3852 request_message
.composeRequest(certProperties
);
3853 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3854 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3856 } catch (const std::exception
&e
) {
3857 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3858 "request for " << certProperties
.commonName
<<
3859 " certificate: " << e
.what() << "; will now block to " <<
3860 "generate that certificate.");
3861 // fall through to do blocking in-process generation.
3863 #endif // USE_SSL_CRTD
3865 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3866 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3867 getSslContextDone(dynCtx
, true);
3870 getSslContextDone(NULL
);
3874 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3876 // Try to add generated ssl context to storage.
3877 if (port
->generateHostCertificates
&& isNew
) {
3879 if (signAlgorithm
== Ssl::algSignTrusted
)
3880 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3881 //else it is self-signed or untrusted do not attrach any certificate
3883 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3884 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3886 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
3887 // If it is not in storage delete after using. Else storage deleted it.
3888 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3891 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3895 // If generated ssl context = NULL, try to use static ssl context.
3897 if (!port
->staticSslContext
) {
3898 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3899 clientConnection
->close();
3902 debugs(33, 5, HERE
<< "Using static ssl context.");
3903 sslContext
= port
->staticSslContext
.get();
3907 if (!httpsCreate(clientConnection
, sslContext
))
3910 // commSetConnTimeout() was called for this request before we switched.
3912 // Disable the client read handler until CachePeer selection is complete
3913 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3914 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3915 switchedToHttps_
= true;
3919 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3921 assert(!switchedToHttps_
);
3923 sslConnectHostOrIp
= request
->GetHost();
3924 sslCommonName
= request
->GetHost();
3926 // We are going to read new request
3927 flags
.readMore
= true;
3928 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3930 // If sslServerBump is set, then we have decided to deny CONNECT
3931 // and now want to switch to SSL to send the error to the client
3932 // without even peeking at the origin server certificate.
3933 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3934 request
->flags
.sslPeek
= 1;
3935 sslServerBump
= new Ssl::ServerBump(request
);
3937 // will call httpsPeeked() with certificate and connection, eventually
3938 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
);
3942 // otherwise, use sslConnectHostOrIp
3943 getSslContextStart();
3947 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3949 Must(sslServerBump
!= NULL
);
3951 if (Comm::IsConnOpen(serverConnection
)) {
3952 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3954 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3955 assert(serverCert
.get() != NULL
);
3956 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
3957 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
3958 " bumped: " << *serverConnection
);
3960 pinConnection(serverConnection
, NULL
, NULL
, false);
3962 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3964 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3965 Ip::Address intendedDest
;
3966 intendedDest
= sslConnectHostOrIp
.termedBuf();
3967 const bool isConnectRequest
= !port
->spoof_client_ip
&& !port
->intercepted
;
3969 // Squid serves its own error page and closes, so we want
3970 // a CN that causes no additional browser errors. Possible
3971 // only when bumping CONNECT with a user-typed address.
3972 if (intendedDest
.IsAnyAddr() || isConnectRequest
)
3973 sslCommonName
= sslConnectHostOrIp
;
3974 else if (sslServerBump
->serverCert
.get())
3975 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
3977 // copy error detail from bump-server-first request to CONNECT request
3978 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
3979 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3982 getSslContextStart();
3985 #endif /* USE_SSL */
3987 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3989 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3991 if (!Comm::IsConnOpen(c
)) {
3992 Must(NHttpSockets
> 0); // we tried to open some
3993 --NHttpSockets
; // there will be fewer sockets than planned
3994 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3996 if (!NHttpSockets
) // we could not open any listen sockets at all
3997 fatalf("Unable to open %s",FdNote(portType
));
4004 /// find any unused HttpSockets[] slot and store fd there or return false
4006 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4009 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4010 if ((found
= HttpSockets
[i
] < 0))
4011 HttpSockets
[i
] = conn
->fd
;
4017 clientHttpConnectionsOpen(void)
4019 AnyP::PortCfg
*s
= NULL
;
4021 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4022 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4023 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4024 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4029 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4030 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4034 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4035 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4039 // Create ssl_ctx cache for this port.
4040 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4044 // Fill out a Comm::Connection which IPC will open as a listener for us
4045 // then pass back when active so we can start a TcpAcceptor subscription.
4046 s
->listenConn
= new Comm::Connection
;
4047 s
->listenConn
->local
= s
->s
;
4048 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) | (s
->intercepted
? COMM_INTERCEPTION
: 0);
4050 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4051 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4052 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4053 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4055 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4056 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4057 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4059 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4066 clientHttpsConnectionsOpen(void)
4070 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4071 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4072 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4073 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4077 if (!s
->staticSslContext
) {
4078 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4079 " due to SSL initialization failure.");
4083 // TODO: merge with similar code in clientHttpConnectionsOpen()
4084 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4085 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4089 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4090 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4095 // Create ssl_ctx cache for this port.
4096 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4099 // Fill out a Comm::Connection which IPC will open as a listener for us
4100 s
->listenConn
= new Comm::Connection
;
4101 s
->listenConn
->local
= s
->s
;
4102 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) |
4103 (s
->intercepted
? COMM_INTERCEPTION
: 0);
4105 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4106 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4107 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4108 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4110 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4111 ListeningStartedDialer(&clientListenerConnectionOpened
,
4112 s
, Ipc::fdnHttpsSocket
, sub
));
4113 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4114 HttpSockets
[NHttpSockets
] = -1;
4120 /// process clientHttpConnectionsOpen result
4122 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4124 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4128 Must(Comm::IsConnOpen(s
->listenConn
));
4130 // TCP: setup a job to handle accept() with subscribed handler
4131 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4133 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4134 (s
->intercepted
? "NAT intercepted " : "") <<
4135 (s
->spoof_client_ip
? "TPROXY spoofing " : "") <<
4136 (s
->sslBump
? "SSL bumped " : "") <<
4137 (s
->accel
? "reverse-proxy " : "")
4138 << FdNote(portTypeNote
) << " connections at "
4141 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4145 clientOpenListenSockets(void)
4147 clientHttpConnectionsOpen();
4149 clientHttpsConnectionsOpen();
4152 if (NHttpSockets
< 1)
4153 fatal("No HTTP or HTTPS ports configured");
4157 clientHttpConnectionsClose(void)
4159 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4160 if (s
->listenConn
!= NULL
) {
4161 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4162 s
->listenConn
->close();
4163 s
->listenConn
= NULL
;
4168 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4169 if (s
->listenConn
!= NULL
) {
4170 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4171 s
->listenConn
->close();
4172 s
->listenConn
= NULL
;
4177 // TODO see if we can drop HttpSockets array entirely */
4178 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4179 HttpSockets
[i
] = -1;
4186 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4188 const char *vary
= request
->vary_headers
;
4189 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4190 #if X_ACCELERATOR_VARY
4193 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4196 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4198 /* Oops... something odd is going on here.. */
4199 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4200 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4201 safe_free(request
->vary_headers
);
4206 /* This is not a varying object */
4210 /* virtual "vary" object found. Calculate the vary key and
4211 * continue the search
4213 vary
= httpMakeVaryMark(request
, entry
->getReply());
4216 request
->vary_headers
= xstrdup(vary
);
4219 /* Ouch.. we cannot handle this kind of variance */
4220 /* XXX This cannot really happen, but just to be complete */
4225 vary
= httpMakeVaryMark(request
, entry
->getReply());
4228 request
->vary_headers
= xstrdup(vary
);
4232 /* Ouch.. we cannot handle this kind of variance */
4233 /* XXX This cannot really happen, but just to be complete */
4235 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4238 /* Oops.. we have already been here and still haven't
4239 * found the requested variant. Bail out
4241 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4242 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4248 ACLFilledChecklist
*
4249 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4251 ConnStateData
* conn
= http
->getConn();
4252 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4253 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4256 * hack for ident ACL. It needs to get full addresses, and a place to store
4257 * the ident result on persistent connections...
4259 /* connection oriented auth also needs these two lines for it's operation. */
4263 CBDATA_CLASS_INIT(ConnStateData
);
4265 ConnStateData::ConnStateData() :
4266 AsyncJob("ConnStateData"),
4268 sslBumpMode(Ssl::bumpEnd
),
4269 switchedToHttps_(false),
4270 sslServerBump(NULL
),
4272 stoppedSending_(NULL
),
4273 stoppedReceiving_(NULL
)
4275 pinning
.host
= NULL
;
4277 pinning
.pinned
= false;
4278 pinning
.auth
= false;
4279 pinning
.zeroReply
= false;
4280 pinning
.peer
= NULL
;
4284 ConnStateData::transparent() const
4286 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4290 ConnStateData::reading() const
4292 return reader
!= NULL
;
4296 ConnStateData::stopReading()
4299 comm_read_cancel(clientConnection
->fd
, reader
);
4305 ConnStateData::expectRequestBody(int64_t size
)
4307 bodyPipe
= new BodyPipe(this);
4309 bodyPipe
->setBodySize(size
);
4311 startDechunkingRequest();
4316 ConnStateData::mayNeedToReadMoreBody() const
4319 return 0; // request without a body or read/produced all body bytes
4321 if (!bodyPipe
->bodySizeKnown())
4322 return -1; // probably need to read more, but we cannot be sure
4324 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4325 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4327 if (needToProduce
<= haveAvailable
)
4328 return 0; // we have read what we need (but are waiting for pipe space)
4330 return needToProduce
- haveAvailable
;
4334 ConnStateData::stopReceiving(const char *error
)
4336 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4337 "; old sending error: " <<
4338 (stoppedSending() ? stoppedSending_
: "none"));
4340 if (const char *oldError
= stoppedReceiving()) {
4341 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4342 return; // nothing has changed as far as this connection is concerned
4345 stoppedReceiving_
= error
;
4347 if (const char *sendError
= stoppedSending()) {
4348 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4349 clientConnection
->close();
4354 ConnStateData::expectNoForwarding()
4356 if (bodyPipe
!= NULL
) {
4357 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4358 bodyPipe
->expectNoConsumption();
4362 /// initialize dechunking state
4364 ConnStateData::startDechunkingRequest()
4366 Must(bodyPipe
!= NULL
);
4367 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4368 assert(!in
.bodyParser
);
4369 in
.bodyParser
= new ChunkedCodingParser
;
4372 /// put parsed content into input buffer and clean up
4374 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4376 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4378 if (bodyPipe
!= NULL
) {
4379 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4380 BodyPipe::Pointer myPipe
= bodyPipe
;
4381 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4382 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4384 Must(myPipe
->bodySizeKnown());
4385 ClientSocketContext::Pointer context
= getCurrentContext();
4386 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4387 context
->http
->request
->setContentLength(myPipe
->bodySize());
4391 delete in
.bodyParser
;
4392 in
.bodyParser
= NULL
;
4396 ConnStateData::In::addressToReadInto() const
4398 return buf
+ notYetUsed
;
4401 ConnStateData::In::In() : bodyParser(NULL
),
4402 buf (NULL
), notYetUsed (0), allocatedSize (0)
4405 ConnStateData::In::~In()
4408 memFreeBuf(allocatedSize
, buf
);
4409 delete bodyParser
; // TODO: pool
4413 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4416 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4420 ClientSocketContext::Pointer context
= getCurrentContext();
4421 if (context
!= NULL
) {
4422 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4426 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4427 clientConnection
->close();
4430 /// Our close handler called by Comm when the pinned connection is closed
4432 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4434 // FwdState might repin a failed connection sooner than this close
4435 // callback is called for the failed connection.
4436 assert(pinning
.serverConnection
== io
.conn
);
4437 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4438 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4441 debugs(33, 3, "Closing client connection on pinned zero reply.");
4442 clientConnection
->close();
4447 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4449 char desc
[FD_DESC_SZ
];
4451 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4452 if (pinning
.serverConnection
->fd
== pinServer
->fd
)
4456 unpinConnection(); // closes pinned connection, if any, and resets fields
4458 pinning
.serverConnection
= pinServer
;
4460 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4462 // when pinning an SSL bumped connection, the request may be NULL
4463 const char *pinnedHost
= "[unknown]";
4465 pinning
.host
= xstrdup(request
->GetHost());
4466 pinning
.port
= request
->port
;
4467 pinnedHost
= pinning
.host
;
4469 pinning
.port
= pinServer
->remote
.GetPort();
4471 pinning
.pinned
= true;
4473 pinning
.peer
= cbdataReference(aPeer
);
4474 pinning
.auth
= auth
;
4475 char stmp
[MAX_IPSTRLEN
];
4476 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4477 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4478 clientConnection
->remote
.ToURL(stmp
,MAX_IPSTRLEN
),
4479 clientConnection
->fd
);
4480 fd_note(pinning
.serverConnection
->fd
, desc
);
4482 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4483 pinning
.closeHandler
= JobCallback(33, 5,
4484 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4485 // remember the pinned connection so that cb does not unpin a fresher one
4486 typedef CommCloseCbParams Params
;
4487 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4488 params
.conn
= pinning
.serverConnection
;
4489 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4492 const Comm::ConnectionPointer
4493 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4495 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4498 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4500 if (pinning
.auth
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0) {
4503 if (request
&& pinning
.port
!= request
->port
) {
4506 if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
)) {
4509 if (aPeer
!= pinning
.peer
) {
4514 /* The pinning info is not safe, remove any pinning info */
4518 return pinning
.serverConnection
;
4522 ConnStateData::unpinConnection()
4524 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4527 cbdataReferenceDone(pinning
.peer
);
4529 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4530 if (pinning
.closeHandler
!= NULL
) {
4531 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4532 pinning
.closeHandler
= NULL
;
4534 /// also close the server side socket, we should not use it for any future requests...
4535 // TODO: do not close if called from our close handler?
4536 pinning
.serverConnection
->close();
4539 safe_free(pinning
.host
);
4541 pinning
.zeroReply
= false;
4543 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4544 * connection has gone away */