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
->content_length
> 0) // negative when no body or unknown length
619 aLogEntry
->cache
.requestSize
+= request
->content_length
;
620 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
623 if (request
->auth_user_request
!= NULL
) {
624 if (request
->auth_user_request
->username())
625 aLogEntry
->cache
.authuser
= xstrdup(request
->auth_user_request
->username());
629 // Adapted request, if any, inherits and then collects all the stats, but
630 // the virgin request gets logged instead; copy the stats to log them.
631 // TODO: avoid losses by keeping these stats in a shared history object?
632 if (aLogEntry
->request
) {
633 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
634 aLogEntry
->request
->errType
= request
->errType
;
635 aLogEntry
->request
->errDetail
= request
->errDetail
;
640 ClientHttpRequest::logRequest()
642 if (!out
.size
&& !logType
)
643 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
645 al
->icp
.opcode
= ICP_INVALID
;
647 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
650 al
->http
.code
= al
->reply
->sline
.status
;
651 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
652 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
653 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status
;
654 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
657 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
659 if (loggingEntry() && loggingEntry()->mem_obj
)
660 al
->cache
.objectSize
= loggingEntry()->contentLen();
662 al
->cache
.caddr
.SetNoAddr();
664 if (getConn() != NULL
) {
665 al
->cache
.caddr
= getConn()->log_addr
;
666 al
->cache
.port
= cbdataReference(getConn()->port
);
669 al
->cache
.requestSize
= req_sz
;
670 al
->cache
.requestHeadersSize
= req_sz
;
672 al
->cache
.replySize
= out
.size
;
673 al
->cache
.replyHeadersSize
= out
.headers_sz
;
675 al
->cache
.highOffset
= out
.offset
;
677 al
->cache
.code
= logType
;
679 al
->cache
.msec
= tvSubMsec(start_time
, current_time
);
682 prepareLogWithRequestDetails(request
, al
);
684 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
685 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
689 /* This is broken. Fails if the connection has been closed. Needs
690 * to snarf the ssl details some place earlier..
692 if (getConn() != NULL
)
693 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
698 typedef Notes::iterator ACAMLI
;
699 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
700 if (const char *value
= (*i
)->match(request
, al
->reply
)) {
701 al
->notes
.addEntry(new HttpHeaderEntry(HDR_OTHER
, (*i
)->key
.termedBuf(), value
));
702 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
706 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.log
, this);
709 checklist
->reply
= HTTPMSGLOCK(al
->reply
);
711 if (!Config
.accessList
.log
|| checklist
->fastCheck() == ACCESS_ALLOWED
) {
713 al
->adapted_request
= HTTPMSGLOCK(request
);
714 accessLogLog(al
, checklist
);
717 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
718 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
725 ClientHttpRequest::freeResources()
729 safe_free(redirect
.location
);
730 range_iter
.boundary
.clean();
731 HTTPMSGUNLOCK(request
);
733 if (client_stream
.tail
)
734 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
738 httpRequestFree(void *data
)
740 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
741 assert(http
!= NULL
);
746 ConnStateData::areAllContextsForThisConnection() const
748 assert(this != NULL
);
749 ClientSocketContext::Pointer context
= getCurrentContext();
751 while (context
.getRaw()) {
752 if (context
->http
->getConn() != this)
755 context
= context
->next
;
762 ConnStateData::freeAllContexts()
764 ClientSocketContext::Pointer context
;
766 while ((context
= getCurrentContext()).getRaw() != NULL
) {
767 assert(getCurrentContext() !=
768 getCurrentContext()->next
);
769 context
->connIsFinished();
770 assert (context
!= currentobject
);
774 /// propagates abort event to all contexts
776 ConnStateData::notifyAllContexts(int xerrno
)
778 typedef ClientSocketContext::Pointer CSCP
;
779 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
780 c
->noteIoError(xerrno
);
783 /* This is a handler normally called by comm_close() */
784 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
786 deleteThis("ConnStateData::connStateClosed");
789 // cleans up before destructor is called
791 ConnStateData::swanSong()
793 debugs(33, 2, HERE
<< clientConnection
);
794 flags
.readMore
= false;
795 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
796 assert(areAllContextsForThisConnection());
799 if (auth_user_request
!= NULL
) {
800 debugs(33, 4, "ConnStateData::swanSong: freeing auth_user_request '" << auth_user_request
<< "' (this is '" << this << "')");
801 auth_user_request
->onConnectionClose(this);
805 if (Comm::IsConnOpen(pinning
.serverConnection
))
806 pinning
.serverConnection
->close();
807 pinning
.serverConnection
= NULL
;
809 if (Comm::IsConnOpen(clientConnection
))
810 clientConnection
->close();
811 clientConnection
= NULL
;
813 BodyProducer::swanSong();
814 flags
.swanSang
= true;
818 ConnStateData::isOpen() const
820 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
821 Comm::IsConnOpen(clientConnection
) &&
822 !fd_table
[clientConnection
->fd
].closing();
825 ConnStateData::~ConnStateData()
827 assert(this != NULL
);
828 debugs(33, 3, HERE
<< clientConnection
);
831 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
834 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
836 cbdataReferenceDone(port
);
838 if (bodyPipe
!= NULL
)
839 stopProducingFor(bodyPipe
, false);
842 delete sslServerBump
;
847 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
848 * This is the client-side persistent connection flag. We need
849 * to set this relatively early in the request processing
850 * to handle hacks for broken servers and clients.
853 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
855 HttpRequest
*request
= http
->request
;
857 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
858 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
859 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
860 RequestMethodStr(request
->method
));
862 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
863 request
->flags
.proxyKeepalive
= request
->persistent() ? 1 : 0;
867 clientIsContentLengthValid(HttpRequest
* r
)
869 switch (r
->method
.id()) {
871 case Http::METHOD_GET
:
873 case Http::METHOD_HEAD
:
874 /* We do not want to see a request entity on GET/HEAD requests */
875 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
878 /* For other types of requests we don't care */
886 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
888 if (Config
.maxRequestBodySize
&&
889 bodyLength
> Config
.maxRequestBodySize
)
890 return 1; /* too large */
897 connIsUsable(ConnStateData
* conn
)
899 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
907 // careful: the "current" context may be gone if we wrote an early response
908 ClientSocketContext::Pointer
909 ConnStateData::getCurrentContext() const
912 return currentobject
;
916 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
918 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
919 assert(flags
.deferred
== 0);
921 deferredparams
.node
= node
;
922 deferredparams
.rep
= rep
;
923 deferredparams
.queuedBuffer
= receivedData
;
928 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
930 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
937 ClientSocketContext::startOfOutput() const
939 return http
->out
.size
== 0;
943 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
945 /*the size of available range can always fit in a size_t type*/
946 size_t maximum
= (size_t)available
.size();
948 if (!http
->request
->range
)
951 assert (canPackMoreRanges());
953 if (http
->range_iter
.debt() == -1)
956 assert (http
->range_iter
.debt() > 0);
958 /* TODO this + the last line could be a range intersection calculation */
959 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
962 return min(http
->range_iter
.debt(), (int64_t)maximum
);
966 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
968 http
->out
.offset
+= bytes
;
970 if (!http
->request
->range
)
973 if (http
->range_iter
.debt() != -1) {
974 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
975 assert (http
->range_iter
.debt() >= 0);
978 /* debt() always stops at -1, below that is a bug */
979 assert (http
->range_iter
.debt() >= -1);
983 ClientHttpRequest::multipartRangeRequest() const
985 return request
->multipartRangeRequest();
989 ClientSocketContext::multipartRangeRequest() const
991 return http
->multipartRangeRequest();
995 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
999 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1000 size_t length
= lengthToSend(bodyData
.range());
1001 noteSentBodyBytes (length
);
1002 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1003 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1004 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1010 if (multipartRangeRequest())
1011 packRange(bodyData
, &mb
);
1013 packChunk(bodyData
, mb
);
1015 if (mb
.contentSize()) {
1017 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1018 CommIoCbPtrFun(clientWriteComplete
, this));
1019 Comm::Write(clientConnection
, &mb
, call
);
1021 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1025 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1026 * if bodyData is empty.
1029 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1031 const uint64_t length
=
1032 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1033 noteSentBodyBytes(length
);
1035 mb
.Printf("%" PRIX64
"\r\n", length
);
1036 mb
.append(bodyData
.data
, length
);
1040 /** put terminating boundary for multiparts */
1042 clientPackTermBound(String boundary
, MemBuf
* mb
)
1044 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1045 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1048 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1050 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1052 HttpHeader
hdr(hoReply
);
1058 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1059 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1060 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1062 /* stuff the header with required entries and pack it */
1064 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1065 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1067 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1069 packerToMemInit(&p
, mb
);
1077 /* append <crlf> (we packed a header, not a reply) */
1082 * extracts a "range" from *buf and appends them to mb, updating
1083 * all offsets and such.
1086 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1088 HttpHdrRangeIter
* i
= &http
->range_iter
;
1089 Range
<int64_t> available (source
.range());
1090 char const *buf
= source
.data
;
1092 while (i
->currentSpec() && available
.size()) {
1093 const size_t copy_sz
= lengthToSend(available
);
1097 * intersection of "have" and "need" ranges must not be empty
1099 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1100 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1103 * put boundary and headers at the beginning of a range in a
1107 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1108 assert(http
->memObject());
1110 http
->memObject()->getReply(), /* original reply */
1111 i
->currentSpec(), /* current range */
1112 i
->boundary
, /* boundary, the same for all */
1119 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1121 noteSentBodyBytes (copy_sz
);
1123 mb
->append(buf
, copy_sz
);
1128 available
.start
+= copy_sz
;
1134 if (!canPackMoreRanges()) {
1135 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1138 /* put terminating boundary for multiparts */
1139 clientPackTermBound(i
->boundary
, mb
);
1144 int64_t nextOffset
= getNextRangeOffset();
1146 assert (nextOffset
>= http
->out
.offset
);
1148 int64_t skip
= nextOffset
- http
->out
.offset
;
1150 /* adjust for not to be transmitted bytes */
1151 http
->out
.offset
= nextOffset
;
1153 if (available
.size() <= (uint64_t)skip
)
1156 available
.start
+= skip
;
1165 /** returns expected content length for multi-range replies
1166 * note: assumes that httpHdrRangeCanonize has already been called
1167 * warning: assumes that HTTP headers for individual ranges at the
1168 * time of the actuall assembly will be exactly the same as
1169 * the headers when clientMRangeCLen() is called */
1171 ClientHttpRequest::mRangeCLen()
1176 assert(memObject());
1179 HttpHdrRange::iterator pos
= request
->range
->begin();
1181 while (pos
!= request
->range
->end()) {
1182 /* account for headers for this range */
1184 clientPackRangeHdr(memObject()->getReply(),
1185 *pos
, range_iter
.boundary
, &mb
);
1188 /* account for range content */
1189 clen
+= (*pos
)->length
;
1191 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1195 /* account for the terminating boundary */
1198 clientPackTermBound(range_iter
.boundary
, &mb
);
1208 * returns true if If-Range specs match reply, false otherwise
1211 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1213 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1214 /* check for parsing falure */
1221 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1222 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1223 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1226 return 0; /* entity has no etag to compare with! */
1228 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1229 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1230 return 0; /* must use strong validator for sub-range requests */
1233 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1236 /* got modification time? */
1237 if (spec
.time
>= 0) {
1238 return http
->storeEntry()->lastmod
<= spec
.time
;
1241 assert(0); /* should not happen */
1246 * generates a "unique" boundary string for multipart responses
1247 * the caller is responsible for cleaning the string */
1249 ClientHttpRequest::rangeBoundaryStr() const
1253 String
b(APP_FULLNAME
);
1255 key
= storeEntry()->getMD5Text();
1256 b
.append(key
, strlen(key
));
1260 /** adds appropriate Range headers if needed */
1262 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1264 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1265 const char *range_err
= NULL
;
1266 HttpRequest
*request
= http
->request
;
1267 assert(request
->range
);
1268 /* check if we still want to do ranges */
1270 int64_t roffLimit
= request
->getRangeOffsetLimit();
1273 range_err
= "no [parse-able] reply";
1274 else if ((rep
->sline
.status
!= HTTP_OK
) && (rep
->sline
.status
!= HTTP_PARTIAL_CONTENT
))
1275 range_err
= "wrong status code";
1276 else if (hdr
->has(HDR_CONTENT_RANGE
))
1277 range_err
= "origin server does ranges";
1278 else if (rep
->content_length
< 0)
1279 range_err
= "unknown length";
1280 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1281 range_err
= "INCONSISTENT length"; /* a bug? */
1283 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1286 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1287 range_err
= "If-Range match failed";
1288 else if (!http
->request
->range
->canonize(rep
))
1289 range_err
= "canonization failed";
1290 else if (http
->request
->range
->isComplex())
1291 range_err
= "too complex range header";
1292 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1293 range_err
= "range outside range_offset_limit";
1295 /* get rid of our range specs on error */
1297 /* XXX We do this here because we need canonisation etc. However, this current
1298 * code will lead to incorrect store offset requests - the store will have the
1299 * offset data, but we won't be requesting it.
1300 * So, we can either re-request, or generate an error
1302 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1303 delete http
->request
->range
;
1304 http
->request
->range
= NULL
;
1306 /* XXX: TODO: Review, this unconditional set may be wrong. - TODO: review. */
1307 httpStatusLineSet(&rep
->sline
, rep
->sline
.version
,
1308 HTTP_PARTIAL_CONTENT
, NULL
);
1309 // web server responded with a valid, but unexpected range.
1310 // will (try-to) forward as-is.
1311 //TODO: we should cope with multirange request/responses
1312 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1313 request
->range
->contains(rep
->content_range
->spec
) :
1315 const int spec_count
= http
->request
->range
->specs
.count
;
1316 int64_t actual_clen
= -1;
1318 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1319 spec_count
<< " virgin clen: " << rep
->content_length
);
1320 assert(spec_count
> 0);
1321 /* append appropriate header(s) */
1323 if (spec_count
== 1) {
1324 if (!replyMatchRequest
) {
1325 hdr
->delById(HDR_CONTENT_RANGE
);
1326 hdr
->putContRange(rep
->content_range
);
1327 actual_clen
= rep
->content_length
;
1328 //http->range_iter.pos = rep->content_range->spec.begin();
1329 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1330 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1333 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1335 /* append Content-Range */
1337 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1338 /* No content range, so this was a full object we are
1341 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1344 /* set new Content-Length to the actual number of bytes
1345 * transmitted in the message-body */
1346 actual_clen
= (*pos
)->length
;
1350 /* generate boundary string */
1351 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1352 /* delete old Content-Type, add ours */
1353 hdr
->delById(HDR_CONTENT_TYPE
);
1354 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1355 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1356 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1357 /* Content-Length is not required in multipart responses
1358 * but it is always nice to have one */
1359 actual_clen
= http
->mRangeCLen();
1360 /* http->out needs to start where we want data at */
1361 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1364 /* replace Content-Length header */
1365 assert(actual_clen
>= 0);
1367 hdr
->delById(HDR_CONTENT_LENGTH
);
1369 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1371 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1373 /* And start the range iter off */
1374 http
->range_iter
.updateSpec();
1379 ClientSocketContext::prepareReply(HttpReply
* rep
)
1383 if (http
->request
->range
)
1384 buildRangeHeader(rep
);
1388 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1392 MemBuf
*mb
= rep
->pack();
1394 // dump now, so we dont output any body.
1395 debugs(11, 2, "HTTP Client " << clientConnection
);
1396 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1398 /* Save length of headers for persistent conn checks */
1399 http
->out
.headers_sz
= mb
->contentSize();
1402 headersLog(0, 0, http
->request
->method
, rep
);
1405 if (bodyData
.data
&& bodyData
.length
) {
1406 if (multipartRangeRequest())
1407 packRange(bodyData
, mb
);
1408 else if (http
->request
->flags
.chunkedReply
) {
1409 packChunk(bodyData
, *mb
);
1411 size_t length
= lengthToSend(bodyData
.range());
1412 noteSentBodyBytes (length
);
1414 mb
->append(bodyData
.data
, length
);
1419 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1420 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1421 CommIoCbPtrFun(clientWriteComplete
, this));
1422 Comm::Write(clientConnection
, mb
, call
);
1427 * Write a chunk of data to a client socket. If the reply is present,
1428 * send the reply headers down the wire too, and clean them up when
1431 * The request is one backed by a connection, not an internal request.
1432 * data context is not NULL
1433 * There are no more entries in the stream chain.
1436 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1437 HttpReply
* rep
, StoreIOBuffer receivedData
)
1439 /* Test preconditions */
1440 assert(node
!= NULL
);
1441 PROF_start(clientSocketRecipient
);
1442 /* TODO: handle this rather than asserting
1443 * - it should only ever happen if we cause an abort and
1444 * the callback chain loops back to here, so we can simply return.
1445 * However, that itself shouldn't happen, so it stays as an assert for now.
1447 assert(cbdataReferenceValid(node
));
1448 assert(node
->node
.next
== NULL
);
1449 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1450 assert(context
!= NULL
);
1451 assert(connIsUsable(http
->getConn()));
1453 /* TODO: check offset is what we asked for */
1455 if (context
!= http
->getConn()->getCurrentContext()) {
1456 context
->deferRecipientForLater(node
, rep
, receivedData
);
1457 PROF_stop(clientSocketRecipient
);
1461 // After sending Transfer-Encoding: chunked (at least), always send
1462 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1463 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1464 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1465 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1466 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1467 PROF_stop(clientSocketRecipient
);
1471 if (!context
->startOfOutput())
1472 context
->sendBody(rep
, receivedData
);
1475 http
->al
->reply
= HTTPMSGLOCK(rep
);
1476 context
->sendStartOfMessage(rep
, receivedData
);
1479 PROF_stop(clientSocketRecipient
);
1483 * Called when a downstream node is no longer interested in
1484 * our data. As we are a terminal node, this means on aborts
1488 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1490 /* Test preconditions */
1491 assert(node
!= NULL
);
1492 /* TODO: handle this rather than asserting
1493 * - it should only ever happen if we cause an abort and
1494 * the callback chain loops back to here, so we can simply return.
1495 * However, that itself shouldn't happen, so it stays as an assert for now.
1497 assert(cbdataReferenceValid(node
));
1498 /* Set null by ContextFree */
1499 assert(node
->node
.next
== NULL
);
1500 /* this is the assert discussed above */
1501 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1502 /* We are only called when the client socket shutsdown.
1503 * Tell the prev pipeline member we're finished
1505 clientStreamDetach(node
, http
);
1509 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1511 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1512 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1516 ConnStateData::readNextRequest()
1518 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1520 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1522 * Set the timeout BEFORE calling clientReadRequest().
1524 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1525 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1526 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1527 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1530 /** Please don't do anything with the FD past here! */
1534 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1536 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1538 /** If the client stream is waiting on a socket write to occur, then */
1540 if (deferredRequest
->flags
.deferred
) {
1541 /** NO data is allowed to have been sent. */
1542 assert(deferredRequest
->http
->out
.size
== 0);
1544 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1545 deferredRequest
->http
,
1546 deferredRequest
->deferredparams
.rep
,
1547 deferredRequest
->deferredparams
.queuedBuffer
);
1550 /** otherwise, the request is still active in a callbacksomewhere,
1555 /// called when we have successfully finished writing the response
1557 ClientSocketContext::keepaliveNextRequest()
1559 ConnStateData
* conn
= http
->getConn();
1561 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1564 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1565 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1566 conn
->clientConnection
->close();
1571 * We are done with the response, and we are either still receiving request
1572 * body (early response!) or have already stopped receiving anything.
1574 * If we are still receiving, then clientParseRequest() below will fail.
1575 * (XXX: but then we will call readNextRequest() which may succeed and
1576 * execute a smuggled request as we are not done with the current request).
1578 * If we stopped because we got everything, then try the next request.
1580 * If we stopped receiving because of an error, then close now to avoid
1581 * getting stuck and to prevent accidental request smuggling.
1584 if (const char *reason
= conn
->stoppedReceiving()) {
1585 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1586 conn
->clientConnection
->close();
1591 * Attempt to parse a request from the request buffer.
1592 * If we've been fed a pipelined request it may already
1593 * be in our read buffer.
1596 * This needs to fall through - if we're unlucky and parse the _last_ request
1597 * from our read buffer we may never re-register for another client read.
1600 if (conn
->clientParseRequests()) {
1601 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1605 * Either we need to kick-start another read or, if we have
1606 * a half-closed connection, kill it after the last request.
1607 * This saves waiting for half-closed connections to finished being
1608 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1609 * the keepalive "Waiting for next request" state.
1611 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1612 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1613 conn
->clientConnection
->close();
1617 ClientSocketContext::Pointer deferredRequest
;
1620 * At this point we either have a parsed request (which we've
1621 * kicked off the processing for) or not. If we have a deferred
1622 * request (parsed but deferred for pipeling processing reasons)
1623 * then look at processing it. If not, simply kickstart
1627 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1628 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1629 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1630 } else if (conn
->flags
.readMore
) {
1631 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1632 conn
->readNextRequest();
1634 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1635 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1640 clientUpdateSocketStats(log_type logType
, size_t size
)
1645 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1647 if (logTypeIsATcpHit(logType
))
1648 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1652 * increments iterator "i"
1653 * used by clientPackMoreRanges
1655 \retval true there is still data available to pack more ranges
1659 ClientSocketContext::canPackMoreRanges() const
1661 /** first update iterator "i" if needed */
1663 if (!http
->range_iter
.debt()) {
1664 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1666 if (http
->range_iter
.pos
.incrementable())
1667 ++http
->range_iter
.pos
;
1669 http
->range_iter
.updateSpec();
1672 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1674 /* paranoid sync condition */
1675 /* continue condition: need_more_data */
1676 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1677 return http
->range_iter
.currentSpec() ? true : false;
1681 ClientSocketContext::getNextRangeOffset() const
1683 if (http
->request
->range
) {
1684 /* offset in range specs does not count the prefix of an http msg */
1685 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1686 /* check: reply was parsed and range iterator was initialized */
1687 assert(http
->range_iter
.valid
);
1688 /* filter out data according to range specs */
1689 assert (canPackMoreRanges());
1691 int64_t start
; /* offset of still missing data */
1692 assert(http
->range_iter
.currentSpec());
1693 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1694 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1695 debugs(33, 3, "clientPackMoreRanges: out:"
1696 " start: " << start
<<
1697 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1698 " [" << http
->range_iter
.currentSpec()->offset
<<
1699 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1700 " len: " << http
->range_iter
.currentSpec()->length
<<
1701 " debt: " << http
->range_iter
.debt());
1702 if (http
->range_iter
.currentSpec()->length
!= -1)
1703 assert(http
->out
.offset
<= start
); /* we did not miss it */
1708 } else if (reply
&& reply
->content_range
) {
1709 /* request does not have ranges, but reply does */
1710 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1711 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1713 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1716 return http
->out
.offset
;
1720 ClientSocketContext::pullData()
1722 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1724 /* More data will be coming from the stream. */
1725 StoreIOBuffer readBuffer
;
1726 /* XXX: Next requested byte in the range sequence */
1727 /* XXX: length = getmaximumrangelenfgth */
1728 readBuffer
.offset
= getNextRangeOffset();
1729 readBuffer
.length
= HTTP_REQBUF_SZ
;
1730 readBuffer
.data
= reqbuf
;
1731 /* we may note we have reached the end of the wanted ranges */
1732 clientStreamRead(getTail(), http
, readBuffer
);
1735 clientStream_status_t
1736 ClientSocketContext::socketState()
1738 switch (clientStreamStatus(getTail(), http
)) {
1741 /* check for range support ending */
1743 if (http
->request
->range
) {
1744 /* check: reply was parsed and range iterator was initialized */
1745 assert(http
->range_iter
.valid
);
1746 /* filter out data according to range specs */
1748 if (!canPackMoreRanges()) {
1749 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1750 "range sequence on " << clientConnection
);
1752 if (http
->request
->flags
.proxyKeepalive
)
1753 return STREAM_COMPLETE
;
1755 return STREAM_UNPLANNED_COMPLETE
;
1757 } else if (reply
&& reply
->content_range
) {
1758 /* reply has content-range, but Squid is not managing ranges */
1759 const int64_t &bytesSent
= http
->out
.offset
;
1760 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1762 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1763 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1764 reply
->content_range
->spec
.offset
<< ")");
1766 // did we get at least what we expected, based on range specs?
1768 if (bytesSent
== bytesExpected
) { // got everything
1769 if (http
->request
->flags
.proxyKeepalive
)
1770 return STREAM_COMPLETE
;
1772 return STREAM_UNPLANNED_COMPLETE
;
1775 // The logic below is not clear: If we got more than we
1776 // expected why would persistency matter? Should not this
1777 // always be an error?
1778 if (bytesSent
> bytesExpected
) { // got extra
1779 if (http
->request
->flags
.proxyKeepalive
)
1780 return STREAM_COMPLETE
;
1782 return STREAM_UNPLANNED_COMPLETE
;
1785 // did not get enough yet, expecting more
1790 case STREAM_COMPLETE
:
1791 return STREAM_COMPLETE
;
1793 case STREAM_UNPLANNED_COMPLETE
:
1794 return STREAM_UNPLANNED_COMPLETE
;
1797 return STREAM_FAILED
;
1800 fatal ("unreachable code\n");
1805 * A write has just completed to the client, or we have just realised there is
1806 * no more data to send.
1809 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1811 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1812 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1815 /// remembers the abnormal connection termination for logging purposes
1817 ClientSocketContext::noteIoError(const int xerrno
)
1820 if (xerrno
== ETIMEDOUT
)
1821 http
->al
->http
.timedout
= true;
1822 else // even if xerrno is zero (which means read abort/eof)
1823 http
->al
->http
.aborted
= true;
1828 ClientSocketContext::doClose()
1830 clientConnection
->close();
1833 /// called when we encounter a response-related error
1835 ClientSocketContext::initiateClose(const char *reason
)
1837 http
->getConn()->stopSending(reason
); // closes ASAP
1841 ConnStateData::stopSending(const char *error
)
1843 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1844 "; old receiving error: " <<
1845 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1847 if (const char *oldError
= stoppedSending()) {
1848 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1849 return; // nothing has changed as far as this connection is concerned
1851 stoppedSending_
= error
;
1853 if (!stoppedReceiving()) {
1854 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1855 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1856 " request body bytes with " << in
.notYetUsed
<< " unused");
1857 return; // wait for the request receiver to finish reading
1861 clientConnection
->close();
1865 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1867 const StoreEntry
*entry
= http
->storeEntry();
1868 http
->out
.size
+= size
;
1869 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1870 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1871 (entry
? entry
->objectLen() : 0));
1872 clientUpdateSocketStats(http
->logType
, size
);
1874 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1876 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1879 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1880 initiateClose("failure or true request status");
1881 /* Do we leak here ? */
1885 switch (socketState()) {
1891 case STREAM_COMPLETE
:
1892 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1893 keepaliveNextRequest();
1896 case STREAM_UNPLANNED_COMPLETE
:
1897 initiateClose("STREAM_UNPLANNED_COMPLETE");
1901 initiateClose("STREAM_FAILED");
1905 fatal("Hit unreachable code in clientWriteComplete\n");
1909 SQUIDCEXTERN CSR clientGetMoreData
;
1910 SQUIDCEXTERN CSS clientReplyStatus
;
1911 SQUIDCEXTERN CSD clientReplyDetach
;
1913 static ClientSocketContext
*
1914 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
1916 ClientHttpRequest
*http
;
1917 ClientSocketContext
*context
;
1918 StoreIOBuffer tempBuffer
;
1919 http
= new ClientHttpRequest(csd
);
1920 http
->req_sz
= csd
->in
.notYetUsed
;
1921 http
->uri
= xstrdup(uri
);
1922 setLogUri (http
, uri
);
1923 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
1924 tempBuffer
.data
= context
->reqbuf
;
1925 tempBuffer
.length
= HTTP_REQBUF_SZ
;
1926 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
1927 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
1928 clientSocketDetach
, context
, tempBuffer
);
1933 skipLeadingSpace(char *aString
)
1935 char *result
= aString
;
1937 while (xisspace(*aString
))
1944 * 'end' defaults to NULL for backwards compatibility
1945 * remove default value if we ever get rid of NULL-terminated
1949 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
1952 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
1956 for (; end
> uriAndHTTPVersion
; --end
) {
1957 if (*end
== '\n' || *end
== '\r')
1960 if (xisspace(*end
)) {
1961 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
1972 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
1974 safe_free(http
->log_uri
);
1977 // The uri is already clean just dump it.
1978 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1981 switch (Config
.uri_whitespace
) {
1982 case URI_WHITESPACE_ALLOW
:
1983 flags
|= RFC1738_ESCAPE_NOSPACE
;
1985 case URI_WHITESPACE_ENCODE
:
1986 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1987 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1990 case URI_WHITESPACE_CHOP
: {
1991 flags
|= RFC1738_ESCAPE_NOSPACE
;
1992 flags
|= RFC1738_ESCAPE_UNESCAPED
;
1993 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
1994 int pos
= strcspn(http
->log_uri
, w_space
);
1995 http
->log_uri
[pos
] = '\0';
1999 case URI_WHITESPACE_DENY
:
2000 case URI_WHITESPACE_STRIP
:
2003 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2007 if (!xisspace(*t
)) {
2014 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2023 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2025 int vhost
= conn
->port
->vhost
;
2026 int vport
= conn
->port
->vport
;
2028 char ipbuf
[MAX_IPSTRLEN
];
2030 http
->flags
.accel
= 1;
2032 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2034 if (strncasecmp(url
, "cache_object://", 15) == 0)
2035 return; /* already in good shape */
2038 if (conn
->port
->vhost
)
2039 return; /* already in good shape */
2041 /* else we need to ignore the host name */
2042 url
= strstr(url
, "//");
2044 #if SHOULD_REJECT_UNKNOWN_URLS
2047 hp
->request_parse_status
= HTTP_BAD_REQUEST
;
2048 return parseHttpRequestAbort(conn
, "error:invalid-request");
2053 url
= strchr(url
+ 2, '/');
2060 vport
= http
->getConn()->clientConnection
->local
.GetPort();
2062 const bool switchedToHttps
= conn
->switchedToHttps();
2063 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2064 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2065 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2070 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2071 strncpy(thost
, host
, (t
-host
));
2072 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2075 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2078 } // else nothing to alter port-wise.
2079 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2081 http
->uri
= (char *)xcalloc(url_sz
, 1);
2082 const char *protocol
= switchedToHttps
?
2083 "https" : conn
->port
->protocol
;
2084 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2085 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2086 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2087 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2088 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2089 strlen(conn
->port
->defaultsite
);
2090 http
->uri
= (char *)xcalloc(url_sz
, 1);
2094 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2096 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2097 conn
->port
->protocol
, conn
->port
->defaultsite
, vportStr
, url
);
2098 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2099 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2100 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2101 /* Put the local socket IP address as the hostname, with whatever vport we found */
2102 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2103 http
->uri
= (char *)xcalloc(url_sz
, 1);
2104 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2105 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2106 http
->getConn()->port
->protocol
,
2108 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2113 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2116 char ipbuf
[MAX_IPSTRLEN
];
2119 return; /* already in good shape */
2121 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2123 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2124 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2126 http
->uri
= (char *)xcalloc(url_sz
, 1);
2127 snprintf(http
->uri
, url_sz
, "%s://%s%s", conn
->port
->protocol
, host
, url
);
2128 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2130 /* Put the local socket IP address as the hostname. */
2131 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2132 http
->uri
= (char *)xcalloc(url_sz
, 1);
2133 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2134 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2135 http
->getConn()->port
->protocol
,
2136 ipbuf
, http
->getConn()->clientConnection
->local
.GetPort(), url
);
2137 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2142 * parseHttpRequest()
2145 * NULL on incomplete requests
2146 * a ClientSocketContext structure on success or failure.
2147 * Sets result->flags.parsed_ok to 0 if failed to parse the request.
2148 * Sets result->flags.parsed_ok to 1 if we have a good request.
2150 static ClientSocketContext
*
2151 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, HttpVersion
*http_ver
)
2153 char *req_hdr
= NULL
;
2156 ClientHttpRequest
*http
;
2157 ClientSocketContext
*result
;
2158 StoreIOBuffer tempBuffer
;
2161 /* pre-set these values to make aborting simpler */
2162 *method_p
= Http::METHOD_NONE
;
2164 /* NP: don't be tempted to move this down or remove again.
2165 * It's the only DDoS protection old-String has against long URL */
2166 if ( hp
->bufsiz
<= 0) {
2167 debugs(33, 5, "Incomplete request, waiting for end of request line");
2169 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2170 debugs(33, 5, "parseHttpRequest: Too large request");
2171 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2172 return parseHttpRequestAbort(csd
, "error:request-too-large");
2175 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2176 r
= HttpParserParseReqLine(hp
);
2179 debugs(33, 5, "Incomplete request, waiting for end of request line");
2184 return parseHttpRequestAbort(csd
, "error:invalid-request");
2187 /* Request line is valid here .. */
2188 *http_ver
= HttpVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2190 /* This call scans the entire request, not just the headers */
2191 if (hp
->req
.v_maj
> 0) {
2192 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2193 debugs(33, 5, "Incomplete request, waiting for end of headers");
2197 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2198 req_sz
= HttpParserReqSz(hp
);
2201 /* We know the whole request is in hp->buf now */
2203 assert(req_sz
<= (size_t) hp
->bufsiz
);
2205 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2206 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2209 hp
->hdr_end
= req_sz
- 1;
2211 hp
->hdr_start
= hp
->req
.end
+ 1;
2213 /* Enforce max_request_size */
2214 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2215 debugs(33, 5, "parseHttpRequest: Too large request");
2216 hp
->request_parse_status
= HTTP_HEADER_TOO_LARGE
;
2217 return parseHttpRequestAbort(csd
, "error:request-too-large");
2221 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2223 /* deny CONNECT via accelerated ports */
2224 if (*method_p
== Http::METHOD_CONNECT
&& csd
&& csd
->port
&& csd
->port
->accel
) {
2225 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->protocol
<< " Accelerator port " << csd
->port
->s
.GetPort() );
2226 /* XXX need a way to say "this many character length string" */
2227 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2228 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2229 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2232 if (*method_p
== Http::METHOD_NONE
) {
2233 /* XXX need a way to say "this many character length string" */
2234 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2235 hp
->request_parse_status
= HTTP_METHOD_NOT_ALLOWED
;
2236 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2240 * Process headers after request line
2241 * TODO: Use httpRequestParse here.
2243 /* XXX this code should be modified to take a const char * later! */
2244 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2246 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2248 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2250 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2252 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2253 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2254 HttpParserReqSz(hp
));
2256 /* Ok, all headers are received */
2257 http
= new ClientHttpRequest(csd
);
2259 http
->req_sz
= HttpParserRequestLen(hp
);
2260 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2261 tempBuffer
.data
= result
->reqbuf
;
2262 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2264 ClientStreamData newServer
= new clientReplyContext(http
);
2265 ClientStreamData newClient
= result
;
2266 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2267 clientReplyStatus
, newServer
, clientSocketRecipient
,
2268 clientSocketDetach
, newClient
, tempBuffer
);
2270 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2274 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2275 * below needs to be modified to not expect a mutable nul-terminated string.
2277 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2279 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2281 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2283 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2285 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2290 debugs(33,5, HERE
<< "repare absolute URL from " << (csd
->transparent()?"intercept":(csd
->port
->accel
? "accel":"")));
2291 /* Rewrite the URL in transparent or accelerator mode */
2292 /* NP: there are several cases to traverse here:
2293 * - standard mode (forward proxy)
2294 * - transparent mode (TPROXY)
2295 * - transparent mode with failures
2296 * - intercept mode (NAT)
2297 * - intercept mode with failures
2298 * - accelerator mode (reverse proxy)
2300 * - mixed combos of the above with internal URL
2302 if (csd
->transparent()) {
2303 /* intercept or transparent mode, properly working with no failures */
2304 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2306 } else if (internalCheck(url
)) {
2307 /* internal URL mode */
2308 /* prepend our name & port */
2309 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2310 // We just re-wrote the URL. Must replace the Host: header.
2311 // But have not parsed there yet!! flag for local-only handling.
2312 http
->flags
.internal
= 1;
2314 } else if (csd
->port
->accel
|| csd
->switchedToHttps()) {
2315 /* accelerator mode */
2316 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2320 /* No special rewrites have been applied above, use the
2321 * requested url. may be rewritten later, so make extra room */
2322 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2323 http
->uri
= (char *)xcalloc(url_sz
, 1);
2324 strcpy(http
->uri
, url
);
2327 debugs(33, 5, "parseHttpRequest: Complete request received");
2329 // XXX: crop this dump at the end of headers. No need for extras
2330 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2331 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2333 result
->flags
.parsed_ok
= 1;
2339 ConnStateData::getAvailableBufferLength() const
2341 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2342 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2343 // huge request_header_max_size may lead to more than INT_MAX unused space
2344 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2349 ConnStateData::maybeMakeSpaceAvailable()
2351 if (getAvailableBufferLength() < 2) {
2353 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2354 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2357 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2358 newSize
=Config
.maxRequestBufferSize
;
2360 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2361 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2367 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2369 ClientSocketContext::Pointer
*S
;
2371 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2379 ConnStateData::getConcurrentRequestCount() const
2382 ClientSocketContext::Pointer
*T
;
2384 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2385 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2390 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2392 if (flag
!= COMM_OK
) {
2393 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2398 if (!ignoreErrno(xerrno
)) {
2399 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2401 } else if (in
.notYetUsed
== 0) {
2402 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2410 ConnStateData::connFinishedWithConn(int size
)
2413 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2414 /* no current or pending requests */
2415 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2417 } else if (!Config
.onoff
.half_closed_clients
) {
2418 /* admin doesn't want to support half-closed client sockets */
2419 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2420 notifyAllContexts(0); // no specific error implies abort
2429 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2431 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2432 conn
->in
.notYetUsed
-= byteCount
;
2433 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2435 * If there is still data that will be used,
2436 * move it to the beginning.
2439 if (conn
->in
.notYetUsed
> 0)
2440 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2443 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2445 ConnStateData::checkHeaderLimits()
2447 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2448 return; // can accumulte more header data
2450 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2451 Config
.maxRequestHeaderSize
<< " bytes)");
2453 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2454 clientStreamNode
*node
= context
->getClientReplyContext();
2455 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2456 assert (repContext
);
2457 repContext
->setReplyToError(ERR_TOO_BIG
,
2458 HTTP_BAD_REQUEST
, Http::METHOD_NONE
, NULL
,
2459 clientConnection
->remote
, NULL
, NULL
, NULL
);
2460 context
->registerWithConn();
2461 context
->pullData();
2465 ConnStateData::clientAfterReadingRequests()
2467 // Were we expecting to read more request body from half-closed connection?
2468 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2469 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2470 clientConnection
->close();
2479 ConnStateData::quitAfterError(HttpRequest
*request
)
2481 // From HTTP p.o.v., we do not have to close after every error detected
2482 // at the client-side, but many such errors do require closure and the
2483 // client-side code is bad at handling errors so we play it safe.
2485 request
->flags
.proxyKeepalive
= 0;
2486 flags
.readMore
= false;
2487 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2491 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2493 ClientHttpRequest
*http
= context
->http
;
2498 assert(sslServerBump
->entry
);
2499 // Did we create an error entry while processing CONNECT?
2500 if (!sslServerBump
->entry
->isEmpty()) {
2501 quitAfterError(http
->request
);
2503 // Get the saved error entry and send it to the client by replacing the
2504 // ClientHttpRequest store entry with it.
2505 clientStreamNode
*node
= context
->getClientReplyContext();
2506 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2508 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2509 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2511 // save the original request for logging purposes
2512 if (!context
->http
->al
->request
)
2513 context
->http
->al
->request
= HTTPMSGLOCK(http
->request
);
2515 // Get error details from the fake certificate-peeking request.
2516 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2517 context
->pullData();
2521 // In bump-server-first mode, we have not necessarily seen the intended
2522 // server name at certificate-peeking time. Check for domain mismatch now,
2523 // when we can extract the intended name from the bumped HTTP request.
2524 if (sslServerBump
->serverCert
.get()) {
2525 HttpRequest
*request
= http
->request
;
2526 if (!Ssl::checkX509ServerValidity(sslServerBump
->serverCert
.get(), request
->GetHost())) {
2527 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2528 "does not match domainname " << request
->GetHost());
2530 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2531 check
.sslErrors
= new Ssl::Errors(SQUID_X509_V_ERR_DOMAIN_MISMATCH
);
2532 const bool allowDomainMismatch
=
2533 check
.fastCheck() == ACCESS_ALLOWED
;
2534 delete check
.sslErrors
;
2535 check
.sslErrors
= NULL
;
2537 if (!allowDomainMismatch
) {
2538 quitAfterError(request
);
2540 clientStreamNode
*node
= context
->getClientReplyContext();
2541 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2542 assert (repContext
);
2544 // Fill the server IP and hostname for error page generation.
2545 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2546 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2548 // Create an error object and fill it
2549 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, HTTP_SERVICE_UNAVAILABLE
, request
);
2550 err
->src_addr
= clientConnection
->remote
;
2551 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2552 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2553 sslServerBump
->serverCert
.get(), NULL
);
2554 err
->detail
= errDetail
;
2555 // Save the original request for logging purposes.
2556 if (!context
->http
->al
->request
)
2557 context
->http
->al
->request
= HTTPMSGLOCK(request
);
2558 repContext
->setReplyToError(request
->method
, err
);
2559 assert(context
->http
->out
.offset
== 0);
2560 context
->pullData();
2571 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, HttpVersion http_ver
)
2573 ClientHttpRequest
*http
= context
->http
;
2574 HttpRequest
*request
= NULL
;
2575 bool notedUseOfBuffer
= false;
2576 bool chunked
= false;
2577 bool mustReplyToOptions
= false;
2578 bool unsupportedTe
= false;
2579 bool expectBody
= false;
2581 /* We have an initial client stream in place should it be needed */
2582 /* setup our private context */
2583 context
->registerWithConn();
2585 if (context
->flags
.parsed_ok
== 0) {
2586 clientStreamNode
*node
= context
->getClientReplyContext();
2587 debugs(33, 2, "clientProcessRequest: Invalid Request");
2588 conn
->quitAfterError(NULL
);
2589 // setLogUri should called before repContext->setReplyToError
2590 setLogUri(http
, http
->uri
, true);
2591 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2592 assert (repContext
);
2593 switch (hp
->request_parse_status
) {
2594 case HTTP_HEADER_TOO_LARGE
:
2595 repContext
->setReplyToError(ERR_TOO_BIG
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2597 case HTTP_METHOD_NOT_ALLOWED
:
2598 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_METHOD_NOT_ALLOWED
, method
, http
->uri
,
2599 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2602 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2603 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2605 assert(context
->http
->out
.offset
== 0);
2606 context
->pullData();
2610 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2611 clientStreamNode
*node
= context
->getClientReplyContext();
2612 debugs(33, 5, "Invalid URL: " << http
->uri
);
2613 conn
->quitAfterError(request
);
2614 // setLogUri should called before repContext->setReplyToError
2615 setLogUri(http
, http
->uri
, true);
2616 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2617 assert (repContext
);
2618 repContext
->setReplyToError(ERR_INVALID_URL
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2619 assert(context
->http
->out
.offset
== 0);
2620 context
->pullData();
2624 /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */
2625 /* We currently only accept 0.9, 1.0, 1.1 */
2626 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2627 (http_ver
.major
== 1 && http_ver
.minor
> 1 ) ||
2628 (http_ver
.major
> 1) ) {
2630 clientStreamNode
*node
= context
->getClientReplyContext();
2631 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2632 conn
->quitAfterError(request
);
2633 // setLogUri should called before repContext->setReplyToError
2634 setLogUri(http
, http
->uri
, true);
2635 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2636 assert (repContext
);
2637 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, HTTP_HTTP_VERSION_NOT_SUPPORTED
, method
, http
->uri
,
2638 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2639 assert(context
->http
->out
.offset
== 0);
2640 context
->pullData();
2644 /* compile headers */
2645 /* we should skip request line! */
2646 /* XXX should actually know the damned buffer size here */
2647 if (http_ver
.major
>= 1 && !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2648 clientStreamNode
*node
= context
->getClientReplyContext();
2649 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2650 conn
->quitAfterError(request
);
2651 // setLogUri should called before repContext->setReplyToError
2652 setLogUri(http
, http
->uri
, true);
2653 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2654 assert (repContext
);
2655 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_BAD_REQUEST
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2656 assert(context
->http
->out
.offset
== 0);
2657 context
->pullData();
2661 request
->clientConnectionManager
= conn
;
2663 request
->flags
.accelerated
= http
->flags
.accel
;
2664 request
->flags
.sslBumped
=conn
->switchedToHttps();
2665 request
->flags
.canRePin
= request
->flags
.sslBumped
&& conn
->pinning
.pinned
;
2666 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2667 // TODO: decouple http->flags.accel from request->flags.sslBumped
2668 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2669 !conn
->port
->allow_direct
: 0;
2671 if (request
->flags
.sslBumped
) {
2672 if (conn
->auth_user_request
!= NULL
)
2673 request
->auth_user_request
= conn
->auth_user_request
;
2678 * If transparent or interception mode is working clone the transparent and interception flags
2679 * from the port settings to the request.
2681 if (http
->clientConnection
!= NULL
) {
2682 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2683 request
->flags
.spoofClientIp
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2686 if (internalCheck(request
->urlpath
.termedBuf())) {
2687 if (internalHostnameIs(request
->GetHost()) &&
2688 request
->port
== getMyPort()) {
2689 http
->flags
.internal
= 1;
2690 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2691 request
->SetHost(internalHostname());
2692 request
->port
= getMyPort();
2693 http
->flags
.internal
= 1;
2697 if (http
->flags
.internal
) {
2698 request
->protocol
= AnyP::PROTO_HTTP
;
2699 request
->login
[0] = '\0';
2702 request
->flags
.internal
= http
->flags
.internal
;
2703 setLogUri (http
, urlCanonicalClean(request
));
2704 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2705 #if FOLLOW_X_FORWARDED_FOR
2706 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2707 // not a details about teh TCP connection itself
2708 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2709 #endif /* FOLLOW_X_FORWARDED_FOR */
2710 request
->my_addr
= conn
->clientConnection
->local
;
2711 request
->myportname
= conn
->port
->name
;
2712 request
->http_ver
= http_ver
;
2714 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2715 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2716 request
->clientConnectionManager
= conn
;
2718 if (request
->header
.chunked()) {
2720 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2721 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2722 // HTTP/1.1 requires chunking to be the last encoding if there is one
2723 unsupportedTe
= te
.size() && te
!= "identity";
2724 } // else implied identity coding
2726 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2727 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2728 if (!urlCheckRequest(request
) || mustReplyToOptions
|| unsupportedTe
) {
2729 clientStreamNode
*node
= context
->getClientReplyContext();
2730 conn
->quitAfterError(request
);
2731 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2732 assert (repContext
);
2733 repContext
->setReplyToError(ERR_UNSUP_REQ
, HTTP_NOT_IMPLEMENTED
, request
->method
, NULL
,
2734 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2735 assert(context
->http
->out
.offset
== 0);
2736 context
->pullData();
2740 if (!chunked
&& !clientIsContentLengthValid(request
)) {
2741 clientStreamNode
*node
= context
->getClientReplyContext();
2742 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2743 assert (repContext
);
2744 conn
->quitAfterError(request
);
2745 repContext
->setReplyToError(ERR_INVALID_REQ
,
2746 HTTP_LENGTH_REQUIRED
, request
->method
, NULL
,
2747 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2748 assert(context
->http
->out
.offset
== 0);
2749 context
->pullData();
2753 if (request
->header
.has(HDR_EXPECT
)) {
2754 const String expect
= request
->header
.getList(HDR_EXPECT
);
2755 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2756 if (!supportedExpect
) {
2757 clientStreamNode
*node
= context
->getClientReplyContext();
2758 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2759 assert (repContext
);
2760 conn
->quitAfterError(request
);
2761 repContext
->setReplyToError(ERR_INVALID_REQ
, HTTP_EXPECTATION_FAILED
, request
->method
, http
->uri
,
2762 conn
->clientConnection
->remote
, request
, NULL
, NULL
);
2763 assert(context
->http
->out
.offset
== 0);
2764 context
->pullData();
2769 http
->request
= HTTPMSGLOCK(request
);
2770 clientSetKeepaliveFlag(http
);
2772 // Let tunneling code be fully responsible for CONNECT requests
2773 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2774 context
->mayUseConnection(true);
2775 conn
->flags
.readMore
= false;
2779 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2783 /* Do we expect a request-body? */
2784 expectBody
= chunked
|| request
->content_length
> 0;
2785 if (!context
->mayUseConnection() && expectBody
) {
2786 request
->body_pipe
= conn
->expectRequestBody(
2787 chunked
? -1 : request
->content_length
);
2789 // consume header early so that body pipe gets just the body
2790 connNoteUseOfBuffer(conn
, http
->req_sz
);
2791 notedUseOfBuffer
= true;
2793 /* Is it too large? */
2794 if (!chunked
&& // if chunked, we will check as we accumulate
2795 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2796 clientStreamNode
*node
= context
->getClientReplyContext();
2797 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2798 assert (repContext
);
2799 conn
->quitAfterError(request
);
2800 repContext
->setReplyToError(ERR_TOO_BIG
,
2801 HTTP_REQUEST_ENTITY_TOO_LARGE
, Http::METHOD_NONE
, NULL
,
2802 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2803 assert(context
->http
->out
.offset
== 0);
2804 context
->pullData();
2808 // We may stop producing, comm_close, and/or call setReplyToError()
2809 // below, so quit on errors to avoid http->doCallouts()
2810 if (!conn
->handleRequestBodyData())
2813 if (!request
->body_pipe
->productionEnded()) {
2814 debugs(33, 5, HERE
<< "need more request body");
2815 context
->mayUseConnection(true);
2816 assert(conn
->flags
.readMore
);
2820 http
->calloutContext
= new ClientRequestContext(http
);
2825 if (!notedUseOfBuffer
)
2826 connNoteUseOfBuffer(conn
, http
->req_sz
);
2830 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2831 * to here because calling comm_reset_close() causes http to
2832 * be freed and the above connNoteUseOfBuffer() would hit an
2833 * assertion, not to mention that we were accessing freed memory.
2835 if (request
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2836 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2837 conn
->flags
.readMore
= false;
2838 comm_reset_close(conn
->clientConnection
);
2843 connStripBufferWhitespace (ConnStateData
* conn
)
2845 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2846 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2847 -- conn
->in
.notYetUsed
;
2852 connOkToAddRequest(ConnStateData
* conn
)
2854 int result
= conn
->getConcurrentRequestCount() < (Config
.onoff
.pipeline_prefetch
? 2 : 1);
2857 debugs(33, 3, HERE
<< conn
->clientConnection
<< " max concurrent requests reached");
2858 debugs(33, 5, HERE
<< conn
->clientConnection
<< " defering new request until one is done");
2865 * Attempt to parse one or more requests from the input buffer.
2866 * If a request is successfully parsed, even if the next request
2867 * is only partially parsed, it will return TRUE.
2870 ConnStateData::clientParseRequests()
2872 HttpRequestMethod method
;
2873 bool parsed_req
= false;
2874 HttpVersion http_ver
;
2876 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
2878 // Loop while we have read bytes that are not needed for producing the body
2879 // On errors, bodyPipe may become nil, but readMore will be cleared
2880 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
2881 connStripBufferWhitespace(this);
2883 /* Don't try to parse if the buffer is empty */
2884 if (in
.notYetUsed
== 0)
2887 /* Limit the number of concurrent requests to 2 */
2888 if (!connOkToAddRequest(this)) {
2892 /* Should not be needed anymore */
2893 /* Terminate the string */
2894 in
.buf
[in
.notYetUsed
] = '\0';
2896 /* Begin the parsing */
2897 PROF_start(parseHttpRequest
);
2898 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
2900 /* Process request */
2901 ClientSocketContext
*context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
2902 PROF_stop(parseHttpRequest
);
2904 /* partial or incomplete request */
2906 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2907 // (which becomes context) but checkHeaderLimits cannot?
2908 checkHeaderLimits();
2912 /* status -1 or 1 */
2914 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
2915 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
2916 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
2917 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
2919 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
2921 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
2923 if (context
->mayUseConnection()) {
2924 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
2930 /* XXX where to 'finish' the parsing pass? */
2935 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
2937 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
2941 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2943 if (io
.flag
== COMM_ERR_CLOSING
) {
2944 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
2948 assert(Comm::IsConnOpen(clientConnection
));
2949 assert(io
.conn
->fd
== clientConnection
->fd
);
2952 * Don't reset the timeout value here. The timeout value will be
2953 * set to Config.Timeout.request by httpAccept() and
2954 * clientWriteComplete(), and should apply to the request as a
2955 * whole, not individual read() calls. Plus, it breaks our
2956 * lame half-close detection
2958 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
2959 notifyAllContexts(io
.xerrno
);
2964 if (io
.flag
== COMM_OK
) {
2966 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
2968 // may comm_close or setReplyToError
2969 if (!handleReadData(io
.buf
, io
.size
))
2972 } else if (io
.size
== 0) {
2973 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
2975 if (connFinishedWithConn(io
.size
)) {
2976 clientConnection
->close();
2980 /* It might be half-closed, we can't tell */
2981 fd_table
[io
.conn
->fd
].flags
.socket_eof
= 1;
2983 commMarkHalfClosed(io
.conn
->fd
);
2985 fd_note(io
.conn
->fd
, "half-closed");
2987 /* There is one more close check at the end, to detect aborted
2988 * (partial) requests. At this point we can't tell if the request
2991 /* Continue to process previously read data */
2995 /* Process next request */
2996 if (getConcurrentRequestCount() == 0)
2997 fd_note(io
.fd
, "Reading next request");
2999 if (!clientParseRequests()) {
3003 * If the client here is half closed and we failed
3004 * to parse a request, close the connection.
3005 * The above check with connFinishedWithConn() only
3006 * succeeds _if_ the buffer is empty which it won't
3007 * be if we have an incomplete request.
3008 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3010 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3011 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3012 clientConnection
->close();
3020 clientAfterReadingRequests();
3024 * called when new request data has been read from the socket
3026 * \retval false called comm_close or setReplyToError (the caller should bail)
3027 * \retval true we did not call comm_close or setReplyToError
3030 ConnStateData::handleReadData(char *buf
, size_t size
)
3032 char *current_buf
= in
.addressToReadInto();
3034 if (buf
!= current_buf
)
3035 memmove(current_buf
, buf
, size
);
3037 in
.notYetUsed
+= size
;
3039 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3041 // if we are reading a body, stuff data into the body pipe
3042 if (bodyPipe
!= NULL
)
3043 return handleRequestBodyData();
3048 * called when new request body data has been buffered in in.buf
3049 * may close the connection if we were closing and piped everything out
3051 * \retval false called comm_close or setReplyToError (the caller should bail)
3052 * \retval true we did not call comm_close or setReplyToError
3055 ConnStateData::handleRequestBodyData()
3057 assert(bodyPipe
!= NULL
);
3061 if (in
.bodyParser
) { // chunked encoding
3062 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3063 abortChunkedRequestBody(error
);
3066 } else { // identity encoding
3067 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3068 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3069 if (!bodyPipe
->mayNeedMoreData()) {
3070 // BodyPipe will clear us automagically when we produced everything
3076 connNoteUseOfBuffer(this, putSize
);
3079 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3081 if (const char *reason
= stoppedSending()) {
3082 /* we've finished reading like good clients,
3083 * now do the close that initiateClose initiated.
3085 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3086 clientConnection
->close();
3094 /// parses available chunked encoded body bytes, checks size, returns errors
3096 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3098 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3100 try { // the parser will throw on errors
3102 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3105 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3106 // add one because MemBuf will assert if it cannot 0-terminate
3107 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3108 raw
.append(in
.buf
, in
.notYetUsed
);
3110 const mb_size_t wasContentSize
= raw
.contentSize();
3111 BodyPipeCheckout
bpc(*bodyPipe
);
3112 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3114 putSize
= wasContentSize
- raw
.contentSize();
3116 // dechunk then check: the size limit applies to _dechunked_ content
3117 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3121 finishDechunkingRequest(true);
3123 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3126 // if chunk parser needs data, then the body pipe must need it too
3127 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3129 // if parser needs more space and we can consume nothing, we will stall
3130 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3131 } catch (...) { // TODO: be more specific
3132 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3133 return ERR_INVALID_REQ
;
3136 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3140 /// quit on errors related to chunked request body handling
3142 ConnStateData::abortChunkedRequestBody(const err_type error
)
3144 finishDechunkingRequest(false);
3146 // XXX: The code below works if we fail during initial request parsing,
3147 // but if we fail when the server-side works already, the server may send
3148 // us its response too, causing various assertions. How to prevent that?
3149 #if WE_KNOW_HOW_TO_SEND_ERRORS
3150 ClientSocketContext::Pointer context
= getCurrentContext();
3151 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3152 clientStreamNode
*node
= context
->getClientReplyContext();
3153 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3155 const http_status scode
= (error
== ERR_TOO_BIG
) ?
3156 HTTP_REQUEST_ENTITY_TOO_LARGE
: HTTP_BAD_REQUEST
;
3157 repContext
->setReplyToError(error
, scode
,
3158 repContext
->http
->request
->method
,
3159 repContext
->http
->uri
,
3161 repContext
->http
->request
,
3163 context
->pullData();
3165 // close or otherwise we may get stuck as nobody will notice the error?
3166 comm_reset_close(clientConnection
);
3169 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3170 comm_reset_close(clientConnection
);
3172 flags
.readMore
= false;
3176 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3178 if (!handleRequestBodyData())
3181 // too late to read more body
3182 if (!isOpen() || stoppedReceiving())
3189 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3191 // request reader may get stuck waiting for space if nobody consumes body
3192 if (bodyPipe
!= NULL
)
3193 bodyPipe
->enableAutoConsumption();
3195 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3198 /** general lifetime handler for HTTP requests */
3200 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3202 #if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS
3203 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3205 if (COMMIO_FD_WRITECB(io
.fd
)->active
) {
3206 /* FIXME: If this code is reinstated, check the conn counters,
3207 * not the fd table state
3210 * Some data has been sent to the client, just close the FD
3212 clientConnection
->close();
3213 } else if (nrequests
) {
3215 * assume its a persistent connection; just close it
3217 clientConnection
->close();
3222 ClientHttpRequest
**H
;
3223 clientStreamNode
*node
;
3224 ClientHttpRequest
*http
= parseHttpRequestAbort(this, "error:Connection%20lifetime%20expired");
3225 node
= http
->client_stream
.tail
->prev
->data
;
3226 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3227 assert (repContext
);
3228 repContext
->setReplyToError(ERR_LIFETIME_EXP
,
3229 HTTP_REQUEST_TIMEOUT
, Http::METHOD_NONE
, "N/A", &CachePeer
.sin_addr
,
3231 /* No requests can be outstanded */
3232 assert(chr
== NULL
);
3233 /* add to the client request queue */
3235 for (H
= &chr
; *H
; H
= &(*H
)->next
);
3238 clientStreamRead(http
->client_stream
.tail
->data
, http
, 0,
3239 HTTP_REQBUF_SZ
, context
->reqbuf
);
3242 * if we don't close() here, we still need a timeout handler!
3244 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3245 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3246 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3247 commSetConnTimeout(io
.conn
, 30, timeoutCall
);
3250 * Aha, but we don't want a read handler!
3252 Comm::SetSelect(io
.fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3257 * Just close the connection to not confuse browsers
3258 * using persistent connections. Some browsers opens
3259 * an connection and then does not use it until much
3260 * later (presumeably because the request triggering
3261 * the open has already been completed on another
3264 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3270 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3272 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3273 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3274 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3275 http
->al
->http
.timedout
= true;
3276 if (Comm::IsConnOpen(io
.conn
))
3281 connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
)
3283 ConnStateData
*result
= new ConnStateData
;
3285 result
->clientConnection
= client
;
3286 result
->log_addr
= client
->remote
;
3287 result
->log_addr
.ApplyMask(Config
.Addrs
.client_netmask
);
3288 result
->in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &result
->in
.allocatedSize
);
3289 result
->port
= cbdataReference(port
);
3291 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3292 (result
->transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3293 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3294 int i
= IP_PMTUDISC_DONT
;
3295 setsockopt(client
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof i
);
3297 static int reported
= 0;
3300 debugs(33, DBG_IMPORTANT
, "Notice: httpd_accel_no_pmtu_disc not supported on your platform");
3306 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3307 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, result
, ConnStateData::connStateClosed
);
3308 comm_add_close_handler(client
->fd
, call
);
3310 if (Config
.onoff
.log_fqdn
)
3311 fqdncache_gethostbyaddr(client
->remote
, FQDN_LOOKUP_IF_MISS
);
3314 if (Ident::TheConfig
.identLookup
) {
3315 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3316 identChecklist
.src_addr
= client
->remote
;
3317 identChecklist
.my_addr
= client
->local
;
3318 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3319 Ident::Start(client
, clientIdentDone
, result
);
3324 if (Eui::TheConfig
.euiLookup
) {
3325 if (client
->remote
.IsIPv4()) {
3326 result
->clientConnection
->remoteEui48
.lookup(client
->remote
);
3327 } else if (client
->remote
.IsIPv6()) {
3328 result
->clientConnection
->remoteEui64
.lookup(client
->remote
);
3333 clientdbEstablished(client
->remote
, 1);
3335 result
->flags
.readMore
= true;
3339 /** Handle a new connection on HTTP socket. */
3341 httpAccept(const CommAcceptCbParams
¶ms
)
3343 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3345 if (params
.flag
!= COMM_OK
) {
3346 // Its possible the call was still queued when the client disconnected
3347 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3351 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3352 fd_note(params
.conn
->fd
, "client http connect");
3354 if (s
->tcp_keepalive
.enabled
) {
3355 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3358 ++ incoming_sockets_accepted
;
3360 // Socket is ready, setup the connection manager to start using it
3361 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3363 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3364 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3365 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3366 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3368 connState
->readSomeData();
3371 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3373 if (Config
.onoff
.client_db
) {
3374 /* it was said several times that client write limiter does not work if client_db is disabled */
3376 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3377 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3379 // TODO: we check early to limit error response bandwith but we
3380 // should recheck when we can honor delay_pool_uses_indirect
3381 // TODO: we should also pass the port details for myportname here.
3382 ch
.src_addr
= params
.conn
->remote
;
3383 ch
.my_addr
= params
.conn
->local
;
3385 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3387 /* pools require explicit 'allow' to assign a client into them */
3388 if (pools
[pool
].access
) {
3389 ch
.accessList
= pools
[pool
].access
;
3390 allow_t answer
= ch
.fastCheck();
3391 if (answer
== ACCESS_ALLOWED
) {
3393 /* request client information from db after we did all checks
3394 this will save hash lookup if client failed checks */
3395 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3398 /* put client info in FDE */
3399 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3401 /* setup write limiter for this request */
3402 const double burst
= floor(0.5 +
3403 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3404 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3407 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3417 /** Create SSL connection structure and update fd_table */
3419 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3421 SSL
*ssl
= SSL_new(sslContext
);
3424 const int ssl_error
= ERR_get_error();
3425 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3430 SSL_set_fd(ssl
, conn
->fd
);
3431 fd_table
[conn
->fd
].ssl
= ssl
;
3432 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3433 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3435 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3436 fd_note(conn
->fd
, "client https start");
3441 /** negotiate an SSL connection */
3443 clientNegotiateSSL(int fd
, void *data
)
3445 ConnStateData
*conn
= (ConnStateData
*)data
;
3447 SSL
*ssl
= fd_table
[fd
].ssl
;
3450 if ((ret
= SSL_accept(ssl
)) <= 0) {
3451 int ssl_error
= SSL_get_error(ssl
, ret
);
3453 switch (ssl_error
) {
3455 case SSL_ERROR_WANT_READ
:
3456 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3459 case SSL_ERROR_WANT_WRITE
:
3460 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3463 case SSL_ERROR_SYSCALL
:
3466 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3472 if (errno
== ECONNRESET
)
3475 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3476 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3483 case SSL_ERROR_ZERO_RETURN
:
3484 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3489 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3490 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3491 " (" << ssl_error
<< "/" << ret
<< ")");
3499 if (SSL_session_reused(ssl
)) {
3500 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3501 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3503 if (do_debug(83, 4)) {
3504 /* Write out the SSL session details.. actually the call below, but
3505 * OpenSSL headers do strange typecasts confusing GCC.. */
3506 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3507 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3508 PEM_ASN1_write((i2d_of_void
*)i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3510 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3512 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3513 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3514 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3515 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3516 * Because there are two possible usable cast, if you get an error here, try the other
3517 * commented line. */
3519 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3520 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3524 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3527 /* Note: This does not automatically fflush the log file.. */
3530 debugs(83, 2, "clientNegotiateSSL: New session " <<
3531 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3532 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3536 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3537 SSL_get_cipher(ssl
));
3539 client_cert
= SSL_get_peer_certificate(ssl
);
3541 if (client_cert
!= NULL
) {
3542 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3543 " client certificate: subject: " <<
3544 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3546 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3547 " client certificate: issuer: " <<
3548 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3550 X509_free(client_cert
);
3552 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3553 " has no certificate.");
3556 conn
->readSomeData();
3560 * If SSL_CTX is given, starts reading the SSL handshake.
3561 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3564 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3568 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3570 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3573 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3574 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3575 connState
, ConnStateData::requestTimeout
);
3576 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3579 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3581 char buf
[MAX_IPSTRLEN
];
3582 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3583 HttpRequest
*fakeRequest
= new HttpRequest
;
3584 fakeRequest
->SetHost(details
->local
.NtoA(buf
, sizeof(buf
)));
3585 fakeRequest
->port
= details
->local
.GetPort();
3586 fakeRequest
->clientConnectionManager
= connState
;
3587 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3588 #if FOLLOW_X_FORWARDED_FOR
3589 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3591 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3592 fakeRequest
->flags
.spoofClientIp
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3593 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3594 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3595 connState
->switchToHttps(fakeRequest
, bumpMode
);
3600 * A callback function to use with the ACLFilledChecklist callback.
3601 * In the case of ACCES_ALLOWED answer initializes a bumped SSL connection,
3602 * else reverts the connection to tunnel mode.
3605 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3607 ConnStateData
*connState
= (ConnStateData
*) data
;
3609 // if the connection is closed or closing, just return.
3610 if (!connState
->isOpen())
3613 // Require both a match and a positive bump mode to work around exceptional
3614 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3615 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3616 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3617 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3618 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3620 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3621 connState
->sslBumpMode
= Ssl::bumpNone
;
3623 // fake a CONNECT request to force connState to tunnel
3624 static char ip
[MAX_IPSTRLEN
];
3625 static char reqStr
[MAX_IPSTRLEN
+ 80];
3626 connState
->clientConnection
->local
.NtoA(ip
, sizeof(ip
));
3627 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s:%d HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, connState
->clientConnection
->local
.GetPort(), ip
);
3628 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3630 ret
= connState
->clientParseRequests();
3633 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3634 connState
->clientConnection
->close();
3639 /** handle a new HTTPS connection */
3641 httpsAccept(const CommAcceptCbParams
¶ms
)
3643 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3645 if (params
.flag
!= COMM_OK
) {
3646 // Its possible the call was still queued when the client disconnected
3647 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3651 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3652 fd_note(params
.conn
->fd
, "client https connect");
3654 if (s
->tcp_keepalive
.enabled
) {
3655 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3658 ++incoming_sockets_accepted
;
3660 // Socket is ready, setup the connection manager to start using it
3661 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3664 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3666 if (!Config
.accessList
.ssl_bump
) {
3667 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3671 // Create a fake HTTP request for ssl_bump ACL check,
3672 // using tproxy/intercept provided destination IP and port.
3673 HttpRequest
*request
= new HttpRequest();
3674 static char ip
[MAX_IPSTRLEN
];
3675 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3676 request
->SetHost(params
.conn
->local
.NtoA(ip
, sizeof(ip
)));
3677 request
->port
= params
.conn
->local
.GetPort();
3678 request
->myportname
= s
->name
;
3680 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3681 acl_checklist
->src_addr
= params
.conn
->remote
;
3682 acl_checklist
->my_addr
= s
->s
;
3683 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3686 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3687 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3692 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3694 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3695 state_data
->sslCrtdHandleReply(reply
);
3699 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3701 if (!reply
.other().hasContent()) {
3702 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper return <NULL> reply");
3704 Ssl::CrtdMessage reply_message
;
3705 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3706 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3708 if (reply
.result
!= HelperReply::Okay
) {
3709 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3711 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3712 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3713 getSslContextDone(ctx
, true);
3718 getSslContextDone(NULL
);
3721 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3723 certProperties
.commonName
= sslCommonName
.defined() ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3725 // fake certificate adaptation requires bump-server-first mode
3726 if (!sslServerBump
) {
3727 assert(port
->signingCert
.get());
3728 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3729 if (port
->signPkey
.get())
3730 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3731 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3735 // In case of an error while connecting to the secure server, use a fake
3736 // trusted certificate, with no mimicked fields and no adaptation
3737 // algorithms. There is nothing we can mimic so we want to minimize the
3738 // number of warnings the user will have to see to get to the error page.
3739 assert(sslServerBump
->entry
);
3740 if (sslServerBump
->entry
->isEmpty()) {
3741 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
3742 certProperties
.mimicCert
.resetAndLock(mimicCert
);
3744 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
,
3745 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
3746 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
3748 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
3749 // If the algorithm already set, then ignore it.
3750 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
3751 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
3752 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
3755 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
3756 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
3757 const char *param
= ca
->param
;
3759 // For parameterless CN adaptation, use hostname from the
3761 if (ca
->alg
== Ssl::algSetCommonName
) {
3763 param
= sslConnectHostOrIp
.termedBuf();
3764 certProperties
.commonName
= param
;
3765 certProperties
.setCommonName
= true;
3766 } else if (ca
->alg
== Ssl::algSetValidAfter
)
3767 certProperties
.setValidAfter
= true;
3768 else if (ca
->alg
== Ssl::algSetValidBefore
)
3769 certProperties
.setValidBefore
= true;
3771 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
3772 alg
<< " param: " << (param
? param
: "-"));
3776 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
3777 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
3778 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
3779 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
3783 } else {// if (!sslServerBump->entry->isEmpty())
3784 // Use trusted certificate for a Squid-generated error
3785 // or the user would have to add a security exception
3786 // just to see the error page. We will close the connection
3787 // so that the trust is not extended to non-Squid content.
3788 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3791 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
3793 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
3794 assert(port
->untrustedSigningCert
.get());
3795 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
3796 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
3798 assert(port
->signingCert
.get());
3799 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3801 if (port
->signPkey
.get())
3802 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3804 signAlgorithm
= certProperties
.signAlgorithm
;
3808 ConnStateData::getSslContextStart()
3810 assert(areAllContextsForThisConnection());
3812 /* careful: freeAllContexts() above frees request, host, etc. */
3814 if (port
->generateHostCertificates
) {
3815 Ssl::CertificateProperties certProperties
;
3816 buildSslCertGenerationParams(certProperties
);
3817 sslBumpCertKey
= certProperties
.dbKey().c_str();
3818 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3820 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
3821 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3822 SSL_CTX
* dynCtx
= ssl_ctx_cache
.find(sslBumpCertKey
.termedBuf());
3824 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
3825 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
3826 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
3827 getSslContextDone(dynCtx
);
3830 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
3831 ssl_ctx_cache
.remove(sslBumpCertKey
.termedBuf());
3834 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
3839 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
3840 Ssl::CrtdMessage request_message
;
3841 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
3842 request_message
.composeRequest(certProperties
);
3843 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
3844 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
3846 } catch (const std::exception
&e
) {
3847 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
3848 "request for " << certProperties
.commonName
<<
3849 " certificate: " << e
.what() << "; will now block to " <<
3850 "generate that certificate.");
3851 // fall through to do blocking in-process generation.
3853 #endif // USE_SSL_CRTD
3855 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
3856 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
3857 getSslContextDone(dynCtx
, true);
3860 getSslContextDone(NULL
);
3864 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
3866 // Try to add generated ssl context to storage.
3867 if (port
->generateHostCertificates
&& isNew
) {
3869 if (signAlgorithm
== Ssl::algSignTrusted
)
3870 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
3871 //else it is self-signed or untrusted do not attrach any certificate
3873 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
3874 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
3876 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), sslContext
)) {
3877 // If it is not in storage delete after using. Else storage deleted it.
3878 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
3881 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
3885 // If generated ssl context = NULL, try to use static ssl context.
3887 if (!port
->staticSslContext
) {
3888 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
3889 clientConnection
->close();
3892 debugs(33, 5, HERE
<< "Using static ssl context.");
3893 sslContext
= port
->staticSslContext
.get();
3898 if (!(ssl
= httpsCreate(clientConnection
, sslContext
)))
3901 // commSetConnTimeout() was called for this request before we switched.
3903 // Disable the client read handler until CachePeer selection is complete
3904 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3905 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
3906 switchedToHttps_
= true;
3910 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
3912 assert(!switchedToHttps_
);
3914 sslConnectHostOrIp
= request
->GetHost();
3915 sslCommonName
= request
->GetHost();
3917 // We are going to read new request
3918 flags
.readMore
= true;
3919 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
3921 // If sslServerBump is set, then we have decided to deny CONNECT
3922 // and now want to switch to SSL to send the error to the client
3923 // without even peeking at the origin server certificate.
3924 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
3925 request
->flags
.sslPeek
= 1;
3926 sslServerBump
= new Ssl::ServerBump(request
);
3928 // will call httpsPeeked() with certificate and connection, eventually
3929 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
);
3933 // otherwise, use sslConnectHostOrIp
3934 getSslContextStart();
3938 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
3940 Must(sslServerBump
!= NULL
);
3942 if (Comm::IsConnOpen(serverConnection
)) {
3943 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
3945 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
3946 assert(serverCert
.get() != NULL
);
3947 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
3948 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
3949 " bumped: " << *serverConnection
);
3951 pinConnection(serverConnection
, NULL
, NULL
, false);
3953 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
3955 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
3956 Ip::Address intendedDest
;
3957 intendedDest
= sslConnectHostOrIp
.termedBuf();
3958 const bool isConnectRequest
= !port
->spoof_client_ip
&& !port
->intercepted
;
3960 // Squid serves its own error page and closes, so we want
3961 // a CN that causes no additional browser errors. Possible
3962 // only when bumping CONNECT with a user-typed address.
3963 if (intendedDest
.IsAnyAddr() || isConnectRequest
)
3964 sslCommonName
= sslConnectHostOrIp
;
3965 else if (sslServerBump
->serverCert
.get())
3966 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
3968 // copy error detail from bump-server-first request to CONNECT request
3969 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
3970 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
3973 getSslContextStart();
3976 #endif /* USE_SSL */
3978 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3980 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
3982 if (!Comm::IsConnOpen(c
)) {
3983 Must(NHttpSockets
> 0); // we tried to open some
3984 --NHttpSockets
; // there will be fewer sockets than planned
3985 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
3987 if (!NHttpSockets
) // we could not open any listen sockets at all
3988 fatalf("Unable to open %s",FdNote(portType
));
3995 /// find any unused HttpSockets[] slot and store fd there or return false
3997 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4000 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4001 if ((found
= HttpSockets
[i
] < 0))
4002 HttpSockets
[i
] = conn
->fd
;
4008 clientHttpConnectionsOpen(void)
4010 AnyP::PortCfg
*s
= NULL
;
4012 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4013 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4014 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4015 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4020 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4021 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4025 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4026 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4030 // Create ssl_ctx cache for this port.
4031 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4035 // Fill out a Comm::Connection which IPC will open as a listener for us
4036 // then pass back when active so we can start a TcpAcceptor subscription.
4037 s
->listenConn
= new Comm::Connection
;
4038 s
->listenConn
->local
= s
->s
;
4039 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) | (s
->intercepted
? COMM_INTERCEPTION
: 0);
4041 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4042 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4043 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4044 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4046 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4047 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4048 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4050 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4057 clientHttpsConnectionsOpen(void)
4061 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4062 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4063 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4064 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4068 if (!s
->staticSslContext
) {
4069 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4070 " due to SSL initialization failure.");
4074 // TODO: merge with similar code in clientHttpConnectionsOpen()
4075 if (s
->sslBump
&& !Config
.accessList
.ssl_bump
) {
4076 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4080 if (s
->sslBump
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4081 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4086 // Create ssl_ctx cache for this port.
4087 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4090 // Fill out a Comm::Connection which IPC will open as a listener for us
4091 s
->listenConn
= new Comm::Connection
;
4092 s
->listenConn
->local
= s
->s
;
4093 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->spoof_client_ip
? COMM_TRANSPARENT
: 0) |
4094 (s
->intercepted
? COMM_INTERCEPTION
: 0);
4096 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4097 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4098 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4099 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4101 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4102 ListeningStartedDialer(&clientListenerConnectionOpened
,
4103 s
, Ipc::fdnHttpsSocket
, sub
));
4104 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4105 HttpSockets
[NHttpSockets
] = -1;
4111 /// process clientHttpConnectionsOpen result
4113 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4115 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4119 Must(Comm::IsConnOpen(s
->listenConn
));
4121 // TCP: setup a job to handle accept() with subscribed handler
4122 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4124 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4125 (s
->intercepted
? "NAT intercepted " : "") <<
4126 (s
->spoof_client_ip
? "TPROXY spoofing " : "") <<
4127 (s
->sslBump
? "SSL bumped " : "") <<
4128 (s
->accel
? "reverse-proxy " : "")
4129 << FdNote(portTypeNote
) << " connections at "
4132 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4136 clientOpenListenSockets(void)
4138 clientHttpConnectionsOpen();
4140 clientHttpsConnectionsOpen();
4143 if (NHttpSockets
< 1)
4144 fatal("No HTTP or HTTPS ports configured");
4148 clientHttpConnectionsClose(void)
4150 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4151 if (s
->listenConn
!= NULL
) {
4152 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4153 s
->listenConn
->close();
4154 s
->listenConn
= NULL
;
4159 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4160 if (s
->listenConn
!= NULL
) {
4161 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4162 s
->listenConn
->close();
4163 s
->listenConn
= NULL
;
4168 // TODO see if we can drop HttpSockets array entirely */
4169 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4170 HttpSockets
[i
] = -1;
4177 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4179 const char *vary
= request
->vary_headers
;
4180 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4181 #if X_ACCELERATOR_VARY
4184 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4187 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4189 /* Oops... something odd is going on here.. */
4190 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4191 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4192 safe_free(request
->vary_headers
);
4197 /* This is not a varying object */
4201 /* virtual "vary" object found. Calculate the vary key and
4202 * continue the search
4204 vary
= httpMakeVaryMark(request
, entry
->getReply());
4207 request
->vary_headers
= xstrdup(vary
);
4210 /* Ouch.. we cannot handle this kind of variance */
4211 /* XXX This cannot really happen, but just to be complete */
4216 vary
= httpMakeVaryMark(request
, entry
->getReply());
4219 request
->vary_headers
= xstrdup(vary
);
4223 /* Ouch.. we cannot handle this kind of variance */
4224 /* XXX This cannot really happen, but just to be complete */
4226 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4229 /* Oops.. we have already been here and still haven't
4230 * found the requested variant. Bail out
4232 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4233 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4239 ACLFilledChecklist
*
4240 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4242 ConnStateData
* conn
= http
->getConn();
4243 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4244 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4247 * hack for ident ACL. It needs to get full addresses, and a place to store
4248 * the ident result on persistent connections...
4250 /* connection oriented auth also needs these two lines for it's operation. */
4254 CBDATA_CLASS_INIT(ConnStateData
);
4256 ConnStateData::ConnStateData() :
4257 AsyncJob("ConnStateData"),
4259 sslBumpMode(Ssl::bumpEnd
),
4260 switchedToHttps_(false),
4261 sslServerBump(NULL
),
4263 stoppedSending_(NULL
),
4264 stoppedReceiving_(NULL
)
4266 pinning
.pinned
= false;
4267 pinning
.auth
= false;
4271 ConnStateData::transparent() const
4273 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4277 ConnStateData::reading() const
4279 return reader
!= NULL
;
4283 ConnStateData::stopReading()
4286 comm_read_cancel(clientConnection
->fd
, reader
);
4292 ConnStateData::expectRequestBody(int64_t size
)
4294 bodyPipe
= new BodyPipe(this);
4296 bodyPipe
->setBodySize(size
);
4298 startDechunkingRequest();
4303 ConnStateData::mayNeedToReadMoreBody() const
4306 return 0; // request without a body or read/produced all body bytes
4308 if (!bodyPipe
->bodySizeKnown())
4309 return -1; // probably need to read more, but we cannot be sure
4311 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4312 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4314 if (needToProduce
<= haveAvailable
)
4315 return 0; // we have read what we need (but are waiting for pipe space)
4317 return needToProduce
- haveAvailable
;
4321 ConnStateData::stopReceiving(const char *error
)
4323 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4324 "; old sending error: " <<
4325 (stoppedSending() ? stoppedSending_
: "none"));
4327 if (const char *oldError
= stoppedReceiving()) {
4328 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4329 return; // nothing has changed as far as this connection is concerned
4332 stoppedReceiving_
= error
;
4334 if (const char *sendError
= stoppedSending()) {
4335 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4336 clientConnection
->close();
4341 ConnStateData::expectNoForwarding()
4343 if (bodyPipe
!= NULL
) {
4344 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4345 bodyPipe
->expectNoConsumption();
4349 /// initialize dechunking state
4351 ConnStateData::startDechunkingRequest()
4353 Must(bodyPipe
!= NULL
);
4354 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4355 assert(!in
.bodyParser
);
4356 in
.bodyParser
= new ChunkedCodingParser
;
4359 /// put parsed content into input buffer and clean up
4361 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4363 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4365 if (bodyPipe
!= NULL
) {
4366 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4367 BodyPipe::Pointer myPipe
= bodyPipe
;
4368 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4369 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4371 Must(myPipe
->bodySizeKnown());
4372 ClientSocketContext::Pointer context
= getCurrentContext();
4373 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4374 context
->http
->request
->setContentLength(myPipe
->bodySize());
4378 delete in
.bodyParser
;
4379 in
.bodyParser
= NULL
;
4383 ConnStateData::In::addressToReadInto() const
4385 return buf
+ notYetUsed
;
4388 ConnStateData::In::In() : bodyParser(NULL
),
4389 buf (NULL
), notYetUsed (0), allocatedSize (0)
4392 ConnStateData::In::~In()
4395 memFreeBuf(allocatedSize
, buf
);
4396 delete bodyParser
; // TODO: pool
4400 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4403 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4407 ClientSocketContext::Pointer context
= getCurrentContext();
4408 if (context
!= NULL
) {
4409 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4413 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4414 clientConnection
->close();
4417 /// Our close handler called by Comm when the pinned connection is closed
4419 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4421 // FwdState might repin a failed connection sooner than this close
4422 // callback is called for the failed connection.
4423 if (pinning
.serverConnection
== io
.conn
) {
4424 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4430 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4432 char desc
[FD_DESC_SZ
];
4434 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4435 if (pinning
.serverConnection
->fd
== pinServer
->fd
)
4439 unpinConnection(); // closes pinned connection, if any, and resets fields
4441 pinning
.serverConnection
= pinServer
;
4443 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4445 // when pinning an SSL bumped connection, the request may be NULL
4446 const char *pinnedHost
= "[unknown]";
4448 pinning
.host
= xstrdup(request
->GetHost());
4449 pinning
.port
= request
->port
;
4450 pinnedHost
= pinning
.host
;
4452 pinning
.port
= pinServer
->remote
.GetPort();
4454 pinning
.pinned
= true;
4456 pinning
.peer
= cbdataReference(aPeer
);
4457 pinning
.auth
= auth
;
4458 char stmp
[MAX_IPSTRLEN
];
4459 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4460 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4461 clientConnection
->remote
.ToURL(stmp
,MAX_IPSTRLEN
),
4462 clientConnection
->fd
);
4463 fd_note(pinning
.serverConnection
->fd
, desc
);
4465 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4466 pinning
.closeHandler
= JobCallback(33, 5,
4467 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4468 // remember the pinned connection so that cb does not unpin a fresher one
4469 typedef CommCloseCbParams Params
;
4470 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4471 params
.conn
= pinning
.serverConnection
;
4472 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4475 const Comm::ConnectionPointer
4476 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4478 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4481 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4483 if (pinning
.auth
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0) {
4486 if (request
&& pinning
.port
!= request
->port
) {
4489 if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
)) {
4492 if (aPeer
!= pinning
.peer
) {
4497 /* The pinning info is not safe, remove any pinning info */
4501 return pinning
.serverConnection
;
4505 ConnStateData::unpinConnection()
4507 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4510 cbdataReferenceDone(pinning
.peer
);
4512 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4513 if (pinning
.closeHandler
!= NULL
) {
4514 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4515 pinning
.closeHandler
= NULL
;
4517 /// also close the server side socket, we should not use it for any future requests...
4518 // TODO: do not close if called from our close handler?
4519 pinning
.serverConnection
->close();
4522 safe_free(pinning
.host
);
4524 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4525 * connection has gone away */