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
);
719 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
720 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
727 ClientHttpRequest::freeResources()
731 safe_free(redirect
.location
);
732 range_iter
.boundary
.clean();
733 HTTPMSGUNLOCK(request
);
735 if (client_stream
.tail
)
736 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
740 httpRequestFree(void *data
)
742 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
743 assert(http
!= NULL
);
748 ConnStateData::areAllContextsForThisConnection() const
750 assert(this != NULL
);
751 ClientSocketContext::Pointer context
= getCurrentContext();
753 while (context
.getRaw()) {
754 if (context
->http
->getConn() != this)
757 context
= context
->next
;
764 ConnStateData::freeAllContexts()
766 ClientSocketContext::Pointer context
;
768 while ((context
= getCurrentContext()).getRaw() != NULL
) {
769 assert(getCurrentContext() !=
770 getCurrentContext()->next
);
771 context
->connIsFinished();
772 assert (context
!= currentobject
);
776 /// propagates abort event to all contexts
778 ConnStateData::notifyAllContexts(int xerrno
)
780 typedef ClientSocketContext::Pointer CSCP
;
781 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
782 c
->noteIoError(xerrno
);
785 /* This is a handler normally called by comm_close() */
786 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
788 deleteThis("ConnStateData::connStateClosed");
791 // cleans up before destructor is called
793 ConnStateData::swanSong()
795 debugs(33, 2, HERE
<< clientConnection
);
796 flags
.readMore
= false;
797 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
798 assert(areAllContextsForThisConnection());
801 if (auth_user_request
!= NULL
) {
802 debugs(33, 4, "ConnStateData::swanSong: freeing auth_user_request '" << auth_user_request
<< "' (this is '" << this << "')");
803 auth_user_request
->onConnectionClose(this);
807 if (Comm::IsConnOpen(pinning
.serverConnection
))
808 pinning
.serverConnection
->close();
809 pinning
.serverConnection
= NULL
;
811 if (Comm::IsConnOpen(clientConnection
))
812 clientConnection
->close();
813 clientConnection
= NULL
;
815 BodyProducer::swanSong();
816 flags
.swanSang
= true;
820 ConnStateData::isOpen() const
822 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
823 Comm::IsConnOpen(clientConnection
) &&
824 !fd_table
[clientConnection
->fd
].closing();
827 ConnStateData::~ConnStateData()
829 assert(this != NULL
);
830 debugs(33, 3, HERE
<< clientConnection
);
833 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
836 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
838 cbdataReferenceDone(port
);
840 if (bodyPipe
!= NULL
)
841 stopProducingFor(bodyPipe
, false);
844 delete sslServerBump
;
849 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
850 * This is the client-side persistent connection flag. We need
851 * to set this relatively early in the request processing
852 * to handle hacks for broken servers and clients.
855 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
857 HttpRequest
*request
= http
->request
;
859 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
860 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
861 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
862 RequestMethodStr(request
->method
));
864 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
865 request
->flags
.proxyKeepalive
= request
->persistent() ? 1 : 0;
869 clientIsContentLengthValid(HttpRequest
* r
)
871 switch (r
->method
.id()) {
873 case Http::METHOD_GET
:
875 case Http::METHOD_HEAD
:
876 /* We do not want to see a request entity on GET/HEAD requests */
877 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
880 /* For other types of requests we don't care */
888 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
890 if (Config
.maxRequestBodySize
&&
891 bodyLength
> Config
.maxRequestBodySize
)
892 return 1; /* too large */
899 connIsUsable(ConnStateData
* conn
)
901 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
909 // careful: the "current" context may be gone if we wrote an early response
910 ClientSocketContext::Pointer
911 ConnStateData::getCurrentContext() const
914 return currentobject
;
918 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
920 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
921 assert(flags
.deferred
== 0);
923 deferredparams
.node
= node
;
924 deferredparams
.rep
= rep
;
925 deferredparams
.queuedBuffer
= receivedData
;
930 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
932 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
939 ClientSocketContext::startOfOutput() const
941 return http
->out
.size
== 0;
945 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
947 /*the size of available range can always fit in a size_t type*/
948 size_t maximum
= (size_t)available
.size();
950 if (!http
->request
->range
)
953 assert (canPackMoreRanges());
955 if (http
->range_iter
.debt() == -1)
958 assert (http
->range_iter
.debt() > 0);
960 /* TODO this + the last line could be a range intersection calculation */
961 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
964 return min(http
->range_iter
.debt(), (int64_t)maximum
);
968 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
970 http
->out
.offset
+= bytes
;
972 if (!http
->request
->range
)
975 if (http
->range_iter
.debt() != -1) {
976 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
977 assert (http
->range_iter
.debt() >= 0);
980 /* debt() always stops at -1, below that is a bug */
981 assert (http
->range_iter
.debt() >= -1);
985 ClientHttpRequest::multipartRangeRequest() const
987 return request
->multipartRangeRequest();
991 ClientSocketContext::multipartRangeRequest() const
993 return http
->multipartRangeRequest();
997 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1001 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1002 size_t length
= lengthToSend(bodyData
.range());
1003 noteSentBodyBytes (length
);
1004 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1005 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1006 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1012 if (multipartRangeRequest())
1013 packRange(bodyData
, &mb
);
1015 packChunk(bodyData
, mb
);
1017 if (mb
.contentSize()) {
1019 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1020 CommIoCbPtrFun(clientWriteComplete
, this));
1021 Comm::Write(clientConnection
, &mb
, call
);
1023 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1027 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1028 * if bodyData is empty.
1031 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1033 const uint64_t length
=
1034 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1035 noteSentBodyBytes(length
);
1037 mb
.Printf("%" PRIX64
"\r\n", length
);
1038 mb
.append(bodyData
.data
, length
);
1042 /** put terminating boundary for multiparts */
1044 clientPackTermBound(String boundary
, MemBuf
* mb
)
1046 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1047 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1050 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1052 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1054 HttpHeader
hdr(hoReply
);
1060 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1061 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1062 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1064 /* stuff the header with required entries and pack it */
1066 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1067 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1069 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1071 packerToMemInit(&p
, mb
);
1079 /* append <crlf> (we packed a header, not a reply) */
1084 * extracts a "range" from *buf and appends them to mb, updating
1085 * all offsets and such.
1088 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1090 HttpHdrRangeIter
* i
= &http
->range_iter
;
1091 Range
<int64_t> available (source
.range());
1092 char const *buf
= source
.data
;
1094 while (i
->currentSpec() && available
.size()) {
1095 const size_t copy_sz
= lengthToSend(available
);
1099 * intersection of "have" and "need" ranges must not be empty
1101 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1102 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1105 * put boundary and headers at the beginning of a range in a
1109 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1110 assert(http
->memObject());
1112 http
->memObject()->getReply(), /* original reply */
1113 i
->currentSpec(), /* current range */
1114 i
->boundary
, /* boundary, the same for all */
1121 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1123 noteSentBodyBytes (copy_sz
);
1125 mb
->append(buf
, copy_sz
);
1130 available
.start
+= copy_sz
;
1136 if (!canPackMoreRanges()) {
1137 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1140 /* put terminating boundary for multiparts */
1141 clientPackTermBound(i
->boundary
, mb
);
1146 int64_t nextOffset
= getNextRangeOffset();
1148 assert (nextOffset
>= http
->out
.offset
);
1150 int64_t skip
= nextOffset
- http
->out
.offset
;
1152 /* adjust for not to be transmitted bytes */
1153 http
->out
.offset
= nextOffset
;
1155 if (available
.size() <= (uint64_t)skip
)
1158 available
.start
+= skip
;
1167 /** returns expected content length for multi-range replies
1168 * note: assumes that httpHdrRangeCanonize has already been called
1169 * warning: assumes that HTTP headers for individual ranges at the
1170 * time of the actuall assembly will be exactly the same as
1171 * the headers when clientMRangeCLen() is called */
1173 ClientHttpRequest::mRangeCLen()
1178 assert(memObject());
1181 HttpHdrRange::iterator pos
= request
->range
->begin();
1183 while (pos
!= request
->range
->end()) {
1184 /* account for headers for this range */
1186 clientPackRangeHdr(memObject()->getReply(),
1187 *pos
, range_iter
.boundary
, &mb
);
1190 /* account for range content */
1191 clen
+= (*pos
)->length
;
1193 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1197 /* account for the terminating boundary */
1200 clientPackTermBound(range_iter
.boundary
, &mb
);
1210 * returns true if If-Range specs match reply, false otherwise
1213 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1215 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1216 /* check for parsing falure */
1223 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1224 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1225 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1228 return 0; /* entity has no etag to compare with! */
1230 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1231 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1232 return 0; /* must use strong validator for sub-range requests */
1235 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1238 /* got modification time? */
1239 if (spec
.time
>= 0) {
1240 return http
->storeEntry()->lastmod
<= spec
.time
;
1243 assert(0); /* should not happen */
1248 * generates a "unique" boundary string for multipart responses
1249 * the caller is responsible for cleaning the string */
1251 ClientHttpRequest::rangeBoundaryStr() const
1255 String
b(APP_FULLNAME
);
1257 key
= storeEntry()->getMD5Text();
1258 b
.append(key
, strlen(key
));
1262 /** adds appropriate Range headers if needed */
1264 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1266 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1267 const char *range_err
= NULL
;
1268 HttpRequest
*request
= http
->request
;
1269 assert(request
->range
);
1270 /* check if we still want to do ranges */
1272 int64_t roffLimit
= request
->getRangeOffsetLimit();
1275 range_err
= "no [parse-able] reply";
1276 else if ((rep
->sline
.status
!= HTTP_OK
) && (rep
->sline
.status
!= HTTP_PARTIAL_CONTENT
))
1277 range_err
= "wrong status code";
1278 else if (hdr
->has(HDR_CONTENT_RANGE
))
1279 range_err
= "origin server does ranges";
1280 else if (rep
->content_length
< 0)
1281 range_err
= "unknown length";
1282 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1283 range_err
= "INCONSISTENT length"; /* a bug? */
1285 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1288 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1289 range_err
= "If-Range match failed";
1290 else if (!http
->request
->range
->canonize(rep
))
1291 range_err
= "canonization failed";
1292 else if (http
->request
->range
->isComplex())
1293 range_err
= "too complex range header";
1294 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1295 range_err
= "range outside range_offset_limit";
1297 /* get rid of our range specs on error */
1299 /* XXX We do this here because we need canonisation etc. However, this current
1300 * code will lead to incorrect store offset requests - the store will have the
1301 * offset data, but we won't be requesting it.
1302 * So, we can either re-request, or generate an error
1304 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1305 delete http
->request
->range
;
1306 http
->request
->range
= NULL
;
1308 /* XXX: TODO: Review, this unconditional set may be wrong. - TODO: review. */
1309 httpStatusLineSet(&rep
->sline
, rep
->sline
.version
,
1310 HTTP_PARTIAL_CONTENT
, NULL
);
1311 // web server responded with a valid, but unexpected range.
1312 // will (try-to) forward as-is.
1313 //TODO: we should cope with multirange request/responses
1314 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1315 request
->range
->contains(rep
->content_range
->spec
) :
1317 const int spec_count
= http
->request
->range
->specs
.count
;
1318 int64_t actual_clen
= -1;
1320 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1321 spec_count
<< " virgin clen: " << rep
->content_length
);
1322 assert(spec_count
> 0);
1323 /* append appropriate header(s) */
1325 if (spec_count
== 1) {
1326 if (!replyMatchRequest
) {
1327 hdr
->delById(HDR_CONTENT_RANGE
);
1328 hdr
->putContRange(rep
->content_range
);
1329 actual_clen
= rep
->content_length
;
1330 //http->range_iter.pos = rep->content_range->spec.begin();
1331 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1332 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1335 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1337 /* append Content-Range */
1339 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1340 /* No content range, so this was a full object we are
1343 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1346 /* set new Content-Length to the actual number of bytes
1347 * transmitted in the message-body */
1348 actual_clen
= (*pos
)->length
;
1352 /* generate boundary string */
1353 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1354 /* delete old Content-Type, add ours */
1355 hdr
->delById(HDR_CONTENT_TYPE
);
1356 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1357 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1358 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1359 /* Content-Length is not required in multipart responses
1360 * but it is always nice to have one */
1361 actual_clen
= http
->mRangeCLen();
1362 /* http->out needs to start where we want data at */
1363 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1366 /* replace Content-Length header */
1367 assert(actual_clen
>= 0);
1369 hdr
->delById(HDR_CONTENT_LENGTH
);
1371 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1373 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1375 /* And start the range iter off */
1376 http
->range_iter
.updateSpec();
1381 ClientSocketContext::prepareReply(HttpReply
* rep
)
1385 if (http
->request
->range
)
1386 buildRangeHeader(rep
);
1390 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1394 MemBuf
*mb
= rep
->pack();
1396 // dump now, so we dont output any body.
1397 debugs(11, 2, "HTTP Client " << clientConnection
);
1398 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1400 /* Save length of headers for persistent conn checks */
1401 http
->out
.headers_sz
= mb
->contentSize();
1404 headersLog(0, 0, http
->request
->method
, rep
);
1407 if (bodyData
.data
&& bodyData
.length
) {
1408 if (multipartRangeRequest())
1409 packRange(bodyData
, mb
);
1410 else if (http
->request
->flags
.chunkedReply
) {
1411 packChunk(bodyData
, *mb
);
1413 size_t length
= lengthToSend(bodyData
.range());
1414 noteSentBodyBytes (length
);
1416 mb
->append(bodyData
.data
, length
);
1421 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1422 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1423 CommIoCbPtrFun(clientWriteComplete
, this));
1424 Comm::Write(clientConnection
, mb
, call
);
1429 * Write a chunk of data to a client socket. If the reply is present,
1430 * send the reply headers down the wire too, and clean them up when
1433 * The request is one backed by a connection, not an internal request.
1434 * data context is not NULL
1435 * There are no more entries in the stream chain.
1438 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1439 HttpReply
* rep
, StoreIOBuffer receivedData
)
1441 /* Test preconditions */
1442 assert(node
!= NULL
);
1443 PROF_start(clientSocketRecipient
);
1444 /* TODO: handle this rather than asserting
1445 * - it should only ever happen if we cause an abort and
1446 * the callback chain loops back to here, so we can simply return.
1447 * However, that itself shouldn't happen, so it stays as an assert for now.
1449 assert(cbdataReferenceValid(node
));
1450 assert(node
->node
.next
== NULL
);
1451 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1452 assert(context
!= NULL
);
1453 assert(connIsUsable(http
->getConn()));
1455 /* TODO: check offset is what we asked for */
1457 if (context
!= http
->getConn()->getCurrentContext()) {
1458 context
->deferRecipientForLater(node
, rep
, receivedData
);
1459 PROF_stop(clientSocketRecipient
);
1463 // After sending Transfer-Encoding: chunked (at least), always send
1464 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1465 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1466 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1467 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1468 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1469 PROF_stop(clientSocketRecipient
);
1473 if (!context
->startOfOutput())
1474 context
->sendBody(rep
, receivedData
);
1477 http
->al
->reply
= HTTPMSGLOCK(rep
);
1478 context
->sendStartOfMessage(rep
, receivedData
);
1481 PROF_stop(clientSocketRecipient
);
1485 * Called when a downstream node is no longer interested in
1486 * our data. As we are a terminal node, this means on aborts
1490 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1492 /* Test preconditions */
1493 assert(node
!= NULL
);
1494 /* TODO: handle this rather than asserting
1495 * - it should only ever happen if we cause an abort and
1496 * the callback chain loops back to here, so we can simply return.
1497 * However, that itself shouldn't happen, so it stays as an assert for now.
1499 assert(cbdataReferenceValid(node
));
1500 /* Set null by ContextFree */
1501 assert(node
->node
.next
== NULL
);
1502 /* this is the assert discussed above */
1503 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1504 /* We are only called when the client socket shutsdown.
1505 * Tell the prev pipeline member we're finished
1507 clientStreamDetach(node
, http
);
1511 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1513 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1514 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1518 ConnStateData::readNextRequest()
1520 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1522 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1524 * Set the timeout BEFORE calling clientReadRequest().
1526 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1527 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1528 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1529 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1532 /** Please don't do anything with the FD past here! */
1536 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1538 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1540 /** If the client stream is waiting on a socket write to occur, then */
1542 if (deferredRequest
->flags
.deferred
) {
1543 /** NO data is allowed to have been sent. */
1544 assert(deferredRequest
->http
->out
.size
== 0);
1546 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1547 deferredRequest
->http
,
1548 deferredRequest
->deferredparams
.rep
,
1549 deferredRequest
->deferredparams
.queuedBuffer
);
1552 /** otherwise, the request is still active in a callbacksomewhere,
1557 /// called when we have successfully finished writing the response
1559 ClientSocketContext::keepaliveNextRequest()
1561 ConnStateData
* conn
= http
->getConn();
1563 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1566 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1567 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1568 conn
->clientConnection
->close();
1573 * We are done with the response, and we are either still receiving request
1574 * body (early response!) or have already stopped receiving anything.
1576 * If we are still receiving, then clientParseRequest() below will fail.
1577 * (XXX: but then we will call readNextRequest() which may succeed and
1578 * execute a smuggled request as we are not done with the current request).
1580 * If we stopped because we got everything, then try the next request.
1582 * If we stopped receiving because of an error, then close now to avoid
1583 * getting stuck and to prevent accidental request smuggling.
1586 if (const char *reason
= conn
->stoppedReceiving()) {
1587 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1588 conn
->clientConnection
->close();
1593 * Attempt to parse a request from the request buffer.
1594 * If we've been fed a pipelined request it may already
1595 * be in our read buffer.
1598 * This needs to fall through - if we're unlucky and parse the _last_ request
1599 * from our read buffer we may never re-register for another client read.
1602 if (conn
->clientParseRequests()) {
1603 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1607 * Either we need to kick-start another read or, if we have
1608 * a half-closed connection, kill it after the last request.
1609 * This saves waiting for half-closed connections to finished being
1610 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1611 * the keepalive "Waiting for next request" state.
1613 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1614 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1615 conn
->clientConnection
->close();
1619 ClientSocketContext::Pointer deferredRequest
;
1622 * At this point we either have a parsed request (which we've
1623 * kicked off the processing for) or not. If we have a deferred
1624 * request (parsed but deferred for pipeling processing reasons)
1625 * then look at processing it. If not, simply kickstart
1629 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1630 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1631 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1632 } else if (conn
->flags
.readMore
) {
1633 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1634 conn
->readNextRequest();
1636 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1637 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1642 clientUpdateSocketStats(log_type logType
, size_t size
)
1647 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1649 if (logTypeIsATcpHit(logType
))
1650 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1654 * increments iterator "i"
1655 * used by clientPackMoreRanges
1657 \retval true there is still data available to pack more ranges
1661 ClientSocketContext::canPackMoreRanges() const
1663 /** first update iterator "i" if needed */
1665 if (!http
->range_iter
.debt()) {
1666 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1668 if (http
->range_iter
.pos
.incrementable())
1669 ++http
->range_iter
.pos
;
1671 http
->range_iter
.updateSpec();
1674 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1676 /* paranoid sync condition */
1677 /* continue condition: need_more_data */
1678 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1679 return http
->range_iter
.currentSpec() ? true : false;
1683 ClientSocketContext::getNextRangeOffset() const
1685 if (http
->request
->range
) {
1686 /* offset in range specs does not count the prefix of an http msg */
1687 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1688 /* check: reply was parsed and range iterator was initialized */
1689 assert(http
->range_iter
.valid
);
1690 /* filter out data according to range specs */
1691 assert (canPackMoreRanges());
1693 int64_t start
; /* offset of still missing data */
1694 assert(http
->range_iter
.currentSpec());
1695 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1696 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1697 debugs(33, 3, "clientPackMoreRanges: out:"
1698 " start: " << start
<<
1699 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1700 " [" << http
->range_iter
.currentSpec()->offset
<<
1701 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1702 " len: " << http
->range_iter
.currentSpec()->length
<<
1703 " debt: " << http
->range_iter
.debt());
1704 if (http
->range_iter
.currentSpec()->length
!= -1)
1705 assert(http
->out
.offset
<= start
); /* we did not miss it */
1710 } else if (reply
&& reply
->content_range
) {
1711 /* request does not have ranges, but reply does */
1712 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1713 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1715 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1718 return http
->out
.offset
;
1722 ClientSocketContext::pullData()
1724 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1726 /* More data will be coming from the stream. */
1727 StoreIOBuffer readBuffer
;
1728 /* XXX: Next requested byte in the range sequence */
1729 /* XXX: length = getmaximumrangelenfgth */
1730 readBuffer
.offset
= getNextRangeOffset();
1731 readBuffer
.length
= HTTP_REQBUF_SZ
;
1732 readBuffer
.data
= reqbuf
;
1733 /* we may note we have reached the end of the wanted ranges */
1734 clientStreamRead(getTail(), http
, readBuffer
);
1737 clientStream_status_t
1738 ClientSocketContext::socketState()
1740 switch (clientStreamStatus(getTail(), http
)) {
1743 /* check for range support ending */
1745 if (http
->request
->range
) {
1746 /* check: reply was parsed and range iterator was initialized */
1747 assert(http
->range_iter
.valid
);
1748 /* filter out data according to range specs */
1750 if (!canPackMoreRanges()) {
1751 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1752 "range sequence on " << clientConnection
);
1754 if (http
->request
->flags
.proxyKeepalive
)
1755 return STREAM_COMPLETE
;
1757 return STREAM_UNPLANNED_COMPLETE
;
1759 } else if (reply
&& reply
->content_range
) {
1760 /* reply has content-range, but Squid is not managing ranges */
1761 const int64_t &bytesSent
= http
->out
.offset
;
1762 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1764 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1765 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1766 reply
->content_range
->spec
.offset
<< ")");
1768 // did we get at least what we expected, based on range specs?
1770 if (bytesSent
== bytesExpected
) { // got everything
1771 if (http
->request
->flags
.proxyKeepalive
)
1772 return STREAM_COMPLETE
;
1774 return STREAM_UNPLANNED_COMPLETE
;
1777 // The logic below is not clear: If we got more than we
1778 // expected why would persistency matter? Should not this
1779 // always be an error?
1780 if (bytesSent
> bytesExpected
) { // got extra
1781 if (http
->request
->flags
.proxyKeepalive
)
1782 return STREAM_COMPLETE
;
1784 return STREAM_UNPLANNED_COMPLETE
;
1787 // did not get enough yet, expecting more
1792 case STREAM_COMPLETE
:
1793 return STREAM_COMPLETE
;
1795 case STREAM_UNPLANNED_COMPLETE
:
1796 return STREAM_UNPLANNED_COMPLETE
;
1799 return STREAM_FAILED
;
1802 fatal ("unreachable code\n");
1807 * A write has just completed to the client, or we have just realised there is
1808 * no more data to send.
1811 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1813 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1814 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1817 /// remembers the abnormal connection termination for logging purposes
1819 ClientSocketContext::noteIoError(const int xerrno
)
1822 if (xerrno
== ETIMEDOUT
)
1823 http
->al
->http
.timedout
= true;
1824 else // even if xerrno is zero (which means read abort/eof)
1825 http
->al
->http
.aborted
= true;
1830 ClientSocketContext::doClose()
1832 clientConnection
->close();
1835 /// called when we encounter a response-related error
1837 ClientSocketContext::initiateClose(const char *reason
)
1839 http
->getConn()->stopSending(reason
); // closes ASAP
1843 ConnStateData::stopSending(const char *error
)
1845 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1846 "; old receiving error: " <<
1847 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1849 if (const char *oldError
= stoppedSending()) {
1850 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1851 return; // nothing has changed as far as this connection is concerned
1853 stoppedSending_
= error
;
1855 if (!stoppedReceiving()) {
1856 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1857 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1858 " request body bytes with " << in
.notYetUsed
<< " unused");
1859 return; // wait for the request receiver to finish reading
1863 clientConnection
->close();
1867 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1869 const StoreEntry
*entry
= http
->storeEntry();
1870 http
->out
.size
+= size
;
1871 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1872 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1873 (entry
? entry
->objectLen() : 0));
1874 clientUpdateSocketStats(http
->logType
, size
);
1876 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1878 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1881 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1882 initiateClose("failure or true request status");
1883 /* Do we leak here ? */
1887 switch (socketState()) {
1893 case STREAM_COMPLETE
:
1894 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1895 keepaliveNextRequest();
1898 case STREAM_UNPLANNED_COMPLETE
:
1899 initiateClose("STREAM_UNPLANNED_COMPLETE");
1903 initiateClose("STREAM_FAILED");
1907 fatal("Hit unreachable code in clientWriteComplete\n");
1911 SQUIDCEXTERN CSR clientGetMoreData
;
1912 SQUIDCEXTERN CSS clientReplyStatus
;
1913 SQUIDCEXTERN CSD clientReplyDetach
;
1915 static ClientSocketContext
*
1916 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1918 ClientHttpRequest
*http
;
1919 ClientSocketContext
*context
;
1920 StoreIOBuffer tempBuffer
;
1921 http
= new ClientHttpRequest(csd
);
1922 http
->req_sz
= csd
->in
.notYetUsed
;
1923 http
->uri
= xstrdup(uri
);
1924 setLogUri (http
, uri
);
1925 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
1926 tempBuffer
.data
= context
->reqbuf
;
1927 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1928 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1929 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1930 clientSocketDetach
, context
, tempBuffer
);
1935 skipLeadingSpace(char *aString
)
1937 char *result
= aString
;
1939 while (xisspace(*aString
))
1946 * 'end' defaults to NULL for backwards compatibility
1947 * remove default value if we ever get rid of NULL-terminated
1951 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1954 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1958 for (; end
> uriAndHTTPVersion
; --end
) {
1959 if (*end
== '\n' || *end
== '\r')
1962 if (xisspace(*end
)) {
1963 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1974 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1976 safe_free(http
->log_uri
);
1979 // The uri is already clean just dump it.
1980 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1983 switch (Config
.uri_whitespace
) {
1984 case URI_WHITESPACE_ALLOW
:
1985 flags
|= RFC1738_ESCAPE_NOSPACE
;
1987 case URI_WHITESPACE_ENCODE
:
1988 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1989 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1992 case URI_WHITESPACE_CHOP
: {
1993 flags
|= RFC1738_ESCAPE_NOSPACE
;
1994 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1995 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1996 int pos
= strcspn(http
->log_uri
, w_space
);
1997 http
->log_uri
[pos
] = '\0';
2001 case URI_WHITESPACE_DENY
:
2002 case URI_WHITESPACE_STRIP
:
2005 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2009 if (!xisspace(*t
)) {
2016 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2025 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2027 int vhost
= conn
->port
->vhost
;
2028 int vport
= conn
->port
->vport
;
2030 char ipbuf
[MAX_IPSTRLEN
];
2032 http
->flags
.accel
= 1;
2034 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2036 if (strncasecmp(url
, "cache_object://", 15) == 0)
2037 return; /* already in good shape */
2040 if (conn
->port
->vhost
)
2041 return; /* already in good shape */
2043 /* else we need to ignore the host name */
2044 url
= strstr(url
, "//");
2046 #if SHOULD_REJECT_UNKNOWN_URLS
2049 hp
->request_parse_status
= HTTP_BAD_REQUEST
;
2050 return parseHttpRequestAbort(conn
, "error:invalid-request");
2055 url
= strchr(url
+ 2, '/');
2062 vport
= http
->getConn()->clientConnection
->local
.GetPort();
2064 const bool switchedToHttps
= conn
->switchedToHttps();
2065 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2066 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2067 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2072 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2073 strncpy(thost
, host
, (t
-host
));
2074 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2077 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2080 } // else nothing to alter port-wise.
2081 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2083 http
->uri
= (char *)xcalloc(url_sz
, 1);
2084 const char *protocol
= switchedToHttps
?
2085 "https" : conn
->port
->protocol
;
2086 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2087 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2088 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2089 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2090 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2091 strlen(conn
->port
->defaultsite
);
2092 http
->uri
= (char *)xcalloc(url_sz
, 1);
2096 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2098 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2099 conn
->port
->protocol
, conn
->port
->defaultsite
, vportStr
, url
);
2100 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2101 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2102 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2103 /* Put the local socket IP address as the hostname, with whatever vport we found */
2104 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2105 http
->uri
= (char *)xcalloc(url_sz
, 1);
2106 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2107 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2108 http
->getConn()->port
->protocol
,
2110 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2115 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2118 char ipbuf
[MAX_IPSTRLEN
];
2121 return; /* already in good shape */
2123 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2125 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2126 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2128 http
->uri
= (char *)xcalloc(url_sz
, 1);
2129 snprintf(http
->uri
, url_sz
, "%s://%s%s", conn
->port
->protocol
, host
, url
);
2130 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2132 /* Put the local socket IP address as the hostname. */
2133 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2134 http
->uri
= (char *)xcalloc(url_sz
, 1);
2135 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2136 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2137 http
->getConn()->port
->protocol
,
2138 ipbuf
, http
->getConn()->clientConnection
->local
.GetPort(), url
);
2139 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2144 * parseHttpRequest()
2147 * NULL on incomplete requests
2148 * a ClientSocketContext structure on success or failure.
2149 * Sets result->flags.parsed_ok to 0 if failed to parse the request.
2150 * Sets result->flags.parsed_ok to 1 if we have a good request.
2152 static ClientSocketContext
*
2153 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, HttpVersion
*http_ver
)
2155 char *req_hdr
= NULL
;
2158 ClientHttpRequest
*http
;
2159 ClientSocketContext
*result
;
2160 StoreIOBuffer tempBuffer
;
2163 /* pre-set these values to make aborting simpler */
2164 *method_p
= Http::METHOD_NONE
;
2166 /* NP: don't be tempted to move this down or remove again.
2167 * It's the only DDoS protection old-String has against long URL */
2168 if ( hp
->bufsiz
<= 0) {
2169 debugs(33, 5, "Incomplete request, waiting for end of request line");
2171 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2172 debugs(33, 5, "parseHttpRequest: Too large request");
2173 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2174 return parseHttpRequestAbort(csd
, "error:request-too-large");
2177 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2178 r
= HttpParserParseReqLine(hp
);
2181 debugs(33, 5, "Incomplete request, waiting for end of request line");
2186 return parseHttpRequestAbort(csd
, "error:invalid-request");
2189 /* Request line is valid here .. */
2190 *http_ver
= HttpVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2192 /* This call scans the entire request, not just the headers */
2193 if (hp
->req
.v_maj
> 0) {
2194 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2195 debugs(33, 5, "Incomplete request, waiting for end of headers");
2199 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2200 req_sz
= HttpParserReqSz(hp
);
2203 /* We know the whole request is in hp->buf now */
2205 assert(req_sz
<= (size_t) hp
->bufsiz
);
2207 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2208 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2211 hp
->hdr_end
= req_sz
- 1;
2213 hp
->hdr_start
= hp
->req
.end
+ 1;
2215 /* Enforce max_request_size */
2216 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2217 debugs(33, 5, "parseHttpRequest: Too large request");
2218 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2219 return parseHttpRequestAbort(csd
, "error:request-too-large");
2223 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2225 /* deny CONNECT via accelerated ports */
2226 if (*method_p
== Http::METHOD_CONNECT
&& csd
&& csd
->port
&& csd
->port
->accel
) {
2227 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->protocol
<< " Accelerator port " << csd
->port
->s
.GetPort() );
2228 /* XXX need a way to say "this many character length string" */
2229 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2230 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2231 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2234 if (*method_p
== Http::METHOD_NONE
) {
2235 /* XXX need a way to say "this many character length string" */
2236 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2237 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2238 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2242 * Process headers after request line
2243 * TODO: Use httpRequestParse here.
2245 /* XXX this code should be modified to take a const char * later! */
2246 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2248 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2250 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2252 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2254 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2255 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2256 HttpParserReqSz(hp
));
2258 /* Ok, all headers are received */
2259 http
= new ClientHttpRequest(csd
);
2261 http
->req_sz
= HttpParserRequestLen(hp
);
2262 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2263 tempBuffer
.data
= result
->reqbuf
;
2264 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2266 ClientStreamData newServer
= new clientReplyContext(http
);
2267 ClientStreamData newClient
= result
;
2268 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2269 clientReplyStatus
, newServer
, clientSocketRecipient
,
2270 clientSocketDetach
, newClient
, tempBuffer
);
2272 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2276 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2277 * below needs to be modified to not expect a mutable nul-terminated string.
2279 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2281 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2283 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2285 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2287 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2292 debugs(33,5, HERE
<< "repare absolute URL from " << (csd
->transparent()?"intercept":(csd
->port
->accel
? "accel":"")));
2293 /* Rewrite the URL in transparent or accelerator mode */
2294 /* NP: there are several cases to traverse here:
2295 * - standard mode (forward proxy)
2296 * - transparent mode (TPROXY)
2297 * - transparent mode with failures
2298 * - intercept mode (NAT)
2299 * - intercept mode with failures
2300 * - accelerator mode (reverse proxy)
2302 * - mixed combos of the above with internal URL
2304 if (csd
->transparent()) {
2305 /* intercept or transparent mode, properly working with no failures */
2306 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2308 } else if (internalCheck(url
)) {
2309 /* internal URL mode */
2310 /* prepend our name & port */
2311 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2312 // We just re-wrote the URL. Must replace the Host: header.
2313 // But have not parsed there yet!! flag for local-only handling.
2314 http
->flags
.internal
= 1;
2316 } else if (csd
->port
->accel
|| csd
->switchedToHttps()) {
2317 /* accelerator mode */
2318 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2322 /* No special rewrites have been applied above, use the
2323 * requested url. may be rewritten later, so make extra room */
2324 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2325 http
->uri
= (char *)xcalloc(url_sz
, 1);
2326 strcpy(http
->uri
, url
);
2329 debugs(33, 5, "parseHttpRequest: Complete request received");
2331 // XXX: crop this dump at the end of headers. No need for extras
2332 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2333 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2335 result
->flags
.parsed_ok
= 1;
2341 ConnStateData::getAvailableBufferLength() const
2343 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2344 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2345 // huge request_header_max_size may lead to more than INT_MAX unused space
2346 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2351 ConnStateData::maybeMakeSpaceAvailable()
2353 if (getAvailableBufferLength() < 2) {
2355 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2356 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2359 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2360 newSize
=Config
.maxRequestBufferSize
;
2362 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2363 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2369 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2371 ClientSocketContext::Pointer
*S
;
2373 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2381 ConnStateData::getConcurrentRequestCount() const
2384 ClientSocketContext::Pointer
*T
;
2386 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2387 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2392 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2394 if (flag
!= COMM_OK
) {
2395 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2400 if (!ignoreErrno(xerrno
)) {
2401 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2403 } else if (in
.notYetUsed
== 0) {
2404 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2412 ConnStateData::connFinishedWithConn(int size
)
2415 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2416 /* no current or pending requests */
2417 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2419 } else if (!Config
.onoff
.half_closed_clients
) {
2420 /* admin doesn't want to support half-closed client sockets */
2421 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2422 notifyAllContexts(0); // no specific error implies abort
2431 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2433 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2434 conn
->in
.notYetUsed
-= byteCount
;
2435 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2437 * If there is still data that will be used,
2438 * move it to the beginning.
2441 if (conn
->in
.notYetUsed
> 0)
2442 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2445 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2447 ConnStateData::checkHeaderLimits()
2449 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2450 return; // can accumulte more header data
2452 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2453 Config
.maxRequestHeaderSize
<< " bytes)");
2455 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2456 clientStreamNode
*node
= context
->getClientReplyContext();
2457 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2458 assert (repContext
);
2459 repContext
->setReplyToError(ERR_TOO_BIG
,
2460 HTTP_BAD_REQUEST
, Http::METHOD_NONE
, NULL
,
2461 clientConnection
->remote
, NULL
, NULL
, NULL
);
2462 context
->registerWithConn();
2463 context
->pullData();
2467 ConnStateData::clientAfterReadingRequests()
2469 // Were we expecting to read more request body from half-closed connection?
2470 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2471 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2472 clientConnection
->close();
2481 ConnStateData::quitAfterError(HttpRequest
*request
)
2483 // From HTTP p.o.v., we do not have to close after every error detected
2484 // at the client-side, but many such errors do require closure and the
2485 // client-side code is bad at handling errors so we play it safe.
2487 request
->flags
.proxyKeepalive
= 0;
2488 flags
.readMore
= false;
2489 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2493 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2495 ClientHttpRequest
*http
= context
->http
;
2500 assert(sslServerBump
->entry
);
2501 // Did we create an error entry while processing CONNECT?
2502 if (!sslServerBump
->entry
->isEmpty()) {
2503 quitAfterError(http
->request
);
2505 // Get the saved error entry and send it to the client by replacing the
2506 // ClientHttpRequest store entry with it.
2507 clientStreamNode
*node
= context
->getClientReplyContext();
2508 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2510 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2511 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2513 // save the original request for logging purposes
2514 if (!context
->http
->al
->request
)
2515 context
->http
->al
->request
= HTTPMSGLOCK(http
->request
);
2517 // Get error details from the fake certificate-peeking request.
2518 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2519 context
->pullData();
2523 // In bump-server-first mode, we have not necessarily seen the intended
2524 // server name at certificate-peeking time. Check for domain mismatch now,
2525 // when we can extract the intended name from the bumped HTTP request.
2526 if (sslServerBump
->serverCert
.get()) {
2527 HttpRequest
*request
= http
->request
;
2528 if (!Ssl::checkX509ServerValidity(sslServerBump
->serverCert
.get(), request
->GetHost())) {
2529 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2530 "does not match domainname " << request
->GetHost());
2532 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2533 check
.sslErrors
= new Ssl::Errors(SQUID_X509_V_ERR_DOMAIN_MISMATCH
);
2534 const bool allowDomainMismatch
=
2535 check
.fastCheck() == ACCESS_ALLOWED
;
2536 delete check
.sslErrors
;
2537 check
.sslErrors
= NULL
;
2539 if (!allowDomainMismatch
) {
2540 quitAfterError(request
);
2542 clientStreamNode
*node
= context
->getClientReplyContext();
2543 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2544 assert (repContext
);
2546 // Fill the server IP and hostname for error page generation.
2547 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2548 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2550 // Create an error object and fill it
2551 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, HTTP_SERVICE_UNAVAILABLE
, request
);
2552 err
->src_addr
= clientConnection
->remote
;
2553 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2554 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2555 sslServerBump
->serverCert
.get(), NULL
);
2556 err
->detail
= errDetail
;
2557 // Save the original request for logging purposes.
2558 if (!context
->http
->al
->request
)
2559 context
->http
->al
->request
= HTTPMSGLOCK(request
);
2560 repContext
->setReplyToError(request
->method
, err
);
2561 assert(context
->http
->out
.offset
== 0);
2562 context
->pullData();
2573 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, HttpVersion http_ver
)
2575 ClientHttpRequest
*http
= context
->http
;
2576 HttpRequest
*request
= NULL
;
2577 bool notedUseOfBuffer
= false;
2578 bool chunked
= false;
2579 bool mustReplyToOptions
= false;
2580 bool unsupportedTe
= false;
2581 bool expectBody
= false;
2583 /* We have an initial client stream in place should it be needed */
2584 /* setup our private context */
2585 context
->registerWithConn();
2587 if (context
->flags
.parsed_ok
== 0) {
2588 clientStreamNode
*node
= context
->getClientReplyContext();
2589 debugs(33, 2, "clientProcessRequest: Invalid Request");
2590 conn
->quitAfterError(NULL
);
2591 // setLogUri should called before repContext->setReplyToError
2592 setLogUri(http
, http
->uri
, true);
2593 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2594 assert (repContext
);
2595 switch (hp
->request_parse_status
) {
2596 case HTTP_HEADER_TOO_LARGE
:
2597 repContext
->setReplyToError(ERR_TOO_BIG
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2599 case HTTP_METHOD_NOT_ALLOWED
:
2600 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_METHOD_NOT_ALLOWED
, method
, http
->uri
,
2601 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2604 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2605 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2607 assert(context
->http
->out
.offset
== 0);
2608 context
->pullData();
2612 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2613 clientStreamNode
*node
= context
->getClientReplyContext();
2614 debugs(33, 5, "Invalid URL: " << http
->uri
);
2615 conn
->quitAfterError(request
);
2616 // setLogUri should called before repContext->setReplyToError
2617 setLogUri(http
, http
->uri
, true);
2618 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2619 assert (repContext
);
2620 repContext
->setReplyToError(ERR_INVALID_URL
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2621 assert(context
->http
->out
.offset
== 0);
2622 context
->pullData();
2626 /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */
2627 /* We currently only accept 0.9, 1.0, 1.1 */
2628 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2629 (http_ver
.major
== 1 && http_ver
.minor
> 1 ) ||
2630 (http_ver
.major
> 1) ) {
2632 clientStreamNode
*node
= context
->getClientReplyContext();
2633 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2634 conn
->quitAfterError(request
);
2635 // setLogUri should called before repContext->setReplyToError
2636 setLogUri(http
, http
->uri
, true);
2637 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2638 assert (repContext
);
2639 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, HTTP_HTTP_VERSION_NOT_SUPPORTED
, method
, http
->uri
,
2640 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2641 assert(context
->http
->out
.offset
== 0);
2642 context
->pullData();
2646 /* compile headers */
2647 /* we should skip request line! */
2648 /* XXX should actually know the damned buffer size here */
2649 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2650 clientStreamNode
*node
= context
->getClientReplyContext();
2651 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2652 conn
->quitAfterError(request
);
2653 // setLogUri should called before repContext->setReplyToError
2654 setLogUri(http
, http
->uri
, true);
2655 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2656 assert (repContext
);
2657 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2658 assert(context
->http
->out
.offset
== 0);
2659 context
->pullData();
2663 request
->clientConnectionManager
= conn
;
2665 request
->flags
.accelerated
= http
->flags
.accel
;
2666 request
->flags
.sslBumped
=conn
->switchedToHttps();
2667 request
->flags
.canRePin
= request
->flags
.sslBumped
&& conn
->pinning
.pinned
;
2668 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2669 // TODO: decouple http->flags.accel from request->flags.sslBumped
2670 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2671 !conn
->port
->allow_direct
: 0;
2673 if (request
->flags
.sslBumped
) {
2674 if (conn
->auth_user_request
!= NULL
)
2675 request
->auth_user_request
= conn
->auth_user_request
;
2680 * If transparent or interception mode is working clone the transparent and interception flags
2681 * from the port settings to the request.
2683 if (http
->clientConnection
!= NULL
) {
2684 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2685 request
->flags
.spoofClientIp
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2688 if (internalCheck(request
->urlpath
.termedBuf())) {
2689 if (internalHostnameIs(request
->GetHost()) &&
2690 request
->port
== getMyPort()) {
2691 http
->flags
.internal
= 1;
2692 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2693 request
->SetHost(internalHostname());
2694 request
->port
= getMyPort();
2695 http
->flags
.internal
= 1;
2699 if (http
->flags
.internal
) {
2700 request
->protocol
= AnyP::PROTO_HTTP
;
2701 request
->login
[0] = '\0';
2704 request
->flags
.internal
= http
->flags
.internal
;
2705 setLogUri (http
, urlCanonicalClean(request
));
2706 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2707 #if FOLLOW_X_FORWARDED_FOR
2708 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2709 // not a details about teh TCP connection itself
2710 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2711 #endif /* FOLLOW_X_FORWARDED_FOR */
2712 request
->my_addr
= conn
->clientConnection
->local
;
2713 request
->myportname
= conn
->port
->name
;
2714 request
->http_ver
= http_ver
;
2716 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2717 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2718 request
->clientConnectionManager
= conn
;
2720 if (request
->header
.chunked()) {
2722 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2723 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2724 // HTTP/1.1 requires chunking to be the last encoding if there is one
2725 unsupportedTe
= te
.size() && te
!= "identity";
2726 } // else implied identity coding
2728 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2729 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2730 if (!urlCheckRequest(request
) || mustReplyToOptions
|| unsupportedTe
) {
2731 clientStreamNode
*node
= context
->getClientReplyContext();
2732 conn
->quitAfterError(request
);
2733 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2734 assert (repContext
);
2735 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_NOT_IMPLEMENTED
, request
->method
, NULL
,
2736 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2737 assert(context
->http
->out
.offset
== 0);
2738 context
->pullData();
2742 if (!chunked
&& !clientIsContentLengthValid(request
)) {
2743 clientStreamNode
*node
= context
->getClientReplyContext();
2744 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2745 assert (repContext
);
2746 conn
->quitAfterError(request
);
2747 repContext
->setReplyToError(ERR_INVALID_REQ
,
2748 HTTP_LENGTH_REQUIRED
, request
->method
, NULL
,
2749 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2750 assert(context
->http
->out
.offset
== 0);
2751 context
->pullData();
2755 if (request
->header
.has(HDR_EXPECT
)) {
2756 const String expect
= request
->header
.getList(HDR_EXPECT
);
2757 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2758 if (!supportedExpect
) {
2759 clientStreamNode
*node
= context
->getClientReplyContext();
2760 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2761 assert (repContext
);
2762 conn
->quitAfterError(request
);
2763 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_EXPECTATION_FAILED
, request
->method
, http
->uri
,
2764 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2765 assert(context
->http
->out
.offset
== 0);
2766 context
->pullData();
2771 http
->request
= HTTPMSGLOCK(request
);
2772 clientSetKeepaliveFlag(http
);
2774 // Let tunneling code be fully responsible for CONNECT requests
2775 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2776 context
->mayUseConnection(true);
2777 conn
->flags
.readMore
= false;
2781 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2785 /* Do we expect a request-body? */
2786 expectBody
= chunked
|| request
->content_length
> 0;
2787 if (!context
->mayUseConnection() && expectBody
) {
2788 request
->body_pipe
= conn
->expectRequestBody(
2789 chunked
? -1 : request
->content_length
);
2791 // consume header early so that body pipe gets just the body
2792 connNoteUseOfBuffer(conn
, http
->req_sz
);
2793 notedUseOfBuffer
= true;
2795 /* Is it too large? */
2796 if (!chunked
&& // if chunked, we will check as we accumulate
2797 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2798 clientStreamNode
*node
= context
->getClientReplyContext();
2799 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2800 assert (repContext
);
2801 conn
->quitAfterError(request
);
2802 repContext
->setReplyToError(ERR_TOO_BIG
,
2803 HTTP_REQUEST_ENTITY_TOO_LARGE
, Http::METHOD_NONE
, NULL
,
2804 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2805 assert(context
->http
->out
.offset
== 0);
2806 context
->pullData();
2810 // We may stop producing, comm_close, and/or call setReplyToError()
2811 // below, so quit on errors to avoid http->doCallouts()
2812 if (!conn
->handleRequestBodyData())
2815 if (!request
->body_pipe
->productionEnded()) {
2816 debugs(33, 5, HERE
<< "need more request body");
2817 context
->mayUseConnection(true);
2818 assert(conn
->flags
.readMore
);
2822 http
->calloutContext
= new ClientRequestContext(http
);
2827 if (!notedUseOfBuffer
)
2828 connNoteUseOfBuffer(conn
, http
->req_sz
);
2832 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2833 * to here because calling comm_reset_close() causes http to
2834 * be freed and the above connNoteUseOfBuffer() would hit an
2835 * assertion, not to mention that we were accessing freed memory.
2837 if (request
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2838 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2839 conn
->flags
.readMore
= false;
2840 comm_reset_close(conn
->clientConnection
);
2845 connStripBufferWhitespace (ConnStateData
* conn
)
2847 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2848 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2849 -- conn
->in
.notYetUsed
;
2854 connOkToAddRequest(ConnStateData
* conn
)
2856 int result
= conn
->getConcurrentRequestCount() < (Config
.onoff
.pipeline_prefetch
? 2 : 1);
2859 debugs(33, 3, HERE
<< conn
->clientConnection
<< " max concurrent requests reached");
2860 debugs(33, 5, HERE
<< conn
->clientConnection
<< " defering new request until one is done");
2867 * Attempt to parse one or more requests from the input buffer.
2868 * If a request is successfully parsed, even if the next request
2869 * is only partially parsed, it will return TRUE.
2872 ConnStateData::clientParseRequests()
2874 HttpRequestMethod method
;
2875 bool parsed_req
= false;
2876 HttpVersion http_ver
;
2878 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2880 // Loop while we have read bytes that are not needed for producing the body
2881 // On errors, bodyPipe may become nil, but readMore will be cleared
2882 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2883 connStripBufferWhitespace(this);
2885 /* Don't try to parse if the buffer is empty */
2886 if (in
.notYetUsed
== 0)
2889 /* Limit the number of concurrent requests to 2 */
2890 if (!connOkToAddRequest(this)) {
2894 /* Should not be needed anymore */
2895 /* Terminate the string */
2896 in
.buf
[in
.notYetUsed
] = '\0';
2898 /* Begin the parsing */
2899 PROF_start(parseHttpRequest
);
2900 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
2902 /* Process request */
2903 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2904 PROF_stop(parseHttpRequest
);
2906 /* partial or incomplete request */
2908 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2909 // (which becomes context) but checkHeaderLimits cannot?
2910 checkHeaderLimits();
2914 /* status -1 or 1 */
2916 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2917 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2918 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2919 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2921 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2923 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2925 if (context
->mayUseConnection()) {
2926 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2932 /* XXX where to 'finish' the parsing pass? */
2937 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
2939 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
2943 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2945 if (io
.flag
== COMM_ERR_CLOSING
) {
2946 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
2950 assert(Comm::IsConnOpen(clientConnection
));
2951 assert(io
.conn
->fd
== clientConnection
->fd
);
2954 * Don't reset the timeout value here. The timeout value will be
2955 * set to Config.Timeout.request by httpAccept() and
2956 * clientWriteComplete(), and should apply to the request as a
2957 * whole, not individual read() calls. Plus, it breaks our
2958 * lame half-close detection
2960 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
2961 notifyAllContexts(io
.xerrno
);
2966 if (io
.flag
== COMM_OK
) {
2968 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
2970 // may comm_close or setReplyToError
2971 if (!handleReadData(io
.buf
, io
.size
))
2974 } else if (io
.size
== 0) {
2975 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
2977 if (connFinishedWithConn(io
.size
)) {
2978 clientConnection
->close();
2982 /* It might be half-closed, we can't tell */
2983 fd_table
[io
.conn
->fd
].flags
.socket_eof
= 1;
2985 commMarkHalfClosed(io
.conn
->fd
);
2987 fd_note(io
.conn
->fd
, "half-closed");
2989 /* There is one more close check at the end, to detect aborted
2990 * (partial) requests. At this point we can't tell if the request
2993 /* Continue to process previously read data */
2997 /* Process next request */
2998 if (getConcurrentRequestCount() == 0)
2999 fd_note(io
.fd
, "Reading next request");
3001 if (!clientParseRequests()) {
3005 * If the client here is half closed and we failed
3006 * to parse a request, close the connection.
3007 * The above check with connFinishedWithConn() only
3008 * succeeds _if_ the buffer is empty which it won't
3009 * be if we have an incomplete request.
3010 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3012 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3013 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3014 clientConnection
->close();
3022 clientAfterReadingRequests();
3026 * called when new request data has been read from the socket
3028 * \retval false called comm_close or setReplyToError (the caller should bail)
3029 * \retval true we did not call comm_close or setReplyToError
3032 ConnStateData::handleReadData(char *buf
, size_t size
)
3034 char *current_buf
= in
.addressToReadInto();
3036 if (buf
!= current_buf
)
3037 memmove(current_buf
, buf
, size
);
3039 in
.notYetUsed
+= size
;
3041 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3043 // if we are reading a body, stuff data into the body pipe
3044 if (bodyPipe
!= NULL
)
3045 return handleRequestBodyData();
3050 * called when new request body data has been buffered in in.buf
3051 * may close the connection if we were closing and piped everything out
3053 * \retval false called comm_close or setReplyToError (the caller should bail)
3054 * \retval true we did not call comm_close or setReplyToError
3057 ConnStateData::handleRequestBodyData()
3059 assert(bodyPipe
!= NULL
);
3063 if (in
.bodyParser
) { // chunked encoding
3064 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3065 abortChunkedRequestBody(error
);
3068 } else { // identity encoding
3069 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3070 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3071 if (!bodyPipe
->mayNeedMoreData()) {
3072 // BodyPipe will clear us automagically when we produced everything
3078 connNoteUseOfBuffer(this, putSize
);
3081 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3083 if (const char *reason
= stoppedSending()) {
3084 /* we've finished reading like good clients,
3085 * now do the close that initiateClose initiated.
3087 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3088 clientConnection
->close();
3096 /// parses available chunked encoded body bytes, checks size, returns errors
3098 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3100 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3102 try { // the parser will throw on errors
3104 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3107 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3108 // add one because MemBuf will assert if it cannot 0-terminate
3109 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3110 raw
.append(in
.buf
, in
.notYetUsed
);
3112 const mb_size_t wasContentSize
= raw
.contentSize();
3113 BodyPipeCheckout
bpc(*bodyPipe
);
3114 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3116 putSize
= wasContentSize
- raw
.contentSize();
3118 // dechunk then check: the size limit applies to _dechunked_ content
3119 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3123 finishDechunkingRequest(true);
3125 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3128 // if chunk parser needs data, then the body pipe must need it too
3129 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3131 // if parser needs more space and we can consume nothing, we will stall
3132 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3133 } catch (...) { // TODO: be more specific
3134 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3135 return ERR_INVALID_REQ
;
3138 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3142 /// quit on errors related to chunked request body handling
3144 ConnStateData::abortChunkedRequestBody(const err_type error
)
3146 finishDechunkingRequest(false);
3148 // XXX: The code below works if we fail during initial request parsing,
3149 // but if we fail when the server-side works already, the server may send
3150 // us its response too, causing various assertions. How to prevent that?
3151 #if WE_KNOW_HOW_TO_SEND_ERRORS
3152 ClientSocketContext::Pointer context
= getCurrentContext();
3153 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3154 clientStreamNode
*node
= context
->getClientReplyContext();
3155 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3157 const http_status scode
= (error
== ERR_TOO_BIG
) ?
3158 HTTP_REQUEST_ENTITY_TOO_LARGE
: HTTP_BAD_REQUEST
;
3159 repContext
->setReplyToError(error
, scode
,
3160 repContext
->http
->request
->method
,
3161 repContext
->http
->uri
,
3163 repContext
->http
->request
,
3165 context
->pullData();
3167 // close or otherwise we may get stuck as nobody will notice the error?
3168 comm_reset_close(clientConnection
);
3171 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3172 comm_reset_close(clientConnection
);
3174 flags
.readMore
= false;
3178 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3180 if (!handleRequestBodyData())
3183 // too late to read more body
3184 if (!isOpen() || stoppedReceiving())
3191 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3193 // request reader may get stuck waiting for space if nobody consumes body
3194 if (bodyPipe
!= NULL
)
3195 bodyPipe
->enableAutoConsumption();
3197 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3200 /** general lifetime handler for HTTP requests */
3202 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3204 #if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS
3205 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3207 if (COMMIO_FD_WRITECB(io
.fd
)->active
) {
3208 /* FIXME: If this code is reinstated, check the conn counters,
3209 * not the fd table state
3212 * Some data has been sent to the client, just close the FD
3214 clientConnection
->close();
3215 } else if (nrequests
) {
3217 * assume its a persistent connection; just close it
3219 clientConnection
->close();
3224 ClientHttpRequest
**H
;
3225 clientStreamNode
*node
;
3226 ClientHttpRequest
*http
= parseHttpRequestAbort(this, "error:Connection%20lifetime%20expired");
3227 node
= http
->client_stream
.tail
->prev
->data
;
3228 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3229 assert (repContext
);
3230 repContext
->setReplyToError(ERR_LIFETIME_EXP
,
3231 HTTP_REQUEST_TIMEOUT
, Http::METHOD_NONE
, "N/A", &CachePeer
.sin_addr
,
3233 /* No requests can be outstanded */
3234 assert(chr
== NULL
);
3235 /* add to the client request queue */
3237 for (H
= &chr
; *H
; H
= &(*H
)->next
);
3240 clientStreamRead(http
->client_stream
.tail
->data
, http
, 0,
3241 HTTP_REQBUF_SZ
, context
->reqbuf
);
3244 * if we don't close() here, we still need a timeout handler!
3246 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3247 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3248 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3249 commSetConnTimeout(io
.conn
, 30, timeoutCall
);
3252 * Aha, but we don't want a read handler!
3254 Comm::SetSelect(io
.fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3259 * Just close the connection to not confuse browsers
3260 * using persistent connections. Some browsers opens
3261 * an connection and then does not use it until much
3262 * later (presumeably because the request triggering
3263 * the open has already been completed on another
3266 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3272 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3274 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3275 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3276 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3277 http
->al
->http
.timedout
= true;
3278 if (Comm::IsConnOpen(io
.conn
))
3283 connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
)
3285 ConnStateData
*result
= new ConnStateData
;
3287 result
->clientConnection
= client
;
3288 result
->log_addr
= client
->remote
;
3289 result
->log_addr
.ApplyMask(Config
.Addrs
.client_netmask
);
3290 result
->in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &result
->in
.allocatedSize
);
3291 result
->port
= cbdataReference(port
);
3293 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3294 (result
->transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3295 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3296 int i
= IP_PMTUDISC_DONT
;
3297 setsockopt(client
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof i
);
3299 static int reported
= 0;
3302 debugs(33, DBG_IMPORTANT
, "Notice: httpd_accel_no_pmtu_disc not supported on your platform");
3308 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3309 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, result
, ConnStateData::connStateClosed
);
3310 comm_add_close_handler(client
->fd
, call
);
3312 if (Config
.onoff
.log_fqdn
)
3313 fqdncache_gethostbyaddr(client
->remote
, FQDN_LOOKUP_IF_MISS
);
3316 if (Ident::TheConfig
.identLookup
) {
3317 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3318 identChecklist
.src_addr
= client
->remote
;
3319 identChecklist
.my_addr
= client
->local
;
3320 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3321 Ident::Start(client
, clientIdentDone
, result
);
3326 if (Eui::TheConfig
.euiLookup
) {
3327 if (client
->remote
.IsIPv4()) {
3328 result
->clientConnection
->remoteEui48
.lookup(client
->remote
);
3329 } else if (client
->remote
.IsIPv6()) {
3330 result
->clientConnection
->remoteEui64
.lookup(client
->remote
);
3335 clientdbEstablished(client
->remote
, 1);
3337 result
->flags
.readMore
= true;
3341 /** Handle a new connection on HTTP socket. */
3343 httpAccept(const CommAcceptCbParams
¶ms
)
3345 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3347 if (params
.flag
!= COMM_OK
) {
3348 // Its possible the call was still queued when the client disconnected
3349 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3353 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3354 fd_note(params
.conn
->fd
, "client http connect");
3356 if (s
->tcp_keepalive
.enabled
) {
3357 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3360 ++ incoming_sockets_accepted
;
3362 // Socket is ready, setup the connection manager to start using it
3363 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3365 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3366 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3367 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3368 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3370 connState
->readSomeData();
3373 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3375 if (Config
.onoff
.client_db
) {
3376 /* it was said several times that client write limiter does not work if client_db is disabled */
3378 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3379 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3381 // TODO: we check early to limit error response bandwith but we
3382 // should recheck when we can honor delay_pool_uses_indirect
3383 // TODO: we should also pass the port details for myportname here.
3384 ch
.src_addr
= params
.conn
->remote
;
3385 ch
.my_addr
= params
.conn
->local
;
3387 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3389 /* pools require explicit 'allow' to assign a client into them */
3390 if (pools
[pool
].access
) {
3391 ch
.accessList
= pools
[pool
].access
;
3392 allow_t answer
= ch
.fastCheck();
3393 if (answer
== ACCESS_ALLOWED
) {
3395 /* request client information from db after we did all checks
3396 this will save hash lookup if client failed checks */
3397 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3400 /* put client info in FDE */
3401 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3403 /* setup write limiter for this request */
3404 const double burst
= floor(0.5 +
3405 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3406 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3409 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3419 /** Create SSL connection structure and update fd_table */
3421 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3423 SSL
*ssl
= SSL_new(sslContext
);
3426 const int ssl_error
= ERR_get_error();
3427 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3432 SSL_set_fd(ssl
, conn
->fd
);
3433 fd_table
[conn
->fd
].ssl
= ssl
;
3434 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3435 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3437 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3438 fd_note(conn
->fd
, "client https start");
3443 /** negotiate an SSL connection */
3445 clientNegotiateSSL(int fd
, void *data
)
3447 ConnStateData
*conn
= (ConnStateData
*)data
;
3449 SSL
*ssl
= fd_table
[fd
].ssl
;
3452 if ((ret
= SSL_accept(ssl
)) <= 0) {
3453 int ssl_error
= SSL_get_error(ssl
, ret
);
3455 switch (ssl_error
) {
3457 case SSL_ERROR_WANT_READ
:
3458 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3461 case SSL_ERROR_WANT_WRITE
:
3462 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3465 case SSL_ERROR_SYSCALL
:
3468 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3474 if (errno
== ECONNRESET
)
3477 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3478 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3485 case SSL_ERROR_ZERO_RETURN
:
3486 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3491 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3492 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3493 " (" << ssl_error
<< "/" << ret
<< ")");
3501 if (SSL_session_reused(ssl
)) {
3502 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3503 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3505 if (do_debug(83, 4)) {
3506 /* Write out the SSL session details.. actually the call below, but
3507 * OpenSSL headers do strange typecasts confusing GCC.. */
3508 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3509 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3510 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
);
3512 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3514 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3515 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3516 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3517 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3518 * Because there are two possible usable cast, if you get an error here, try the other
3519 * commented line. */
3521 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3522 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3526 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3529 /* Note: This does not automatically fflush the log file.. */
3532 debugs(83, 2, "clientNegotiateSSL: New session " <<
3533 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3534 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3538 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3539 SSL_get_cipher(ssl
));
3541 client_cert
= SSL_get_peer_certificate(ssl
);
3543 if (client_cert
!= NULL
) {
3544 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3545 " client certificate: subject: " <<
3546 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3548 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3549 " client certificate: issuer: " <<
3550 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3552 X509_free(client_cert
);
3554 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3555 " has no certificate.");
3558 conn
->readSomeData();
3562 * If SSL_CTX is given, starts reading the SSL handshake.
3563 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3566 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3570 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3572 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3575 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3576 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3577 connState
, ConnStateData::requestTimeout
);
3578 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3581 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3583 char buf
[MAX_IPSTRLEN
];
3584 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3585 HttpRequest
*fakeRequest
= new HttpRequest
;
3586 fakeRequest
->SetHost(details
->local
.NtoA(buf
, sizeof(buf
)));
3587 fakeRequest
->port
= details
->local
.GetPort();
3588 fakeRequest
->clientConnectionManager
= connState
;
3589 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3590 #if FOLLOW_X_FORWARDED_FOR
3591 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3593 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3594 fakeRequest
->flags
.spoofClientIp
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3595 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3596 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3597 connState
->switchToHttps(fakeRequest
, bumpMode
);
3602 * A callback function to use with the ACLFilledChecklist callback.
3603 * In the case of ACCES_ALLOWED answer initializes a bumped SSL connection,
3604 * else reverts the connection to tunnel mode.
3607 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3609 ConnStateData
*connState
= (ConnStateData
*) data
;
3611 // if the connection is closed or closing, just return.
3612 if (!connState
->isOpen())
3615 // Require both a match and a positive bump mode to work around exceptional
3616 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3617 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3618 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3619 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3620 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3622 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3623 connState
->sslBumpMode
= Ssl::bumpNone
;
3625 // fake a CONNECT request to force connState to tunnel
3626 static char ip
[MAX_IPSTRLEN
];
3627 static char reqStr
[MAX_IPSTRLEN
+ 80];
3628 connState
->clientConnection
->local
.NtoA(ip
, sizeof(ip
));
3629 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s:%d HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, connState
->clientConnection
->local
.GetPort(), ip
);
3630 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3632 ret
= connState
->clientParseRequests();
3635 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3636 connState
->clientConnection
->close();
3641 /** handle a new HTTPS connection */
3643 httpsAccept(const CommAcceptCbParams
¶ms
)
3645 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3647 if (params
.flag
!= COMM_OK
) {
3648 // Its possible the call was still queued when the client disconnected
3649 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3653 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3654 fd_note(params
.conn
->fd
, "client https connect");
3656 if (s
->tcp_keepalive
.enabled
) {
3657 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3660 ++incoming_sockets_accepted
;
3662 // Socket is ready, setup the connection manager to start using it
3663 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3666 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3668 if (!Config
.accessList
.ssl_bump
) {
3669 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3673 // Create a fake HTTP request for ssl_bump ACL check,
3674 // using tproxy/intercept provided destination IP and port.
3675 HttpRequest
*request
= new HttpRequest();
3676 static char ip
[MAX_IPSTRLEN
];
3677 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3678 request
->SetHost(params
.conn
->local
.NtoA(ip
, sizeof(ip
)));
3679 request
->port
= params
.conn
->local
.GetPort();
3680 request
->myportname
= s
->name
;
3682 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3683 acl_checklist
->src_addr
= params
.conn
->remote
;
3684 acl_checklist
->my_addr
= s
->s
;
3685 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3688 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3689 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3694 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3696 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3697 state_data
->sslCrtdHandleReply(reply
);
3701 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3703 if (reply
.result
== HelperReply::BrokenHelper
) {
3704 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3705 } else if (!reply
.other().hasContent()) {
3706 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3708 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3709 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3710 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3712 if (reply
.result
!= HelperReply::Okay
) {
3713 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3715 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3716 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3717 getSslContextDone(ctx
, true);
3722 getSslContextDone(NULL
);
3725 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3727 certProperties
.commonName
= sslCommonName
.defined() ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3729 // fake certificate adaptation requires bump-server-first mode
3730 if (!sslServerBump
) {
3731 assert(port
->signingCert
.get());
3732 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3733 if (port
->signPkey
.get())
3734 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3735 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3739 // In case of an error while connecting to the secure server, use a fake
3740 // trusted certificate, with no mimicked fields and no adaptation
3741 // algorithms. There is nothing we can mimic so we want to minimize the
3742 // number of warnings the user will have to see to get to the error page.
3743 assert(sslServerBump
->entry
);
3744 if (sslServerBump
->entry
->isEmpty()) {
3745 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3746 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3748 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
,
3749 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3750 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3752 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3753 // If the algorithm already set, then ignore it.
3754 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3755 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3756 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3759 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3760 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3761 const char *param
= ca
->param
;
3763 // For parameterless CN adaptation, use hostname from the
3765 if (ca
->alg
== Ssl::algSetCommonName
) {
3767 param
= sslConnectHostOrIp
.termedBuf();
3768 certProperties
.commonName
= param
;
3769 certProperties
.setCommonName
= true;
3770 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3771 certProperties
.setValidAfter
= true;
3772 else if (ca
->alg
== Ssl::algSetValidBefore
)
3773 certProperties
.setValidBefore
= true;
3775 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3776 alg
<< " param: " << (param
? param
: "-"));
3780 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3781 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3782 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3783 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3787 } else {// if (!sslServerBump->entry->isEmpty())
3788 // Use trusted certificate for a Squid-generated error
3789 // or the user would have to add a security exception
3790 // just to see the error page. We will close the connection
3791 // so that the trust is not extended to non-Squid content.
3792 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3795 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3797 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3798 assert(port
->untrustedSigningCert
.get());
3799 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3800 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3802 assert(port
->signingCert
.get());
3803 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3805 if (port
->signPkey
.get())
3806 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3808 signAlgorithm
= certProperties
.signAlgorithm
;
3812 ConnStateData::getSslContextStart()
3814 assert(areAllContextsForThisConnection());
3816 /* careful: freeAllContexts() above frees request, host, etc. */
3818 if (port
->generateHostCertificates
) {
3819 Ssl::CertificateProperties certProperties
;
3820 buildSslCertGenerationParams(certProperties
);
3821 sslBumpCertKey
= certProperties
.dbKey().c_str();
3822 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3824 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3825 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3826 SSL_CTX
* dynCtx
= ssl_ctx_cache
.find(sslBumpCertKey
.termedBuf());
3828 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3829 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3830 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3831 getSslContextDone(dynCtx
);
3834 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3835 ssl_ctx_cache
.remove(sslBumpCertKey
.termedBuf());
3838 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3843 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3844 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
3845 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3846 request_message
.composeRequest(certProperties
);
3847 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3848 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3850 } catch (const std::exception
&e
) {
3851 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3852 "request for " << certProperties
.commonName
<<
3853 " certificate: " << e
.what() << "; will now block to " <<
3854 "generate that certificate.");
3855 // fall through to do blocking in-process generation.
3857 #endif // USE_SSL_CRTD
3859 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3860 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3861 getSslContextDone(dynCtx
, true);
3864 getSslContextDone(NULL
);
3868 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3870 // Try to add generated ssl context to storage.
3871 if (port
->generateHostCertificates
&& isNew
) {
3873 if (signAlgorithm
== Ssl::algSignTrusted
)
3874 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3875 //else it is self-signed or untrusted do not attrach any certificate
3877 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3878 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3880 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), sslContext
)) {
3881 // If it is not in storage delete after using. Else storage deleted it.
3882 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3885 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3889 // If generated ssl context = NULL, try to use static ssl context.
3891 if (!port
->staticSslContext
) {
3892 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3893 clientConnection
->close();
3896 debugs(33, 5, HERE
<< "Using static ssl context.");
3897 sslContext
= port
->staticSslContext
.get();
3902 if (!(ssl
= httpsCreate(clientConnection
, sslContext
)))
3905 // commSetConnTimeout() was called for this request before we switched.
3907 // Disable the client read handler until CachePeer selection is complete
3908 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3909 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3910 switchedToHttps_
= true;
3914 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3916 assert(!switchedToHttps_
);
3918 sslConnectHostOrIp
= request
->GetHost();
3919 sslCommonName
= request
->GetHost();
3921 // We are going to read new request
3922 flags
.readMore
= true;
3923 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3925 // If sslServerBump is set, then we have decided to deny CONNECT
3926 // and now want to switch to SSL to send the error to the client
3927 // without even peeking at the origin server certificate.
3928 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3929 request
->flags
.sslPeek
= 1;
3930 sslServerBump
= new Ssl::ServerBump(request
);
3932 // will call httpsPeeked() with certificate and connection, eventually
3933 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
);
3937 // otherwise, use sslConnectHostOrIp
3938 getSslContextStart();
3942 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3944 Must(sslServerBump
!= NULL
);
3946 if (Comm::IsConnOpen(serverConnection
)) {
3947 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3949 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3950 assert(serverCert
.get() != NULL
);
3951 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
3952 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
3953 " bumped: " << *serverConnection
);
3955 pinConnection(serverConnection
, NULL
, NULL
, false);
3957 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3959 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3960 Ip::Address intendedDest
;
3961 intendedDest
= sslConnectHostOrIp
.termedBuf();
3962 const bool isConnectRequest
= !port
->spoof_client_ip
&& !port
->intercepted
;
3964 // Squid serves its own error page and closes, so we want
3965 // a CN that causes no additional browser errors. Possible
3966 // only when bumping CONNECT with a user-typed address.
3967 if (intendedDest
.IsAnyAddr() || isConnectRequest
)
3968 sslCommonName
= sslConnectHostOrIp
;
3969 else if (sslServerBump
->serverCert
.get())
3970 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
3972 // copy error detail from bump-server-first request to CONNECT request
3973 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
3974 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3977 getSslContextStart();
3980 #endif /* USE_SSL */
3982 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3984 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3986 if (!Comm::IsConnOpen(c
)) {
3987 Must(NHttpSockets
> 0); // we tried to open some
3988 --NHttpSockets
; // there will be fewer sockets than planned
3989 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3991 if (!NHttpSockets
) // we could not open any listen sockets at all
3992 fatalf("Unable to open %s",FdNote(portType
));
3999 /// find any unused HttpSockets[] slot and store fd there or return false
4001 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4004 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4005 if ((found
= HttpSockets
[i
] < 0))
4006 HttpSockets
[i
] = conn
->fd
;
4012 clientHttpConnectionsOpen(void)
4014 AnyP::PortCfg
*s
= NULL
;
4016 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4017 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4018 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4019 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4024 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4025 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4029 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4030 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4034 // Create ssl_ctx cache for this port.
4035 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4039 // Fill out a Comm::Connection which IPC will open as a listener for us
4040 // then pass back when active so we can start a TcpAcceptor subscription.
4041 s
->listenConn
= new Comm::Connection
;
4042 s
->listenConn
->local
= s
->s
;
4043 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) | (s
->intercepted
? COMM_INTERCEPTION
: 0);
4045 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4046 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4047 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4048 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4050 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4051 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4052 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4054 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4061 clientHttpsConnectionsOpen(void)
4065 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4066 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4067 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4068 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4072 if (!s
->staticSslContext
) {
4073 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4074 " due to SSL initialization failure.");
4078 // TODO: merge with similar code in clientHttpConnectionsOpen()
4079 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4080 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4084 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4085 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4090 // Create ssl_ctx cache for this port.
4091 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4094 // Fill out a Comm::Connection which IPC will open as a listener for us
4095 s
->listenConn
= new Comm::Connection
;
4096 s
->listenConn
->local
= s
->s
;
4097 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) |
4098 (s
->intercepted
? COMM_INTERCEPTION
: 0);
4100 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4101 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4102 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4103 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4105 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4106 ListeningStartedDialer(&clientListenerConnectionOpened
,
4107 s
, Ipc::fdnHttpsSocket
, sub
));
4108 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4109 HttpSockets
[NHttpSockets
] = -1;
4115 /// process clientHttpConnectionsOpen result
4117 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4119 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4123 Must(Comm::IsConnOpen(s
->listenConn
));
4125 // TCP: setup a job to handle accept() with subscribed handler
4126 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4128 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4129 (s
->intercepted
? "NAT intercepted " : "") <<
4130 (s
->spoof_client_ip
? "TPROXY spoofing " : "") <<
4131 (s
->sslBump
? "SSL bumped " : "") <<
4132 (s
->accel
? "reverse-proxy " : "")
4133 << FdNote(portTypeNote
) << " connections at "
4136 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4140 clientOpenListenSockets(void)
4142 clientHttpConnectionsOpen();
4144 clientHttpsConnectionsOpen();
4147 if (NHttpSockets
< 1)
4148 fatal("No HTTP or HTTPS ports configured");
4152 clientHttpConnectionsClose(void)
4154 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4155 if (s
->listenConn
!= NULL
) {
4156 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4157 s
->listenConn
->close();
4158 s
->listenConn
= NULL
;
4163 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4164 if (s
->listenConn
!= NULL
) {
4165 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4166 s
->listenConn
->close();
4167 s
->listenConn
= NULL
;
4172 // TODO see if we can drop HttpSockets array entirely */
4173 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4174 HttpSockets
[i
] = -1;
4181 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4183 const char *vary
= request
->vary_headers
;
4184 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4185 #if X_ACCELERATOR_VARY
4188 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4191 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4193 /* Oops... something odd is going on here.. */
4194 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4195 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4196 safe_free(request
->vary_headers
);
4201 /* This is not a varying object */
4205 /* virtual "vary" object found. Calculate the vary key and
4206 * continue the search
4208 vary
= httpMakeVaryMark(request
, entry
->getReply());
4211 request
->vary_headers
= xstrdup(vary
);
4214 /* Ouch.. we cannot handle this kind of variance */
4215 /* XXX This cannot really happen, but just to be complete */
4220 vary
= httpMakeVaryMark(request
, entry
->getReply());
4223 request
->vary_headers
= xstrdup(vary
);
4227 /* Ouch.. we cannot handle this kind of variance */
4228 /* XXX This cannot really happen, but just to be complete */
4230 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4233 /* Oops.. we have already been here and still haven't
4234 * found the requested variant. Bail out
4236 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4237 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4243 ACLFilledChecklist
*
4244 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4246 ConnStateData
* conn
= http
->getConn();
4247 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4248 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4251 * hack for ident ACL. It needs to get full addresses, and a place to store
4252 * the ident result on persistent connections...
4254 /* connection oriented auth also needs these two lines for it's operation. */
4258 CBDATA_CLASS_INIT(ConnStateData
);
4260 ConnStateData::ConnStateData() :
4261 AsyncJob("ConnStateData"),
4263 sslBumpMode(Ssl::bumpEnd
),
4264 switchedToHttps_(false),
4265 sslServerBump(NULL
),
4267 stoppedSending_(NULL
),
4268 stoppedReceiving_(NULL
)
4270 pinning
.pinned
= false;
4271 pinning
.auth
= false;
4275 ConnStateData::transparent() const
4277 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4281 ConnStateData::reading() const
4283 return reader
!= NULL
;
4287 ConnStateData::stopReading()
4290 comm_read_cancel(clientConnection
->fd
, reader
);
4296 ConnStateData::expectRequestBody(int64_t size
)
4298 bodyPipe
= new BodyPipe(this);
4300 bodyPipe
->setBodySize(size
);
4302 startDechunkingRequest();
4307 ConnStateData::mayNeedToReadMoreBody() const
4310 return 0; // request without a body or read/produced all body bytes
4312 if (!bodyPipe
->bodySizeKnown())
4313 return -1; // probably need to read more, but we cannot be sure
4315 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4316 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4318 if (needToProduce
<= haveAvailable
)
4319 return 0; // we have read what we need (but are waiting for pipe space)
4321 return needToProduce
- haveAvailable
;
4325 ConnStateData::stopReceiving(const char *error
)
4327 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4328 "; old sending error: " <<
4329 (stoppedSending() ? stoppedSending_
: "none"));
4331 if (const char *oldError
= stoppedReceiving()) {
4332 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4333 return; // nothing has changed as far as this connection is concerned
4336 stoppedReceiving_
= error
;
4338 if (const char *sendError
= stoppedSending()) {
4339 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4340 clientConnection
->close();
4345 ConnStateData::expectNoForwarding()
4347 if (bodyPipe
!= NULL
) {
4348 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4349 bodyPipe
->expectNoConsumption();
4353 /// initialize dechunking state
4355 ConnStateData::startDechunkingRequest()
4357 Must(bodyPipe
!= NULL
);
4358 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4359 assert(!in
.bodyParser
);
4360 in
.bodyParser
= new ChunkedCodingParser
;
4363 /// put parsed content into input buffer and clean up
4365 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4367 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4369 if (bodyPipe
!= NULL
) {
4370 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4371 BodyPipe::Pointer myPipe
= bodyPipe
;
4372 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4373 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4375 Must(myPipe
->bodySizeKnown());
4376 ClientSocketContext::Pointer context
= getCurrentContext();
4377 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4378 context
->http
->request
->setContentLength(myPipe
->bodySize());
4382 delete in
.bodyParser
;
4383 in
.bodyParser
= NULL
;
4387 ConnStateData::In::addressToReadInto() const
4389 return buf
+ notYetUsed
;
4392 ConnStateData::In::In() : bodyParser(NULL
),
4393 buf (NULL
), notYetUsed (0), allocatedSize (0)
4396 ConnStateData::In::~In()
4399 memFreeBuf(allocatedSize
, buf
);
4400 delete bodyParser
; // TODO: pool
4404 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4407 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4411 ClientSocketContext::Pointer context
= getCurrentContext();
4412 if (context
!= NULL
) {
4413 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4417 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4418 clientConnection
->close();
4421 /// Our close handler called by Comm when the pinned connection is closed
4423 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4425 // FwdState might repin a failed connection sooner than this close
4426 // callback is called for the failed connection.
4427 if (pinning
.serverConnection
== io
.conn
) {
4428 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4434 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4436 char desc
[FD_DESC_SZ
];
4438 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4439 if (pinning
.serverConnection
->fd
== pinServer
->fd
)
4443 unpinConnection(); // closes pinned connection, if any, and resets fields
4445 pinning
.serverConnection
= pinServer
;
4447 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4449 // when pinning an SSL bumped connection, the request may be NULL
4450 const char *pinnedHost
= "[unknown]";
4452 pinning
.host
= xstrdup(request
->GetHost());
4453 pinning
.port
= request
->port
;
4454 pinnedHost
= pinning
.host
;
4456 pinning
.port
= pinServer
->remote
.GetPort();
4458 pinning
.pinned
= true;
4460 pinning
.peer
= cbdataReference(aPeer
);
4461 pinning
.auth
= auth
;
4462 char stmp
[MAX_IPSTRLEN
];
4463 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4464 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4465 clientConnection
->remote
.ToURL(stmp
,MAX_IPSTRLEN
),
4466 clientConnection
->fd
);
4467 fd_note(pinning
.serverConnection
->fd
, desc
);
4469 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4470 pinning
.closeHandler
= JobCallback(33, 5,
4471 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4472 // remember the pinned connection so that cb does not unpin a fresher one
4473 typedef CommCloseCbParams Params
;
4474 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4475 params
.conn
= pinning
.serverConnection
;
4476 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4479 const Comm::ConnectionPointer
4480 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4482 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4485 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4487 if (pinning
.auth
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0) {
4490 if (request
&& pinning
.port
!= request
->port
) {
4493 if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
)) {
4496 if (aPeer
!= pinning
.peer
) {
4501 /* The pinning info is not safe, remove any pinning info */
4505 return pinning
.serverConnection
;
4509 ConnStateData::unpinConnection()
4511 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4514 cbdataReferenceDone(pinning
.peer
);
4516 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4517 if (pinning
.closeHandler
!= NULL
) {
4518 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4519 pinning
.closeHandler
= NULL
;
4521 /// also close the server side socket, we should not use it for any future requests...
4522 // TODO: do not close if called from our close handler?
4523 pinning
.serverConnection
->close();
4526 safe_free(pinning
.host
);
4528 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4529 * connection has gone away */