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/ConnOpener.h"
97 #include "comm/Loops.h"
98 #include "comm/TcpAcceptor.h"
99 #include "comm/Write.h"
100 #include "CommCalls.h"
101 #include "errorpage.h"
102 #include "eui/Config.h"
106 #include "fqdncache.h"
109 #include "HttpHdrCc.h"
110 #include "HttpHdrContRange.h"
111 #include "HttpHeaderTools.h"
112 #include "HttpReply.h"
113 #include "HttpRequest.h"
114 #include "ident/Config.h"
115 #include "ident/Ident.h"
116 #include "internal.h"
117 #include "ipc/FdNotes.h"
118 #include "ipc/StartListening.h"
119 #include "log/access_log.h"
122 #include "MemObject.h"
123 #include "mime_header.h"
124 #include "profiler/Profiler.h"
126 #include "SquidConfig.h"
127 #include "SquidTime.h"
128 #include "StatCounters.h"
129 #include "StatHist.h"
131 #include "TimeOrTag.h"
136 #include "auth/UserRequest.h"
139 #include "ClientInfo.h"
142 #include "ssl/ProxyCerts.h"
143 #include "ssl/context_storage.h"
144 #include "ssl/helper.h"
145 #include "ssl/ServerBump.h"
146 #include "ssl/support.h"
147 #include "ssl/gadgets.h"
150 #include "ssl/crtd_message.h"
151 #include "ssl/certificate_db.h"
165 #define comm_close comm_lingering_close
168 /// dials clientListenerConnectionOpened call
169 class ListeningStartedDialer
: public CallDialer
, public Ipc::StartListeningCb
172 typedef void (*Handler
)(AnyP::PortCfg
*portCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&sub
);
173 ListeningStartedDialer(Handler aHandler
, AnyP::PortCfg
*aPortCfg
, const Ipc::FdNoteId note
, const Subscription::Pointer
&aSub
):
174 handler(aHandler
), portCfg(aPortCfg
), portTypeNote(note
), sub(aSub
) {}
176 virtual void print(std::ostream
&os
) const {
178 ", " << FdNote(portTypeNote
) << " port=" << (void*)portCfg
<< ')';
181 virtual bool canDial(AsyncCall
&) const { return true; }
182 virtual void dial(AsyncCall
&) { (handler
)(portCfg
, portTypeNote
, sub
); }
188 AnyP::PortCfg
*portCfg
; ///< from Config.Sockaddr.http
189 Ipc::FdNoteId portTypeNote
; ///< Type of IPC socket being opened
190 Subscription::Pointer sub
; ///< The handler to be subscribed for this connetion listener
193 static void clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
);
195 /* our socket-related context */
197 CBDATA_CLASS_INIT(ClientSocketContext
);
200 ClientSocketContext::operator new (size_t byteCount
)
202 /* derived classes with different sizes must implement their own new */
203 assert (byteCount
== sizeof (ClientSocketContext
));
204 CBDATA_INIT_TYPE(ClientSocketContext
);
205 return cbdataAlloc(ClientSocketContext
);
209 ClientSocketContext::operator delete (void *address
)
211 cbdataFree (address
);
214 /* Local functions */
215 /* ClientSocketContext */
216 static ClientSocketContext
*ClientSocketContextNew(const Comm::ConnectionPointer
&clientConn
, ClientHttpRequest
*);
218 static IOCB clientWriteComplete
;
219 static IOCB clientWriteBodyComplete
;
220 static IOACB httpAccept
;
222 static IOACB httpsAccept
;
224 static IOACB ftpAccept
;
225 static CTCB clientLifetimeTimeout
;
226 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
227 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, Http::ProtocolVersion
*);
229 static IDCB clientIdentDone
;
231 static CSCB clientSocketRecipient
;
232 static CSD clientSocketDetach
;
233 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
234 static int clientIsContentLengthValid(HttpRequest
* r
);
235 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
237 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
238 static void clientUpdateStatCounters(LogTags logType
);
239 static void clientUpdateHierCounters(HierarchyLogEntry
*);
240 static bool clientPingHasFinished(ping_data
const *aPing
);
241 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
243 static bool connIsUsable(ConnStateData
* conn
);
245 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
246 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
247 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
249 char *skipLeadingSpace(char *aString
);
250 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
252 static ConnStateData
*connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
);
254 static IOACB FtpAcceptDataConnection
;
255 static void FtpCloseDataConnection(ConnStateData
*conn
);
256 static void FtpWriteGreeting(ConnStateData
*conn
);
257 static ClientSocketContext
*FtpParseRequest(ConnStateData
*connState
, HttpRequestMethod
*method_p
, Http::ProtocolVersion
*http_ver
);
258 static bool FtpHandleUserRequest(ConnStateData
*connState
, const String
&cmd
, String
¶ms
);
259 static CNCB FtpHandleConnectDone
;
261 static void FtpHandleReply(ClientSocketContext
*context
, HttpReply
*reply
, StoreIOBuffer data
);
262 typedef void FtpReplyHandler(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
);
263 static FtpReplyHandler FtpHandlePasvReply
;
264 static FtpReplyHandler FtpHandlePortReply
;
265 static FtpReplyHandler FtpHandleErrorReply
;
266 static FtpReplyHandler FtpHandleDataReply
;
267 static FtpReplyHandler FtpHandleUploadReply
;
269 static void FtpWriteEarlyReply(ConnStateData
*conn
, const int code
, const char *msg
);
270 static void FtpWriteReply(ClientSocketContext
*context
, MemBuf
&mb
);
271 static void FtpWriteCustomReply(ClientSocketContext
*context
, const int code
, const char *msg
, const HttpReply
*reply
= NULL
);
272 static void FtpWriteForwardedReply(ClientSocketContext
*context
, const HttpReply
*reply
);
273 static void FtpWriteForwardedReply(ClientSocketContext
*context
, const HttpReply
*reply
, AsyncCall::Pointer call
);
274 static void FtpPrintReply(MemBuf
&mb
, const HttpReply
*reply
, const char *const prefix
= "");
275 static IOCB FtpWroteEarlyReply
;
276 static IOCB FtpWroteReply
;
277 static IOCB FtpWroteReplyData
;
279 typedef bool FtpRequestHandler(ClientSocketContext
*context
, String
&cmd
, String
¶ms
);
280 static FtpRequestHandler FtpHandleRequest
;
281 static FtpRequestHandler FtpHandlePasvRequest
;
282 static FtpRequestHandler FtpHandlePortRequest
;
283 static FtpRequestHandler FtpHandleDataRequest
;
284 static FtpRequestHandler FtpHandleUploadRequest
;
286 static bool FtpCheckDataConnection(ClientSocketContext
*context
);
287 static void FtpSetReply(ClientSocketContext
*context
, const int code
, const char *msg
);
290 ClientSocketContext::getTail() const
292 if (http
->client_stream
.tail
)
293 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
299 ClientSocketContext::getClientReplyContext() const
301 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
305 ClientSocketContext::getConn() const
307 return http
->getConn();
311 * This routine should be called to grow the inbuf and then
315 ConnStateData::readSomeData()
320 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
322 if (!maybeMakeSpaceAvailable())
325 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
326 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
327 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
331 ConnStateData::readSomeFtpData()
333 if (ftp
.reader
!= NULL
)
336 const size_t availSpace
= sizeof(ftp
.uploadBuf
) - ftp
.uploadAvailSize
;
340 debugs(33, 4, HERE
<< ftp
.dataConn
<< ": reading FTP data...");
342 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
343 ftp
.reader
= JobCallback(33, 5, Dialer
, this,
344 ConnStateData::clientReadFtpData
);
345 comm_read(ftp
.dataConn
, ftp
.uploadBuf
+ ftp
.uploadAvailSize
, availSpace
,
350 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
352 ClientSocketContext::Pointer
*tempContextPointer
;
353 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
354 assert(conn
->getCurrentContext() != NULL
);
355 /* Unlink us from the connection request list */
356 tempContextPointer
= & conn
->currentobject
;
358 while (tempContextPointer
->getRaw()) {
359 if (*tempContextPointer
== this)
362 tempContextPointer
= &(*tempContextPointer
)->next
;
365 assert(tempContextPointer
->getRaw() != NULL
);
366 *tempContextPointer
= next
;
370 ClientSocketContext::~ClientSocketContext()
372 clientStreamNode
*node
= getTail();
375 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
378 /* We are *always* the tail - prevent recursive free */
379 assert(this == streamContext
);
385 deRegisterWithConn();
387 httpRequestFree(http
);
389 /* clean up connection links to us */
390 assert(this != next
.getRaw());
394 ClientSocketContext::registerWithConn()
396 assert (!connRegistered_
);
398 assert (http
->getConn() != NULL
);
399 connRegistered_
= true;
400 http
->getConn()->addContextToQueue(this);
404 ClientSocketContext::deRegisterWithConn()
406 assert (connRegistered_
);
407 removeFromConnectionList(http
->getConn());
408 connRegistered_
= false;
412 ClientSocketContext::connIsFinished()
415 assert (http
->getConn() != NULL
);
416 deRegisterWithConn();
417 /* we can't handle any more stream data - detach */
418 clientStreamDetach(getTail(), http
);
421 ClientSocketContext::ClientSocketContext() : http(NULL
), reply(NULL
), next(NULL
),
423 mayUseConnection_ (false),
424 connRegistered_ (false)
426 memset (reqbuf
, '\0', sizeof (reqbuf
));
429 deferredparams
.node
= NULL
;
430 deferredparams
.rep
= NULL
;
433 ClientSocketContext
*
434 ClientSocketContextNew(const Comm::ConnectionPointer
&client
, ClientHttpRequest
* http
)
436 ClientSocketContext
*newContext
;
437 assert(http
!= NULL
);
438 newContext
= new ClientSocketContext
;
439 newContext
->http
= http
;
440 newContext
->clientConnection
= client
;
445 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
447 const HttpReply::Pointer
rep(msg
.reply
);
450 // remember the callback
451 cbControlMsgSent
= msg
.cbSuccess
;
453 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
454 CommIoCbPtrFun(&WroteControlMsg
, this));
456 if (getConn()->isFtp
) {
457 FtpWriteForwardedReply(this, rep
.getRaw(), call
);
461 // apply selected clientReplyContext::buildReplyHeader() mods
462 // it is not clear what headers are required for control messages
463 rep
->header
.removeHopByHopEntries();
464 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
465 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
467 MemBuf
*mb
= rep
->pack();
469 debugs(11, 2, "HTTP Client " << clientConnection
);
470 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
472 Comm::Write(clientConnection
, mb
, call
);
477 /// called when we wrote the 1xx response
479 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
481 if (errflag
== COMM_ERR_CLOSING
)
484 if (errflag
== COMM_OK
) {
485 ScheduleCallHere(cbControlMsgSent
);
489 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
490 // no error notification: see HttpControlMsg.h for rationale and
491 // note that some errors are detected elsewhere (e.g., close handler)
493 // close on 1xx errors to be conservative and to simplify the code
494 // (if we do not close, we must notify the source of a failure!)
498 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
500 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
502 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
503 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
508 clientIdentDone(const char *ident
, void *data
)
510 ConnStateData
*conn
= (ConnStateData
*)data
;
511 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
516 clientUpdateStatCounters(LogTags logType
)
518 ++statCounter
.client_http
.requests
;
520 if (logTypeIsATcpHit(logType
))
521 ++statCounter
.client_http
.hits
;
523 if (logType
== LOG_TCP_HIT
)
524 ++statCounter
.client_http
.disk_hits
;
525 else if (logType
== LOG_TCP_MEM_HIT
)
526 ++statCounter
.client_http
.mem_hits
;
530 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
532 statCounter
.client_http
.allSvcTime
.count(svc_time
);
534 * The idea here is not to be complete, but to get service times
535 * for only well-defined types. For example, we don't include
536 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
537 * (we *tried* to validate it, but failed).
542 case LOG_TCP_REFRESH_UNMODIFIED
:
543 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
546 case LOG_TCP_IMS_HIT
:
547 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
552 case LOG_TCP_MEM_HIT
:
554 case LOG_TCP_OFFLINE_HIT
:
555 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
560 case LOG_TCP_CLIENT_REFRESH_MISS
:
561 statCounter
.client_http
.missSvcTime
.count(svc_time
);
565 /* make compiler warnings go away */
571 clientPingHasFinished(ping_data
const *aPing
)
573 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
580 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
584 switch (someEntry
->code
) {
585 #if USE_CACHE_DIGESTS
590 ++ statCounter
.cd
.times_used
;
598 case FIRST_PARENT_MISS
:
600 case CLOSEST_PARENT_MISS
:
601 ++ statCounter
.icp
.times_used
;
602 i
= &someEntry
->ping
;
604 if (clientPingHasFinished(i
))
605 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
608 ++ statCounter
.icp
.query_timeouts
;
615 ++ statCounter
.netdb
.times_used
;
625 ClientHttpRequest::updateCounters()
627 clientUpdateStatCounters(logType
);
629 if (request
->errType
!= ERR_NONE
)
630 ++ statCounter
.client_http
.errors
;
632 clientUpdateStatHistCounters(logType
,
633 tvSubMsec(start_time
, current_time
));
635 clientUpdateHierCounters(&request
->hier
);
639 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
642 assert(aLogEntry
!= NULL
);
644 if (Config
.onoff
.log_mime_hdrs
) {
648 packerToMemInit(&p
, &mb
);
649 request
->header
.packInto(&p
);
650 //This is the request after adaptation or redirection
651 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
653 // the virgin request is saved to aLogEntry->request
654 if (aLogEntry
->request
) {
657 packerToMemInit(&p
, &mb
);
658 aLogEntry
->request
->header
.packInto(&p
);
659 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
663 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
667 packerToMemInit(&p
, &mb
);
668 ah
->lastMeta
.packInto(&p
);
669 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
670 aLogEntry
->notes
.append(&ah
->metaHeaders
);
679 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
681 aLogEntry
->icap
.processingTime
= ih
->processingTime();
684 aLogEntry
->http
.method
= request
->method
;
685 aLogEntry
->http
.version
= request
->http_ver
;
686 aLogEntry
->hier
= request
->hier
;
687 if (request
->helperNotes
)
688 aLogEntry
->notes
.append(request
->helperNotes
->notes
);
689 if (request
->content_length
> 0) // negative when no body or unknown length
690 aLogEntry
->cache
.requestSize
+= request
->content_length
;
691 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
694 if (request
->auth_user_request
!= NULL
) {
695 if (request
->auth_user_request
->username())
696 aLogEntry
->cache
.authuser
= xstrdup(request
->auth_user_request
->username());
700 // Adapted request, if any, inherits and then collects all the stats, but
701 // the virgin request gets logged instead; copy the stats to log them.
702 // TODO: avoid losses by keeping these stats in a shared history object?
703 if (aLogEntry
->request
) {
704 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
705 aLogEntry
->request
->errType
= request
->errType
;
706 aLogEntry
->request
->errDetail
= request
->errDetail
;
711 ClientHttpRequest::logRequest()
713 if (!out
.size
&& !logType
)
714 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
716 al
->icp
.opcode
= ICP_INVALID
;
718 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
721 al
->http
.code
= al
->reply
->sline
.status();
722 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
723 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
724 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
725 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
728 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
730 if (loggingEntry() && loggingEntry()->mem_obj
)
731 al
->cache
.objectSize
= loggingEntry()->contentLen();
733 al
->cache
.caddr
.SetNoAddr();
735 if (getConn() != NULL
) {
736 al
->cache
.caddr
= getConn()->log_addr
;
737 al
->cache
.port
= cbdataReference(getConn()->port
);
740 al
->cache
.requestSize
= req_sz
;
741 al
->cache
.requestHeadersSize
= req_sz
;
743 al
->cache
.replySize
= out
.size
;
744 al
->cache
.replyHeadersSize
= out
.headers_sz
;
746 al
->cache
.highOffset
= out
.offset
;
748 al
->cache
.code
= logType
;
750 al
->cache
.msec
= tvSubMsec(start_time
, current_time
);
753 prepareLogWithRequestDetails(request
, al
);
755 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
756 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
760 /* This is broken. Fails if the connection has been closed. Needs
761 * to snarf the ssl details some place earlier..
763 if (getConn() != NULL
)
764 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
769 typedef Notes::iterator ACAMLI
;
770 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
771 if (const char *value
= (*i
)->match(request
, al
->reply
)) {
772 al
->notes
.addEntry(new HttpHeaderEntry(HDR_OTHER
, (*i
)->key
.termedBuf(), value
));
773 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
777 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.log
, this);
780 checklist
->reply
= al
->reply
;
781 HTTPMSGLOCK(checklist
->reply
);
784 if (!Config
.accessList
.log
|| checklist
->fastCheck() == ACCESS_ALLOWED
) {
786 al
->adapted_request
= request
;
787 HTTPMSGLOCK(al
->adapted_request
);
789 accessLogLog(al
, checklist
);
793 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
794 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
801 ClientHttpRequest::freeResources()
805 safe_free(redirect
.location
);
806 range_iter
.boundary
.clean();
807 HTTPMSGUNLOCK(request
);
809 if (client_stream
.tail
)
810 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
814 httpRequestFree(void *data
)
816 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
817 assert(http
!= NULL
);
822 ConnStateData::areAllContextsForThisConnection() const
824 assert(this != NULL
);
825 ClientSocketContext::Pointer context
= getCurrentContext();
827 while (context
.getRaw()) {
828 if (context
->http
->getConn() != this)
831 context
= context
->next
;
838 ConnStateData::freeAllContexts()
840 ClientSocketContext::Pointer context
;
842 while ((context
= getCurrentContext()).getRaw() != NULL
) {
843 assert(getCurrentContext() !=
844 getCurrentContext()->next
);
845 context
->connIsFinished();
846 assert (context
!= currentobject
);
850 /// propagates abort event to all contexts
852 ConnStateData::notifyAllContexts(int xerrno
)
854 typedef ClientSocketContext::Pointer CSCP
;
855 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
856 c
->noteIoError(xerrno
);
859 /* This is a handler normally called by comm_close() */
860 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
862 deleteThis("ConnStateData::connStateClosed");
865 // cleans up before destructor is called
867 ConnStateData::swanSong()
869 debugs(33, 2, HERE
<< clientConnection
);
870 flags
.readMore
= false;
871 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
872 assert(areAllContextsForThisConnection());
875 if (auth_user_request
!= NULL
) {
876 debugs(33, 4, "ConnStateData::swanSong: freeing auth_user_request '" << auth_user_request
<< "' (this is '" << this << "')");
877 auth_user_request
->onConnectionClose(this);
881 if (Comm::IsConnOpen(pinning
.serverConnection
))
882 pinning
.serverConnection
->close();
883 pinning
.serverConnection
= NULL
;
885 if (Comm::IsConnOpen(clientConnection
))
886 clientConnection
->close();
887 clientConnection
= NULL
;
889 BodyProducer::swanSong();
890 flags
.swanSang
= true;
894 ConnStateData::isOpen() const
896 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
897 Comm::IsConnOpen(clientConnection
) &&
898 !fd_table
[clientConnection
->fd
].closing();
901 ConnStateData::~ConnStateData()
903 assert(this != NULL
);
904 debugs(33, 3, HERE
<< clientConnection
);
906 FtpCloseDataConnection(this);
909 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
912 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
914 cbdataReferenceDone(port
);
916 if (bodyPipe
!= NULL
)
917 stopProducingFor(bodyPipe
, false);
920 delete sslServerBump
;
925 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
926 * This is the client-side persistent connection flag. We need
927 * to set this relatively early in the request processing
928 * to handle hacks for broken servers and clients.
931 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
933 HttpRequest
*request
= http
->request
;
935 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
936 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
937 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
938 RequestMethodStr(request
->method
));
940 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
941 request
->flags
.proxyKeepalive
= request
->persistent();
945 clientIsContentLengthValid(HttpRequest
* r
)
947 switch (r
->method
.id()) {
949 case Http::METHOD_GET
:
951 case Http::METHOD_HEAD
:
952 /* We do not want to see a request entity on GET/HEAD requests */
953 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
956 /* For other types of requests we don't care */
964 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
966 if (Config
.maxRequestBodySize
&&
967 bodyLength
> Config
.maxRequestBodySize
)
968 return 1; /* too large */
975 connIsUsable(ConnStateData
* conn
)
977 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
985 // careful: the "current" context may be gone if we wrote an early response
986 ClientSocketContext::Pointer
987 ConnStateData::getCurrentContext() const
990 return currentobject
;
994 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
996 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
997 assert(flags
.deferred
== 0);
999 deferredparams
.node
= node
;
1000 deferredparams
.rep
= rep
;
1001 deferredparams
.queuedBuffer
= receivedData
;
1006 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
1008 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
1015 ClientSocketContext::startOfOutput() const
1017 return http
->out
.size
== 0;
1021 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
1023 /*the size of available range can always fit in a size_t type*/
1024 size_t maximum
= (size_t)available
.size();
1026 if (!http
->request
->range
)
1029 assert (canPackMoreRanges());
1031 if (http
->range_iter
.debt() == -1)
1034 assert (http
->range_iter
.debt() > 0);
1036 /* TODO this + the last line could be a range intersection calculation */
1037 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
1040 return min(http
->range_iter
.debt(), (int64_t)maximum
);
1044 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
1046 http
->out
.offset
+= bytes
;
1048 if (!http
->request
->range
)
1051 if (http
->range_iter
.debt() != -1) {
1052 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
1053 assert (http
->range_iter
.debt() >= 0);
1056 /* debt() always stops at -1, below that is a bug */
1057 assert (http
->range_iter
.debt() >= -1);
1061 ClientHttpRequest::multipartRangeRequest() const
1063 return request
->multipartRangeRequest();
1067 ClientSocketContext::multipartRangeRequest() const
1069 return http
->multipartRangeRequest();
1073 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1075 assert(rep
== NULL
);
1077 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1078 size_t length
= lengthToSend(bodyData
.range());
1079 noteSentBodyBytes (length
);
1080 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1081 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1082 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1088 if (multipartRangeRequest())
1089 packRange(bodyData
, &mb
);
1091 packChunk(bodyData
, mb
);
1093 if (mb
.contentSize()) {
1095 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1096 CommIoCbPtrFun(clientWriteComplete
, this));
1097 Comm::Write(clientConnection
, &mb
, call
);
1099 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1103 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1104 * if bodyData is empty.
1107 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1109 const uint64_t length
=
1110 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1111 noteSentBodyBytes(length
);
1113 mb
.Printf("%" PRIX64
"\r\n", length
);
1114 mb
.append(bodyData
.data
, length
);
1118 /** put terminating boundary for multiparts */
1120 clientPackTermBound(String boundary
, MemBuf
* mb
)
1122 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1123 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1126 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1128 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1130 HttpHeader
hdr(hoReply
);
1136 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1137 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1138 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1140 /* stuff the header with required entries and pack it */
1142 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1143 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1145 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1147 packerToMemInit(&p
, mb
);
1155 /* append <crlf> (we packed a header, not a reply) */
1160 * extracts a "range" from *buf and appends them to mb, updating
1161 * all offsets and such.
1164 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1166 HttpHdrRangeIter
* i
= &http
->range_iter
;
1167 Range
<int64_t> available (source
.range());
1168 char const *buf
= source
.data
;
1170 while (i
->currentSpec() && available
.size()) {
1171 const size_t copy_sz
= lengthToSend(available
);
1175 * intersection of "have" and "need" ranges must not be empty
1177 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1178 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1181 * put boundary and headers at the beginning of a range in a
1185 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1186 assert(http
->memObject());
1188 http
->memObject()->getReply(), /* original reply */
1189 i
->currentSpec(), /* current range */
1190 i
->boundary
, /* boundary, the same for all */
1197 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1199 noteSentBodyBytes (copy_sz
);
1201 mb
->append(buf
, copy_sz
);
1206 available
.start
+= copy_sz
;
1212 if (!canPackMoreRanges()) {
1213 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1216 /* put terminating boundary for multiparts */
1217 clientPackTermBound(i
->boundary
, mb
);
1222 int64_t nextOffset
= getNextRangeOffset();
1224 assert (nextOffset
>= http
->out
.offset
);
1226 int64_t skip
= nextOffset
- http
->out
.offset
;
1228 /* adjust for not to be transmitted bytes */
1229 http
->out
.offset
= nextOffset
;
1231 if (available
.size() <= (uint64_t)skip
)
1234 available
.start
+= skip
;
1243 /** returns expected content length for multi-range replies
1244 * note: assumes that httpHdrRangeCanonize has already been called
1245 * warning: assumes that HTTP headers for individual ranges at the
1246 * time of the actuall assembly will be exactly the same as
1247 * the headers when clientMRangeCLen() is called */
1249 ClientHttpRequest::mRangeCLen()
1254 assert(memObject());
1257 HttpHdrRange::iterator pos
= request
->range
->begin();
1259 while (pos
!= request
->range
->end()) {
1260 /* account for headers for this range */
1262 clientPackRangeHdr(memObject()->getReply(),
1263 *pos
, range_iter
.boundary
, &mb
);
1266 /* account for range content */
1267 clen
+= (*pos
)->length
;
1269 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1273 /* account for the terminating boundary */
1276 clientPackTermBound(range_iter
.boundary
, &mb
);
1286 * returns true if If-Range specs match reply, false otherwise
1289 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1291 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1292 /* check for parsing falure */
1299 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1300 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1301 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1304 return 0; /* entity has no etag to compare with! */
1306 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1307 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1308 return 0; /* must use strong validator for sub-range requests */
1311 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1314 /* got modification time? */
1315 if (spec
.time
>= 0) {
1316 return http
->storeEntry()->lastmod
<= spec
.time
;
1319 assert(0); /* should not happen */
1324 * generates a "unique" boundary string for multipart responses
1325 * the caller is responsible for cleaning the string */
1327 ClientHttpRequest::rangeBoundaryStr() const
1331 String
b(APP_FULLNAME
);
1333 key
= storeEntry()->getMD5Text();
1334 b
.append(key
, strlen(key
));
1338 /** adds appropriate Range headers if needed */
1340 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1342 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1343 const char *range_err
= NULL
;
1344 HttpRequest
*request
= http
->request
;
1345 assert(request
->range
);
1346 /* check if we still want to do ranges */
1348 int64_t roffLimit
= request
->getRangeOffsetLimit();
1351 range_err
= "no [parse-able] reply";
1352 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1353 range_err
= "wrong status code";
1354 else if (hdr
->has(HDR_CONTENT_RANGE
))
1355 range_err
= "origin server does ranges";
1356 else if (rep
->content_length
< 0)
1357 range_err
= "unknown length";
1358 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1359 range_err
= "INCONSISTENT length"; /* a bug? */
1361 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1364 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1365 range_err
= "If-Range match failed";
1366 else if (!http
->request
->range
->canonize(rep
))
1367 range_err
= "canonization failed";
1368 else if (http
->request
->range
->isComplex())
1369 range_err
= "too complex range header";
1370 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1371 range_err
= "range outside range_offset_limit";
1373 /* get rid of our range specs on error */
1375 /* XXX We do this here because we need canonisation etc. However, this current
1376 * code will lead to incorrect store offset requests - the store will have the
1377 * offset data, but we won't be requesting it.
1378 * So, we can either re-request, or generate an error
1380 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1381 delete http
->request
->range
;
1382 http
->request
->range
= NULL
;
1384 /* XXX: TODO: Review, this unconditional set may be wrong. */
1385 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1386 // web server responded with a valid, but unexpected range.
1387 // will (try-to) forward as-is.
1388 //TODO: we should cope with multirange request/responses
1389 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1390 request
->range
->contains(rep
->content_range
->spec
) :
1392 const int spec_count
= http
->request
->range
->specs
.count
;
1393 int64_t actual_clen
= -1;
1395 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1396 spec_count
<< " virgin clen: " << rep
->content_length
);
1397 assert(spec_count
> 0);
1398 /* append appropriate header(s) */
1400 if (spec_count
== 1) {
1401 if (!replyMatchRequest
) {
1402 hdr
->delById(HDR_CONTENT_RANGE
);
1403 hdr
->putContRange(rep
->content_range
);
1404 actual_clen
= rep
->content_length
;
1405 //http->range_iter.pos = rep->content_range->spec.begin();
1406 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1407 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1410 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1412 /* append Content-Range */
1414 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1415 /* No content range, so this was a full object we are
1418 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1421 /* set new Content-Length to the actual number of bytes
1422 * transmitted in the message-body */
1423 actual_clen
= (*pos
)->length
;
1427 /* generate boundary string */
1428 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1429 /* delete old Content-Type, add ours */
1430 hdr
->delById(HDR_CONTENT_TYPE
);
1431 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1432 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1433 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1434 /* Content-Length is not required in multipart responses
1435 * but it is always nice to have one */
1436 actual_clen
= http
->mRangeCLen();
1437 /* http->out needs to start where we want data at */
1438 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1441 /* replace Content-Length header */
1442 assert(actual_clen
>= 0);
1444 hdr
->delById(HDR_CONTENT_LENGTH
);
1446 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1448 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1450 /* And start the range iter off */
1451 http
->range_iter
.updateSpec();
1456 ClientSocketContext::prepareReply(HttpReply
* rep
)
1460 if (http
->request
->range
)
1461 buildRangeHeader(rep
);
1465 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1469 MemBuf
*mb
= rep
->pack();
1471 // dump now, so we dont output any body.
1472 debugs(11, 2, "HTTP Client " << clientConnection
);
1473 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1475 /* Save length of headers for persistent conn checks */
1476 http
->out
.headers_sz
= mb
->contentSize();
1479 headersLog(0, 0, http
->request
->method
, rep
);
1482 if (bodyData
.data
&& bodyData
.length
) {
1483 if (multipartRangeRequest())
1484 packRange(bodyData
, mb
);
1485 else if (http
->request
->flags
.chunkedReply
) {
1486 packChunk(bodyData
, *mb
);
1488 size_t length
= lengthToSend(bodyData
.range());
1489 noteSentBodyBytes (length
);
1491 mb
->append(bodyData
.data
, length
);
1496 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1497 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1498 CommIoCbPtrFun(clientWriteComplete
, this));
1499 Comm::Write(clientConnection
, mb
, call
);
1504 * Write a chunk of data to a client socket. If the reply is present,
1505 * send the reply headers down the wire too, and clean them up when
1508 * The request is one backed by a connection, not an internal request.
1509 * data context is not NULL
1510 * There are no more entries in the stream chain.
1513 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1514 HttpReply
* rep
, StoreIOBuffer receivedData
)
1516 debugs(33,7, HERE
<< "rep->content_length=" << (rep
? rep
->content_length
: -2) << " receivedData.length=" << receivedData
.length
);
1517 /* Test preconditions */
1518 assert(node
!= NULL
);
1519 PROF_start(clientSocketRecipient
);
1520 /* TODO: handle this rather than asserting
1521 * - it should only ever happen if we cause an abort and
1522 * the callback chain loops back to here, so we can simply return.
1523 * However, that itself shouldn't happen, so it stays as an assert for now.
1525 assert(cbdataReferenceValid(node
));
1526 assert(node
->node
.next
== NULL
);
1527 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1528 assert(context
!= NULL
);
1529 assert(connIsUsable(http
->getConn()));
1531 /* TODO: check offset is what we asked for */
1533 if (context
!= http
->getConn()->getCurrentContext()) {
1534 context
->deferRecipientForLater(node
, rep
, receivedData
);
1535 PROF_stop(clientSocketRecipient
);
1539 if (http
->getConn()->isFtp
) {
1540 assert(context
->http
== http
);
1541 FtpHandleReply(context
.getRaw(), rep
, receivedData
);
1542 PROF_stop(clientSocketRecipient
);
1546 // After sending Transfer-Encoding: chunked (at least), always send
1547 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1548 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1549 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1550 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1551 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1552 PROF_stop(clientSocketRecipient
);
1556 if (!context
->startOfOutput())
1557 context
->sendBody(rep
, receivedData
);
1560 http
->al
->reply
= rep
;
1561 HTTPMSGLOCK(http
->al
->reply
);
1562 context
->sendStartOfMessage(rep
, receivedData
);
1565 PROF_stop(clientSocketRecipient
);
1569 * Called when a downstream node is no longer interested in
1570 * our data. As we are a terminal node, this means on aborts
1574 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1576 /* Test preconditions */
1577 assert(node
!= NULL
);
1578 /* TODO: handle this rather than asserting
1579 * - it should only ever happen if we cause an abort and
1580 * the callback chain loops back to here, so we can simply return.
1581 * However, that itself shouldn't happen, so it stays as an assert for now.
1583 assert(cbdataReferenceValid(node
));
1584 /* Set null by ContextFree */
1585 assert(node
->node
.next
== NULL
);
1586 /* this is the assert discussed above */
1587 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1588 /* We are only called when the client socket shutsdown.
1589 * Tell the prev pipeline member we're finished
1591 clientStreamDetach(node
, http
);
1595 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1597 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1598 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1602 ConnStateData::readNextRequest()
1604 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1606 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1608 * Set the timeout BEFORE calling clientReadRequest().
1610 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1611 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1612 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1613 commSetConnTimeout(clientConnection
, Config
.Timeout
.clientIdlePconn
, timeoutCall
);
1616 /** Please don't do anything with the FD past here! */
1620 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1622 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1624 /** If the client stream is waiting on a socket write to occur, then */
1626 if (deferredRequest
->flags
.deferred
) {
1627 /** NO data is allowed to have been sent. */
1628 assert(deferredRequest
->http
->out
.size
== 0);
1630 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1631 deferredRequest
->http
,
1632 deferredRequest
->deferredparams
.rep
,
1633 deferredRequest
->deferredparams
.queuedBuffer
);
1636 /** otherwise, the request is still active in a callbacksomewhere,
1641 /// called when we have successfully finished writing the response
1643 ClientSocketContext::keepaliveNextRequest()
1645 ConnStateData
* conn
= http
->getConn();
1647 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1650 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1651 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1652 conn
->clientConnection
->close();
1657 * We are done with the response, and we are either still receiving request
1658 * body (early response!) or have already stopped receiving anything.
1660 * If we are still receiving, then clientParseRequest() below will fail.
1661 * (XXX: but then we will call readNextRequest() which may succeed and
1662 * execute a smuggled request as we are not done with the current request).
1664 * If we stopped because we got everything, then try the next request.
1666 * If we stopped receiving because of an error, then close now to avoid
1667 * getting stuck and to prevent accidental request smuggling.
1670 if (const char *reason
= conn
->stoppedReceiving()) {
1671 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1672 conn
->clientConnection
->close();
1677 * Attempt to parse a request from the request buffer.
1678 * If we've been fed a pipelined request it may already
1679 * be in our read buffer.
1682 * This needs to fall through - if we're unlucky and parse the _last_ request
1683 * from our read buffer we may never re-register for another client read.
1686 if (conn
->clientParseRequests()) {
1687 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1691 * Either we need to kick-start another read or, if we have
1692 * a half-closed connection, kill it after the last request.
1693 * This saves waiting for half-closed connections to finished being
1694 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1695 * the keepalive "Waiting for next request" state.
1697 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1698 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1699 conn
->clientConnection
->close();
1703 ClientSocketContext::Pointer deferredRequest
;
1706 * At this point we either have a parsed request (which we've
1707 * kicked off the processing for) or not. If we have a deferred
1708 * request (parsed but deferred for pipeling processing reasons)
1709 * then look at processing it. If not, simply kickstart
1713 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1714 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1715 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1716 } else if (conn
->flags
.readMore
) {
1717 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1718 conn
->readNextRequest();
1720 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1721 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1726 clientUpdateSocketStats(LogTags logType
, size_t size
)
1731 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1733 if (logTypeIsATcpHit(logType
))
1734 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1738 * increments iterator "i"
1739 * used by clientPackMoreRanges
1741 \retval true there is still data available to pack more ranges
1745 ClientSocketContext::canPackMoreRanges() const
1747 /** first update iterator "i" if needed */
1749 if (!http
->range_iter
.debt()) {
1750 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1752 if (http
->range_iter
.pos
.incrementable())
1753 ++http
->range_iter
.pos
;
1755 http
->range_iter
.updateSpec();
1758 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1760 /* paranoid sync condition */
1761 /* continue condition: need_more_data */
1762 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1763 return http
->range_iter
.currentSpec() ? true : false;
1767 ClientSocketContext::getNextRangeOffset() const
1769 if (http
->request
->range
) {
1770 /* offset in range specs does not count the prefix of an http msg */
1771 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1772 /* check: reply was parsed and range iterator was initialized */
1773 assert(http
->range_iter
.valid
);
1774 /* filter out data according to range specs */
1775 assert (canPackMoreRanges());
1777 int64_t start
; /* offset of still missing data */
1778 assert(http
->range_iter
.currentSpec());
1779 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1780 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1781 debugs(33, 3, "clientPackMoreRanges: out:"
1782 " start: " << start
<<
1783 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1784 " [" << http
->range_iter
.currentSpec()->offset
<<
1785 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1786 " len: " << http
->range_iter
.currentSpec()->length
<<
1787 " debt: " << http
->range_iter
.debt());
1788 if (http
->range_iter
.currentSpec()->length
!= -1)
1789 assert(http
->out
.offset
<= start
); /* we did not miss it */
1794 } else if (reply
&& reply
->content_range
) {
1795 /* request does not have ranges, but reply does */
1796 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1797 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1799 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1802 return http
->out
.offset
;
1806 ClientSocketContext::pullData()
1808 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1810 /* More data will be coming from the stream. */
1811 StoreIOBuffer readBuffer
;
1812 /* XXX: Next requested byte in the range sequence */
1813 /* XXX: length = getmaximumrangelenfgth */
1814 readBuffer
.offset
= getNextRangeOffset();
1815 readBuffer
.length
= HTTP_REQBUF_SZ
;
1816 readBuffer
.data
= reqbuf
;
1817 /* we may note we have reached the end of the wanted ranges */
1818 clientStreamRead(getTail(), http
, readBuffer
);
1821 clientStream_status_t
1822 ClientSocketContext::socketState()
1824 switch (clientStreamStatus(getTail(), http
)) {
1827 /* check for range support ending */
1829 if (http
->request
->range
) {
1830 /* check: reply was parsed and range iterator was initialized */
1831 assert(http
->range_iter
.valid
);
1832 /* filter out data according to range specs */
1834 if (!canPackMoreRanges()) {
1835 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1836 "range sequence on " << clientConnection
);
1838 if (http
->request
->flags
.proxyKeepalive
)
1839 return STREAM_COMPLETE
;
1841 return STREAM_UNPLANNED_COMPLETE
;
1843 } else if (reply
&& reply
->content_range
) {
1844 /* reply has content-range, but Squid is not managing ranges */
1845 const int64_t &bytesSent
= http
->out
.offset
;
1846 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1848 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1849 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1850 reply
->content_range
->spec
.offset
<< ")");
1852 // did we get at least what we expected, based on range specs?
1854 if (bytesSent
== bytesExpected
) { // got everything
1855 if (http
->request
->flags
.proxyKeepalive
)
1856 return STREAM_COMPLETE
;
1858 return STREAM_UNPLANNED_COMPLETE
;
1861 // The logic below is not clear: If we got more than we
1862 // expected why would persistency matter? Should not this
1863 // always be an error?
1864 if (bytesSent
> bytesExpected
) { // got extra
1865 if (http
->request
->flags
.proxyKeepalive
)
1866 return STREAM_COMPLETE
;
1868 return STREAM_UNPLANNED_COMPLETE
;
1871 // did not get enough yet, expecting more
1876 case STREAM_COMPLETE
:
1877 return STREAM_COMPLETE
;
1879 case STREAM_UNPLANNED_COMPLETE
:
1880 return STREAM_UNPLANNED_COMPLETE
;
1883 return STREAM_FAILED
;
1886 fatal ("unreachable code\n");
1891 * A write has just completed to the client, or we have just realised there is
1892 * no more data to send.
1895 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1897 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1898 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1901 /// remembers the abnormal connection termination for logging purposes
1903 ClientSocketContext::noteIoError(const int xerrno
)
1906 if (xerrno
== ETIMEDOUT
)
1907 http
->al
->http
.timedout
= true;
1908 else // even if xerrno is zero (which means read abort/eof)
1909 http
->al
->http
.aborted
= true;
1914 ClientSocketContext::doClose()
1916 clientConnection
->close();
1919 /// called when we encounter a response-related error
1921 ClientSocketContext::initiateClose(const char *reason
)
1923 http
->getConn()->stopSending(reason
); // closes ASAP
1927 ConnStateData::stopSending(const char *error
)
1929 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
1930 "; old receiving error: " <<
1931 (stoppedReceiving() ? stoppedReceiving_
: "none"));
1933 if (const char *oldError
= stoppedSending()) {
1934 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
1935 return; // nothing has changed as far as this connection is concerned
1937 stoppedSending_
= error
;
1939 if (!stoppedReceiving()) {
1940 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
1941 debugs(33, 5, HERE
<< "must still read " << expecting
<<
1942 " request body bytes with " << in
.notYetUsed
<< " unused");
1943 return; // wait for the request receiver to finish reading
1947 clientConnection
->close();
1951 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
1953 const StoreEntry
*entry
= http
->storeEntry();
1954 http
->out
.size
+= size
;
1955 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
1956 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
1957 (entry
? entry
->objectLen() : 0));
1958 clientUpdateSocketStats(http
->logType
, size
);
1960 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
1962 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
1965 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
1966 initiateClose("failure or true request status");
1967 /* Do we leak here ? */
1971 switch (socketState()) {
1977 case STREAM_COMPLETE
:
1978 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
1979 keepaliveNextRequest();
1982 case STREAM_UNPLANNED_COMPLETE
:
1983 initiateClose("STREAM_UNPLANNED_COMPLETE");
1987 initiateClose("STREAM_FAILED");
1991 fatal("Hit unreachable code in clientWriteComplete\n");
1995 SQUIDCEXTERN CSR clientGetMoreData
;
1996 SQUIDCEXTERN CSS clientReplyStatus
;
1997 SQUIDCEXTERN CSD clientReplyDetach
;
1999 static ClientSocketContext
*
2000 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
2002 ClientHttpRequest
*http
;
2003 ClientSocketContext
*context
;
2004 StoreIOBuffer tempBuffer
;
2005 http
= new ClientHttpRequest(csd
);
2006 http
->req_sz
= csd
->in
.notYetUsed
;
2007 http
->uri
= xstrdup(uri
);
2008 setLogUri (http
, uri
);
2009 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
2010 tempBuffer
.data
= context
->reqbuf
;
2011 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2012 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2013 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
2014 clientSocketDetach
, context
, tempBuffer
);
2019 skipLeadingSpace(char *aString
)
2021 char *result
= aString
;
2023 while (xisspace(*aString
))
2030 * 'end' defaults to NULL for backwards compatibility
2031 * remove default value if we ever get rid of NULL-terminated
2035 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
2038 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
2042 for (; end
> uriAndHTTPVersion
; --end
) {
2043 if (*end
== '\n' || *end
== '\r')
2046 if (xisspace(*end
)) {
2047 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2058 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2060 safe_free(http
->log_uri
);
2063 // The uri is already clean just dump it.
2064 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2067 switch (Config
.uri_whitespace
) {
2068 case URI_WHITESPACE_ALLOW
:
2069 flags
|= RFC1738_ESCAPE_NOSPACE
;
2071 case URI_WHITESPACE_ENCODE
:
2072 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2073 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2076 case URI_WHITESPACE_CHOP
: {
2077 flags
|= RFC1738_ESCAPE_NOSPACE
;
2078 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2079 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2080 int pos
= strcspn(http
->log_uri
, w_space
);
2081 http
->log_uri
[pos
] = '\0';
2085 case URI_WHITESPACE_DENY
:
2086 case URI_WHITESPACE_STRIP
:
2089 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2093 if (!xisspace(*t
)) {
2100 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2109 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2111 int vhost
= conn
->port
->vhost
;
2112 int vport
= conn
->port
->vport
;
2114 char ipbuf
[MAX_IPSTRLEN
];
2116 http
->flags
.accel
= true;
2118 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2120 if (strncasecmp(url
, "cache_object://", 15) == 0)
2121 return; /* already in good shape */
2124 if (conn
->port
->vhost
)
2125 return; /* already in good shape */
2127 /* else we need to ignore the host name */
2128 url
= strstr(url
, "//");
2130 #if SHOULD_REJECT_UNKNOWN_URLS
2133 hp
->request_parse_status
= Http::scBadRequest
;
2134 return parseHttpRequestAbort(conn
, "error:invalid-request");
2139 url
= strchr(url
+ 2, '/');
2146 vport
= http
->getConn()->clientConnection
->local
.GetPort();
2148 const bool switchedToHttps
= conn
->switchedToHttps();
2149 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2150 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2151 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2156 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2157 strncpy(thost
, host
, (t
-host
));
2158 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2161 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2164 } // else nothing to alter port-wise.
2165 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2167 http
->uri
= (char *)xcalloc(url_sz
, 1);
2168 const char *protocol
= switchedToHttps
?
2169 "https" : conn
->port
->protocol
;
2170 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2171 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2172 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2173 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2174 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2175 strlen(conn
->port
->defaultsite
);
2176 http
->uri
= (char *)xcalloc(url_sz
, 1);
2180 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2182 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2183 conn
->port
->protocol
, conn
->port
->defaultsite
, vportStr
, url
);
2184 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2185 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2186 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2187 /* Put the local socket IP address as the hostname, with whatever vport we found */
2188 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2189 http
->uri
= (char *)xcalloc(url_sz
, 1);
2190 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2191 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2192 http
->getConn()->port
->protocol
,
2194 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2199 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2202 char ipbuf
[MAX_IPSTRLEN
];
2205 return; /* already in good shape */
2207 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2209 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2210 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2212 http
->uri
= (char *)xcalloc(url_sz
, 1);
2213 snprintf(http
->uri
, url_sz
, "%s://%s%s", conn
->port
->protocol
, host
, url
);
2214 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2216 /* Put the local socket IP address as the hostname. */
2217 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2218 http
->uri
= (char *)xcalloc(url_sz
, 1);
2219 http
->getConn()->clientConnection
->local
.ToHostname(ipbuf
,MAX_IPSTRLEN
);
2220 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2221 http
->getConn()->port
->protocol
,
2222 ipbuf
, http
->getConn()->clientConnection
->local
.GetPort(), url
);
2223 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2227 /** Parse an HTTP request
2229 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2230 * to 1 if the request was correctly parsed.
2231 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2232 * \param[in] hp an HttpParser
2233 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2234 * Pointed-to value will be set to Http::METHOD_NONE in case of
2236 * \param[out] http_ver will be set as a side-effect of the parsing
2237 * \return NULL on incomplete requests,
2238 * a ClientSocketContext structure on success or failure.
2240 static ClientSocketContext
*
2241 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2243 char *req_hdr
= NULL
;
2246 ClientHttpRequest
*http
;
2247 ClientSocketContext
*result
;
2248 StoreIOBuffer tempBuffer
;
2251 /* pre-set these values to make aborting simpler */
2252 *method_p
= Http::METHOD_NONE
;
2254 /* NP: don't be tempted to move this down or remove again.
2255 * It's the only DDoS protection old-String has against long URL */
2256 if ( hp
->bufsiz
<= 0) {
2257 debugs(33, 5, "Incomplete request, waiting for end of request line");
2259 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2260 debugs(33, 5, "parseHttpRequest: Too large request");
2261 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2262 return parseHttpRequestAbort(csd
, "error:request-too-large");
2265 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2266 r
= HttpParserParseReqLine(hp
);
2269 debugs(33, 5, "Incomplete request, waiting for end of request line");
2274 return parseHttpRequestAbort(csd
, "error:invalid-request");
2277 /* Request line is valid here .. */
2278 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2280 /* This call scans the entire request, not just the headers */
2281 if (hp
->req
.v_maj
> 0) {
2282 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2283 debugs(33, 5, "Incomplete request, waiting for end of headers");
2287 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2288 req_sz
= HttpParserReqSz(hp
);
2291 /* We know the whole request is in hp->buf now */
2293 assert(req_sz
<= (size_t) hp
->bufsiz
);
2295 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2296 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2299 hp
->hdr_end
= req_sz
- 1;
2301 hp
->hdr_start
= hp
->req
.end
+ 1;
2303 /* Enforce max_request_size */
2304 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2305 debugs(33, 5, "parseHttpRequest: Too large request");
2306 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2307 return parseHttpRequestAbort(csd
, "error:request-too-large");
2311 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2313 /* deny CONNECT via accelerated ports */
2314 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2315 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->protocol
<< " Accelerator port " << csd
->port
->s
.GetPort() );
2316 /* XXX need a way to say "this many character length string" */
2317 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2318 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2319 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2322 if (*method_p
== Http::METHOD_NONE
) {
2323 /* XXX need a way to say "this many character length string" */
2324 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2325 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2326 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2330 * Process headers after request line
2331 * TODO: Use httpRequestParse here.
2333 /* XXX this code should be modified to take a const char * later! */
2334 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2336 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2338 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2340 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2342 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2343 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2344 HttpParserReqSz(hp
));
2346 /* Ok, all headers are received */
2347 http
= new ClientHttpRequest(csd
);
2349 http
->req_sz
= HttpParserRequestLen(hp
);
2350 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2351 tempBuffer
.data
= result
->reqbuf
;
2352 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2354 ClientStreamData newServer
= new clientReplyContext(http
);
2355 ClientStreamData newClient
= result
;
2356 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2357 clientReplyStatus
, newServer
, clientSocketRecipient
,
2358 clientSocketDetach
, newClient
, tempBuffer
);
2360 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2364 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2365 * below needs to be modified to not expect a mutable nul-terminated string.
2367 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2369 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2371 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2373 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2375 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2380 debugs(33,5, HERE
<< "repare absolute URL from " <<
2381 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2382 /* Rewrite the URL in transparent or accelerator mode */
2383 /* NP: there are several cases to traverse here:
2384 * - standard mode (forward proxy)
2385 * - transparent mode (TPROXY)
2386 * - transparent mode with failures
2387 * - intercept mode (NAT)
2388 * - intercept mode with failures
2389 * - accelerator mode (reverse proxy)
2391 * - mixed combos of the above with internal URL
2393 if (csd
->transparent()) {
2394 /* intercept or transparent mode, properly working with no failures */
2395 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2397 } else if (internalCheck(url
)) {
2398 /* internal URL mode */
2399 /* prepend our name & port */
2400 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2401 // We just re-wrote the URL. Must replace the Host: header.
2402 // But have not parsed there yet!! flag for local-only handling.
2403 http
->flags
.internal
= true;
2405 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2406 /* accelerator mode */
2407 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2411 /* No special rewrites have been applied above, use the
2412 * requested url. may be rewritten later, so make extra room */
2413 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2414 http
->uri
= (char *)xcalloc(url_sz
, 1);
2415 strcpy(http
->uri
, url
);
2418 debugs(33, 5, "parseHttpRequest: Complete request received");
2420 // XXX: crop this dump at the end of headers. No need for extras
2421 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2422 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2424 result
->flags
.parsed_ok
= 1;
2430 ConnStateData::getAvailableBufferLength() const
2432 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2433 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2434 // huge request_header_max_size may lead to more than INT_MAX unused space
2435 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2440 ConnStateData::maybeMakeSpaceAvailable()
2442 if (getAvailableBufferLength() < 2) {
2444 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2445 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2448 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2449 newSize
=Config
.maxRequestBufferSize
;
2451 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2452 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2458 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2460 ClientSocketContext::Pointer
*S
;
2462 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2470 ConnStateData::getConcurrentRequestCount() const
2473 ClientSocketContext::Pointer
*T
;
2475 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2476 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2481 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2483 if (flag
!= COMM_OK
) {
2484 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2489 if (!ignoreErrno(xerrno
)) {
2490 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2492 } else if (in
.notYetUsed
== 0) {
2493 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2501 ConnStateData::connFinishedWithConn(int size
)
2504 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2505 /* no current or pending requests */
2506 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2508 } else if (!Config
.onoff
.half_closed_clients
) {
2509 /* admin doesn't want to support half-closed client sockets */
2510 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2511 notifyAllContexts(0); // no specific error implies abort
2520 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2522 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2523 conn
->in
.notYetUsed
-= byteCount
;
2524 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2526 * If there is still data that will be used,
2527 * move it to the beginning.
2530 if (conn
->in
.notYetUsed
> 0)
2531 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2534 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2536 ConnStateData::checkHeaderLimits()
2538 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2539 return; // can accumulte more header data
2541 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2542 Config
.maxRequestHeaderSize
<< " bytes)");
2544 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2545 clientStreamNode
*node
= context
->getClientReplyContext();
2546 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2547 assert (repContext
);
2548 repContext
->setReplyToError(ERR_TOO_BIG
,
2549 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2550 clientConnection
->remote
, NULL
, NULL
, NULL
);
2551 context
->registerWithConn();
2552 context
->pullData();
2556 ConnStateData::clientAfterReadingRequests()
2558 // Were we expecting to read more request body from half-closed connection?
2559 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2560 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2561 clientConnection
->close();
2570 ConnStateData::quitAfterError(HttpRequest
*request
)
2572 // From HTTP p.o.v., we do not have to close after every error detected
2573 // at the client-side, but many such errors do require closure and the
2574 // client-side code is bad at handling errors so we play it safe.
2576 request
->flags
.proxyKeepalive
= false;
2577 flags
.readMore
= false;
2578 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2582 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2584 ClientHttpRequest
*http
= context
->http
;
2589 assert(sslServerBump
->entry
);
2590 // Did we create an error entry while processing CONNECT?
2591 if (!sslServerBump
->entry
->isEmpty()) {
2592 quitAfterError(http
->request
);
2594 // Get the saved error entry and send it to the client by replacing the
2595 // ClientHttpRequest store entry with it.
2596 clientStreamNode
*node
= context
->getClientReplyContext();
2597 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2599 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2600 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2602 // save the original request for logging purposes
2603 if (!context
->http
->al
->request
) {
2604 context
->http
->al
->request
= http
->request
;
2605 HTTPMSGLOCK(context
->http
->al
->request
);
2608 // Get error details from the fake certificate-peeking request.
2609 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2610 context
->pullData();
2614 // In bump-server-first mode, we have not necessarily seen the intended
2615 // server name at certificate-peeking time. Check for domain mismatch now,
2616 // when we can extract the intended name from the bumped HTTP request.
2617 if (sslServerBump
->serverCert
.get()) {
2618 HttpRequest
*request
= http
->request
;
2619 if (!Ssl::checkX509ServerValidity(sslServerBump
->serverCert
.get(), request
->GetHost())) {
2620 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2621 "does not match domainname " << request
->GetHost());
2623 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2624 check
.sslErrors
= new Ssl::Errors(SQUID_X509_V_ERR_DOMAIN_MISMATCH
);
2625 const bool allowDomainMismatch
=
2626 check
.fastCheck() == ACCESS_ALLOWED
;
2627 delete check
.sslErrors
;
2628 check
.sslErrors
= NULL
;
2630 if (!allowDomainMismatch
) {
2631 quitAfterError(request
);
2633 clientStreamNode
*node
= context
->getClientReplyContext();
2634 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2635 assert (repContext
);
2637 // Fill the server IP and hostname for error page generation.
2638 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2639 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2641 // Create an error object and fill it
2642 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2643 err
->src_addr
= clientConnection
->remote
;
2644 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2645 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2646 sslServerBump
->serverCert
.get(), NULL
);
2647 err
->detail
= errDetail
;
2648 // Save the original request for logging purposes.
2649 if (!context
->http
->al
->request
) {
2650 context
->http
->al
->request
= request
;
2651 HTTPMSGLOCK(context
->http
->al
->request
);
2653 repContext
->setReplyToError(request
->method
, err
);
2654 assert(context
->http
->out
.offset
== 0);
2655 context
->pullData();
2666 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2668 ClientHttpRequest
*http
= context
->http
;
2669 HttpRequest::Pointer request
;
2670 bool notedUseOfBuffer
= false;
2671 bool chunked
= false;
2672 bool mustReplyToOptions
= false;
2673 bool unsupportedTe
= false;
2674 bool expectBody
= false;
2676 /* We have an initial client stream in place should it be needed */
2677 /* setup our private context */
2679 context
->registerWithConn();
2681 if (context
->flags
.parsed_ok
== 0) {
2682 clientStreamNode
*node
= context
->getClientReplyContext();
2683 debugs(33, 2, "clientProcessRequest: Invalid Request");
2684 conn
->quitAfterError(NULL
);
2685 // setLogUri should called before repContext->setReplyToError
2686 setLogUri(http
, http
->uri
, true);
2687 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2688 assert (repContext
);
2689 switch (hp
->request_parse_status
) {
2690 case Http::scHeaderTooLarge
:
2691 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2693 case Http::scMethodNotAllowed
:
2694 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2695 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2698 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2699 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2701 assert(context
->http
->out
.offset
== 0);
2702 context
->pullData();
2707 assert(http
->request
);
2708 request
= http
->request
;
2709 notedUseOfBuffer
= true;
2711 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2712 clientStreamNode
*node
= context
->getClientReplyContext();
2713 debugs(33, 5, "Invalid URL: " << http
->uri
);
2714 conn
->quitAfterError(request
.getRaw());
2715 // setLogUri should called before repContext->setReplyToError
2716 setLogUri(http
, http
->uri
, true);
2717 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2718 assert (repContext
);
2719 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2720 assert(context
->http
->out
.offset
== 0);
2721 context
->pullData();
2725 /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */
2726 /* We currently only accept 0.9, 1.0, 1.1 */
2727 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2728 (http_ver
.major
== 1 && http_ver
.minor
> 1 ) ||
2729 (http_ver
.major
> 1) ) {
2731 clientStreamNode
*node
= context
->getClientReplyContext();
2732 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2733 conn
->quitAfterError(request
.getRaw());
2734 // setLogUri should called before repContext->setReplyToError
2735 setLogUri(http
, http
->uri
, true);
2736 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2737 assert (repContext
);
2738 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2739 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2740 assert(context
->http
->out
.offset
== 0);
2741 context
->pullData();
2745 /* compile headers */
2746 /* we should skip request line! */
2747 /* XXX should actually know the damned buffer size here */
2748 if (!conn
->isFtp
&& http_ver
.major
>= 1 &&
2749 !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2750 clientStreamNode
*node
= context
->getClientReplyContext();
2751 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2752 conn
->quitAfterError(request
.getRaw());
2753 // setLogUri should called before repContext->setReplyToError
2754 setLogUri(http
, http
->uri
, true);
2755 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2756 assert (repContext
);
2757 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2758 assert(context
->http
->out
.offset
== 0);
2759 context
->pullData();
2763 request
->clientConnectionManager
= conn
;
2765 request
->flags
.accelerated
= http
->flags
.accel
;
2766 request
->flags
.sslBumped
=conn
->switchedToHttps();
2767 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2768 // TODO: decouple http->flags.accel from request->flags.sslBumped
2769 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2770 !conn
->port
->allow_direct
: 0;
2772 if (request
->flags
.sslBumped
) {
2773 if (conn
->auth_user_request
!= NULL
)
2774 request
->auth_user_request
= conn
->auth_user_request
;
2779 * If transparent or interception mode is working clone the transparent and interception flags
2780 * from the port settings to the request.
2782 if (http
->clientConnection
!= NULL
) {
2783 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2784 request
->flags
.spoofClientIp
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2787 if (internalCheck(request
->urlpath
.termedBuf())) {
2788 if (internalHostnameIs(request
->GetHost()) &&
2789 request
->port
== getMyPort()) {
2790 http
->flags
.internal
= true;
2791 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2792 request
->SetHost(internalHostname());
2793 request
->port
= getMyPort();
2794 http
->flags
.internal
= true;
2798 if (http
->flags
.internal
) {
2799 request
->protocol
= AnyP::PROTO_HTTP
;
2800 request
->login
[0] = '\0';
2803 request
->flags
.internal
= http
->flags
.internal
;
2804 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2805 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2806 #if FOLLOW_X_FORWARDED_FOR
2807 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2808 // not a details about teh TCP connection itself
2809 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2810 #endif /* FOLLOW_X_FORWARDED_FOR */
2811 request
->my_addr
= conn
->clientConnection
->local
;
2812 request
->myportname
= conn
->port
->name
;
2813 request
->http_ver
= http_ver
;
2815 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2816 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2817 request
->clientConnectionManager
= conn
;
2819 if (request
->header
.chunked()) {
2821 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2822 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2823 // HTTP/1.1 requires chunking to be the last encoding if there is one
2824 unsupportedTe
= te
.size() && te
!= "identity";
2825 } // else implied identity coding
2827 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2828 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2829 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2830 clientStreamNode
*node
= context
->getClientReplyContext();
2831 conn
->quitAfterError(request
.getRaw());
2832 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2833 assert (repContext
);
2834 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2835 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2836 assert(context
->http
->out
.offset
== 0);
2837 context
->pullData();
2841 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2842 clientStreamNode
*node
= context
->getClientReplyContext();
2843 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2844 assert (repContext
);
2845 conn
->quitAfterError(request
.getRaw());
2846 repContext
->setReplyToError(ERR_INVALID_REQ
,
2847 Http::scLengthRequired
, request
->method
, NULL
,
2848 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2849 assert(context
->http
->out
.offset
== 0);
2850 context
->pullData();
2854 if (request
->header
.has(HDR_EXPECT
)) {
2855 const String expect
= request
->header
.getList(HDR_EXPECT
);
2856 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2857 if (!supportedExpect
) {
2858 clientStreamNode
*node
= context
->getClientReplyContext();
2859 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2860 assert (repContext
);
2861 conn
->quitAfterError(request
.getRaw());
2862 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2863 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2864 assert(context
->http
->out
.offset
== 0);
2865 context
->pullData();
2871 http
->request
= request
.getRaw();
2872 HTTPMSGLOCK(http
->request
);
2874 clientSetKeepaliveFlag(http
);
2876 // Let tunneling code be fully responsible for CONNECT requests
2877 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2878 context
->mayUseConnection(true);
2879 conn
->flags
.readMore
= false;
2883 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2887 /* Do we expect a request-body? */
2888 expectBody
= chunked
|| request
->content_length
> 0;
2889 if (!context
->mayUseConnection() && expectBody
) {
2890 request
->body_pipe
= conn
->expectRequestBody(
2891 chunked
? -1 : request
->content_length
);
2893 if (!notedUseOfBuffer
) {
2894 // consume header early so that body pipe gets just the body
2895 connNoteUseOfBuffer(conn
, http
->req_sz
);
2896 notedUseOfBuffer
= true;
2899 /* Is it too large? */
2900 if (!chunked
&& // if chunked, we will check as we accumulate
2901 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2902 clientStreamNode
*node
= context
->getClientReplyContext();
2903 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2904 assert (repContext
);
2905 conn
->quitAfterError(request
.getRaw());
2906 repContext
->setReplyToError(ERR_TOO_BIG
,
2907 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2908 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2909 assert(context
->http
->out
.offset
== 0);
2910 context
->pullData();
2915 // We may stop producing, comm_close, and/or call setReplyToError()
2916 // below, so quit on errors to avoid http->doCallouts()
2917 if (!conn
->handleRequestBodyData())
2920 if (!request
->body_pipe
->productionEnded()) {
2921 debugs(33, 5, HERE
<< "need more request body");
2922 context
->mayUseConnection(true);
2923 assert(conn
->flags
.readMore
);
2928 http
->calloutContext
= new ClientRequestContext(http
);
2933 if (!notedUseOfBuffer
)
2934 connNoteUseOfBuffer(conn
, http
->req_sz
);
2938 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2939 * to here because calling comm_reset_close() causes http to
2940 * be freed and the above connNoteUseOfBuffer() would hit an
2941 * assertion, not to mention that we were accessing freed memory.
2943 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
2944 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
2945 conn
->flags
.readMore
= false;
2946 comm_reset_close(conn
->clientConnection
);
2951 ConnStateData::processFtpRequest(ClientSocketContext
*const context
)
2953 ClientHttpRequest
*const http
= context
->http
;
2954 assert(http
!= NULL
);
2955 HttpRequest
*const request
= http
->request
;
2956 assert(request
!= NULL
);
2957 debugs(33, 9, request
);
2959 HttpHeader
&header
= request
->header
;
2960 assert(header
.has(HDR_FTP_COMMAND
));
2961 String
&cmd
= header
.findEntry(HDR_FTP_COMMAND
)->value
;
2962 assert(header
.has(HDR_FTP_ARGUMENTS
));
2963 String
¶ms
= header
.findEntry(HDR_FTP_ARGUMENTS
)->value
;
2965 const bool fwd
= !http
->storeEntry() &&
2966 FtpHandleRequest(context
, cmd
, params
);
2968 if (http
->storeEntry() != NULL
) {
2969 debugs(33, 4, "got an immediate response");
2970 assert(http
->storeEntry() != NULL
);
2971 clientSetKeepaliveFlag(http
);
2972 context
->pullData();
2974 debugs(33, 4, "forwarding request to server side");
2975 assert(http
->storeEntry() == NULL
);
2976 clientProcessRequest(this, &parser_
, context
, request
->method
,
2979 debugs(33, 4, "will resume processing later");
2984 ConnStateData::resumeFtpRequest(ClientSocketContext
*const context
)
2986 debugs(33, 4, "resuming");
2987 processFtpRequest(context
);
2991 connStripBufferWhitespace (ConnStateData
* conn
)
2993 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
2994 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
2995 -- conn
->in
.notYetUsed
;
3000 connOkToAddRequest(ConnStateData
* conn
)
3002 const int limit
= !conn
->isFtp
&& Config
.onoff
.pipeline_prefetch
? 2 : 1;
3003 const int result
= conn
->getConcurrentRequestCount() < limit
;
3006 debugs(33, 3, HERE
<< conn
->clientConnection
<< " max concurrent requests reached");
3007 debugs(33, 5, HERE
<< conn
->clientConnection
<< " defering new request until one is done");
3014 * Attempt to parse one or more requests from the input buffer.
3015 * If a request is successfully parsed, even if the next request
3016 * is only partially parsed, it will return TRUE.
3019 ConnStateData::clientParseRequests()
3021 HttpRequestMethod method
;
3022 bool parsed_req
= false;
3024 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
3026 // Loop while we have read bytes that are not needed for producing the body
3027 // On errors, bodyPipe may become nil, but readMore will be cleared
3028 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
3029 connStripBufferWhitespace(this);
3031 /* Don't try to parse if the buffer is empty */
3032 if (in
.notYetUsed
== 0)
3035 /* Limit the number of concurrent requests to 2 */
3036 if (!connOkToAddRequest(this)) {
3040 /* Should not be needed anymore */
3041 /* Terminate the string */
3042 in
.buf
[in
.notYetUsed
] = '\0';
3044 Http::ProtocolVersion http_ver
;
3045 ClientSocketContext
*context
= NULL
;
3047 /* Begin the parsing */
3048 PROF_start(parseHttpRequest
);
3049 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
3051 /* Process request */
3052 context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
3053 PROF_stop(parseHttpRequest
);
3055 context
= FtpParseRequest(this, &method
, &http_ver
);
3057 /* partial or incomplete request */
3059 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
3060 // (which becomes context) but checkHeaderLimits cannot?
3061 checkHeaderLimits();
3065 /* status -1 or 1 */
3067 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
3068 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3069 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
3070 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3073 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
3075 // Process FTP request asynchronously to make sure FTP
3076 // data connection accept callback is fired first.
3077 CallJobHere1(33, 4, CbcPointer
<ConnStateData
>(this),
3078 ConnStateData
, ConnStateData::processFtpRequest
, context
);
3081 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3083 if (context
->mayUseConnection()) {
3084 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3090 /* XXX where to 'finish' the parsing pass? */
3095 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3097 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3101 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
3103 if (io
.flag
== COMM_ERR_CLOSING
) {
3104 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
3108 assert(Comm::IsConnOpen(clientConnection
));
3109 assert(io
.conn
->fd
== clientConnection
->fd
);
3112 * Don't reset the timeout value here. The timeout value will be
3113 * set to Config.Timeout.request by httpAccept() and
3114 * clientWriteComplete(), and should apply to the request as a
3115 * whole, not individual read() calls. Plus, it breaks our
3116 * lame half-close detection
3118 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3119 notifyAllContexts(io
.xerrno
);
3124 if (io
.flag
== COMM_OK
) {
3126 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3128 // may comm_close or setReplyToError
3129 if (!handleReadData(io
.buf
, io
.size
))
3132 } else if (io
.size
== 0) {
3133 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3135 if (connFinishedWithConn(io
.size
)) {
3136 clientConnection
->close();
3140 /* It might be half-closed, we can't tell */
3141 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3143 commMarkHalfClosed(io
.conn
->fd
);
3145 fd_note(io
.conn
->fd
, "half-closed");
3147 /* There is one more close check at the end, to detect aborted
3148 * (partial) requests. At this point we can't tell if the request
3151 /* Continue to process previously read data */
3155 /* Process next request */
3156 if (getConcurrentRequestCount() == 0)
3157 fd_note(io
.fd
, "Reading next request");
3159 if (!clientParseRequests()) {
3163 * If the client here is half closed and we failed
3164 * to parse a request, close the connection.
3165 * The above check with connFinishedWithConn() only
3166 * succeeds _if_ the buffer is empty which it won't
3167 * be if we have an incomplete request.
3168 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3170 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3171 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3172 clientConnection
->close();
3180 clientAfterReadingRequests();
3184 ConnStateData::clientReadFtpData(const CommIoCbParams
&io
)
3186 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3187 Must(ftp
.reader
!= NULL
);
3190 assert(Comm::IsConnOpen(ftp
.dataConn
));
3191 assert(io
.conn
->fd
== ftp
.dataConn
->fd
);
3193 if (io
.flag
== COMM_OK
) {
3195 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3197 char *const current_buf
= ftp
.uploadBuf
+ ftp
.uploadAvailSize
;
3198 if (io
.buf
!= current_buf
)
3199 memmove(current_buf
, io
.buf
, io
.size
);
3200 ftp
.uploadAvailSize
+= io
.size
;
3201 handleFtpRequestData();
3202 } else if (io
.size
== 0) {
3203 debugs(33, 5, HERE
<< io
.conn
<< " closed");
3204 FtpCloseDataConnection(this);
3205 if (ftp
.uploadAvailSize
<= 0)
3206 finishDechunkingRequest(true);
3209 debugs(33, 5, HERE
<< io
.conn
<< " closed");
3210 FtpCloseDataConnection(this);
3211 finishDechunkingRequest(false);
3217 ConnStateData::handleFtpRequestData()
3219 assert(bodyPipe
!= NULL
);
3221 debugs(33,5, HERE
<< "handling FTP request data for " << clientConnection
);
3222 const size_t putSize
= bodyPipe
->putMoreData(ftp
.uploadBuf
,
3223 ftp
.uploadAvailSize
);
3225 ftp
.uploadAvailSize
-= putSize
;
3226 if (ftp
.uploadAvailSize
> 0)
3227 memmove(ftp
.uploadBuf
, ftp
.uploadBuf
+ putSize
, ftp
.uploadAvailSize
);
3230 if (Comm::IsConnOpen(ftp
.dataConn
))
3232 else if (ftp
.uploadAvailSize
<= 0)
3233 finishDechunkingRequest(true);
3237 * called when new request data has been read from the socket
3239 * \retval false called comm_close or setReplyToError (the caller should bail)
3240 * \retval true we did not call comm_close or setReplyToError
3243 ConnStateData::handleReadData(char *buf
, size_t size
)
3245 char *current_buf
= in
.addressToReadInto();
3247 if (buf
!= current_buf
)
3248 memmove(current_buf
, buf
, size
);
3250 in
.notYetUsed
+= size
;
3252 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3254 // if we are reading a body, stuff data into the body pipe
3255 if (bodyPipe
!= NULL
)
3256 return handleRequestBodyData();
3261 * called when new request body data has been buffered in in.buf
3262 * may close the connection if we were closing and piped everything out
3264 * \retval false called comm_close or setReplyToError (the caller should bail)
3265 * \retval true we did not call comm_close or setReplyToError
3268 ConnStateData::handleRequestBodyData()
3270 assert(bodyPipe
!= NULL
);
3274 if (in
.bodyParser
) { // chunked encoding
3275 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3276 abortChunkedRequestBody(error
);
3279 } else { // identity encoding
3280 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3281 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3282 if (!bodyPipe
->mayNeedMoreData()) {
3283 // BodyPipe will clear us automagically when we produced everything
3289 connNoteUseOfBuffer(this, putSize
);
3292 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3294 if (const char *reason
= stoppedSending()) {
3295 /* we've finished reading like good clients,
3296 * now do the close that initiateClose initiated.
3298 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3299 clientConnection
->close();
3307 /// parses available chunked encoded body bytes, checks size, returns errors
3309 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3311 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3313 try { // the parser will throw on errors
3315 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3318 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3319 // add one because MemBuf will assert if it cannot 0-terminate
3320 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3321 raw
.append(in
.buf
, in
.notYetUsed
);
3323 const mb_size_t wasContentSize
= raw
.contentSize();
3324 BodyPipeCheckout
bpc(*bodyPipe
);
3325 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3327 putSize
= wasContentSize
- raw
.contentSize();
3329 // dechunk then check: the size limit applies to _dechunked_ content
3330 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3334 finishDechunkingRequest(true);
3336 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3339 // if chunk parser needs data, then the body pipe must need it too
3340 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3342 // if parser needs more space and we can consume nothing, we will stall
3343 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3344 } catch (...) { // TODO: be more specific
3345 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3346 return ERR_INVALID_REQ
;
3349 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3353 /// quit on errors related to chunked request body handling
3355 ConnStateData::abortChunkedRequestBody(const err_type error
)
3357 finishDechunkingRequest(false);
3359 // XXX: The code below works if we fail during initial request parsing,
3360 // but if we fail when the server-side works already, the server may send
3361 // us its response too, causing various assertions. How to prevent that?
3362 #if WE_KNOW_HOW_TO_SEND_ERRORS
3363 ClientSocketContext::Pointer context
= getCurrentContext();
3364 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3365 clientStreamNode
*node
= context
->getClientReplyContext();
3366 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3368 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3369 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3370 repContext
->setReplyToError(error
, scode
,
3371 repContext
->http
->request
->method
,
3372 repContext
->http
->uri
,
3374 repContext
->http
->request
,
3376 context
->pullData();
3378 // close or otherwise we may get stuck as nobody will notice the error?
3379 comm_reset_close(clientConnection
);
3382 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3383 comm_reset_close(clientConnection
);
3385 flags
.readMore
= false;
3389 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3392 handleFtpRequestData();
3396 if (!handleRequestBodyData())
3399 // too late to read more body
3400 if (!isOpen() || stoppedReceiving())
3407 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3409 // request reader may get stuck waiting for space if nobody consumes body
3410 if (bodyPipe
!= NULL
)
3411 bodyPipe
->enableAutoConsumption();
3414 FtpCloseDataConnection(this);
3418 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3421 /** general lifetime handler for HTTP requests */
3423 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3425 #if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS
3426 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3428 if (COMMIO_FD_WRITECB(io
.fd
)->active
) {
3429 /* FIXME: If this code is reinstated, check the conn counters,
3430 * not the fd table state
3433 * Some data has been sent to the client, just close the FD
3435 clientConnection
->close();
3436 } else if (nrequests
) {
3438 * assume its a persistent connection; just close it
3440 clientConnection
->close();
3445 ClientHttpRequest
**H
;
3446 clientStreamNode
*node
;
3447 ClientHttpRequest
*http
= parseHttpRequestAbort(this, "error:Connection%20lifetime%20expired");
3448 node
= http
->client_stream
.tail
->prev
->data
;
3449 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3450 assert (repContext
);
3451 repContext
->setReplyToError(ERR_LIFETIME_EXP
,
3452 Http::scRequestTimeout
, Http::METHOD_NONE
, "N/A", &CachePeer
.sin_addr
,
3454 /* No requests can be outstanded */
3455 assert(chr
== NULL
);
3456 /* add to the client request queue */
3458 for (H
= &chr
; *H
; H
= &(*H
)->next
);
3461 clientStreamRead(http
->client_stream
.tail
->data
, http
, 0,
3462 HTTP_REQBUF_SZ
, context
->reqbuf
);
3465 * if we don't close() here, we still need a timeout handler!
3467 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3468 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3469 TimeoutDialer
, this, ConnStateData::requestTimeout
);
3470 commSetConnTimeout(io
.conn
, 30, timeoutCall
);
3473 * Aha, but we don't want a read handler!
3475 Comm::SetSelect(io
.fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
3480 * Just close the connection to not confuse browsers
3481 * using persistent connections. Some browsers opens
3482 * an connection and then does not use it until much
3483 * later (presumeably because the request triggering
3484 * the open has already been completed on another
3487 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3493 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3495 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3496 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3497 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3498 http
->al
->http
.timedout
= true;
3499 if (Comm::IsConnOpen(io
.conn
))
3504 connStateCreate(const Comm::ConnectionPointer
&client
, AnyP::PortCfg
*port
)
3506 ConnStateData
*result
= new ConnStateData(port
->protocol
);
3508 result
->clientConnection
= client
;
3509 result
->log_addr
= client
->remote
;
3510 result
->log_addr
.ApplyMask(Config
.Addrs
.client_netmask
);
3511 result
->in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &result
->in
.allocatedSize
);
3512 result
->port
= cbdataReference(port
);
3514 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3515 (result
->transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3516 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3517 int i
= IP_PMTUDISC_DONT
;
3518 if (setsockopt(client
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3519 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << client
<< " : " << xstrerror());
3521 static bool reported
= false;
3524 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3530 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3531 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, result
, ConnStateData::connStateClosed
);
3532 comm_add_close_handler(client
->fd
, call
);
3534 if (Config
.onoff
.log_fqdn
)
3535 fqdncache_gethostbyaddr(client
->remote
, FQDN_LOOKUP_IF_MISS
);
3538 if (Ident::TheConfig
.identLookup
) {
3539 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3540 identChecklist
.src_addr
= client
->remote
;
3541 identChecklist
.my_addr
= client
->local
;
3542 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3543 Ident::Start(client
, clientIdentDone
, result
);
3548 if (Eui::TheConfig
.euiLookup
) {
3549 if (client
->remote
.IsIPv4()) {
3550 result
->clientConnection
->remoteEui48
.lookup(client
->remote
);
3551 } else if (client
->remote
.IsIPv6()) {
3552 result
->clientConnection
->remoteEui64
.lookup(client
->remote
);
3557 clientdbEstablished(client
->remote
, 1);
3560 result
->flags
.readMore
= true;
3565 /** Handle a new connection on HTTP socket. */
3567 httpAccept(const CommAcceptCbParams
¶ms
)
3569 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3571 if (params
.flag
!= COMM_OK
) {
3572 // Its possible the call was still queued when the client disconnected
3573 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3577 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3578 fd_note(params
.conn
->fd
, "client http connect");
3580 if (s
->tcp_keepalive
.enabled
) {
3581 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3584 ++ incoming_sockets_accepted
;
3586 // Socket is ready, setup the connection manager to start using it
3587 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3589 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3590 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3591 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3592 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3594 connState
->readSomeData();
3597 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3599 if (Config
.onoff
.client_db
) {
3600 /* it was said several times that client write limiter does not work if client_db is disabled */
3602 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3603 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3605 // TODO: we check early to limit error response bandwith but we
3606 // should recheck when we can honor delay_pool_uses_indirect
3607 // TODO: we should also pass the port details for myportname here.
3608 ch
.src_addr
= params
.conn
->remote
;
3609 ch
.my_addr
= params
.conn
->local
;
3611 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3613 /* pools require explicit 'allow' to assign a client into them */
3614 if (pools
[pool
].access
) {
3615 ch
.accessList
= pools
[pool
].access
;
3616 allow_t answer
= ch
.fastCheck();
3617 if (answer
== ACCESS_ALLOWED
) {
3619 /* request client information from db after we did all checks
3620 this will save hash lookup if client failed checks */
3621 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3624 /* put client info in FDE */
3625 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3627 /* setup write limiter for this request */
3628 const double burst
= floor(0.5 +
3629 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3630 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3633 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3643 /** Create SSL connection structure and update fd_table */
3645 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3647 SSL
*ssl
= SSL_new(sslContext
);
3650 const int ssl_error
= ERR_get_error();
3651 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3656 SSL_set_fd(ssl
, conn
->fd
);
3657 fd_table
[conn
->fd
].ssl
= ssl
;
3658 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3659 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3661 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3662 fd_note(conn
->fd
, "client https start");
3667 /** negotiate an SSL connection */
3669 clientNegotiateSSL(int fd
, void *data
)
3671 ConnStateData
*conn
= (ConnStateData
*)data
;
3673 SSL
*ssl
= fd_table
[fd
].ssl
;
3676 if ((ret
= SSL_accept(ssl
)) <= 0) {
3677 int ssl_error
= SSL_get_error(ssl
, ret
);
3679 switch (ssl_error
) {
3681 case SSL_ERROR_WANT_READ
:
3682 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3685 case SSL_ERROR_WANT_WRITE
:
3686 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3689 case SSL_ERROR_SYSCALL
:
3692 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3698 if (errno
== ECONNRESET
)
3701 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3702 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3709 case SSL_ERROR_ZERO_RETURN
:
3710 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3715 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3716 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3717 " (" << ssl_error
<< "/" << ret
<< ")");
3725 if (SSL_session_reused(ssl
)) {
3726 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3727 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3729 if (do_debug(83, 4)) {
3730 /* Write out the SSL session details.. actually the call below, but
3731 * OpenSSL headers do strange typecasts confusing GCC.. */
3732 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3733 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3734 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
);
3736 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3738 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3739 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3740 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3741 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3742 * Because there are two possible usable cast, if you get an error here, try the other
3743 * commented line. */
3745 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3746 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3750 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3753 /* Note: This does not automatically fflush the log file.. */
3756 debugs(83, 2, "clientNegotiateSSL: New session " <<
3757 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3758 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3762 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3763 SSL_get_cipher(ssl
));
3765 client_cert
= SSL_get_peer_certificate(ssl
);
3767 if (client_cert
!= NULL
) {
3768 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3769 " client certificate: subject: " <<
3770 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3772 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3773 " client certificate: issuer: " <<
3774 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3776 X509_free(client_cert
);
3778 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3779 " has no certificate.");
3782 conn
->readSomeData();
3786 * If SSL_CTX is given, starts reading the SSL handshake.
3787 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3790 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3794 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3796 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3799 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3800 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3801 connState
, ConnStateData::requestTimeout
);
3802 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3805 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3807 char buf
[MAX_IPSTRLEN
];
3808 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3809 HttpRequest
*fakeRequest
= new HttpRequest
;
3810 fakeRequest
->SetHost(details
->local
.NtoA(buf
, sizeof(buf
)));
3811 fakeRequest
->port
= details
->local
.GetPort();
3812 fakeRequest
->clientConnectionManager
= connState
;
3813 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3814 #if FOLLOW_X_FORWARDED_FOR
3815 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3817 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3818 fakeRequest
->flags
.spoofClientIp
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3819 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3820 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3821 connState
->switchToHttps(fakeRequest
, bumpMode
);
3826 * A callback function to use with the ACLFilledChecklist callback.
3827 * In the case of ACCES_ALLOWED answer initializes a bumped SSL connection,
3828 * else reverts the connection to tunnel mode.
3831 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3833 ConnStateData
*connState
= (ConnStateData
*) data
;
3835 // if the connection is closed or closing, just return.
3836 if (!connState
->isOpen())
3839 // Require both a match and a positive bump mode to work around exceptional
3840 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3841 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3842 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3843 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3844 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3846 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3847 connState
->sslBumpMode
= Ssl::bumpNone
;
3849 // fake a CONNECT request to force connState to tunnel
3850 static char ip
[MAX_IPSTRLEN
];
3851 static char reqStr
[MAX_IPSTRLEN
+ 80];
3852 connState
->clientConnection
->local
.ToURL(ip
, sizeof(ip
));
3853 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, ip
);
3854 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3856 ret
= connState
->clientParseRequests();
3859 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3860 connState
->clientConnection
->close();
3865 /** handle a new HTTPS connection */
3867 httpsAccept(const CommAcceptCbParams
¶ms
)
3869 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3871 if (params
.flag
!= COMM_OK
) {
3872 // Its possible the call was still queued when the client disconnected
3873 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3877 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3878 fd_note(params
.conn
->fd
, "client https connect");
3880 if (s
->tcp_keepalive
.enabled
) {
3881 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3884 ++incoming_sockets_accepted
;
3886 // Socket is ready, setup the connection manager to start using it
3887 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3889 if (s
->flags
.tunnelSslBumping
) {
3890 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3892 if (!Config
.accessList
.ssl_bump
) {
3893 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3897 // Create a fake HTTP request for ssl_bump ACL check,
3898 // using tproxy/intercept provided destination IP and port.
3899 HttpRequest
*request
= new HttpRequest();
3900 static char ip
[MAX_IPSTRLEN
];
3901 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3902 request
->SetHost(params
.conn
->local
.NtoA(ip
, sizeof(ip
)));
3903 request
->port
= params
.conn
->local
.GetPort();
3904 request
->myportname
= s
->name
;
3906 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3907 acl_checklist
->src_addr
= params
.conn
->remote
;
3908 acl_checklist
->my_addr
= s
->s
;
3909 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3912 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3913 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3917 /** handle a new FTP connection */
3919 ftpAccept(const CommAcceptCbParams
¶ms
)
3921 AnyP::PortCfg
*s
= static_cast<AnyP::PortCfg
*>(params
.data
);
3923 if (params
.flag
!= COMM_OK
) {
3924 // Its possible the call was still queued when the client disconnected
3925 debugs(33, 2, "ftpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3929 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3930 fd_note(params
.conn
->fd
, "client ftp connect");
3932 if (s
->tcp_keepalive
.enabled
) {
3933 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3936 ++incoming_sockets_accepted
;
3938 // Socket is ready, setup the connection manager to start using it
3939 ConnStateData
*connState
= connStateCreate(params
.conn
, s
);
3941 if (connState
->transparent()) {
3942 char buf
[MAX_IPSTRLEN
];
3943 connState
->clientConnection
->local
.ToURL(buf
,MAX_IPSTRLEN
);
3944 connState
->ftp
.uri
= "ftp://";
3945 connState
->ftp
.uri
.append(buf
);
3946 connState
->ftp
.uri
.append("/");
3947 debugs(33, 5, HERE
<< "FTP transparent URL: " << connState
->ftp
.uri
);
3950 FtpWriteGreeting(connState
);
3954 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
3956 ConnStateData
* state_data
= (ConnStateData
*)(data
);
3957 state_data
->sslCrtdHandleReply(reply
);
3961 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
3963 if (reply
.result
== HelperReply::BrokenHelper
) {
3964 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
3965 } else if (!reply
.other().hasContent()) {
3966 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
3968 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
3969 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
3970 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
3972 if (reply
.result
!= HelperReply::Okay
) {
3973 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
3975 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
3976 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
3977 getSslContextDone(ctx
, true);
3982 getSslContextDone(NULL
);
3985 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
3987 certProperties
.commonName
= sslCommonName
.defined() ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
3989 // fake certificate adaptation requires bump-server-first mode
3990 if (!sslServerBump
) {
3991 assert(port
->signingCert
.get());
3992 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
3993 if (port
->signPkey
.get())
3994 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
3995 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
3999 // In case of an error while connecting to the secure server, use a fake
4000 // trusted certificate, with no mimicked fields and no adaptation
4001 // algorithms. There is nothing we can mimic so we want to minimize the
4002 // number of warnings the user will have to see to get to the error page.
4003 assert(sslServerBump
->entry
);
4004 if (sslServerBump
->entry
->isEmpty()) {
4005 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
4006 certProperties
.mimicCert
.resetAndLock(mimicCert
);
4008 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
4009 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
4010 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
4012 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
4013 // If the algorithm already set, then ignore it.
4014 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
4015 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
4016 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
4019 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
4020 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
4021 const char *param
= ca
->param
;
4023 // For parameterless CN adaptation, use hostname from the
4025 if (ca
->alg
== Ssl::algSetCommonName
) {
4027 param
= sslConnectHostOrIp
.termedBuf();
4028 certProperties
.commonName
= param
;
4029 certProperties
.setCommonName
= true;
4030 } else if (ca
->alg
== Ssl::algSetValidAfter
)
4031 certProperties
.setValidAfter
= true;
4032 else if (ca
->alg
== Ssl::algSetValidBefore
)
4033 certProperties
.setValidBefore
= true;
4035 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
4036 alg
<< " param: " << (param
? param
: "-"));
4040 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
4041 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
4042 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
4043 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
4047 } else {// if (!sslServerBump->entry->isEmpty())
4048 // Use trusted certificate for a Squid-generated error
4049 // or the user would have to add a security exception
4050 // just to see the error page. We will close the connection
4051 // so that the trust is not extended to non-Squid content.
4052 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
4055 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
4057 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
4058 assert(port
->untrustedSigningCert
.get());
4059 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
4060 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
4062 assert(port
->signingCert
.get());
4063 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
4065 if (port
->signPkey
.get())
4066 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
4068 signAlgorithm
= certProperties
.signAlgorithm
;
4072 ConnStateData::getSslContextStart()
4074 assert(areAllContextsForThisConnection());
4076 /* careful: freeAllContexts() above frees request, host, etc. */
4078 if (port
->generateHostCertificates
) {
4079 Ssl::CertificateProperties certProperties
;
4080 buildSslCertGenerationParams(certProperties
);
4081 sslBumpCertKey
= certProperties
.dbKey().c_str();
4082 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
4084 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
4085 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
4086 SSL_CTX
* dynCtx
= NULL
;
4087 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
.get(sslBumpCertKey
.termedBuf());
4088 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
4089 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
4090 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
4091 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
4092 getSslContextDone(dynCtx
);
4095 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
4096 ssl_ctx_cache
.del(sslBumpCertKey
.termedBuf());
4099 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
4104 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
4105 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
4106 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
4107 request_message
.composeRequest(certProperties
);
4108 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
4109 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
4111 } catch (const std::exception
&e
) {
4112 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
4113 "request for " << certProperties
.commonName
<<
4114 " certificate: " << e
.what() << "; will now block to " <<
4115 "generate that certificate.");
4116 // fall through to do blocking in-process generation.
4118 #endif // USE_SSL_CRTD
4120 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
4121 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
4122 getSslContextDone(dynCtx
, true);
4125 getSslContextDone(NULL
);
4129 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
4131 // Try to add generated ssl context to storage.
4132 if (port
->generateHostCertificates
&& isNew
) {
4134 if (signAlgorithm
== Ssl::algSignTrusted
)
4135 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
4136 //else it is self-signed or untrusted do not attrach any certificate
4138 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
4139 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
4141 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
4142 // If it is not in storage delete after using. Else storage deleted it.
4143 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
4146 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
4150 // If generated ssl context = NULL, try to use static ssl context.
4152 if (!port
->staticSslContext
) {
4153 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
4154 clientConnection
->close();
4157 debugs(33, 5, HERE
<< "Using static ssl context.");
4158 sslContext
= port
->staticSslContext
.get();
4162 if (!httpsCreate(clientConnection
, sslContext
))
4165 // commSetConnTimeout() was called for this request before we switched.
4167 // Disable the client read handler until CachePeer selection is complete
4168 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4169 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
4170 switchedToHttps_
= true;
4174 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
4176 assert(!switchedToHttps_
);
4178 sslConnectHostOrIp
= request
->GetHost();
4179 sslCommonName
= request
->GetHost();
4181 // We are going to read new request
4182 flags
.readMore
= true;
4183 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
4185 // If sslServerBump is set, then we have decided to deny CONNECT
4186 // and now want to switch to SSL to send the error to the client
4187 // without even peeking at the origin server certificate.
4188 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
4189 request
->flags
.sslPeek
= true;
4190 sslServerBump
= new Ssl::ServerBump(request
);
4192 // will call httpsPeeked() with certificate and connection, eventually
4193 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4197 // otherwise, use sslConnectHostOrIp
4198 getSslContextStart();
4202 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4204 Must(sslServerBump
!= NULL
);
4206 if (Comm::IsConnOpen(serverConnection
)) {
4207 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
4209 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
4210 assert(serverCert
.get() != NULL
);
4211 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4212 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4213 " bumped: " << *serverConnection
);
4215 pinConnection(serverConnection
, NULL
, NULL
, false);
4217 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4219 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4220 Ip::Address intendedDest
;
4221 intendedDest
= sslConnectHostOrIp
.termedBuf();
4222 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4224 // Squid serves its own error page and closes, so we want
4225 // a CN that causes no additional browser errors. Possible
4226 // only when bumping CONNECT with a user-typed address.
4227 if (intendedDest
.IsAnyAddr() || isConnectRequest
)
4228 sslCommonName
= sslConnectHostOrIp
;
4229 else if (sslServerBump
->serverCert
.get())
4230 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4232 // copy error detail from bump-server-first request to CONNECT request
4233 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4234 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4237 getSslContextStart();
4240 #endif /* USE_SSL */
4242 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4244 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4246 if (!Comm::IsConnOpen(c
)) {
4247 Must(NHttpSockets
> 0); // we tried to open some
4248 --NHttpSockets
; // there will be fewer sockets than planned
4249 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4251 if (!NHttpSockets
) // we could not open any listen sockets at all
4252 fatalf("Unable to open %s",FdNote(portType
));
4259 /// find any unused HttpSockets[] slot and store fd there or return false
4261 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4264 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4265 if ((found
= HttpSockets
[i
] < 0))
4266 HttpSockets
[i
] = conn
->fd
;
4272 clientHttpConnectionsOpen(void)
4274 AnyP::PortCfg
*s
= NULL
;
4276 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4277 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4278 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4279 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4284 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4285 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4286 s
->flags
.tunnelSslBumping
= false;
4289 if (s
->flags
.tunnelSslBumping
&&
4290 !s
->staticSslContext
&&
4291 !s
->generateHostCertificates
) {
4292 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4293 s
->flags
.tunnelSslBumping
= false;
4295 if (s
->flags
.tunnelSslBumping
) {
4296 // Create ssl_ctx cache for this port.
4297 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4301 // Fill out a Comm::Connection which IPC will open as a listener for us
4302 // then pass back when active so we can start a TcpAcceptor subscription.
4303 s
->listenConn
= new Comm::Connection
;
4304 s
->listenConn
->local
= s
->s
;
4305 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4307 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4308 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4309 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4310 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4312 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4313 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4314 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4316 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4323 clientHttpsConnectionsOpen(void)
4327 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4328 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4329 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4330 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4334 if (!s
->staticSslContext
) {
4335 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4336 " due to SSL initialization failure.");
4340 // TODO: merge with similar code in clientHttpConnectionsOpen()
4341 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4342 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4343 s
->flags
.tunnelSslBumping
= false;
4346 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4347 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4348 s
->flags
.tunnelSslBumping
= false;
4351 if (s
->flags
.tunnelSslBumping
) {
4352 // Create ssl_ctx cache for this port.
4353 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4356 // Fill out a Comm::Connection which IPC will open as a listener for us
4357 s
->listenConn
= new Comm::Connection
;
4358 s
->listenConn
->local
= s
->s
;
4359 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4360 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4362 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4363 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4364 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4365 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4367 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4368 ListeningStartedDialer(&clientListenerConnectionOpened
,
4369 s
, Ipc::fdnHttpsSocket
, sub
));
4370 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4371 HttpSockets
[NHttpSockets
] = -1;
4378 clientFtpConnectionsOpen(void)
4382 for (s
= Config
.Sockaddr
.ftp
; s
; s
= s
->next
) {
4383 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4384 debugs(1, DBG_IMPORTANT
, "Ignoring 'ftp_port' lines exceeding the limit.");
4385 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " FTP ports.");
4389 // Fill out a Comm::Connection which IPC will open as a listener for us
4390 s
->listenConn
= new Comm::Connection
;
4391 s
->listenConn
->local
= s
->s
;
4392 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4393 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4395 // setup the subscriptions such that new connections accepted by listenConn are handled by FTP
4396 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4397 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "ftpAccept", CommAcceptCbPtrFun(ftpAccept
, s
));
4398 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4400 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4401 ListeningStartedDialer(&clientListenerConnectionOpened
,
4402 s
, Ipc::fdnFtpSocket
, sub
));
4403 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnFtpSocket
, listenCall
);
4404 HttpSockets
[NHttpSockets
] = -1;
4409 /// process clientHttpConnectionsOpen result
4411 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4413 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4417 Must(Comm::IsConnOpen(s
->listenConn
));
4419 // TCP: setup a job to handle accept() with subscribed handler
4420 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4422 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4423 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4424 (s
->flags
.tproxyIntercept
? "TPROXY spoofing " : "") <<
4425 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4426 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4427 << FdNote(portTypeNote
) << " connections at "
4430 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4434 clientOpenListenSockets(void)
4436 clientHttpConnectionsOpen();
4438 clientHttpsConnectionsOpen();
4440 clientFtpConnectionsOpen();
4442 if (NHttpSockets
< 1)
4443 fatal("No HTTP, HTTPS or FTP ports configured");
4447 clientConnectionsClose(void)
4449 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4450 if (s
->listenConn
!= NULL
) {
4451 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4452 s
->listenConn
->close();
4453 s
->listenConn
= NULL
;
4458 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4459 if (s
->listenConn
!= NULL
) {
4460 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4461 s
->listenConn
->close();
4462 s
->listenConn
= NULL
;
4467 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.ftp
; s
; s
= s
->next
) {
4468 if (s
->listenConn
!= NULL
) {
4469 debugs(1, DBG_IMPORTANT
, "Closing FTP port " << s
->listenConn
->local
);
4470 s
->listenConn
->close();
4471 s
->listenConn
= NULL
;
4475 // TODO see if we can drop HttpSockets array entirely */
4476 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4477 HttpSockets
[i
] = -1;
4484 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4486 const char *vary
= request
->vary_headers
;
4487 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4488 #if X_ACCELERATOR_VARY
4491 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4494 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4496 /* Oops... something odd is going on here.. */
4497 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4498 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4499 safe_free(request
->vary_headers
);
4504 /* This is not a varying object */
4508 /* virtual "vary" object found. Calculate the vary key and
4509 * continue the search
4511 vary
= httpMakeVaryMark(request
, entry
->getReply());
4514 request
->vary_headers
= xstrdup(vary
);
4517 /* Ouch.. we cannot handle this kind of variance */
4518 /* XXX This cannot really happen, but just to be complete */
4523 vary
= httpMakeVaryMark(request
, entry
->getReply());
4526 request
->vary_headers
= xstrdup(vary
);
4530 /* Ouch.. we cannot handle this kind of variance */
4531 /* XXX This cannot really happen, but just to be complete */
4533 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4536 /* Oops.. we have already been here and still haven't
4537 * found the requested variant. Bail out
4539 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4540 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4546 ACLFilledChecklist
*
4547 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4549 ConnStateData
* conn
= http
->getConn();
4550 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4551 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4554 * hack for ident ACL. It needs to get full addresses, and a place to store
4555 * the ident result on persistent connections...
4557 /* connection oriented auth also needs these two lines for it's operation. */
4561 CBDATA_CLASS_INIT(ConnStateData
);
4563 ConnStateData::ConnStateData(const char *protocol
) :
4564 AsyncJob("ConnStateData"),
4565 isFtp(strcmp(protocol
, "ftp") == 0),
4567 sslBumpMode(Ssl::bumpEnd
),
4568 switchedToHttps_(false),
4569 sslServerBump(NULL
),
4571 stoppedSending_(NULL
),
4572 stoppedReceiving_(NULL
)
4574 pinning
.host
= NULL
;
4576 pinning
.pinned
= false;
4577 pinning
.auth
= false;
4578 pinning
.zeroReply
= false;
4579 pinning
.peer
= NULL
;
4583 ConnStateData::transparent() const
4585 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4589 ConnStateData::reading() const
4591 return reader
!= NULL
;
4595 ConnStateData::stopReading()
4598 comm_read_cancel(clientConnection
->fd
, reader
);
4604 ConnStateData::expectRequestBody(int64_t size
)
4606 bodyPipe
= new BodyPipe(this);
4608 bodyPipe
->setBodySize(size
);
4610 startDechunkingRequest();
4615 ConnStateData::mayNeedToReadMoreBody() const
4618 return 0; // request without a body or read/produced all body bytes
4620 if (!bodyPipe
->bodySizeKnown())
4621 return -1; // probably need to read more, but we cannot be sure
4623 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4624 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4626 if (needToProduce
<= haveAvailable
)
4627 return 0; // we have read what we need (but are waiting for pipe space)
4629 return needToProduce
- haveAvailable
;
4633 ConnStateData::stopReceiving(const char *error
)
4635 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4636 "; old sending error: " <<
4637 (stoppedSending() ? stoppedSending_
: "none"));
4639 if (const char *oldError
= stoppedReceiving()) {
4640 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4641 return; // nothing has changed as far as this connection is concerned
4644 stoppedReceiving_
= error
;
4646 if (const char *sendError
= stoppedSending()) {
4647 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4648 clientConnection
->close();
4653 ConnStateData::expectNoForwarding()
4655 if (bodyPipe
!= NULL
) {
4656 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4657 bodyPipe
->expectNoConsumption();
4661 /// initialize dechunking state
4663 ConnStateData::startDechunkingRequest()
4665 Must(bodyPipe
!= NULL
);
4666 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4667 assert(!in
.bodyParser
);
4668 in
.bodyParser
= new ChunkedCodingParser
;
4671 /// put parsed content into input buffer and clean up
4673 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4675 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4677 if (bodyPipe
!= NULL
) {
4678 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4679 BodyPipe::Pointer myPipe
= bodyPipe
;
4680 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4681 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4683 Must(myPipe
->bodySizeKnown());
4684 ClientSocketContext::Pointer context
= getCurrentContext();
4685 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4686 context
->http
->request
->setContentLength(myPipe
->bodySize());
4690 delete in
.bodyParser
;
4691 in
.bodyParser
= NULL
;
4695 ConnStateData::In::addressToReadInto() const
4697 return buf
+ notYetUsed
;
4700 ConnStateData::In::In() : bodyParser(NULL
),
4701 buf (NULL
), notYetUsed (0), allocatedSize (0)
4704 ConnStateData::In::~In()
4707 memFreeBuf(allocatedSize
, buf
);
4708 delete bodyParser
; // TODO: pool
4712 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4715 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4719 ClientSocketContext::Pointer context
= getCurrentContext();
4720 if (context
!= NULL
) {
4721 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4725 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4726 clientConnection
->close();
4729 /// Our close handler called by Comm when the pinned connection is closed
4731 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4733 // FwdState might repin a failed connection sooner than this close
4734 // callback is called for the failed connection.
4735 assert(pinning
.serverConnection
== io
.conn
);
4736 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4737 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4740 debugs(33, 3, "Closing client connection on pinned zero reply.");
4741 clientConnection
->close();
4746 debugs(33, 5, HERE << "FTP server connection closed, closing client "
4748 clientConnection->close();
4754 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4756 char desc
[FD_DESC_SZ
];
4758 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4759 if (pinning
.serverConnection
->fd
== pinServer
->fd
)
4763 unpinConnection(); // closes pinned connection, if any, and resets fields
4765 pinning
.serverConnection
= pinServer
;
4767 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4769 // when pinning an SSL bumped connection, the request may be NULL
4770 const char *pinnedHost
= "[unknown]";
4772 pinning
.host
= xstrdup(request
->GetHost());
4773 pinning
.port
= request
->port
;
4774 pinnedHost
= pinning
.host
;
4776 pinning
.port
= pinServer
->remote
.GetPort();
4778 pinning
.pinned
= true;
4780 pinning
.peer
= cbdataReference(aPeer
);
4781 pinning
.auth
= auth
;
4782 char stmp
[MAX_IPSTRLEN
];
4783 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4784 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4785 clientConnection
->remote
.ToURL(stmp
,MAX_IPSTRLEN
),
4786 clientConnection
->fd
);
4787 fd_note(pinning
.serverConnection
->fd
, desc
);
4789 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4790 pinning
.closeHandler
= JobCallback(33, 5,
4791 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4792 // remember the pinned connection so that cb does not unpin a fresher one
4793 typedef CommCloseCbParams Params
;
4794 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4795 params
.conn
= pinning
.serverConnection
;
4796 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4799 const Comm::ConnectionPointer
4800 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4802 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4805 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4807 if (pinning
.auth
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0) {
4810 if (request
&& pinning
.port
!= request
->port
) {
4813 if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
)) {
4816 if (aPeer
!= pinning
.peer
) {
4821 /* The pinning info is not safe, remove any pinning info */
4825 return pinning
.serverConnection
;
4829 ConnStateData::unpinConnection()
4831 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4834 cbdataReferenceDone(pinning
.peer
);
4836 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4837 if (pinning
.closeHandler
!= NULL
) {
4838 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4839 pinning
.closeHandler
= NULL
;
4841 /// also close the server side socket, we should not use it for any future requests...
4842 // TODO: do not close if called from our close handler?
4843 pinning
.serverConnection
->close();
4846 safe_free(pinning
.host
);
4848 pinning
.zeroReply
= false;
4850 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4851 * connection has gone away */
4856 FtpAcceptDataConnection(const CommAcceptCbParams
¶ms
)
4858 ConnStateData
*connState
= static_cast<ConnStateData
*>(params
.data
);
4860 if (params
.flag
!= COMM_OK
) {
4861 // Its possible the call was still queued when the client disconnected
4862 debugs(33, 2, HERE
<< connState
->ftp
.dataListenConn
<< ": accept "
4863 "failure: " << xstrerr(params
.xerrno
));
4867 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
4868 fd_note(params
.conn
->fd
, "client ftp data connect");
4869 ++incoming_sockets_accepted
;
4871 FtpCloseDataConnection(connState
);
4872 connState
->ftp
.dataConn
= params
.conn
;
4873 connState
->ftp
.uploadAvailSize
= 0;
4877 FtpCloseDataConnection(ConnStateData
*conn
)
4879 if (Comm::IsConnOpen(conn
->ftp
.dataListenConn
)) {
4880 debugs(33, 5, HERE
<< "FTP closing client data listen socket: " <<
4881 *conn
->ftp
.dataListenConn
);
4882 conn
->ftp
.dataListenConn
->close();
4884 conn
->ftp
.dataListenConn
= NULL
;
4886 if (Comm::IsConnOpen(conn
->ftp
.dataConn
)) {
4887 debugs(33, 5, HERE
<< "FTP closing client data connection: " <<
4888 *conn
->ftp
.dataConn
);
4889 conn
->ftp
.dataConn
->close();
4891 conn
->ftp
.dataConn
= NULL
;
4892 conn
->ftp
.reader
= NULL
;
4896 FtpWriteGreeting(ConnStateData
*conn
)
4899 const String msg
= "220 Service ready\r\n";
4900 mb
.init(msg
.size(), msg
.size());
4901 mb
.append(msg
.rawBuf(), msg
.size());
4903 AsyncCall::Pointer call
= commCbCall(33, 5, "FtpWroteEarlyReply",
4904 CommIoCbPtrFun(&FtpWroteEarlyReply
, conn
));
4905 Comm::Write(conn
->clientConnection
, &mb
, call
);
4909 FtpWriteEarlyReply(ConnStateData
*connState
, const int code
, const char *msg
)
4911 debugs(33, 7, HERE
<< code
<< ' ' << msg
);
4912 assert(99 < code
&& code
< 1000);
4916 mb
.Printf("%i %s\r\n", code
, msg
);
4918 AsyncCall::Pointer call
= commCbCall(33, 5, "FtpWroteEarlyReply",
4919 CommIoCbPtrFun(&FtpWroteEarlyReply
, connState
));
4920 Comm::Write(connState
->clientConnection
, &mb
, call
);
4922 connState
->flags
.readMore
= false;
4926 FtpWriteReply(ClientSocketContext
*context
, MemBuf
&mb
)
4928 debugs(11, 2, "FTP Client " << context
->clientConnection
);
4929 debugs(11, 2, "FTP Client REPLY:\n---------\n" << mb
.buf
<<
4932 AsyncCall::Pointer call
= commCbCall(33, 5, "FtpWroteReply",
4933 CommIoCbPtrFun(&FtpWroteReply
, context
));
4934 Comm::Write(context
->clientConnection
, &mb
, call
);
4938 FtpWriteCustomReply(ClientSocketContext
*context
, const int code
, const char *msg
, const HttpReply
*reply
)
4940 debugs(33, 7, HERE
<< code
<< ' ' << msg
);
4941 assert(99 < code
&& code
< 1000);
4943 const bool sendDetails
= reply
!= NULL
&&
4944 reply
->header
.has(HDR_FTP_STATUS
) && reply
->header
.has(HDR_FTP_REASON
);
4949 mb
.Printf("%i-%s\r\n", code
, msg
);
4950 mb
.Printf(" Server reply:\r\n");
4951 FtpPrintReply(mb
, reply
, " ");
4952 mb
.Printf("%i \r\n", code
);
4954 mb
.Printf("%i %s\r\n", code
, msg
);
4956 FtpWriteReply(context
, mb
);
4959 /** Parse an FTP request
4961 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
4962 * to 1 if the request was correctly parsed.
4963 * \param[in] connState a ConnStateData. The caller must make sure it is not null
4964 * \param[out] mehtod_p will be set as a side-effect of the parsing.
4965 * Pointed-to value will be set to Http::METHOD_NONE in case of
4967 * \param[out] http_ver will be set as a side-effect of the parsing
4968 * \return NULL on incomplete requests,
4969 * a ClientSocketContext structure on success or failure.
4971 static ClientSocketContext
*
4972 FtpParseRequest(ConnStateData
*connState
, HttpRequestMethod
*method_p
, Http::ProtocolVersion
*http_ver
)
4974 *http_ver
= Http::ProtocolVersion(1, 1);
4976 const char *const eor
=
4977 static_cast<const char *>(memchr(connState
->in
.buf
, '\n',
4978 min(connState
->in
.notYetUsed
, Config
.maxRequestHeaderSize
)));
4979 const size_t req_sz
= eor
+ 1 - connState
->in
.buf
;
4981 if (eor
== NULL
&& connState
->in
.notYetUsed
>= Config
.maxRequestHeaderSize
) {
4982 connState
->ftp
.state
= ConnStateData::FTP_ERROR
;
4983 FtpWriteEarlyReply(connState
, 421, "Too large request");
4988 debugs(33, 5, HERE
<< "Incomplete request, waiting for end of request");
4992 connNoteUseOfBuffer(connState
, req_sz
);
4994 // skip leading whitespaces
4995 const char *boc
= connState
->in
.buf
;
4996 while (boc
< eor
&& isspace(*boc
)) ++boc
;
4998 debugs(33, 5, HERE
<< "Empty request, ignoring");
5002 const char *eoc
= boc
;
5003 while (eoc
< eor
&& !isspace(*eoc
)) ++eoc
;
5004 connState
->in
.buf
[eoc
- connState
->in
.buf
] = '\0';
5006 const char *bop
= eoc
+ 1;
5007 while (bop
< eor
&& isspace(*bop
)) ++bop
;
5009 const char *eop
= eor
- 1;
5010 while (isspace(*eop
)) --eop
;
5012 connState
->in
.buf
[eop
+ 1 - connState
->in
.buf
] = '\0';
5016 debugs(33, 7, HERE
<< "Parsed FTP command " << boc
<< " with " <<
5017 (bop
== NULL
? "no " : "") << "parameters" <<
5018 (bop
!= NULL
? ": " : "") << bop
);
5020 const String cmd
= boc
;
5021 String params
= bop
;
5023 *method_p
= !cmd
.caseCmp("APPE") || !cmd
.caseCmp("STOR") ||
5024 !cmd
.caseCmp("STOU") ? Http::METHOD_PUT
: Http::METHOD_GET
;
5026 if (connState
->ftp
.uri
.size() == 0) {
5027 // the first command must be USER
5028 if (cmd
.caseCmp("USER") != 0) {
5029 FtpWriteEarlyReply(connState
, 530, "Must login first");
5033 if (params
.size() == 0) {
5034 FtpWriteEarlyReply(connState
, 501, "Missing username");
5039 // We need to process USER request now because it sets request URI.
5040 if (cmd
.caseCmp("USER") == 0 &&
5041 !FtpHandleUserRequest(connState
, cmd
, params
))
5044 assert(connState
->ftp
.uri
.size() > 0);
5045 char *uri
= xstrdup(connState
->ftp
.uri
.termedBuf());
5046 HttpRequest
*const request
=
5047 HttpRequest::CreateFromUrlAndMethod(uri
, *method_p
);
5048 if (request
== NULL
) {
5049 debugs(33, 5, HERE
<< "Invalid FTP URL: " << connState
->ftp
.uri
);
5050 FtpWriteEarlyReply(connState
, 501, "Invalid host");
5051 connState
->ftp
.uri
.clean();
5056 request
->http_ver
= *http_ver
;
5057 request
->header
.putStr(HDR_FTP_COMMAND
, cmd
.termedBuf());
5058 request
->header
.putStr(HDR_FTP_ARGUMENTS
, params
.termedBuf() != NULL
?
5059 params
.termedBuf() : "");
5060 if (*method_p
== Http::METHOD_PUT
)
5061 request
->header
.putStr(HDR_TRANSFER_ENCODING
, "chunked");
5063 ClientHttpRequest
*const http
= new ClientHttpRequest(connState
);
5064 http
->request
= request
;
5065 HTTPMSGLOCK(http
->request
);
5066 http
->req_sz
= req_sz
;
5069 ClientSocketContext
*const result
=
5070 ClientSocketContextNew(connState
->clientConnection
, http
);
5072 StoreIOBuffer tempBuffer
;
5073 tempBuffer
.data
= result
->reqbuf
;
5074 tempBuffer
.length
= HTTP_REQBUF_SZ
;
5076 ClientStreamData newServer
= new clientReplyContext(http
);
5077 ClientStreamData newClient
= result
;
5078 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
5079 clientReplyStatus
, newServer
, clientSocketRecipient
,
5080 clientSocketDetach
, newClient
, tempBuffer
);
5082 result
->registerWithConn();
5083 result
->flags
.parsed_ok
= 1;
5084 connState
->flags
.readMore
= false;
5089 FtpHandleReply(ClientSocketContext
*context
, HttpReply
*reply
, StoreIOBuffer data
)
5091 static FtpReplyHandler
*handlers
[] = {
5093 NULL
, // FTP_CONNECTED
5094 FtpHandlePasvReply
, // FTP_HANDLE_PASV
5095 FtpHandlePortReply
, // FTP_HANDLE_PORT
5096 FtpHandleDataReply
, // FTP_HANDLE_DATA_REQUEST
5097 FtpHandleUploadReply
, // FTP_HANDLE_DATA_REQUEST
5098 FtpHandleErrorReply
// FTP_ERROR
5100 const ConnStateData::FtpState state
= context
->getConn()->ftp
.state
;
5101 FtpReplyHandler
*const handler
= handlers
[state
];
5103 (*handler
)(context
, reply
, data
);
5105 FtpWriteForwardedReply(context
, reply
);
5109 FtpHandlePasvReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5111 if (context
->http
->request
->errType
!= ERR_NONE
) {
5112 FtpWriteCustomReply(context
, 502, "Server does not support PASV", reply
);
5116 FtpCloseDataConnection(context
->getConn());
5118 Comm::ConnectionPointer conn
= new Comm::Connection
;
5119 ConnStateData
* const connState
= context
->getConn();
5120 conn
->flags
= COMM_NONBLOCKING
;
5121 conn
->local
= connState
->transparent() ?
5122 connState
->port
->s
: context
->clientConnection
->local
;
5123 conn
->local
.SetPort(0);
5124 const char *const note
= connState
->ftp
.uri
.termedBuf();
5125 comm_open_listener(SOCK_STREAM
, IPPROTO_TCP
, conn
, note
);
5126 if (!Comm::IsConnOpen(conn
)) {
5127 debugs(5, DBG_CRITICAL
, HERE
<< "comm_open_listener failed:" <<
5128 conn
->local
<< " error: " << errno
);
5129 FtpWriteCustomReply(context
, 451, "Internal error");
5133 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
5134 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "FtpAcceptDataConnection",
5135 CommAcceptCbPtrFun(FtpAcceptDataConnection
, connState
));
5136 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
5137 AsyncJob::Start(new Comm::TcpAcceptor(conn
, note
, sub
));
5139 connState
->ftp
.dataListenConn
= conn
;
5141 char addr
[MAX_IPSTRLEN
];
5142 // remote server in interception setups and local address otherwise
5143 const Ip::Address
&server
= connState
->transparent() ?
5144 context
->clientConnection
->local
: conn
->local
;
5145 server
.NtoA(addr
, MAX_IPSTRLEN
, AF_INET
);
5146 addr
[MAX_IPSTRLEN
- 1] = '\0';
5147 for (char *c
= addr
; *c
!= '\0'; ++c
) {
5152 // conn->fd is the client data connection (and its local port)
5153 const unsigned short port
= comm_local_port(conn
->fd
);
5154 conn
->local
.SetPort(port
);
5156 // In interception setups, we combine remote server address with a
5157 // local port number and hope that traffic will be redirected to us.
5160 mb
.Printf("227 =%s,%i,%i\r\n", addr
, static_cast<int>(port
>> 8),
5161 static_cast<int>(port
% 256));
5163 debugs(11, 3, Raw("writing", mb
.buf
, mb
.size
));
5164 FtpWriteReply(context
, mb
);
5168 FtpHandlePortReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5170 if (context
->http
->request
->errType
!= ERR_NONE
) {
5171 FtpWriteCustomReply(context
, 502, "Server does not support PASV (converted from PORT)", reply
);
5175 FtpWriteCustomReply(context
, 200, "PORT successfully converted to PASV.");
5177 // and wait for RETR
5181 FtpHandleErrorReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5184 ConnStateData
*const connState
= context
->getConn();
5185 if (!connState
->pinning
.pinned
) { // we failed to connect to server
5186 connState
->ftp
.uri
.clean();
5190 const char *const msg
= err_type_str
[context
->http
->request
->errType
];
5191 FtpWriteCustomReply(context
, code
, msg
, reply
);
5195 FtpHandleDataReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5197 if (reply
!= NULL
&& reply
->sline
.status() != Http::scOkay
) {
5198 FtpWriteForwardedReply(context
, reply
);
5202 debugs(33, 7, HERE
<< data
.length
);
5204 ConnStateData
*const conn
= context
->getConn();
5206 if (data
.length
<= 0) {
5207 FtpWroteReplyData(conn
->clientConnection
, NULL
, 0, COMM_OK
, 0, context
);
5211 if (!Comm::IsConnOpen(conn
->ftp
.dataConn
)) {
5212 debugs(33, 3, HERE
<< "got FTP reply data when client data connection "
5213 "is closed, ignoring");
5218 mb
.init(data
.length
+ 1, data
.length
+ 1);
5219 mb
.append(data
.data
, data
.length
);
5221 AsyncCall::Pointer call
= commCbCall(33, 5, "FtpWroteReplyData",
5222 CommIoCbPtrFun(&FtpWroteReplyData
, context
));
5223 Comm::Write(conn
->ftp
.dataConn
, &mb
, call
);
5225 context
->noteSentBodyBytes(data
.length
);
5229 FtpWroteReplyData(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
5231 if (errflag
== COMM_ERR_CLOSING
)
5234 ClientSocketContext
*const context
= static_cast<ClientSocketContext
*>(data
);
5235 ConnStateData
*const connState
= context
->getConn();
5237 if (errflag
!= COMM_OK
) {
5238 debugs(33, 3, HERE
<< "FTP reply data writing failed: " <<
5240 FtpCloseDataConnection(connState
);
5241 FtpWriteCustomReply(context
, 426, "Data connection error; transfer aborted");
5245 switch (context
->socketState()) {
5247 context
->pullData();
5249 case STREAM_COMPLETE
:
5250 debugs(33, 3, HERE
<< "FTP reply data transfer successfully complete");
5251 FtpWriteCustomReply(context
, 226, "Transfer complete");
5253 case STREAM_UNPLANNED_COMPLETE
:
5254 debugs(33, 3, HERE
<< "FTP reply data transfer failed: STREAM_UNPLANNED_COMPLETE");
5255 FtpWriteCustomReply(context
, 451, "Server error; transfer aborted");
5258 debugs(33, 3, HERE
<< "FTP reply data transfer failed: STREAM_FAILED");
5259 FtpWriteCustomReply(context
, 451, "Server error; transfer aborted");
5262 fatal("unreachable code");
5265 FtpCloseDataConnection(connState
);
5269 FtpHandleUploadReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5271 FtpWriteForwardedReply(context
, reply
);
5275 FtpWriteForwardedReply(ClientSocketContext
*context
, const HttpReply
*reply
)
5277 const AsyncCall::Pointer call
= commCbCall(33, 5, "FtpWroteReply",
5278 CommIoCbPtrFun(&FtpWroteReply
, context
));
5279 FtpWriteForwardedReply(context
, reply
, call
);
5283 FtpWriteForwardedReply(ClientSocketContext
*context
, const HttpReply
*reply
, AsyncCall::Pointer call
)
5285 assert(reply
!= NULL
);
5286 const HttpHeader
&header
= reply
->header
;
5287 ConnStateData
*const connState
= context
->getConn();
5289 if (!header
.has(HDR_FTP_STATUS
)) {
5290 // Reply without FTP-Status header may come from ICAP or ACL.
5291 connState
->ftp
.state
= ConnStateData::FTP_ERROR
;
5292 FtpWriteCustomReply(context
, 421, reply
->sline
.reason());
5296 assert(header
.has(HDR_FTP_REASON
));
5298 const int status
= header
.getInt(HDR_FTP_STATUS
);
5299 debugs(33, 7, HERE
<< "status: " << status
);
5301 if (status
== 150 && connState
->ftp
.state
==
5302 ConnStateData::FTP_HANDLE_UPLOAD_REQUEST
)
5303 connState
->readSomeFtpData();
5307 FtpPrintReply(mb
, reply
);
5309 debugs(11, 2, "FTP Client " << context
->clientConnection
);
5310 debugs(11, 2, "FTP Client REPLY:\n---------\n" << mb
.buf
<<
5313 Comm::Write(context
->clientConnection
, &mb
, call
);
5317 FtpPrintReply(MemBuf
&mb
, const HttpReply
*reply
, const char *const prefix
)
5319 const HttpHeader
&header
= reply
->header
;
5322 if (header
.has(HDR_FTP_STATUS
))
5323 snprintf(status
, sizeof(status
), "%i", header
.getInt(HDR_FTP_STATUS
));
5327 HttpHeaderPos pos
= HttpHeaderInitPos
;
5328 const HttpHeaderEntry
*e
= header
.getEntry(&pos
);
5330 const HttpHeaderEntry
*const next
= header
.getEntry(&pos
);
5331 if (e
->id
== HDR_FTP_REASON
) {
5332 const bool isLastLine
= next
== NULL
|| next
->id
!= HDR_FTP_REASON
;
5333 const int separator
= status
[0] == '\0' || isLastLine
? ' ' : '-';
5334 mb
.Printf("%s%s%c%s\r\n", prefix
, status
, separator
,
5335 e
->value
.termedBuf());
5342 FtpWroteEarlyReply(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
5344 if (errflag
== COMM_ERR_CLOSING
)
5347 if (errflag
!= COMM_OK
) {
5348 debugs(33, 3, HERE
<< "FTP reply writing failed: " << xstrerr(xerrno
));
5353 ConnStateData
*const connState
= static_cast<ConnStateData
*>(data
);
5354 connState
->flags
.readMore
= true;
5355 connState
->readSomeData();
5359 FtpWroteReply(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
5361 if (errflag
== COMM_ERR_CLOSING
)
5364 if (errflag
!= COMM_OK
) {
5365 debugs(33, 3, HERE
<< "FTP reply writing failed: " <<
5371 ClientSocketContext
*const context
=
5372 static_cast<ClientSocketContext
*>(data
);
5373 ConnStateData
*const connState
= context
->getConn();
5375 if (connState
->ftp
.state
== ConnStateData::FTP_ERROR
||
5376 context
->socketState() != STREAM_COMPLETE
) {
5381 assert(context
->socketState() == STREAM_COMPLETE
);
5382 connState
->flags
.readMore
= true;
5383 connState
->ftp
.state
= ConnStateData::FTP_CONNECTED
;
5384 if (connState
->in
.bodyParser
)
5385 connState
->finishDechunkingRequest(false);
5386 context
->keepaliveNextRequest();
5390 FtpHandleRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
) {
5391 if (HttpRequest
*request
= context
->http
->request
) {
5392 MemBuf
*mb
= new MemBuf
;
5395 packerToMemInit(&p
, mb
);
5399 debugs(11, 2, "FTP Client " << context
->clientConnection
);
5400 debugs(11, 2, "FTP Client REQUEST:\n---------\n" << mb
->buf
<<
5405 static std::pair
<const char *, FtpRequestHandler
*> handlers
[] = {
5406 std::make_pair("LIST", FtpHandleDataRequest
),
5407 std::make_pair("NLST", FtpHandleDataRequest
),
5408 std::make_pair("PASV", FtpHandlePasvRequest
),
5409 std::make_pair("PORT", FtpHandlePortRequest
),
5410 std::make_pair("RETR", FtpHandleDataRequest
)
5413 FtpRequestHandler
*handler
= NULL
;
5414 if (context
->http
->request
->method
== Http::METHOD_PUT
)
5415 handler
= FtpHandleUploadRequest
;
5417 for (size_t i
= 0; i
< sizeof(handlers
) / sizeof(*handlers
); ++i
) {
5418 if (cmd
.caseCmp(handlers
[i
].first
) == 0) {
5419 handler
= handlers
[i
].second
;
5425 return handler
!= NULL
? (*handler
)(context
, cmd
, params
) : true;
5429 FtpHandleUserRequest(ConnStateData
*connState
, const String
&cmd
, String
¶ms
)
5431 if (params
.size() == 0) {
5432 FtpWriteEarlyReply(connState
, 501, "Missing username");
5436 const String::size_type eou
= params
.rfind('@');
5437 if (eou
== String::npos
|| eou
+ 1 >= params
.size()) {
5438 if (connState
->ftp
.uri
.size() > 0)
5440 FtpWriteEarlyReply(connState
, 501, "Missing host");
5444 static const String scheme
= "ftp://";
5445 const String host
= params
.substr(eou
+ 1, params
.size());
5446 String uri
= scheme
;
5450 if (connState
->ftp
.uri
.size() == 0)
5451 connState
->ftp
.uri
= uri
;
5452 else if (uri
.caseCmp(connState
->ftp
.uri
) != 0) {
5453 debugs(11, 3, "expected " << connState
->ftp
.uri
);
5454 debugs(11, 3, " but got " << uri
);
5455 FtpWriteEarlyReply(connState
, 501, "Cannot change host");
5465 FtpHandlePasvRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
)
5467 if (params
.size() > 0) {
5468 FtpSetReply(context
, 501, "Unexpected parameter");
5472 context
->getConn()->ftp
.state
= ConnStateData::FTP_HANDLE_PASV
;
5477 #include "FtpServer.h" /* XXX: For Ftp::ParseIpPort() */
5480 FtpHandlePortRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
)
5482 if (!params
.size()) {
5483 FtpSetReply(context
, 501, "Missing parameter");
5487 Ip::Address cltAddr
;
5488 if (!Ftp::ParseIpPort(params
.termedBuf(), NULL
, cltAddr
)) {
5489 FtpSetReply(context
, 501, "Invalid parameter");
5493 FtpCloseDataConnection(context
->getConn());
5494 debugs(11, 3, "will actively connect to " << cltAddr
);
5496 Comm::ConnectionPointer conn
= new Comm::Connection();
5497 conn
->remote
= cltAddr
;
5499 // TODO: should we use getOutgoingAddress() here instead?
5500 if (conn
->remote
.IsIPv4())
5501 conn
->local
.SetIPv4();
5503 // RFC 959 requires active FTP connections to originate from port 20
5504 // but that would preclude us from supporting concurrent transfers! (XXX?)
5505 // conn->flags |= COMM_DOBIND;
5506 // conn->local.SetPort(20);
5508 context
->getConn()->ftp
.dataConn
= conn
;
5509 context
->getConn()->ftp
.uploadAvailSize
= 0; // XXX: FtpCloseDataConnection should do that
5511 context
->getConn()->ftp
.state
= ConnStateData::FTP_HANDLE_PORT
;
5513 // convert client PORT command to Squid PASV command because Squid
5514 // does not support active FTP transfers on the server side (yet?)
5515 ClientHttpRequest
*const http
= context
->http
;
5516 assert(http
!= NULL
);
5517 HttpRequest
*const request
= http
->request
;
5518 assert(request
!= NULL
);
5519 HttpHeader
&header
= request
->header
;
5520 header
.delById(HDR_FTP_COMMAND
);
5521 header
.putStr(HDR_FTP_COMMAND
, "PASV");
5522 header
.delById(HDR_FTP_ARGUMENTS
);
5523 header
.putStr(HDR_FTP_ARGUMENTS
, "");
5524 return true; // forward our fake PASV request
5528 FtpHandleDataRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
)
5530 if (!FtpCheckDataConnection(context
))
5533 context
->getConn()->ftp
.state
= ConnStateData::FTP_HANDLE_DATA_REQUEST
;
5539 FtpHandleUploadRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
)
5541 if (!FtpCheckDataConnection(context
))
5544 context
->getConn()->ftp
.state
= ConnStateData::FTP_HANDLE_UPLOAD_REQUEST
;
5550 FtpCheckDataConnection(ClientSocketContext
*context
)
5552 ConnStateData
*const connState
= context
->getConn();
5553 if (Comm::IsConnOpen(connState
->ftp
.dataConn
))
5556 if (Comm::IsConnOpen(connState
->ftp
.dataListenConn
)) {
5557 FtpSetReply(context
, 425, "Data connection is not established");
5561 if (connState
->ftp
.dataConn
->remote
.IsAnyAddr()) {
5562 // XXX: use client address and default port instead.
5563 FtpSetReply(context
, 425, "Use PORT first");
5567 // active transfer: open a connection from Squid to client
5568 AsyncCall::Pointer connector
= context
->getConn()->ftp
.connector
=
5569 commCbCall(17, 3, "FtpConnectDoneWrapper",
5570 CommConnectCbPtrFun(FtpHandleConnectDone
, context
));
5572 Comm::ConnOpener
*cs
= new Comm::ConnOpener(connState
->ftp
.dataConn
,
5574 Config
.Timeout
.connect
);
5575 AsyncJob::Start(cs
);
5576 return false; // ConnStateData::processFtpRequest waits FtpHandleConnectDone
5580 FtpHandleConnectDone(const Comm::ConnectionPointer
&conn
, comm_err_t status
, int xerrno
, void *data
)
5582 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
5583 context
->getConn()->ftp
.connector
= NULL
;
5585 if (status
!= COMM_OK
) {
5587 FtpSetReply(context
, 425, "Cannot open data connection.");
5588 assert(context
->http
&& context
->http
->storeEntry() != NULL
);
5590 context
->getConn()->ftp
.dataConn
= conn
;
5591 context
->getConn()->ftp
.uploadAvailSize
= 0;
5592 assert(Comm::IsConnOpen(context
->getConn()->ftp
.dataConn
));
5594 context
->getConn()->resumeFtpRequest(context
);
5598 FtpSetReply(ClientSocketContext
*context
, const int code
, const char *msg
)
5600 ClientHttpRequest
*const http
= context
->http
;
5601 assert(http
!= NULL
);
5602 assert(http
->storeEntry() == NULL
);
5604 HttpReply
*const reply
= new HttpReply
;
5605 reply
->sline
.set(Http::ProtocolVersion(1, 1), Http::scNoContent
);
5606 HttpHeader
&header
= reply
->header
;
5607 header
.putTime(HDR_DATE
, squid_curtime
);
5613 header
.putInt64(HDR_CONTENT_LENGTH
, 0);
5614 header
.putInt(HDR_FTP_STATUS
, code
);
5615 header
.putStr(HDR_FTP_REASON
, msg
);
5616 reply
->hdrCacheInit();
5618 setLogUri(http
, http
->uri
, true);
5620 clientStreamNode
*const node
= context
->getClientReplyContext();
5621 clientReplyContext
*const repContext
=
5622 dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
5623 assert(repContext
!= NULL
);
5624 repContext
->createStoreEntry(http
->request
->method
, RequestFlags());
5625 http
->storeEntry()->replaceHttpReply(reply
);