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"
104 #include "fqdncache.h"
105 #include "FwdState.h"
108 #include "HttpHdrCc.h"
109 #include "HttpHdrContRange.h"
110 #include "HttpHeaderTools.h"
111 #include "HttpReply.h"
112 #include "HttpRequest.h"
113 #include "ident/Config.h"
114 #include "ident/Ident.h"
115 #include "internal.h"
116 #include "ipc/FdNotes.h"
117 #include "ipc/StartListening.h"
118 #include "log/access_log.h"
121 #include "MemObject.h"
122 #include "mime_header.h"
123 #include "profiler/Profiler.h"
125 #include "SquidConfig.h"
126 #include "SquidTime.h"
127 #include "StatCounters.h"
128 #include "StatHist.h"
130 #include "TimeOrTag.h"
135 #include "auth/UserRequest.h"
138 #include "ClientInfo.h"
141 #include "ssl/ProxyCerts.h"
142 #include "ssl/context_storage.h"
143 #include "ssl/helper.h"
144 #include "ssl/ServerBump.h"
145 #include "ssl/support.h"
146 #include "ssl/gadgets.h"
149 #include "ssl/crtd_message.h"
150 #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
);
199 /* Local functions */
200 /* ClientSocketContext */
201 static ClientSocketContext
*ClientSocketContextNew(const Comm::ConnectionPointer
&clientConn
, ClientHttpRequest
*);
203 static IOCB clientWriteComplete
;
204 static IOCB clientWriteBodyComplete
;
205 static IOACB httpAccept
;
207 static IOACB httpsAccept
;
209 static IOACB ftpAccept
;
210 static CTCB clientLifetimeTimeout
;
211 static ClientSocketContext
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
212 static ClientSocketContext
*parseHttpRequest(ConnStateData
*, HttpParser
*, HttpRequestMethod
*, Http::ProtocolVersion
*);
214 static IDCB clientIdentDone
;
216 static CSCB clientSocketRecipient
;
217 static CSD clientSocketDetach
;
218 static void clientSetKeepaliveFlag(ClientHttpRequest
*);
219 static int clientIsContentLengthValid(HttpRequest
* r
);
220 static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
);
222 static void clientUpdateStatHistCounters(LogTags logType
, int svc_time
);
223 static void clientUpdateStatCounters(LogTags logType
);
224 static void clientUpdateHierCounters(HierarchyLogEntry
*);
225 static bool clientPingHasFinished(ping_data
const *aPing
);
226 void prepareLogWithRequestDetails(HttpRequest
*, AccessLogEntry::Pointer
&);
228 static bool connIsUsable(ConnStateData
* conn
);
230 static int responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const &receivedData
);
231 static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
);
232 static void clientUpdateSocketStats(LogTags logType
, size_t size
);
234 char *skipLeadingSpace(char *aString
);
235 static void connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
);
237 static IOACB FtpAcceptDataConnection
;
238 static void FtpCloseDataConnection(ConnStateData
*conn
);
239 static ClientSocketContext
*FtpParseRequest(ConnStateData
*connState
, HttpRequestMethod
*method_p
, Http::ProtocolVersion
*http_ver
);
240 static bool FtpHandleUserRequest(ConnStateData
*connState
, const String
&cmd
, String
¶ms
);
241 static CNCB FtpHandleConnectDone
;
243 static void FtpHandleReply(ClientSocketContext
*context
, HttpReply
*reply
, StoreIOBuffer data
);
244 typedef void FtpReplyHandler(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
);
245 static FtpReplyHandler FtpHandleFeatReply
;
246 static FtpReplyHandler FtpHandlePasvReply
;
247 static FtpReplyHandler FtpHandlePortReply
;
248 static FtpReplyHandler FtpHandleErrorReply
;
249 static FtpReplyHandler FtpHandleDataReply
;
250 static FtpReplyHandler FtpHandleUploadReply
;
252 static void FtpWriteEarlyReply(ConnStateData
*conn
, const int code
, const char *msg
);
253 static void FtpWriteReply(ClientSocketContext
*context
, MemBuf
&mb
);
254 static void FtpWriteCustomReply(ClientSocketContext
*context
, const int code
, const char *msg
, const HttpReply
*reply
= NULL
);
255 static void FtpWriteForwardedReply(ClientSocketContext
*context
, const HttpReply
*reply
);
256 static void FtpWriteForwardedReply(ClientSocketContext
*context
, const HttpReply
*reply
, AsyncCall::Pointer call
);
257 static void FtpWriteErrorReply(ClientSocketContext
*context
, const HttpReply
*reply
, const int status
);
259 static void FtpPrintReply(MemBuf
&mb
, const HttpReply
*reply
, const char *const prefix
= "");
260 static IOCB FtpWroteEarlyReply
;
261 static IOCB FtpWroteReply
;
262 static IOCB FtpWroteReplyData
;
264 typedef bool FtpRequestHandler(ClientSocketContext
*context
, String
&cmd
, String
¶ms
);
265 static FtpRequestHandler FtpHandleRequest
;
266 static FtpRequestHandler FtpHandleFeatRequest
;
267 static FtpRequestHandler FtpHandlePasvRequest
;
268 static FtpRequestHandler FtpHandlePortRequest
;
269 static FtpRequestHandler FtpHandleDataRequest
;
270 static FtpRequestHandler FtpHandleUploadRequest
;
272 static bool FtpCheckDataConnPre(ClientSocketContext
*context
);
273 static bool FtpCheckDataConnPost(ClientSocketContext
*context
);
274 static void FtpSetReply(ClientSocketContext
*context
, const int code
, const char *msg
);
275 static bool FtpSupportedCommand(const String
&name
);
279 ClientSocketContext::getTail() const
281 if (http
->client_stream
.tail
)
282 return (clientStreamNode
*)http
->client_stream
.tail
->data
;
288 ClientSocketContext::getClientReplyContext() const
290 return (clientStreamNode
*)http
->client_stream
.tail
->prev
->data
;
294 ClientSocketContext::getConn() const
296 return http
->getConn();
300 * This routine should be called to grow the inbuf and then
304 ConnStateData::readSomeData()
309 debugs(33, 4, HERE
<< clientConnection
<< ": reading request...");
311 if (!maybeMakeSpaceAvailable())
314 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
315 reader
= JobCallback(33, 5, Dialer
, this, ConnStateData::clientReadRequest
);
316 comm_read(clientConnection
, in
.addressToReadInto(), getAvailableBufferLength(), reader
);
320 ConnStateData::readSomeFtpData()
322 if (ftp
.reader
!= NULL
)
325 const size_t availSpace
= sizeof(ftp
.uploadBuf
) - ftp
.uploadAvailSize
;
329 debugs(33, 4, HERE
<< ftp
.dataConn
<< ": reading FTP data...");
331 typedef CommCbMemFunT
<ConnStateData
, CommIoCbParams
> Dialer
;
332 ftp
.reader
= JobCallback(33, 5, Dialer
, this,
333 ConnStateData::clientReadFtpData
);
334 comm_read(ftp
.dataConn
, ftp
.uploadBuf
+ ftp
.uploadAvailSize
, availSpace
,
339 ClientSocketContext::removeFromConnectionList(ConnStateData
* conn
)
341 ClientSocketContext::Pointer
*tempContextPointer
;
342 assert(conn
!= NULL
&& cbdataReferenceValid(conn
));
343 assert(conn
->getCurrentContext() != NULL
);
344 /* Unlink us from the connection request list */
345 tempContextPointer
= & conn
->currentobject
;
347 while (tempContextPointer
->getRaw()) {
348 if (*tempContextPointer
== this)
351 tempContextPointer
= &(*tempContextPointer
)->next
;
354 assert(tempContextPointer
->getRaw() != NULL
);
355 *tempContextPointer
= next
;
359 ClientSocketContext::~ClientSocketContext()
361 clientStreamNode
*node
= getTail();
364 ClientSocketContext
*streamContext
= dynamic_cast<ClientSocketContext
*> (node
->data
.getRaw());
367 /* We are *always* the tail - prevent recursive free */
368 assert(this == streamContext
);
374 deRegisterWithConn();
376 httpRequestFree(http
);
378 /* clean up connection links to us */
379 assert(this != next
.getRaw());
383 ClientSocketContext::registerWithConn()
385 assert (!connRegistered_
);
387 assert (http
->getConn() != NULL
);
388 connRegistered_
= true;
389 http
->getConn()->addContextToQueue(this);
393 ClientSocketContext::deRegisterWithConn()
395 assert (connRegistered_
);
396 removeFromConnectionList(http
->getConn());
397 connRegistered_
= false;
401 ClientSocketContext::connIsFinished()
404 assert (http
->getConn() != NULL
);
405 deRegisterWithConn();
406 /* we can't handle any more stream data - detach */
407 clientStreamDetach(getTail(), http
);
410 ClientSocketContext::ClientSocketContext() : http(NULL
), reply(NULL
), next(NULL
),
412 mayUseConnection_ (false),
413 connRegistered_ (false)
415 memset (reqbuf
, '\0', sizeof (reqbuf
));
418 deferredparams
.node
= NULL
;
419 deferredparams
.rep
= NULL
;
422 ClientSocketContext
*
423 ClientSocketContextNew(const Comm::ConnectionPointer
&client
, ClientHttpRequest
* http
)
425 ClientSocketContext
*newContext
;
426 assert(http
!= NULL
);
427 newContext
= new ClientSocketContext
;
428 newContext
->http
= http
;
429 newContext
->clientConnection
= client
;
434 ClientSocketContext::writeControlMsg(HttpControlMsg
&msg
)
436 const HttpReply::Pointer
rep(msg
.reply
);
439 // remember the callback
440 cbControlMsgSent
= msg
.cbSuccess
;
442 AsyncCall::Pointer call
= commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
443 CommIoCbPtrFun(&WroteControlMsg
, this));
445 if (getConn()->isFtp
) {
446 FtpWriteForwardedReply(this, rep
.getRaw(), call
);
450 // apply selected clientReplyContext::buildReplyHeader() mods
451 // it is not clear what headers are required for control messages
452 rep
->header
.removeHopByHopEntries();
453 rep
->header
.putStr(HDR_CONNECTION
, "keep-alive");
454 httpHdrMangleList(&rep
->header
, http
->request
, ROR_REPLY
);
456 MemBuf
*mb
= rep
->pack();
458 debugs(11, 2, "HTTP Client " << clientConnection
);
459 debugs(11, 2, "HTTP Client CONTROL MSG:\n---------\n" << mb
->buf
<< "\n----------");
461 Comm::Write(clientConnection
, mb
, call
);
466 /// called when we wrote the 1xx response
468 ClientSocketContext::wroteControlMsg(const Comm::ConnectionPointer
&conn
, char *, size_t, comm_err_t errflag
, int xerrno
)
470 if (errflag
== COMM_ERR_CLOSING
)
473 if (errflag
== COMM_OK
) {
474 ScheduleCallHere(cbControlMsgSent
);
478 debugs(33, 3, HERE
<< "1xx writing failed: " << xstrerr(xerrno
));
479 // no error notification: see HttpControlMsg.h for rationale and
480 // note that some errors are detected elsewhere (e.g., close handler)
482 // close on 1xx errors to be conservative and to simplify the code
483 // (if we do not close, we must notify the source of a failure!)
487 /// wroteControlMsg() wrapper: ClientSocketContext is not an AsyncJob
489 ClientSocketContext::WroteControlMsg(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
491 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
492 context
->wroteControlMsg(conn
, bufnotused
, size
, errflag
, xerrno
);
497 clientIdentDone(const char *ident
, void *data
)
499 ConnStateData
*conn
= (ConnStateData
*)data
;
500 xstrncpy(conn
->clientConnection
->rfc931
, ident
? ident
: dash_str
, USER_IDENT_SZ
);
505 clientUpdateStatCounters(LogTags logType
)
507 ++statCounter
.client_http
.requests
;
509 if (logTypeIsATcpHit(logType
))
510 ++statCounter
.client_http
.hits
;
512 if (logType
== LOG_TCP_HIT
)
513 ++statCounter
.client_http
.disk_hits
;
514 else if (logType
== LOG_TCP_MEM_HIT
)
515 ++statCounter
.client_http
.mem_hits
;
519 clientUpdateStatHistCounters(LogTags logType
, int svc_time
)
521 statCounter
.client_http
.allSvcTime
.count(svc_time
);
523 * The idea here is not to be complete, but to get service times
524 * for only well-defined types. For example, we don't include
525 * LOG_TCP_REFRESH_FAIL because its not really a cache hit
526 * (we *tried* to validate it, but failed).
531 case LOG_TCP_REFRESH_UNMODIFIED
:
532 statCounter
.client_http
.nearHitSvcTime
.count(svc_time
);
535 case LOG_TCP_IMS_HIT
:
536 statCounter
.client_http
.nearMissSvcTime
.count(svc_time
);
541 case LOG_TCP_MEM_HIT
:
543 case LOG_TCP_OFFLINE_HIT
:
544 statCounter
.client_http
.hitSvcTime
.count(svc_time
);
549 case LOG_TCP_CLIENT_REFRESH_MISS
:
550 statCounter
.client_http
.missSvcTime
.count(svc_time
);
554 /* make compiler warnings go away */
560 clientPingHasFinished(ping_data
const *aPing
)
562 if (0 != aPing
->stop
.tv_sec
&& 0 != aPing
->start
.tv_sec
)
569 clientUpdateHierCounters(HierarchyLogEntry
* someEntry
)
573 switch (someEntry
->code
) {
574 #if USE_CACHE_DIGESTS
579 ++ statCounter
.cd
.times_used
;
587 case FIRST_PARENT_MISS
:
589 case CLOSEST_PARENT_MISS
:
590 ++ statCounter
.icp
.times_used
;
591 i
= &someEntry
->ping
;
593 if (clientPingHasFinished(i
))
594 statCounter
.icp
.querySvcTime
.count(tvSubUsec(i
->start
, i
->stop
));
597 ++ statCounter
.icp
.query_timeouts
;
604 ++ statCounter
.netdb
.times_used
;
614 ClientHttpRequest::updateCounters()
616 clientUpdateStatCounters(logType
);
618 if (request
->errType
!= ERR_NONE
)
619 ++ statCounter
.client_http
.errors
;
621 clientUpdateStatHistCounters(logType
,
622 tvSubMsec(start_time
, current_time
));
624 clientUpdateHierCounters(&request
->hier
);
628 prepareLogWithRequestDetails(HttpRequest
* request
, AccessLogEntry::Pointer
&aLogEntry
)
631 assert(aLogEntry
!= NULL
);
633 if (Config
.onoff
.log_mime_hdrs
) {
637 packerToMemInit(&p
, &mb
);
638 request
->header
.packInto(&p
);
639 //This is the request after adaptation or redirection
640 aLogEntry
->headers
.adapted_request
= xstrdup(mb
.buf
);
642 // the virgin request is saved to aLogEntry->request
643 if (aLogEntry
->request
) {
646 packerToMemInit(&p
, &mb
);
647 aLogEntry
->request
->header
.packInto(&p
);
648 aLogEntry
->headers
.request
= xstrdup(mb
.buf
);
652 const Adaptation::History::Pointer ah
= request
->adaptLogHistory();
656 packerToMemInit(&p
, &mb
);
657 ah
->lastMeta
.packInto(&p
);
658 aLogEntry
->adapt
.last_meta
= xstrdup(mb
.buf
);
667 const Adaptation::Icap::History::Pointer ih
= request
->icapHistory();
669 aLogEntry
->icap
.processingTime
= ih
->processingTime();
672 aLogEntry
->http
.method
= request
->method
;
673 aLogEntry
->http
.version
= request
->http_ver
;
674 aLogEntry
->hier
= request
->hier
;
675 if (request
->content_length
> 0) // negative when no body or unknown length
676 aLogEntry
->cache
.requestSize
+= request
->content_length
;
677 aLogEntry
->cache
.extuser
= request
->extacl_user
.termedBuf();
679 // Adapted request, if any, inherits and then collects all the stats, but
680 // the virgin request gets logged instead; copy the stats to log them.
681 // TODO: avoid losses by keeping these stats in a shared history object?
682 if (aLogEntry
->request
) {
683 aLogEntry
->request
->dnsWait
= request
->dnsWait
;
684 aLogEntry
->request
->errType
= request
->errType
;
685 aLogEntry
->request
->errDetail
= request
->errDetail
;
690 ClientHttpRequest::logRequest()
692 if (!out
.size
&& !logType
)
693 debugs(33, 5, HERE
<< "logging half-baked transaction: " << log_uri
);
695 al
->icp
.opcode
= ICP_INVALID
;
697 debugs(33, 9, "clientLogRequest: al.url='" << al
->url
<< "'");
700 al
->http
.code
= al
->reply
->sline
.status();
701 al
->http
.content_type
= al
->reply
->content_type
.termedBuf();
702 } else if (loggingEntry() && loggingEntry()->mem_obj
) {
703 al
->http
.code
= loggingEntry()->mem_obj
->getReply()->sline
.status();
704 al
->http
.content_type
= loggingEntry()->mem_obj
->getReply()->content_type
.termedBuf();
707 debugs(33, 9, "clientLogRequest: http.code='" << al
->http
.code
<< "'");
709 if (loggingEntry() && loggingEntry()->mem_obj
&& loggingEntry()->objectLen() >= 0)
710 al
->cache
.objectSize
= loggingEntry()->contentLen();
712 al
->cache
.caddr
.setNoAddr();
714 if (getConn() != NULL
) {
715 al
->cache
.caddr
= getConn()->log_addr
;
716 al
->cache
.port
= cbdataReference(getConn()->port
);
719 al
->cache
.requestSize
= req_sz
;
720 al
->cache
.requestHeadersSize
= req_sz
;
722 al
->cache
.replySize
= out
.size
;
723 al
->cache
.replyHeadersSize
= out
.headers_sz
;
725 al
->cache
.highOffset
= out
.offset
;
727 al
->cache
.code
= logType
;
729 al
->cache
.msec
= tvSubMsec(start_time
, current_time
);
732 prepareLogWithRequestDetails(request
, al
);
734 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
&& getConn()->clientConnection
->rfc931
[0])
735 al
->cache
.rfc931
= getConn()->clientConnection
->rfc931
;
739 /* This is broken. Fails if the connection has been closed. Needs
740 * to snarf the ssl details some place earlier..
742 if (getConn() != NULL
)
743 al
->cache
.ssluser
= sslGetUserEmail(fd_table
[getConn()->fd
].ssl
);
748 // The al->notes and request->notes must point to the same object.
749 // Enable the following assertion to check for possible bugs.
750 // assert(request->notes == al->notes);
751 typedef Notes::iterator ACAMLI
;
752 for (ACAMLI i
= Config
.notes
.begin(); i
!= Config
.notes
.end(); ++i
) {
753 if (const char *value
= (*i
)->match(request
, al
->reply
)) {
754 NotePairs
¬es
= SyncNotes(*al
, *request
);
755 notes
.add((*i
)->key
.termedBuf(), value
);
756 debugs(33, 3, HERE
<< (*i
)->key
.termedBuf() << " " << value
);
760 ACLFilledChecklist
checklist(NULL
, request
, NULL
);
762 checklist
.reply
= al
->reply
;
763 HTTPMSGLOCK(checklist
.reply
);
767 al
->adapted_request
= request
;
768 HTTPMSGLOCK(al
->adapted_request
);
770 accessLogLog(al
, &checklist
);
772 bool updatePerformanceCounters
= true;
773 if (Config
.accessList
.stats_collection
) {
774 ACLFilledChecklist
statsCheck(Config
.accessList
.stats_collection
, request
, NULL
);
776 statsCheck
.reply
= al
->reply
;
777 HTTPMSGLOCK(statsCheck
.reply
);
779 updatePerformanceCounters
= (statsCheck
.fastCheck() == ACCESS_ALLOWED
);
782 if (updatePerformanceCounters
) {
786 if (getConn() != NULL
&& getConn()->clientConnection
!= NULL
)
787 clientdbUpdate(getConn()->clientConnection
->remote
, logType
, AnyP::PROTO_HTTP
, out
.size
);
792 ClientHttpRequest::freeResources()
796 safe_free(redirect
.location
);
797 range_iter
.boundary
.clean();
798 HTTPMSGUNLOCK(request
);
800 if (client_stream
.tail
)
801 clientStreamAbort((clientStreamNode
*)client_stream
.tail
->data
, this);
805 httpRequestFree(void *data
)
807 ClientHttpRequest
*http
= (ClientHttpRequest
*)data
;
808 assert(http
!= NULL
);
813 ConnStateData::areAllContextsForThisConnection() const
815 assert(this != NULL
);
816 ClientSocketContext::Pointer context
= getCurrentContext();
818 while (context
.getRaw()) {
819 if (context
->http
->getConn() != this)
822 context
= context
->next
;
829 ConnStateData::freeAllContexts()
831 ClientSocketContext::Pointer context
;
833 while ((context
= getCurrentContext()).getRaw() != NULL
) {
834 assert(getCurrentContext() !=
835 getCurrentContext()->next
);
836 context
->connIsFinished();
837 assert (context
!= currentobject
);
841 /// propagates abort event to all contexts
843 ConnStateData::notifyAllContexts(int xerrno
)
845 typedef ClientSocketContext::Pointer CSCP
;
846 for (CSCP c
= getCurrentContext(); c
.getRaw(); c
= c
->next
)
847 c
->noteIoError(xerrno
);
850 /* This is a handler normally called by comm_close() */
851 void ConnStateData::connStateClosed(const CommCloseCbParams
&io
)
853 deleteThis("ConnStateData::connStateClosed");
858 ConnStateData::setAuth(const Auth::UserRequest::Pointer
&aur
, const char *by
)
862 debugs(33, 2, "Adding connection-auth to " << clientConnection
<< " from " << by
);
868 // clobered with self-pointer
869 // NP: something nasty is going on in Squid, but harmless.
871 debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection
<< " from " << by
);
876 * Connection-auth relies on a single set of credentials being preserved
877 * for all requests on a connection once they have been setup.
878 * There are several things which need to happen to preserve security
879 * when connection-auth credentials change unexpectedly or are unset.
881 * 1) auth helper released from any active state
883 * They can only be reserved by a handshake process which this
884 * connection can now never complete.
885 * This prevents helpers hanging when their connections close.
887 * 2) pinning is expected to be removed and server conn closed
889 * The upstream link is authenticated with the same credentials.
890 * Expecting the same level of consistency we should have received.
891 * This prevents upstream being faced with multiple or missing
892 * credentials after authentication.
893 * NP: un-pin is left to the cleanup in ConnStateData::swanSong()
894 * we just trigger that cleanup here via comm_reset_close() or
895 * ConnStateData::stopReceiving()
897 * 3) the connection needs to close.
899 * This prevents attackers injecting requests into a connection,
900 * or gateways wrongly multiplexing users into a single connection.
902 * When credentials are missing closure needs to follow an auth
903 * challenge for best recovery by the client.
905 * When credentials change there is nothing we can do but abort as
906 * fast as possible. Sending TCP RST instead of an HTTP response
907 * is the best-case action.
910 // clobbered with nul-pointer
912 debugs(33, 2, "WARNING: Graceful closure on " << clientConnection
<< " due to connection-auth erase from " << by
);
913 auth_
->releaseAuthServer();
915 // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
916 // NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
917 // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
918 stopReceiving("connection-auth removed");
922 // clobbered with alternative credentials
924 debugs(33, 2, "ERROR: Closing " << clientConnection
<< " due to change of connection-auth from " << by
);
925 auth_
->releaseAuthServer();
927 // this is a fatal type of problem.
928 // Close the connection immediately with TCP RST to abort all traffic flow
929 comm_reset_close(clientConnection
);
937 // cleans up before destructor is called
939 ConnStateData::swanSong()
941 debugs(33, 2, HERE
<< clientConnection
);
942 flags
.readMore
= false;
943 clientdbEstablished(clientConnection
->remote
, -1); /* decrement */
944 assert(areAllContextsForThisConnection());
949 if (Comm::IsConnOpen(clientConnection
))
950 clientConnection
->close();
953 // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
954 setAuth(NULL
, "ConnStateData::SwanSong cleanup");
957 BodyProducer::swanSong();
958 flags
.swanSang
= true;
962 ConnStateData::isOpen() const
964 return cbdataReferenceValid(this) && // XXX: checking "this" in a method
965 Comm::IsConnOpen(clientConnection
) &&
966 !fd_table
[clientConnection
->fd
].closing();
969 ConnStateData::~ConnStateData()
971 assert(this != NULL
);
972 debugs(33, 3, HERE
<< clientConnection
);
974 FtpCloseDataConnection(this);
977 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData did not close " << clientConnection
);
980 debugs(33, DBG_IMPORTANT
, "BUG: ConnStateData was not destroyed properly; " << clientConnection
);
982 cbdataReferenceDone(port
);
984 if (bodyPipe
!= NULL
)
985 stopProducingFor(bodyPipe
, false);
988 delete sslServerBump
;
993 * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive.
994 * This is the client-side persistent connection flag. We need
995 * to set this relatively early in the request processing
996 * to handle hacks for broken servers and clients.
999 clientSetKeepaliveFlag(ClientHttpRequest
* http
)
1001 HttpRequest
*request
= http
->request
;
1003 debugs(33, 3, "clientSetKeepaliveFlag: http_ver = " <<
1004 request
->http_ver
.major
<< "." << request
->http_ver
.minor
);
1005 debugs(33, 3, "clientSetKeepaliveFlag: method = " <<
1006 RequestMethodStr(request
->method
));
1008 // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply.
1009 request
->flags
.proxyKeepalive
= request
->persistent();
1013 clientIsContentLengthValid(HttpRequest
* r
)
1015 switch (r
->method
.id()) {
1017 case Http::METHOD_GET
:
1019 case Http::METHOD_HEAD
:
1020 /* We do not want to see a request entity on GET/HEAD requests */
1021 return (r
->content_length
<= 0 || Config
.onoff
.request_entities
);
1024 /* For other types of requests we don't care */
1032 clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength
)
1034 if (Config
.maxRequestBodySize
&&
1035 bodyLength
> Config
.maxRequestBodySize
)
1036 return 1; /* too large */
1043 connIsUsable(ConnStateData
* conn
)
1045 if (conn
== NULL
|| !cbdataReferenceValid(conn
) || !Comm::IsConnOpen(conn
->clientConnection
))
1053 // careful: the "current" context may be gone if we wrote an early response
1054 ClientSocketContext::Pointer
1055 ConnStateData::getCurrentContext() const
1058 return currentobject
;
1062 ClientSocketContext::deferRecipientForLater(clientStreamNode
* node
, HttpReply
* rep
, StoreIOBuffer receivedData
)
1064 debugs(33, 2, "clientSocketRecipient: Deferring request " << http
->uri
);
1065 assert(flags
.deferred
== 0);
1067 deferredparams
.node
= node
;
1068 deferredparams
.rep
= rep
;
1069 deferredparams
.queuedBuffer
= receivedData
;
1074 responseFinishedOrFailed(HttpReply
* rep
, StoreIOBuffer
const & receivedData
)
1076 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0)
1083 ClientSocketContext::startOfOutput() const
1085 return http
->out
.size
== 0;
1089 ClientSocketContext::lengthToSend(Range
<int64_t> const &available
)
1091 /*the size of available range can always fit in a size_t type*/
1092 size_t maximum
= (size_t)available
.size();
1094 if (!http
->request
->range
)
1097 assert (canPackMoreRanges());
1099 if (http
->range_iter
.debt() == -1)
1102 assert (http
->range_iter
.debt() > 0);
1104 /* TODO this + the last line could be a range intersection calculation */
1105 if (available
.start
< http
->range_iter
.currentSpec()->offset
)
1108 return min(http
->range_iter
.debt(), (int64_t)maximum
);
1112 ClientSocketContext::noteSentBodyBytes(size_t bytes
)
1114 http
->out
.offset
+= bytes
;
1116 if (!http
->request
->range
)
1119 if (http
->range_iter
.debt() != -1) {
1120 http
->range_iter
.debt(http
->range_iter
.debt() - bytes
);
1121 assert (http
->range_iter
.debt() >= 0);
1124 /* debt() always stops at -1, below that is a bug */
1125 assert (http
->range_iter
.debt() >= -1);
1129 ClientHttpRequest::multipartRangeRequest() const
1131 return request
->multipartRangeRequest();
1135 ClientSocketContext::multipartRangeRequest() const
1137 return http
->multipartRangeRequest();
1141 ClientSocketContext::sendBody(HttpReply
* rep
, StoreIOBuffer bodyData
)
1143 assert(rep
== NULL
);
1145 if (!multipartRangeRequest() && !http
->request
->flags
.chunkedReply
) {
1146 size_t length
= lengthToSend(bodyData
.range());
1147 noteSentBodyBytes (length
);
1148 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteBodyComplete",
1149 CommIoCbPtrFun(clientWriteBodyComplete
, this));
1150 Comm::Write(clientConnection
, bodyData
.data
, length
, call
, NULL
);
1156 if (multipartRangeRequest())
1157 packRange(bodyData
, &mb
);
1159 packChunk(bodyData
, mb
);
1161 if (mb
.contentSize()) {
1163 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1164 CommIoCbPtrFun(clientWriteComplete
, this));
1165 Comm::Write(clientConnection
, &mb
, call
);
1167 writeComplete(clientConnection
, NULL
, 0, COMM_OK
);
1171 * Packs bodyData into mb using chunked encoding. Packs the last-chunk
1172 * if bodyData is empty.
1175 ClientSocketContext::packChunk(const StoreIOBuffer
&bodyData
, MemBuf
&mb
)
1177 const uint64_t length
=
1178 static_cast<uint64_t>(lengthToSend(bodyData
.range()));
1179 noteSentBodyBytes(length
);
1181 mb
.Printf("%" PRIX64
"\r\n", length
);
1182 mb
.append(bodyData
.data
, length
);
1186 /** put terminating boundary for multiparts */
1188 clientPackTermBound(String boundary
, MemBuf
* mb
)
1190 mb
->Printf("\r\n--" SQUIDSTRINGPH
"--\r\n", SQUIDSTRINGPRINT(boundary
));
1191 debugs(33, 6, "clientPackTermBound: buf offset: " << mb
->size
);
1194 /** appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1196 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1198 HttpHeader
hdr(hoReply
);
1204 debugs(33, 5, "clientPackRangeHdr: appending boundary: " << boundary
);
1205 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1206 mb
->Printf("\r\n--" SQUIDSTRINGPH
"\r\n", SQUIDSTRINGPRINT(boundary
));
1208 /* stuff the header with required entries and pack it */
1210 if (rep
->header
.has(HDR_CONTENT_TYPE
))
1211 hdr
.putStr(HDR_CONTENT_TYPE
, rep
->header
.getStr(HDR_CONTENT_TYPE
));
1213 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1215 packerToMemInit(&p
, mb
);
1223 /* append <crlf> (we packed a header, not a reply) */
1228 * extracts a "range" from *buf and appends them to mb, updating
1229 * all offsets and such.
1232 ClientSocketContext::packRange(StoreIOBuffer
const &source
, MemBuf
* mb
)
1234 HttpHdrRangeIter
* i
= &http
->range_iter
;
1235 Range
<int64_t> available (source
.range());
1236 char const *buf
= source
.data
;
1238 while (i
->currentSpec() && available
.size()) {
1239 const size_t copy_sz
= lengthToSend(available
);
1243 * intersection of "have" and "need" ranges must not be empty
1245 assert(http
->out
.offset
< i
->currentSpec()->offset
+ i
->currentSpec()->length
);
1246 assert(http
->out
.offset
+ (int64_t)available
.size() > i
->currentSpec()->offset
);
1249 * put boundary and headers at the beginning of a range in a
1253 if (http
->multipartRangeRequest() && i
->debt() == i
->currentSpec()->length
) {
1254 assert(http
->memObject());
1256 http
->memObject()->getReply(), /* original reply */
1257 i
->currentSpec(), /* current range */
1258 i
->boundary
, /* boundary, the same for all */
1265 debugs(33, 3, "clientPackRange: appending " << copy_sz
<< " bytes");
1267 noteSentBodyBytes (copy_sz
);
1269 mb
->append(buf
, copy_sz
);
1274 available
.start
+= copy_sz
;
1280 if (!canPackMoreRanges()) {
1281 debugs(33, 3, "clientPackRange: Returning because !canPackMoreRanges.");
1284 /* put terminating boundary for multiparts */
1285 clientPackTermBound(i
->boundary
, mb
);
1290 int64_t nextOffset
= getNextRangeOffset();
1292 assert (nextOffset
>= http
->out
.offset
);
1294 int64_t skip
= nextOffset
- http
->out
.offset
;
1296 /* adjust for not to be transmitted bytes */
1297 http
->out
.offset
= nextOffset
;
1299 if (available
.size() <= (uint64_t)skip
)
1302 available
.start
+= skip
;
1311 /** returns expected content length for multi-range replies
1312 * note: assumes that httpHdrRangeCanonize has already been called
1313 * warning: assumes that HTTP headers for individual ranges at the
1314 * time of the actuall assembly will be exactly the same as
1315 * the headers when clientMRangeCLen() is called */
1317 ClientHttpRequest::mRangeCLen()
1322 assert(memObject());
1325 HttpHdrRange::iterator pos
= request
->range
->begin();
1327 while (pos
!= request
->range
->end()) {
1328 /* account for headers for this range */
1330 clientPackRangeHdr(memObject()->getReply(),
1331 *pos
, range_iter
.boundary
, &mb
);
1334 /* account for range content */
1335 clen
+= (*pos
)->length
;
1337 debugs(33, 6, "clientMRangeCLen: (clen += " << mb
.size
<< " + " << (*pos
)->length
<< ") == " << clen
);
1341 /* account for the terminating boundary */
1344 clientPackTermBound(range_iter
.boundary
, &mb
);
1354 * returns true if If-Range specs match reply, false otherwise
1357 clientIfRangeMatch(ClientHttpRequest
* http
, HttpReply
* rep
)
1359 const TimeOrTag spec
= http
->request
->header
.getTimeOrTag(HDR_IF_RANGE
);
1360 /* check for parsing falure */
1367 ETag rep_tag
= rep
->header
.getETag(HDR_ETAG
);
1368 debugs(33, 3, "clientIfRangeMatch: ETags: " << spec
.tag
.str
<< " and " <<
1369 (rep_tag
.str
? rep_tag
.str
: "<none>"));
1372 return 0; /* entity has no etag to compare with! */
1374 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1375 debugs(33, DBG_IMPORTANT
, "clientIfRangeMatch: Weak ETags are not allowed in If-Range: " << spec
.tag
.str
<< " ? " << rep_tag
.str
);
1376 return 0; /* must use strong validator for sub-range requests */
1379 return etagIsStrongEqual(rep_tag
, spec
.tag
);
1382 /* got modification time? */
1383 if (spec
.time
>= 0) {
1384 return http
->storeEntry()->lastmod
<= spec
.time
;
1387 assert(0); /* should not happen */
1392 * generates a "unique" boundary string for multipart responses
1393 * the caller is responsible for cleaning the string */
1395 ClientHttpRequest::rangeBoundaryStr() const
1399 String
b(APP_FULLNAME
);
1401 key
= storeEntry()->getMD5Text();
1402 b
.append(key
, strlen(key
));
1406 /** adds appropriate Range headers if needed */
1408 ClientSocketContext::buildRangeHeader(HttpReply
* rep
)
1410 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1411 const char *range_err
= NULL
;
1412 HttpRequest
*request
= http
->request
;
1413 assert(request
->range
);
1414 /* check if we still want to do ranges */
1416 int64_t roffLimit
= request
->getRangeOffsetLimit();
1419 range_err
= "no [parse-able] reply";
1420 else if ((rep
->sline
.status() != Http::scOkay
) && (rep
->sline
.status() != Http::scPartialContent
))
1421 range_err
= "wrong status code";
1422 else if (hdr
->has(HDR_CONTENT_RANGE
))
1423 range_err
= "origin server does ranges";
1424 else if (rep
->content_length
< 0)
1425 range_err
= "unknown length";
1426 else if (rep
->content_length
!= http
->memObject()->getReply()->content_length
)
1427 range_err
= "INCONSISTENT length"; /* a bug? */
1429 /* hits only - upstream CachePeer determines correct behaviour on misses, and client_side_reply determines
1432 else if (logTypeIsATcpHit(http
->logType
) && http
->request
->header
.has(HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1433 range_err
= "If-Range match failed";
1434 else if (!http
->request
->range
->canonize(rep
))
1435 range_err
= "canonization failed";
1436 else if (http
->request
->range
->isComplex())
1437 range_err
= "too complex range header";
1438 else if (!logTypeIsATcpHit(http
->logType
) && http
->request
->range
->offsetLimitExceeded(roffLimit
))
1439 range_err
= "range outside range_offset_limit";
1441 /* get rid of our range specs on error */
1443 /* XXX We do this here because we need canonisation etc. However, this current
1444 * code will lead to incorrect store offset requests - the store will have the
1445 * offset data, but we won't be requesting it.
1446 * So, we can either re-request, or generate an error
1448 debugs(33, 3, "clientBuildRangeHeader: will not do ranges: " << range_err
<< ".");
1449 delete http
->request
->range
;
1450 http
->request
->range
= NULL
;
1452 /* XXX: TODO: Review, this unconditional set may be wrong. */
1453 rep
->sline
.set(rep
->sline
.version
, Http::scPartialContent
);
1454 // web server responded with a valid, but unexpected range.
1455 // will (try-to) forward as-is.
1456 //TODO: we should cope with multirange request/responses
1457 bool replyMatchRequest
= rep
->content_range
!= NULL
?
1458 request
->range
->contains(rep
->content_range
->spec
) :
1460 const int spec_count
= http
->request
->range
->specs
.count
;
1461 int64_t actual_clen
= -1;
1463 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
1464 spec_count
<< " virgin clen: " << rep
->content_length
);
1465 assert(spec_count
> 0);
1466 /* append appropriate header(s) */
1468 if (spec_count
== 1) {
1469 if (!replyMatchRequest
) {
1470 hdr
->delById(HDR_CONTENT_RANGE
);
1471 hdr
->putContRange(rep
->content_range
);
1472 actual_clen
= rep
->content_length
;
1473 //http->range_iter.pos = rep->content_range->spec.begin();
1474 (*http
->range_iter
.pos
)->offset
= rep
->content_range
->spec
.offset
;
1475 (*http
->range_iter
.pos
)->length
= rep
->content_range
->spec
.length
;
1478 HttpHdrRange::iterator pos
= http
->request
->range
->begin();
1480 /* append Content-Range */
1482 if (!hdr
->has(HDR_CONTENT_RANGE
)) {
1483 /* No content range, so this was a full object we are
1486 httpHeaderAddContRange(hdr
, **pos
, rep
->content_length
);
1489 /* set new Content-Length to the actual number of bytes
1490 * transmitted in the message-body */
1491 actual_clen
= (*pos
)->length
;
1495 /* generate boundary string */
1496 http
->range_iter
.boundary
= http
->rangeBoundaryStr();
1497 /* delete old Content-Type, add ours */
1498 hdr
->delById(HDR_CONTENT_TYPE
);
1499 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1500 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH
"\"",
1501 SQUIDSTRINGPRINT(http
->range_iter
.boundary
));
1502 /* Content-Length is not required in multipart responses
1503 * but it is always nice to have one */
1504 actual_clen
= http
->mRangeCLen();
1505 /* http->out needs to start where we want data at */
1506 http
->out
.offset
= http
->range_iter
.currentSpec()->offset
;
1509 /* replace Content-Length header */
1510 assert(actual_clen
>= 0);
1512 hdr
->delById(HDR_CONTENT_LENGTH
);
1514 hdr
->putInt64(HDR_CONTENT_LENGTH
, actual_clen
);
1516 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen
);
1518 /* And start the range iter off */
1519 http
->range_iter
.updateSpec();
1524 ClientSocketContext::prepareReply(HttpReply
* rep
)
1528 if (http
->request
->range
)
1529 buildRangeHeader(rep
);
1533 ClientSocketContext::sendStartOfMessage(HttpReply
* rep
, StoreIOBuffer bodyData
)
1537 MemBuf
*mb
= rep
->pack();
1539 // dump now, so we dont output any body.
1540 debugs(11, 2, "HTTP Client " << clientConnection
);
1541 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb
->buf
<< "\n----------");
1543 /* Save length of headers for persistent conn checks */
1544 http
->out
.headers_sz
= mb
->contentSize();
1547 headersLog(0, 0, http
->request
->method
, rep
);
1550 if (bodyData
.data
&& bodyData
.length
) {
1551 if (multipartRangeRequest())
1552 packRange(bodyData
, mb
);
1553 else if (http
->request
->flags
.chunkedReply
) {
1554 packChunk(bodyData
, *mb
);
1556 size_t length
= lengthToSend(bodyData
.range());
1557 noteSentBodyBytes (length
);
1559 mb
->append(bodyData
.data
, length
);
1564 debugs(33,7, HERE
<< "sendStartOfMessage schedules clientWriteComplete");
1565 AsyncCall::Pointer call
= commCbCall(33, 5, "clientWriteComplete",
1566 CommIoCbPtrFun(clientWriteComplete
, this));
1567 Comm::Write(clientConnection
, mb
, call
);
1572 * Write a chunk of data to a client socket. If the reply is present,
1573 * send the reply headers down the wire too, and clean them up when
1576 * The request is one backed by a connection, not an internal request.
1577 * data context is not NULL
1578 * There are no more entries in the stream chain.
1581 clientSocketRecipient(clientStreamNode
* node
, ClientHttpRequest
* http
,
1582 HttpReply
* rep
, StoreIOBuffer receivedData
)
1584 debugs(33,7, HERE
<< "rep->content_length=" << (rep
? rep
->content_length
: -2) << " receivedData.length=" << receivedData
.length
);
1585 /* Test preconditions */
1586 assert(node
!= NULL
);
1587 PROF_start(clientSocketRecipient
);
1588 /* TODO: handle this rather than asserting
1589 * - it should only ever happen if we cause an abort and
1590 * the callback chain loops back to here, so we can simply return.
1591 * However, that itself shouldn't happen, so it stays as an assert for now.
1593 assert(cbdataReferenceValid(node
));
1594 assert(node
->node
.next
== NULL
);
1595 ClientSocketContext::Pointer context
= dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw());
1596 assert(context
!= NULL
);
1597 assert(connIsUsable(http
->getConn()));
1599 /* TODO: check offset is what we asked for */
1601 if (context
!= http
->getConn()->getCurrentContext()) {
1602 context
->deferRecipientForLater(node
, rep
, receivedData
);
1603 PROF_stop(clientSocketRecipient
);
1607 if (http
->getConn()->isFtp
) {
1608 assert(context
->http
== http
);
1609 FtpHandleReply(context
.getRaw(), rep
, receivedData
);
1610 PROF_stop(clientSocketRecipient
);
1614 // After sending Transfer-Encoding: chunked (at least), always send
1615 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
1616 const bool mustSendLastChunk
= http
->request
->flags
.chunkedReply
&&
1617 !http
->request
->flags
.streamError
&& !context
->startOfOutput();
1618 if (responseFinishedOrFailed(rep
, receivedData
) && !mustSendLastChunk
) {
1619 context
->writeComplete(context
->clientConnection
, NULL
, 0, COMM_OK
);
1620 PROF_stop(clientSocketRecipient
);
1624 if (!context
->startOfOutput())
1625 context
->sendBody(rep
, receivedData
);
1628 http
->al
->reply
= rep
;
1629 HTTPMSGLOCK(http
->al
->reply
);
1630 context
->sendStartOfMessage(rep
, receivedData
);
1633 PROF_stop(clientSocketRecipient
);
1637 * Called when a downstream node is no longer interested in
1638 * our data. As we are a terminal node, this means on aborts
1642 clientSocketDetach(clientStreamNode
* node
, ClientHttpRequest
* http
)
1644 /* Test preconditions */
1645 assert(node
!= NULL
);
1646 /* TODO: handle this rather than asserting
1647 * - it should only ever happen if we cause an abort and
1648 * the callback chain loops back to here, so we can simply return.
1649 * However, that itself shouldn't happen, so it stays as an assert for now.
1651 assert(cbdataReferenceValid(node
));
1652 /* Set null by ContextFree */
1653 assert(node
->node
.next
== NULL
);
1654 /* this is the assert discussed above */
1655 assert(NULL
== dynamic_cast<ClientSocketContext
*>(node
->data
.getRaw()));
1656 /* We are only called when the client socket shutsdown.
1657 * Tell the prev pipeline member we're finished
1659 clientStreamDetach(node
, http
);
1663 clientWriteBodyComplete(const Comm::ConnectionPointer
&conn
, char *buf
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1665 debugs(33,7, HERE
<< "clientWriteBodyComplete schedules clientWriteComplete");
1666 clientWriteComplete(conn
, NULL
, size
, errflag
, xerrno
, data
);
1670 ConnStateData::readNextRequest()
1672 debugs(33, 5, HERE
<< clientConnection
<< " reading next req");
1674 fd_note(clientConnection
->fd
, "Idle client: Waiting for next request");
1676 * Set the timeout BEFORE calling clientReadRequest().
1678 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
1679 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
1680 TimeoutDialer
, this, ConnStateData::requestTimeout
);
1681 const int timeout
= isFtp
? Config
.Timeout
.ftpClientIdle
:
1682 Config
.Timeout
.clientIdlePconn
;
1683 commSetConnTimeout(clientConnection
, timeout
, timeoutCall
);
1686 /** Please don't do anything with the FD past here! */
1690 ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest
, ConnStateData
* conn
)
1692 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Sending next");
1694 /** If the client stream is waiting on a socket write to occur, then */
1696 if (deferredRequest
->flags
.deferred
) {
1697 /** NO data is allowed to have been sent. */
1698 assert(deferredRequest
->http
->out
.size
== 0);
1700 clientSocketRecipient(deferredRequest
->deferredparams
.node
,
1701 deferredRequest
->http
,
1702 deferredRequest
->deferredparams
.rep
,
1703 deferredRequest
->deferredparams
.queuedBuffer
);
1706 /** otherwise, the request is still active in a callbacksomewhere,
1711 /// called when we have successfully finished writing the response
1713 ClientSocketContext::keepaliveNextRequest()
1715 ConnStateData
* conn
= http
->getConn();
1717 debugs(33, 3, HERE
<< "ConnnStateData(" << conn
->clientConnection
<< "), Context(" << clientConnection
<< ")");
1720 if (conn
->pinning
.pinned
&& !Comm::IsConnOpen(conn
->pinning
.serverConnection
)) {
1721 debugs(33, 2, HERE
<< conn
->clientConnection
<< " Connection was pinned but server side gone. Terminating client connection");
1722 conn
->clientConnection
->close();
1727 * We are done with the response, and we are either still receiving request
1728 * body (early response!) or have already stopped receiving anything.
1730 * If we are still receiving, then clientParseRequest() below will fail.
1731 * (XXX: but then we will call readNextRequest() which may succeed and
1732 * execute a smuggled request as we are not done with the current request).
1734 * If we stopped because we got everything, then try the next request.
1736 * If we stopped receiving because of an error, then close now to avoid
1737 * getting stuck and to prevent accidental request smuggling.
1740 if (const char *reason
= conn
->stoppedReceiving()) {
1741 debugs(33, 3, HERE
<< "closing for earlier request error: " << reason
);
1742 conn
->clientConnection
->close();
1747 * Attempt to parse a request from the request buffer.
1748 * If we've been fed a pipelined request it may already
1749 * be in our read buffer.
1752 * This needs to fall through - if we're unlucky and parse the _last_ request
1753 * from our read buffer we may never re-register for another client read.
1756 if (conn
->clientParseRequests()) {
1757 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": parsed next request from buffer");
1761 * Either we need to kick-start another read or, if we have
1762 * a half-closed connection, kill it after the last request.
1763 * This saves waiting for half-closed connections to finished being
1764 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1765 * the keepalive "Waiting for next request" state.
1767 if (commIsHalfClosed(conn
->clientConnection
->fd
) && (conn
->getConcurrentRequestCount() == 0)) {
1768 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
1769 conn
->clientConnection
->close();
1773 ClientSocketContext::Pointer deferredRequest
;
1776 * At this point we either have a parsed request (which we've
1777 * kicked off the processing for) or not. If we have a deferred
1778 * request (parsed but deferred for pipeling processing reasons)
1779 * then look at processing it. If not, simply kickstart
1783 if ((deferredRequest
= conn
->getCurrentContext()).getRaw()) {
1784 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling PushDeferredIfNeeded");
1785 ClientSocketContextPushDeferredIfNeeded(deferredRequest
, conn
);
1786 } else if (conn
->flags
.readMore
) {
1787 debugs(33, 3, HERE
<< conn
->clientConnection
<< ": calling conn->readNextRequest()");
1788 conn
->readNextRequest();
1790 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1791 debugs(33, DBG_IMPORTANT
, HERE
<< "abandoning " << conn
->clientConnection
);
1796 clientUpdateSocketStats(LogTags logType
, size_t size
)
1801 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1803 if (logTypeIsATcpHit(logType
))
1804 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1808 * increments iterator "i"
1809 * used by clientPackMoreRanges
1811 \retval true there is still data available to pack more ranges
1815 ClientSocketContext::canPackMoreRanges() const
1817 /** first update iterator "i" if needed */
1819 if (!http
->range_iter
.debt()) {
1820 debugs(33, 5, HERE
<< "At end of current range spec for " << clientConnection
);
1822 if (http
->range_iter
.pos
.incrementable())
1823 ++http
->range_iter
.pos
;
1825 http
->range_iter
.updateSpec();
1828 assert(!http
->range_iter
.debt() == !http
->range_iter
.currentSpec());
1830 /* paranoid sync condition */
1831 /* continue condition: need_more_data */
1832 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http
->range_iter
.currentSpec() ? true : false));
1833 return http
->range_iter
.currentSpec() ? true : false;
1837 ClientSocketContext::getNextRangeOffset() const
1839 if (http
->request
->range
) {
1840 /* offset in range specs does not count the prefix of an http msg */
1841 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http
->out
.offset
);
1842 /* check: reply was parsed and range iterator was initialized */
1843 assert(http
->range_iter
.valid
);
1844 /* filter out data according to range specs */
1845 assert (canPackMoreRanges());
1847 int64_t start
; /* offset of still missing data */
1848 assert(http
->range_iter
.currentSpec());
1849 start
= http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
- http
->range_iter
.debt();
1850 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http
->out
.offset
);
1851 debugs(33, 3, "clientPackMoreRanges: out:"
1852 " start: " << start
<<
1853 " spec[" << http
->range_iter
.pos
- http
->request
->range
->begin() << "]:" <<
1854 " [" << http
->range_iter
.currentSpec()->offset
<<
1855 ", " << http
->range_iter
.currentSpec()->offset
+ http
->range_iter
.currentSpec()->length
<< "),"
1856 " len: " << http
->range_iter
.currentSpec()->length
<<
1857 " debt: " << http
->range_iter
.debt());
1858 if (http
->range_iter
.currentSpec()->length
!= -1)
1859 assert(http
->out
.offset
<= start
); /* we did not miss it */
1864 } else if (reply
&& reply
->content_range
) {
1865 /* request does not have ranges, but reply does */
1866 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1867 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1869 return http
->out
.offset
+ reply
->content_range
->spec
.offset
;
1872 return http
->out
.offset
;
1876 ClientSocketContext::pullData()
1878 debugs(33, 5, HERE
<< clientConnection
<< " attempting to pull upstream data");
1880 /* More data will be coming from the stream. */
1881 StoreIOBuffer readBuffer
;
1882 /* XXX: Next requested byte in the range sequence */
1883 /* XXX: length = getmaximumrangelenfgth */
1884 readBuffer
.offset
= getNextRangeOffset();
1885 readBuffer
.length
= HTTP_REQBUF_SZ
;
1886 readBuffer
.data
= reqbuf
;
1887 /* we may note we have reached the end of the wanted ranges */
1888 clientStreamRead(getTail(), http
, readBuffer
);
1891 clientStream_status_t
1892 ClientSocketContext::socketState()
1894 switch (clientStreamStatus(getTail(), http
)) {
1897 /* check for range support ending */
1899 if (http
->request
->range
) {
1900 /* check: reply was parsed and range iterator was initialized */
1901 assert(http
->range_iter
.valid
);
1902 /* filter out data according to range specs */
1904 if (!canPackMoreRanges()) {
1905 debugs(33, 5, HERE
<< "Range request at end of returnable " <<
1906 "range sequence on " << clientConnection
);
1908 if (http
->request
->flags
.proxyKeepalive
)
1909 return STREAM_COMPLETE
;
1911 return STREAM_UNPLANNED_COMPLETE
;
1913 } else if (reply
&& reply
->content_range
) {
1914 /* reply has content-range, but Squid is not managing ranges */
1915 const int64_t &bytesSent
= http
->out
.offset
;
1916 const int64_t &bytesExpected
= reply
->content_range
->spec
.length
;
1918 debugs(33, 7, HERE
<< "body bytes sent vs. expected: " <<
1919 bytesSent
<< " ? " << bytesExpected
<< " (+" <<
1920 reply
->content_range
->spec
.offset
<< ")");
1922 // did we get at least what we expected, based on range specs?
1924 if (bytesSent
== bytesExpected
) { // got everything
1925 if (http
->request
->flags
.proxyKeepalive
)
1926 return STREAM_COMPLETE
;
1928 return STREAM_UNPLANNED_COMPLETE
;
1931 // The logic below is not clear: If we got more than we
1932 // expected why would persistency matter? Should not this
1933 // always be an error?
1934 if (bytesSent
> bytesExpected
) { // got extra
1935 if (http
->request
->flags
.proxyKeepalive
)
1936 return STREAM_COMPLETE
;
1938 return STREAM_UNPLANNED_COMPLETE
;
1941 // did not get enough yet, expecting more
1946 case STREAM_COMPLETE
:
1947 return STREAM_COMPLETE
;
1949 case STREAM_UNPLANNED_COMPLETE
:
1950 return STREAM_UNPLANNED_COMPLETE
;
1953 return STREAM_FAILED
;
1956 fatal ("unreachable code\n");
1961 * A write has just completed to the client, or we have just realised there is
1962 * no more data to send.
1965 clientWriteComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
1967 ClientSocketContext
*context
= (ClientSocketContext
*)data
;
1968 context
->writeComplete(conn
, bufnotused
, size
, errflag
);
1971 /// remembers the abnormal connection termination for logging purposes
1973 ClientSocketContext::noteIoError(const int xerrno
)
1976 if (xerrno
== ETIMEDOUT
)
1977 http
->al
->http
.timedout
= true;
1978 else // even if xerrno is zero (which means read abort/eof)
1979 http
->al
->http
.aborted
= true;
1984 ClientSocketContext::doClose()
1986 clientConnection
->close();
1989 /// called when we encounter a response-related error
1991 ClientSocketContext::initiateClose(const char *reason
)
1993 http
->getConn()->stopSending(reason
); // closes ASAP
1997 ConnStateData::stopSending(const char *error
)
1999 debugs(33, 4, HERE
<< "sending error (" << clientConnection
<< "): " << error
<<
2000 "; old receiving error: " <<
2001 (stoppedReceiving() ? stoppedReceiving_
: "none"));
2003 if (const char *oldError
= stoppedSending()) {
2004 debugs(33, 3, HERE
<< "already stopped sending: " << oldError
);
2005 return; // nothing has changed as far as this connection is concerned
2007 stoppedSending_
= error
;
2009 if (!stoppedReceiving()) {
2010 if (const int64_t expecting
= mayNeedToReadMoreBody()) {
2011 debugs(33, 5, HERE
<< "must still read " << expecting
<<
2012 " request body bytes with " << in
.notYetUsed
<< " unused");
2013 return; // wait for the request receiver to finish reading
2017 clientConnection
->close();
2021 ClientSocketContext::writeComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
)
2023 const StoreEntry
*entry
= http
->storeEntry();
2024 http
->out
.size
+= size
;
2025 debugs(33, 5, HERE
<< conn
<< ", sz " << size
<<
2026 ", err " << errflag
<< ", off " << http
->out
.size
<< ", len " <<
2027 (entry
? entry
->objectLen() : 0));
2028 clientUpdateSocketStats(http
->logType
, size
);
2030 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
2032 if (errflag
== COMM_ERR_CLOSING
|| !Comm::IsConnOpen(conn
))
2035 if (errflag
|| clientHttpRequestStatus(conn
->fd
, http
)) {
2036 initiateClose("failure or true request status");
2037 /* Do we leak here ? */
2041 switch (socketState()) {
2047 case STREAM_COMPLETE
:
2048 debugs(33, 5, HERE
<< conn
<< " Keeping Alive");
2049 keepaliveNextRequest();
2052 case STREAM_UNPLANNED_COMPLETE
:
2053 initiateClose("STREAM_UNPLANNED_COMPLETE");
2057 initiateClose("STREAM_FAILED");
2061 fatal("Hit unreachable code in clientWriteComplete\n");
2065 SQUIDCEXTERN CSR clientGetMoreData
;
2066 SQUIDCEXTERN CSS clientReplyStatus
;
2067 SQUIDCEXTERN CSD clientReplyDetach
;
2069 static ClientSocketContext
*
2070 parseHttpRequestAbort(ConnStateData
* csd
, const char *uri
)
2072 ClientHttpRequest
*http
;
2073 ClientSocketContext
*context
;
2074 StoreIOBuffer tempBuffer
;
2075 http
= new ClientHttpRequest(csd
);
2076 http
->req_sz
= csd
->in
.notYetUsed
;
2077 http
->uri
= xstrdup(uri
);
2078 setLogUri (http
, uri
);
2079 context
= ClientSocketContextNew(csd
->clientConnection
, http
);
2080 tempBuffer
.data
= context
->reqbuf
;
2081 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2082 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2083 clientReplyStatus
, new clientReplyContext(http
), clientSocketRecipient
,
2084 clientSocketDetach
, context
, tempBuffer
);
2089 skipLeadingSpace(char *aString
)
2091 char *result
= aString
;
2093 while (xisspace(*aString
))
2100 * 'end' defaults to NULL for backwards compatibility
2101 * remove default value if we ever get rid of NULL-terminated
2105 findTrailingHTTPVersion(const char *uriAndHTTPVersion
, const char *end
)
2108 end
= uriAndHTTPVersion
+ strcspn(uriAndHTTPVersion
, "\r\n");
2112 for (; end
> uriAndHTTPVersion
; --end
) {
2113 if (*end
== '\n' || *end
== '\r')
2116 if (xisspace(*end
)) {
2117 if (strncasecmp(end
+ 1, "HTTP/", 5) == 0)
2128 setLogUri(ClientHttpRequest
* http
, char const *uri
, bool cleanUrl
)
2130 safe_free(http
->log_uri
);
2133 // The uri is already clean just dump it.
2134 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2137 switch (Config
.uri_whitespace
) {
2138 case URI_WHITESPACE_ALLOW
:
2139 flags
|= RFC1738_ESCAPE_NOSPACE
;
2141 case URI_WHITESPACE_ENCODE
:
2142 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2143 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2146 case URI_WHITESPACE_CHOP
: {
2147 flags
|= RFC1738_ESCAPE_NOSPACE
;
2148 flags
|= RFC1738_ESCAPE_UNESCAPED
;
2149 http
->log_uri
= xstrndup(rfc1738_do_escape(uri
, flags
), MAX_URL
);
2150 int pos
= strcspn(http
->log_uri
, w_space
);
2151 http
->log_uri
[pos
] = '\0';
2155 case URI_WHITESPACE_DENY
:
2156 case URI_WHITESPACE_STRIP
:
2159 char *tmp_uri
= static_cast<char*>(xmalloc(strlen(uri
) + 1));
2163 if (!xisspace(*t
)) {
2170 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(tmp_uri
), MAX_URL
);
2179 prepareAcceleratedURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2181 int vhost
= conn
->port
->vhost
;
2182 int vport
= conn
->port
->vport
;
2184 char ipbuf
[MAX_IPSTRLEN
];
2186 http
->flags
.accel
= true;
2188 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2190 if (strncasecmp(url
, "cache_object://", 15) == 0)
2191 return; /* already in good shape */
2194 if (conn
->port
->vhost
)
2195 return; /* already in good shape */
2197 /* else we need to ignore the host name */
2198 url
= strstr(url
, "//");
2200 #if SHOULD_REJECT_UNKNOWN_URLS
2203 hp
->request_parse_status
= Http::scBadRequest
;
2204 return parseHttpRequestAbort(conn
, "error:invalid-request");
2209 url
= strchr(url
+ 2, '/');
2216 vport
= http
->getConn()->clientConnection
->local
.port();
2218 const bool switchedToHttps
= conn
->switchedToHttps();
2219 const bool tryHostHeader
= vhost
|| switchedToHttps
;
2220 if (tryHostHeader
&& (host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2221 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host
<< " + vport=" << vport
);
2226 if (host
[strlen(host
)] != ']' && (t
= strrchr(host
,':')) != NULL
) {
2227 strncpy(thost
, host
, (t
-host
));
2228 snprintf(thost
+(t
-host
), sizeof(thost
)-(t
-host
), ":%d", vport
);
2231 snprintf(thost
, sizeof(thost
), "%s:%d",host
, vport
);
2234 } // else nothing to alter port-wise.
2235 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2237 http
->uri
= (char *)xcalloc(url_sz
, 1);
2238 const char *protocol
= switchedToHttps
?
2239 "https" : conn
->port
->protocol
;
2240 snprintf(http
->uri
, url_sz
, "%s://%s%s", protocol
, host
, url
);
2241 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http
->uri
<< "'");
2242 } else if (conn
->port
->defaultsite
/* && !vhost */) {
2243 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn
->port
->defaultsite
<< " + vport=" << vport
);
2244 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2245 strlen(conn
->port
->defaultsite
);
2246 http
->uri
= (char *)xcalloc(url_sz
, 1);
2250 snprintf(vportStr
, sizeof(vportStr
),":%d",vport
);
2252 snprintf(http
->uri
, url_sz
, "%s://%s%s%s",
2253 conn
->port
->protocol
, conn
->port
->defaultsite
, vportStr
, url
);
2254 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http
->uri
<<"'");
2255 } else if (vport
> 0 /* && (!vhost || no Host:) */) {
2256 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport
);
2257 /* Put the local socket IP address as the hostname, with whatever vport we found */
2258 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2259 http
->uri
= (char *)xcalloc(url_sz
, 1);
2260 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2261 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2262 http
->getConn()->port
->protocol
,
2264 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http
->uri
<< "'");
2269 prepareTransparentURL(ConnStateData
* conn
, ClientHttpRequest
*http
, char *url
, const char *req_hdr
)
2272 char ipbuf
[MAX_IPSTRLEN
];
2275 return; /* already in good shape */
2277 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2279 if ((host
= mime_get_header(req_hdr
, "Host")) != NULL
) {
2280 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2282 http
->uri
= (char *)xcalloc(url_sz
, 1);
2283 snprintf(http
->uri
, url_sz
, "%s://%s%s", conn
->port
->protocol
, host
, url
);
2284 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http
->uri
<<"'");
2286 /* Put the local socket IP address as the hostname. */
2287 int url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2288 http
->uri
= (char *)xcalloc(url_sz
, 1);
2289 http
->getConn()->clientConnection
->local
.toHostStr(ipbuf
,MAX_IPSTRLEN
);
2290 snprintf(http
->uri
, url_sz
, "%s://%s:%d%s",
2291 http
->getConn()->port
->protocol
,
2292 ipbuf
, http
->getConn()->clientConnection
->local
.port(), url
);
2293 debugs(33, 5, "TRANSPARENT REWRITE: '" << http
->uri
<< "'");
2297 /** Parse an HTTP request
2299 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2300 * to 1 if the request was correctly parsed.
2301 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2302 * \param[in] hp an HttpParser
2303 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2304 * Pointed-to value will be set to Http::METHOD_NONE in case of
2306 * \param[out] http_ver will be set as a side-effect of the parsing
2307 * \return NULL on incomplete requests,
2308 * a ClientSocketContext structure on success or failure.
2310 static ClientSocketContext
*
2311 parseHttpRequest(ConnStateData
*csd
, HttpParser
*hp
, HttpRequestMethod
* method_p
, Http::ProtocolVersion
*http_ver
)
2313 char *req_hdr
= NULL
;
2316 ClientHttpRequest
*http
;
2317 ClientSocketContext
*result
;
2318 StoreIOBuffer tempBuffer
;
2321 /* pre-set these values to make aborting simpler */
2322 *method_p
= Http::METHOD_NONE
;
2324 /* NP: don't be tempted to move this down or remove again.
2325 * It's the only DDoS protection old-String has against long URL */
2326 if ( hp
->bufsiz
<= 0) {
2327 debugs(33, 5, "Incomplete request, waiting for end of request line");
2329 } else if ( (size_t)hp
->bufsiz
>= Config
.maxRequestHeaderSize
&& headersEnd(hp
->buf
, Config
.maxRequestHeaderSize
) == 0) {
2330 debugs(33, 5, "parseHttpRequest: Too large request");
2331 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2332 return parseHttpRequestAbort(csd
, "error:request-too-large");
2335 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2336 r
= HttpParserParseReqLine(hp
);
2339 debugs(33, 5, "Incomplete request, waiting for end of request line");
2344 return parseHttpRequestAbort(csd
, "error:invalid-request");
2347 /* Request line is valid here .. */
2348 *http_ver
= Http::ProtocolVersion(hp
->req
.v_maj
, hp
->req
.v_min
);
2350 /* This call scans the entire request, not just the headers */
2351 if (hp
->req
.v_maj
> 0) {
2352 if ((req_sz
= headersEnd(hp
->buf
, hp
->bufsiz
)) == 0) {
2353 debugs(33, 5, "Incomplete request, waiting for end of headers");
2357 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
2358 req_sz
= HttpParserReqSz(hp
);
2361 /* We know the whole request is in hp->buf now */
2363 assert(req_sz
<= (size_t) hp
->bufsiz
);
2365 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2366 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2369 hp
->hdr_end
= req_sz
- 1;
2371 hp
->hdr_start
= hp
->req
.end
+ 1;
2373 /* Enforce max_request_size */
2374 if (req_sz
>= Config
.maxRequestHeaderSize
) {
2375 debugs(33, 5, "parseHttpRequest: Too large request");
2376 hp
->request_parse_status
= Http::scHeaderTooLarge
;
2377 return parseHttpRequestAbort(csd
, "error:request-too-large");
2381 *method_p
= HttpRequestMethod(&hp
->buf
[hp
->req
.m_start
], &hp
->buf
[hp
->req
.m_end
]+1);
2383 /* deny CONNECT via accelerated ports */
2384 if (*method_p
== Http::METHOD_CONNECT
&& csd
->port
&& csd
->port
->flags
.accelSurrogate
) {
2385 debugs(33, DBG_IMPORTANT
, "WARNING: CONNECT method received on " << csd
->port
->protocol
<< " Accelerator port " << csd
->port
->s
.port() );
2386 /* XXX need a way to say "this many character length string" */
2387 debugs(33, DBG_IMPORTANT
, "WARNING: for request: " << hp
->buf
);
2388 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2389 return parseHttpRequestAbort(csd
, "error:method-not-allowed");
2392 if (*method_p
== Http::METHOD_NONE
) {
2393 /* XXX need a way to say "this many character length string" */
2394 debugs(33, DBG_IMPORTANT
, "clientParseRequestMethod: Unsupported method in request '" << hp
->buf
<< "'");
2395 hp
->request_parse_status
= Http::scMethodNotAllowed
;
2396 return parseHttpRequestAbort(csd
, "error:unsupported-request-method");
2400 * Process headers after request line
2401 * TODO: Use httpRequestParse here.
2403 /* XXX this code should be modified to take a const char * later! */
2404 req_hdr
= (char *) hp
->buf
+ hp
->req
.end
+ 1;
2406 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr
<< "}");
2408 end
= (char *) hp
->buf
+ hp
->hdr_end
;
2410 debugs(33, 3, "parseHttpRequest: end = {" << end
<< "}");
2412 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2413 (int) HttpParserRequestLen(hp
) << ", req_line_sz = " <<
2414 HttpParserReqSz(hp
));
2416 /* Ok, all headers are received */
2417 http
= new ClientHttpRequest(csd
);
2419 http
->req_sz
= HttpParserRequestLen(hp
);
2420 result
= ClientSocketContextNew(csd
->clientConnection
, http
);
2421 tempBuffer
.data
= result
->reqbuf
;
2422 tempBuffer
.length
= HTTP_REQBUF_SZ
;
2424 ClientStreamData newServer
= new clientReplyContext(http
);
2425 ClientStreamData newClient
= result
;
2426 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
2427 clientReplyStatus
, newServer
, clientSocketRecipient
,
2428 clientSocketDetach
, newClient
, tempBuffer
);
2430 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp
->buf
) + hp
->hdr_start
);
2434 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2435 * below needs to be modified to not expect a mutable nul-terminated string.
2437 char *url
= (char *)xmalloc(hp
->req
.u_end
- hp
->req
.u_start
+ 16);
2439 memcpy(url
, hp
->buf
+ hp
->req
.u_start
, hp
->req
.u_end
- hp
->req
.u_start
+ 1);
2441 url
[hp
->req
.u_end
- hp
->req
.u_start
+ 1] = '\0';
2443 #if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
2445 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2450 debugs(33,5, HERE
<< "repare absolute URL from " <<
2451 (csd
->transparent()?"intercept":(csd
->port
->flags
.accelSurrogate
? "accel":"")));
2452 /* Rewrite the URL in transparent or accelerator mode */
2453 /* NP: there are several cases to traverse here:
2454 * - standard mode (forward proxy)
2455 * - transparent mode (TPROXY)
2456 * - transparent mode with failures
2457 * - intercept mode (NAT)
2458 * - intercept mode with failures
2459 * - accelerator mode (reverse proxy)
2461 * - mixed combos of the above with internal URL
2463 if (csd
->transparent()) {
2464 /* intercept or transparent mode, properly working with no failures */
2465 prepareTransparentURL(csd
, http
, url
, req_hdr
);
2467 } else if (internalCheck(url
)) {
2468 /* internal URL mode */
2469 /* prepend our name & port */
2470 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2471 // We just re-wrote the URL. Must replace the Host: header.
2472 // But have not parsed there yet!! flag for local-only handling.
2473 http
->flags
.internal
= true;
2475 } else if (csd
->port
->flags
.accelSurrogate
|| csd
->switchedToHttps()) {
2476 /* accelerator mode */
2477 prepareAcceleratedURL(csd
, http
, url
, req_hdr
);
2481 /* No special rewrites have been applied above, use the
2482 * requested url. may be rewritten later, so make extra room */
2483 int url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2484 http
->uri
= (char *)xcalloc(url_sz
, 1);
2485 strcpy(http
->uri
, url
);
2488 debugs(33, 5, "parseHttpRequest: Complete request received");
2490 // XXX: crop this dump at the end of headers. No need for extras
2491 debugs(11, 2, "HTTP Client " << csd
->clientConnection
);
2492 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp
->buf
) + hp
->req
.m_start
<< "\n----------");
2494 result
->flags
.parsed_ok
= 1;
2500 ConnStateData::getAvailableBufferLength() const
2502 assert (in
.allocatedSize
> in
.notYetUsed
); // allocated more than used
2503 const size_t result
= in
.allocatedSize
- in
.notYetUsed
- 1;
2504 // huge request_header_max_size may lead to more than INT_MAX unused space
2505 assert (static_cast<ssize_t
>(result
) <= INT_MAX
);
2510 ConnStateData::maybeMakeSpaceAvailable()
2512 if (getAvailableBufferLength() < 2) {
2514 if (in
.allocatedSize
>= Config
.maxRequestBufferSize
) {
2515 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config
.maxRequestBufferSize
);
2518 if ((newSize
=in
.allocatedSize
* 2) > Config
.maxRequestBufferSize
) {
2519 newSize
=Config
.maxRequestBufferSize
;
2521 in
.buf
= (char *)memReallocBuf(in
.buf
, newSize
, &in
.allocatedSize
);
2522 debugs(33, 2, "growing request buffer: notYetUsed=" << in
.notYetUsed
<< " size=" << in
.allocatedSize
);
2528 ConnStateData::addContextToQueue(ClientSocketContext
* context
)
2530 ClientSocketContext::Pointer
*S
;
2532 for (S
= (ClientSocketContext::Pointer
*) & currentobject
; S
->getRaw();
2540 ConnStateData::getConcurrentRequestCount() const
2543 ClientSocketContext::Pointer
*T
;
2545 for (T
= (ClientSocketContext::Pointer
*) ¤tobject
;
2546 T
->getRaw(); T
= &(*T
)->next
, ++result
);
2551 ConnStateData::connReadWasError(comm_err_t flag
, int size
, int xerrno
)
2553 if (flag
!= COMM_OK
) {
2554 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": got flag " << flag
);
2559 if (!ignoreErrno(xerrno
)) {
2560 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": " << xstrerr(xerrno
));
2562 } else if (in
.notYetUsed
== 0) {
2563 debugs(33, 2, "connReadWasError: FD " << clientConnection
<< ": no data to process (" << xstrerr(xerrno
) << ")");
2571 ConnStateData::connFinishedWithConn(int size
)
2574 if (getConcurrentRequestCount() == 0 && in
.notYetUsed
== 0) {
2575 /* no current or pending requests */
2576 debugs(33, 4, HERE
<< clientConnection
<< " closed");
2578 } else if (!Config
.onoff
.half_closed_clients
) {
2579 /* admin doesn't want to support half-closed client sockets */
2580 debugs(33, 3, HERE
<< clientConnection
<< " aborted (half_closed_clients disabled)");
2581 notifyAllContexts(0); // no specific error implies abort
2590 connNoteUseOfBuffer(ConnStateData
* conn
, size_t byteCount
)
2592 assert(byteCount
> 0 && byteCount
<= conn
->in
.notYetUsed
);
2593 conn
->in
.notYetUsed
-= byteCount
;
2594 debugs(33, 5, HERE
<< "conn->in.notYetUsed = " << conn
->in
.notYetUsed
);
2596 * If there is still data that will be used,
2597 * move it to the beginning.
2600 if (conn
->in
.notYetUsed
> 0)
2601 memmove(conn
->in
.buf
, conn
->in
.buf
+ byteCount
, conn
->in
.notYetUsed
);
2604 /// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2606 ConnStateData::checkHeaderLimits()
2608 if (in
.notYetUsed
< Config
.maxRequestHeaderSize
)
2609 return; // can accumulte more header data
2611 debugs(33, 3, "Request header is too large (" << in
.notYetUsed
<< " > " <<
2612 Config
.maxRequestHeaderSize
<< " bytes)");
2614 ClientSocketContext
*context
= parseHttpRequestAbort(this, "error:request-too-large");
2615 clientStreamNode
*node
= context
->getClientReplyContext();
2616 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2617 assert (repContext
);
2618 repContext
->setReplyToError(ERR_TOO_BIG
,
2619 Http::scBadRequest
, Http::METHOD_NONE
, NULL
,
2620 clientConnection
->remote
, NULL
, NULL
, NULL
);
2621 context
->registerWithConn();
2622 context
->pullData();
2626 ConnStateData::clientAfterReadingRequests()
2628 // Were we expecting to read more request body from half-closed connection?
2629 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection
->fd
)) {
2630 debugs(33, 3, HERE
<< "truncated body: closing half-closed " << clientConnection
);
2631 clientConnection
->close();
2640 ConnStateData::quitAfterError(HttpRequest
*request
)
2642 // From HTTP p.o.v., we do not have to close after every error detected
2643 // at the client-side, but many such errors do require closure and the
2644 // client-side code is bad at handling errors so we play it safe.
2646 request
->flags
.proxyKeepalive
= false;
2647 flags
.readMore
= false;
2648 debugs(33,4, HERE
<< "Will close after error: " << clientConnection
);
2652 bool ConnStateData::serveDelayedError(ClientSocketContext
*context
)
2654 ClientHttpRequest
*http
= context
->http
;
2659 assert(sslServerBump
->entry
);
2660 // Did we create an error entry while processing CONNECT?
2661 if (!sslServerBump
->entry
->isEmpty()) {
2662 quitAfterError(http
->request
);
2664 // Get the saved error entry and send it to the client by replacing the
2665 // ClientHttpRequest store entry with it.
2666 clientStreamNode
*node
= context
->getClientReplyContext();
2667 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2669 debugs(33, 5, "Responding with delated error for " << http
->uri
);
2670 repContext
->setReplyToStoreEntry(sslServerBump
->entry
);
2672 // save the original request for logging purposes
2673 if (!context
->http
->al
->request
) {
2674 context
->http
->al
->request
= http
->request
;
2675 HTTPMSGLOCK(context
->http
->al
->request
);
2678 // Get error details from the fake certificate-peeking request.
2679 http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
2680 context
->pullData();
2684 // In bump-server-first mode, we have not necessarily seen the intended
2685 // server name at certificate-peeking time. Check for domain mismatch now,
2686 // when we can extract the intended name from the bumped HTTP request.
2687 if (X509
*srvCert
= sslServerBump
->serverCert
.get()) {
2688 HttpRequest
*request
= http
->request
;
2689 if (!Ssl::checkX509ServerValidity(srvCert
, request
->GetHost())) {
2690 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2691 "does not match domainname " << request
->GetHost());
2693 bool allowDomainMismatch
= false;
2694 if (Config
.ssl_client
.cert_error
) {
2695 ACLFilledChecklist
check(Config
.ssl_client
.cert_error
, request
, dash_str
);
2696 check
.sslErrors
= new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH
, srvCert
));
2697 allowDomainMismatch
= (check
.fastCheck() == ACCESS_ALLOWED
);
2698 delete check
.sslErrors
;
2699 check
.sslErrors
= NULL
;
2702 if (!allowDomainMismatch
) {
2703 quitAfterError(request
);
2705 clientStreamNode
*node
= context
->getClientReplyContext();
2706 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2707 assert (repContext
);
2709 // Fill the server IP and hostname for error page generation.
2710 HttpRequest::Pointer
const & peekerRequest
= sslServerBump
->request
;
2711 request
->hier
.note(peekerRequest
->hier
.tcpServer
, request
->GetHost());
2713 // Create an error object and fill it
2714 ErrorState
*err
= new ErrorState(ERR_SECURE_CONNECT_FAIL
, Http::scServiceUnavailable
, request
);
2715 err
->src_addr
= clientConnection
->remote
;
2716 Ssl::ErrorDetail
*errDetail
= new Ssl::ErrorDetail(
2717 SQUID_X509_V_ERR_DOMAIN_MISMATCH
,
2719 err
->detail
= errDetail
;
2720 // Save the original request for logging purposes.
2721 if (!context
->http
->al
->request
) {
2722 context
->http
->al
->request
= request
;
2723 HTTPMSGLOCK(context
->http
->al
->request
);
2725 repContext
->setReplyToError(request
->method
, err
);
2726 assert(context
->http
->out
.offset
== 0);
2727 context
->pullData();
2738 clientProcessRequest(ConnStateData
*conn
, HttpParser
*hp
, ClientSocketContext
*context
, const HttpRequestMethod
& method
, Http::ProtocolVersion http_ver
)
2740 ClientHttpRequest
*http
= context
->http
;
2741 HttpRequest::Pointer request
;
2742 bool notedUseOfBuffer
= false;
2743 bool chunked
= false;
2744 bool mustReplyToOptions
= false;
2745 bool unsupportedTe
= false;
2746 bool expectBody
= false;
2748 /* We have an initial client stream in place should it be needed */
2749 /* setup our private context */
2751 context
->registerWithConn();
2753 if (context
->flags
.parsed_ok
== 0) {
2754 clientStreamNode
*node
= context
->getClientReplyContext();
2755 debugs(33, 2, "clientProcessRequest: Invalid Request");
2756 conn
->quitAfterError(NULL
);
2757 // setLogUri should called before repContext->setReplyToError
2758 setLogUri(http
, http
->uri
, true);
2759 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2760 assert (repContext
);
2761 switch (hp
->request_parse_status
) {
2762 case Http::scHeaderTooLarge
:
2763 repContext
->setReplyToError(ERR_TOO_BIG
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2765 case Http::scMethodNotAllowed
:
2766 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scMethodNotAllowed
, method
, http
->uri
,
2767 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2770 repContext
->setReplyToError(ERR_INVALID_REQ
, hp
->request_parse_status
, method
, http
->uri
,
2771 conn
->clientConnection
->remote
, NULL
, conn
->in
.buf
, NULL
);
2773 assert(context
->http
->out
.offset
== 0);
2774 context
->pullData();
2779 assert(http
->request
);
2780 request
= http
->request
;
2781 notedUseOfBuffer
= true;
2783 if ((request
= HttpRequest::CreateFromUrlAndMethod(http
->uri
, method
)) == NULL
) {
2784 clientStreamNode
*node
= context
->getClientReplyContext();
2785 debugs(33, 5, "Invalid URL: " << http
->uri
);
2786 conn
->quitAfterError(request
.getRaw());
2787 // setLogUri should called before repContext->setReplyToError
2788 setLogUri(http
, http
->uri
, true);
2789 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2790 assert (repContext
);
2791 repContext
->setReplyToError(ERR_INVALID_URL
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2792 assert(context
->http
->out
.offset
== 0);
2793 context
->pullData();
2797 /* RFC 2616 section 10.5.6 : handle unsupported HTTP major versions cleanly. */
2798 /* We currently only support 0.9, 1.0, 1.1 properly */
2799 if ( (http_ver
.major
== 0 && http_ver
.minor
!= 9) ||
2800 (http_ver
.major
> 1) ) {
2802 clientStreamNode
*node
= context
->getClientReplyContext();
2803 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp
));
2804 conn
->quitAfterError(request
.getRaw());
2805 // setLogUri should called before repContext->setReplyToError
2806 setLogUri(http
, http
->uri
, true);
2807 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2808 assert (repContext
);
2809 repContext
->setReplyToError(ERR_UNSUP_HTTPVERSION
, Http::scHttpVersionNotSupported
, method
, http
->uri
,
2810 conn
->clientConnection
->remote
, NULL
, HttpParserHdrBuf(hp
), NULL
);
2811 assert(context
->http
->out
.offset
== 0);
2812 context
->pullData();
2816 /* compile headers */
2817 /* we should skip request line! */
2818 /* XXX should actually know the damned buffer size here */
2819 if (!conn
->isFtp
&& http_ver
.major
>= 1 &&
2820 !request
->parseHeader(HttpParserHdrBuf(hp
), HttpParserHdrSz(hp
))) {
2821 clientStreamNode
*node
= context
->getClientReplyContext();
2822 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp
));
2823 conn
->quitAfterError(request
.getRaw());
2824 // setLogUri should called before repContext->setReplyToError
2825 setLogUri(http
, http
->uri
, true);
2826 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2827 assert (repContext
);
2828 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scBadRequest
, method
, http
->uri
, conn
->clientConnection
->remote
, NULL
, NULL
, NULL
);
2829 assert(context
->http
->out
.offset
== 0);
2830 context
->pullData();
2834 request
->clientConnectionManager
= conn
;
2836 request
->flags
.accelerated
= http
->flags
.accel
;
2837 request
->flags
.sslBumped
=conn
->switchedToHttps();
2838 request
->flags
.ignoreCc
= conn
->port
->ignore_cc
;
2839 // TODO: decouple http->flags.accel from request->flags.sslBumped
2840 request
->flags
.noDirect
= (request
->flags
.accelerated
&& !request
->flags
.sslBumped
) ?
2841 !conn
->port
->allow_direct
: 0;
2843 if (request
->flags
.sslBumped
) {
2844 if (conn
->getAuth() != NULL
)
2845 request
->auth_user_request
= conn
->getAuth();
2850 * If transparent or interception mode is working clone the transparent and interception flags
2851 * from the port settings to the request.
2853 if (http
->clientConnection
!= NULL
) {
2854 request
->flags
.intercepted
= ((http
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
2855 request
->flags
.interceptTproxy
= ((http
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
2856 if (request
->flags
.interceptTproxy
) {
2857 if (Config
.accessList
.spoof_client_ip
) {
2858 ACLFilledChecklist
*checklist
= clientAclChecklistCreate(Config
.accessList
.spoof_client_ip
, http
);
2859 request
->flags
.spoofClientIp
= (checklist
->fastCheck() == ACCESS_ALLOWED
);
2862 request
->flags
.spoofClientIp
= true;
2864 request
->flags
.spoofClientIp
= false;
2867 if (internalCheck(request
->urlpath
.termedBuf())) {
2868 if (internalHostnameIs(request
->GetHost()) &&
2869 request
->port
== getMyPort()) {
2870 http
->flags
.internal
= true;
2871 } else if (Config
.onoff
.global_internal_static
&& internalStaticCheck(request
->urlpath
.termedBuf())) {
2872 request
->SetHost(internalHostname());
2873 request
->port
= getMyPort();
2874 http
->flags
.internal
= true;
2878 if (http
->flags
.internal
) {
2879 request
->protocol
= AnyP::PROTO_HTTP
;
2880 request
->login
[0] = '\0';
2883 request
->flags
.internal
= http
->flags
.internal
;
2884 setLogUri (http
, urlCanonicalClean(request
.getRaw()));
2885 request
->client_addr
= conn
->clientConnection
->remote
; // XXX: remove reuest->client_addr member.
2886 #if FOLLOW_X_FORWARDED_FOR
2887 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2888 // not a details about teh TCP connection itself
2889 request
->indirect_client_addr
= conn
->clientConnection
->remote
;
2890 #endif /* FOLLOW_X_FORWARDED_FOR */
2891 request
->my_addr
= conn
->clientConnection
->local
;
2892 request
->myportname
= conn
->port
->name
;
2893 request
->http_ver
= http_ver
;
2895 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2896 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2897 request
->clientConnectionManager
= conn
;
2899 if (request
->header
.chunked()) {
2901 } else if (request
->header
.has(HDR_TRANSFER_ENCODING
)) {
2902 const String te
= request
->header
.getList(HDR_TRANSFER_ENCODING
);
2903 // HTTP/1.1 requires chunking to be the last encoding if there is one
2904 unsupportedTe
= te
.size() && te
!= "identity";
2905 } // else implied identity coding
2907 mustReplyToOptions
= (method
== Http::METHOD_OPTIONS
) &&
2908 (request
->header
.getInt64(HDR_MAX_FORWARDS
) == 0);
2909 if (!urlCheckRequest(request
.getRaw()) || mustReplyToOptions
|| unsupportedTe
) {
2910 clientStreamNode
*node
= context
->getClientReplyContext();
2911 conn
->quitAfterError(request
.getRaw());
2912 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2913 assert (repContext
);
2914 repContext
->setReplyToError(ERR_UNSUP_REQ
, Http::scNotImplemented
, request
->method
, NULL
,
2915 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2916 assert(context
->http
->out
.offset
== 0);
2917 context
->pullData();
2921 if (!chunked
&& !clientIsContentLengthValid(request
.getRaw())) {
2922 clientStreamNode
*node
= context
->getClientReplyContext();
2923 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2924 assert (repContext
);
2925 conn
->quitAfterError(request
.getRaw());
2926 repContext
->setReplyToError(ERR_INVALID_REQ
,
2927 Http::scLengthRequired
, request
->method
, NULL
,
2928 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2929 assert(context
->http
->out
.offset
== 0);
2930 context
->pullData();
2934 if (request
->header
.has(HDR_EXPECT
)) {
2935 const String expect
= request
->header
.getList(HDR_EXPECT
);
2936 const bool supportedExpect
= (expect
.caseCmp("100-continue") == 0);
2937 if (!supportedExpect
) {
2938 clientStreamNode
*node
= context
->getClientReplyContext();
2939 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2940 assert (repContext
);
2941 conn
->quitAfterError(request
.getRaw());
2942 repContext
->setReplyToError(ERR_INVALID_REQ
, Http::scExpectationFailed
, request
->method
, http
->uri
,
2943 conn
->clientConnection
->remote
, request
.getRaw(), NULL
, NULL
);
2944 assert(context
->http
->out
.offset
== 0);
2945 context
->pullData();
2951 http
->request
= request
.getRaw();
2952 HTTPMSGLOCK(http
->request
);
2954 clientSetKeepaliveFlag(http
);
2956 // Let tunneling code be fully responsible for CONNECT requests
2957 if (http
->request
->method
== Http::METHOD_CONNECT
) {
2958 context
->mayUseConnection(true);
2959 conn
->flags
.readMore
= false;
2963 if (conn
->switchedToHttps() && conn
->serveDelayedError(context
))
2967 /* Do we expect a request-body? */
2968 expectBody
= chunked
|| request
->content_length
> 0;
2969 if (!context
->mayUseConnection() && expectBody
) {
2970 request
->body_pipe
= conn
->expectRequestBody(
2971 chunked
? -1 : request
->content_length
);
2973 if (!notedUseOfBuffer
) {
2974 // consume header early so that body pipe gets just the body
2975 connNoteUseOfBuffer(conn
, http
->req_sz
);
2976 notedUseOfBuffer
= true;
2979 /* Is it too large? */
2980 if (!chunked
&& // if chunked, we will check as we accumulate
2981 clientIsRequestBodyTooLargeForPolicy(request
->content_length
)) {
2982 clientStreamNode
*node
= context
->getClientReplyContext();
2983 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
2984 assert (repContext
);
2985 conn
->quitAfterError(request
.getRaw());
2986 repContext
->setReplyToError(ERR_TOO_BIG
,
2987 Http::scRequestEntityTooLarge
, Http::METHOD_NONE
, NULL
,
2988 conn
->clientConnection
->remote
, http
->request
, NULL
, NULL
);
2989 assert(context
->http
->out
.offset
== 0);
2990 context
->pullData();
2995 // We may stop producing, comm_close, and/or call setReplyToError()
2996 // below, so quit on errors to avoid http->doCallouts()
2997 if (!conn
->handleRequestBodyData())
3000 if (!request
->body_pipe
->productionEnded()) {
3001 debugs(33, 5, HERE
<< "need more request body");
3002 context
->mayUseConnection(true);
3003 assert(conn
->flags
.readMore
);
3008 http
->calloutContext
= new ClientRequestContext(http
);
3013 if (!notedUseOfBuffer
)
3014 connNoteUseOfBuffer(conn
, http
->req_sz
);
3018 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
3019 * to here because calling comm_reset_close() causes http to
3020 * be freed and the above connNoteUseOfBuffer() would hit an
3021 * assertion, not to mention that we were accessing freed memory.
3023 if (request
!= NULL
&& request
->flags
.resetTcp
&& Comm::IsConnOpen(conn
->clientConnection
)) {
3024 debugs(33, 3, HERE
<< "Sending TCP RST on " << conn
->clientConnection
);
3025 conn
->flags
.readMore
= false;
3026 comm_reset_close(conn
->clientConnection
);
3031 ConnStateData::processFtpRequest(ClientSocketContext
*const context
)
3033 ClientHttpRequest
*const http
= context
->http
;
3034 assert(http
!= NULL
);
3035 HttpRequest
*const request
= http
->request
;
3036 assert(request
!= NULL
);
3037 debugs(33, 9, request
);
3039 HttpHeader
&header
= request
->header
;
3040 assert(header
.has(HDR_FTP_COMMAND
));
3041 String
&cmd
= header
.findEntry(HDR_FTP_COMMAND
)->value
;
3042 assert(header
.has(HDR_FTP_ARGUMENTS
));
3043 String
¶ms
= header
.findEntry(HDR_FTP_ARGUMENTS
)->value
;
3045 const bool fwd
= !http
->storeEntry() &&
3046 FtpHandleRequest(context
, cmd
, params
);
3048 if (http
->storeEntry() != NULL
) {
3049 debugs(33, 4, "got an immediate response");
3050 assert(http
->storeEntry() != NULL
);
3051 clientSetKeepaliveFlag(http
);
3052 context
->pullData();
3054 debugs(33, 4, "forwarding request to server side");
3055 assert(http
->storeEntry() == NULL
);
3056 clientProcessRequest(this, &parser_
, context
, request
->method
,
3059 debugs(33, 4, "will resume processing later");
3064 ConnStateData::resumeFtpRequest(ClientSocketContext
*const context
)
3066 debugs(33, 4, "resuming");
3067 processFtpRequest(context
);
3071 connStripBufferWhitespace (ConnStateData
* conn
)
3073 while (conn
->in
.notYetUsed
> 0 && xisspace(conn
->in
.buf
[0])) {
3074 memmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.notYetUsed
- 1);
3075 -- conn
->in
.notYetUsed
;
3080 * Limit the number of concurrent requests.
3081 * \return true when there are available position(s) in the pipeline queue for another request.
3082 * \return false when the pipeline queue is full or disabled.
3085 ConnStateData::concurrentRequestQueueFilled() const
3087 const int existingRequestCount
= getConcurrentRequestCount();
3089 // default to the configured pipeline size.
3090 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
3091 const int concurrentRequestLimit
= (isFtp
? 0 : Config
.pipeline_max_prefetch
) + 1;
3093 // when queue filled already we cant add more.
3094 if (existingRequestCount
>= concurrentRequestLimit
) {
3095 debugs(33, 3, clientConnection
<< " max concurrent requests reached (" << concurrentRequestLimit
<< ")");
3096 debugs(33, 5, clientConnection
<< " deferring new request until one is done");
3104 * Attempt to parse one or more requests from the input buffer.
3105 * If a request is successfully parsed, even if the next request
3106 * is only partially parsed, it will return TRUE.
3109 ConnStateData::clientParseRequests()
3111 HttpRequestMethod method
;
3112 bool parsed_req
= false;
3114 debugs(33, 5, HERE
<< clientConnection
<< ": attempting to parse");
3116 // Loop while we have read bytes that are not needed for producing the body
3117 // On errors, bodyPipe may become nil, but readMore will be cleared
3118 while (in
.notYetUsed
> 0 && !bodyPipe
&& flags
.readMore
) {
3119 connStripBufferWhitespace(this);
3121 /* Don't try to parse if the buffer is empty */
3122 if (in
.notYetUsed
== 0)
3125 /* Limit the number of concurrent requests */
3126 if (concurrentRequestQueueFilled())
3129 /* Should not be needed anymore */
3130 /* Terminate the string */
3131 in
.buf
[in
.notYetUsed
] = '\0';
3133 Http::ProtocolVersion http_ver
;
3134 ClientSocketContext
*context
= NULL
;
3136 /* Begin the parsing */
3137 PROF_start(parseHttpRequest
);
3138 HttpParserInit(&parser_
, in
.buf
, in
.notYetUsed
);
3140 /* Process request */
3141 context
= parseHttpRequest(this, &parser_
, &method
, &http_ver
);
3142 PROF_stop(parseHttpRequest
);
3144 context
= FtpParseRequest(this, &method
, &http_ver
);
3146 /* partial or incomplete request */
3148 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
3149 // (which becomes context) but checkHeaderLimits cannot?
3150 checkHeaderLimits();
3154 /* status -1 or 1 */
3156 debugs(33, 5, HERE
<< clientConnection
<< ": parsed a request");
3157 AsyncCall::Pointer timeoutCall
= commCbCall(5, 4, "clientLifetimeTimeout",
3158 CommTimeoutCbPtrFun(clientLifetimeTimeout
, context
->http
));
3159 commSetConnTimeout(clientConnection
, Config
.Timeout
.lifetime
, timeoutCall
);
3162 clientProcessRequest(this, &parser_
, context
, method
, http_ver
);
3164 // Process FTP request asynchronously to make sure FTP
3165 // data connection accept callback is fired first.
3166 CallJobHere1(33, 4, CbcPointer
<ConnStateData
>(this),
3167 ConnStateData
, ConnStateData::processFtpRequest
, context
);
3170 parsed_req
= true; // XXX: do we really need to parse everything right NOW ?
3172 if (context
->mayUseConnection()) {
3173 debugs(33, 3, HERE
<< "Not parsing new requests, as this request may need the connection");
3179 /* XXX where to 'finish' the parsing pass? */
3184 ConnStateData::clientReadRequest(const CommIoCbParams
&io
)
3186 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3190 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
3192 if (io
.flag
== COMM_ERR_CLOSING
) {
3193 debugs(33,5, HERE
<< io
.conn
<< " closing Bailout.");
3197 assert(Comm::IsConnOpen(clientConnection
));
3198 assert(io
.conn
->fd
== clientConnection
->fd
);
3201 * Don't reset the timeout value here. The timeout value will be
3202 * set to Config.Timeout.request by httpAccept() and
3203 * clientWriteComplete(), and should apply to the request as a
3204 * whole, not individual read() calls. Plus, it breaks our
3205 * lame half-close detection
3207 if (connReadWasError(io
.flag
, io
.size
, io
.xerrno
)) {
3208 notifyAllContexts(io
.xerrno
);
3213 if (io
.flag
== COMM_OK
) {
3215 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3217 // may comm_close or setReplyToError
3218 if (!handleReadData(io
.buf
, io
.size
))
3221 } else if (io
.size
== 0) {
3222 debugs(33, 5, HERE
<< io
.conn
<< " closed?");
3224 if (connFinishedWithConn(io
.size
)) {
3225 clientConnection
->close();
3229 /* It might be half-closed, we can't tell */
3230 fd_table
[io
.conn
->fd
].flags
.socket_eof
= true;
3232 commMarkHalfClosed(io
.conn
->fd
);
3234 fd_note(io
.conn
->fd
, "half-closed");
3236 /* There is one more close check at the end, to detect aborted
3237 * (partial) requests. At this point we can't tell if the request
3240 /* Continue to process previously read data */
3244 /* Process next request */
3245 if (getConcurrentRequestCount() == 0)
3246 fd_note(io
.fd
, "Reading next request");
3248 if (!clientParseRequests()) {
3252 * If the client here is half closed and we failed
3253 * to parse a request, close the connection.
3254 * The above check with connFinishedWithConn() only
3255 * succeeds _if_ the buffer is empty which it won't
3256 * be if we have an incomplete request.
3257 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
3259 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io
.fd
)) {
3260 debugs(33, 5, HERE
<< io
.conn
<< ": half-closed connection, no completed request parsed, connection closing.");
3261 clientConnection
->close();
3269 clientAfterReadingRequests();
3273 ConnStateData::clientReadFtpData(const CommIoCbParams
&io
)
3275 debugs(33,5,HERE
<< io
.conn
<< " size " << io
.size
);
3276 Must(ftp
.reader
!= NULL
);
3279 assert(Comm::IsConnOpen(ftp
.dataConn
));
3280 assert(io
.conn
->fd
== ftp
.dataConn
->fd
);
3282 if (io
.flag
== COMM_OK
) {
3284 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
3286 char *const current_buf
= ftp
.uploadBuf
+ ftp
.uploadAvailSize
;
3287 if (io
.buf
!= current_buf
)
3288 memmove(current_buf
, io
.buf
, io
.size
);
3289 ftp
.uploadAvailSize
+= io
.size
;
3290 handleFtpRequestData();
3291 } else if (io
.size
== 0) {
3292 debugs(33, 5, HERE
<< io
.conn
<< " closed");
3293 FtpCloseDataConnection(this);
3294 if (ftp
.uploadAvailSize
<= 0)
3295 finishDechunkingRequest(true);
3298 debugs(33, 5, HERE
<< io
.conn
<< " closed");
3299 FtpCloseDataConnection(this);
3300 finishDechunkingRequest(false);
3306 ConnStateData::handleFtpRequestData()
3308 assert(bodyPipe
!= NULL
);
3310 debugs(33,5, HERE
<< "handling FTP request data for " << clientConnection
);
3311 const size_t putSize
= bodyPipe
->putMoreData(ftp
.uploadBuf
,
3312 ftp
.uploadAvailSize
);
3314 ftp
.uploadAvailSize
-= putSize
;
3315 if (ftp
.uploadAvailSize
> 0)
3316 memmove(ftp
.uploadBuf
, ftp
.uploadBuf
+ putSize
, ftp
.uploadAvailSize
);
3319 if (Comm::IsConnOpen(ftp
.dataConn
))
3321 else if (ftp
.uploadAvailSize
<= 0)
3322 finishDechunkingRequest(true);
3326 * called when new request data has been read from the socket
3328 * \retval false called comm_close or setReplyToError (the caller should bail)
3329 * \retval true we did not call comm_close or setReplyToError
3332 ConnStateData::handleReadData(char *buf
, size_t size
)
3334 char *current_buf
= in
.addressToReadInto();
3336 if (buf
!= current_buf
)
3337 memmove(current_buf
, buf
, size
);
3339 in
.notYetUsed
+= size
;
3341 in
.buf
[in
.notYetUsed
] = '\0'; /* Terminate the string */
3343 // if we are reading a body, stuff data into the body pipe
3344 if (bodyPipe
!= NULL
)
3345 return handleRequestBodyData();
3350 * called when new request body data has been buffered in in.buf
3351 * may close the connection if we were closing and piped everything out
3353 * \retval false called comm_close or setReplyToError (the caller should bail)
3354 * \retval true we did not call comm_close or setReplyToError
3357 ConnStateData::handleRequestBodyData()
3359 assert(bodyPipe
!= NULL
);
3363 if (in
.bodyParser
) { // chunked encoding
3364 if (const err_type error
= handleChunkedRequestBody(putSize
)) {
3365 abortChunkedRequestBody(error
);
3368 } else { // identity encoding
3369 debugs(33,5, HERE
<< "handling plain request body for " << clientConnection
);
3370 putSize
= bodyPipe
->putMoreData(in
.buf
, in
.notYetUsed
);
3371 if (!bodyPipe
->mayNeedMoreData()) {
3372 // BodyPipe will clear us automagically when we produced everything
3378 connNoteUseOfBuffer(this, putSize
);
3381 debugs(33,5, HERE
<< "produced entire request body for " << clientConnection
);
3383 if (const char *reason
= stoppedSending()) {
3384 /* we've finished reading like good clients,
3385 * now do the close that initiateClose initiated.
3387 debugs(33, 3, HERE
<< "closing for earlier sending error: " << reason
);
3388 clientConnection
->close();
3396 /// parses available chunked encoded body bytes, checks size, returns errors
3398 ConnStateData::handleChunkedRequestBody(size_t &putSize
)
3400 debugs(33,7, HERE
<< "chunked from " << clientConnection
<< ": " << in
.notYetUsed
);
3402 try { // the parser will throw on errors
3404 if (!in
.notYetUsed
) // nothing to do (MemBuf::init requires this check)
3407 MemBuf raw
; // ChunkedCodingParser only works with MemBufs
3408 // add one because MemBuf will assert if it cannot 0-terminate
3409 raw
.init(in
.notYetUsed
, in
.notYetUsed
+1);
3410 raw
.append(in
.buf
, in
.notYetUsed
);
3412 const mb_size_t wasContentSize
= raw
.contentSize();
3413 BodyPipeCheckout
bpc(*bodyPipe
);
3414 const bool parsed
= in
.bodyParser
->parse(&raw
, &bpc
.buf
);
3416 putSize
= wasContentSize
- raw
.contentSize();
3418 // dechunk then check: the size limit applies to _dechunked_ content
3419 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe
->producedSize()))
3423 finishDechunkingRequest(true);
3425 return ERR_NONE
; // nil bodyPipe implies body end for the caller
3428 // if chunk parser needs data, then the body pipe must need it too
3429 Must(!in
.bodyParser
->needsMoreData() || bodyPipe
->mayNeedMoreData());
3431 // if parser needs more space and we can consume nothing, we will stall
3432 Must(!in
.bodyParser
->needsMoreSpace() || bodyPipe
->buf().hasContent());
3433 } catch (...) { // TODO: be more specific
3434 debugs(33, 3, HERE
<< "malformed chunks" << bodyPipe
->status());
3435 return ERR_INVALID_REQ
;
3438 debugs(33, 7, HERE
<< "need more chunked data" << *bodyPipe
->status());
3442 /// quit on errors related to chunked request body handling
3444 ConnStateData::abortChunkedRequestBody(const err_type error
)
3446 finishDechunkingRequest(false);
3448 // XXX: The code below works if we fail during initial request parsing,
3449 // but if we fail when the server-side works already, the server may send
3450 // us its response too, causing various assertions. How to prevent that?
3451 #if WE_KNOW_HOW_TO_SEND_ERRORS
3452 ClientSocketContext::Pointer context
= getCurrentContext();
3453 if (context
!= NULL
&& !context
->http
->out
.offset
) { // output nothing yet
3454 clientStreamNode
*node
= context
->getClientReplyContext();
3455 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
3457 const Http::StatusCode scode
= (error
== ERR_TOO_BIG
) ?
3458 Http::scRequestEntityTooLarge
: HTTP_BAD_REQUEST
;
3459 repContext
->setReplyToError(error
, scode
,
3460 repContext
->http
->request
->method
,
3461 repContext
->http
->uri
,
3463 repContext
->http
->request
,
3465 context
->pullData();
3467 // close or otherwise we may get stuck as nobody will notice the error?
3468 comm_reset_close(clientConnection
);
3471 debugs(33, 3, HERE
<< "aborting chunked request without error " << error
);
3472 comm_reset_close(clientConnection
);
3474 flags
.readMore
= false;
3478 ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
3481 handleFtpRequestData();
3485 if (!handleRequestBodyData())
3488 // too late to read more body
3489 if (!isOpen() || stoppedReceiving())
3496 ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer
)
3498 // request reader may get stuck waiting for space if nobody consumes body
3499 if (bodyPipe
!= NULL
)
3500 bodyPipe
->enableAutoConsumption();
3503 FtpCloseDataConnection(this);
3507 stopReceiving("virgin request body consumer aborted"); // closes ASAP
3510 /** general lifetime handler for HTTP requests */
3512 ConnStateData::requestTimeout(const CommTimeoutCbParams
&io
)
3515 * Just close the connection to not confuse browsers
3516 * using persistent connections. Some browsers open
3517 * a connection and then do not use it until much
3518 * later (presumeably because the request triggering
3519 * the open has already been completed on another
3522 debugs(33, 3, "requestTimeout: FD " << io
.fd
<< ": lifetime is expired.");
3527 clientLifetimeTimeout(const CommTimeoutCbParams
&io
)
3529 ClientHttpRequest
*http
= static_cast<ClientHttpRequest
*>(io
.data
);
3530 debugs(33, DBG_IMPORTANT
, "WARNING: Closing client connection due to lifetime timeout");
3531 debugs(33, DBG_IMPORTANT
, "\t" << http
->uri
);
3532 http
->al
->http
.timedout
= true;
3533 if (Comm::IsConnOpen(io
.conn
))
3537 ConnStateData::ConnStateData(const MasterXaction::Pointer
&xact
):
3538 AsyncJob("ConnStateData"),
3539 isFtp(strcmp(xact
->squidPort
->protocol
, "ftp") == 0), // TODO: convert into a method?
3541 sslBumpMode(Ssl::bumpEnd
),
3542 switchedToHttps_(false),
3543 sslServerBump(NULL
),
3545 stoppedSending_(NULL
),
3546 stoppedReceiving_(NULL
)
3548 pinning
.host
= NULL
;
3550 pinning
.pinned
= false;
3551 pinning
.auth
= false;
3552 pinning
.zeroReply
= false;
3553 pinning
.peer
= NULL
;
3555 // store the details required for creating more MasterXaction objects as new requests come in
3556 clientConnection
= xact
->tcpClient
;
3557 port
= cbdataReference(xact
->squidPort
.get());
3558 log_addr
= xact
->tcpClient
->remote
;
3559 log_addr
.applyMask(Config
.Addrs
.client_netmask
);
3561 in
.buf
= (char *)memAllocBuf(CLIENT_REQ_BUF_SZ
, &in
.allocatedSize
);
3563 if (port
->disable_pmtu_discovery
!= DISABLE_PMTU_OFF
&&
3564 (transparent() || port
->disable_pmtu_discovery
== DISABLE_PMTU_ALWAYS
)) {
3565 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3566 int i
= IP_PMTUDISC_DONT
;
3567 if (setsockopt(clientConnection
->fd
, SOL_IP
, IP_MTU_DISCOVER
, &i
, sizeof(i
)) < 0)
3568 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection
<< " : " << xstrerror());
3570 static bool reported
= false;
3573 debugs(33, DBG_IMPORTANT
, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3579 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
3580 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, ConnStateData::connStateClosed
);
3581 comm_add_close_handler(clientConnection
->fd
, call
);
3583 if (Config
.onoff
.log_fqdn
)
3584 fqdncache_gethostbyaddr(clientConnection
->remote
, FQDN_LOOKUP_IF_MISS
);
3587 if (Ident::TheConfig
.identLookup
) {
3588 ACLFilledChecklist
identChecklist(Ident::TheConfig
.identLookup
, NULL
, NULL
);
3589 identChecklist
.src_addr
= xact
->tcpClient
->remote
;
3590 identChecklist
.my_addr
= xact
->tcpClient
->local
;
3591 if (identChecklist
.fastCheck() == ACCESS_ALLOWED
)
3592 Ident::Start(xact
->tcpClient
, clientIdentDone
, this);
3596 clientdbEstablished(clientConnection
->remote
, 1);
3598 flags
.readMore
= !isFtp
;
3601 /** Handle a new connection on HTTP socket. */
3603 httpAccept(const CommAcceptCbParams
¶ms
)
3605 MasterXaction::Pointer xact
= params
.xaction
;
3606 AnyP::PortCfgPointer s
= xact
->squidPort
;
3609 // it is possible the call or accept() was still queued when the port was reconfigured
3610 debugs(33, 2, "HTTP accept failure: port reconfigured.");
3614 if (params
.flag
!= COMM_OK
) {
3615 // Its possible the call was still queued when the client disconnected
3616 debugs(33, 2, "httpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3620 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3621 fd_note(params
.conn
->fd
, "client http connect");
3623 if (s
->tcp_keepalive
.enabled
) {
3624 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3627 ++ incoming_sockets_accepted
;
3629 // Socket is ready, setup the connection manager to start using it
3630 ConnStateData
*connState
= new ConnStateData(xact
);
3632 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3633 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5,
3634 TimeoutDialer
, connState
, ConnStateData::requestTimeout
);
3635 commSetConnTimeout(params
.conn
, Config
.Timeout
.request
, timeoutCall
);
3637 connState
->readSomeData();
3640 fd_table
[params
.conn
->fd
].clientInfo
= NULL
;
3642 if (Config
.onoff
.client_db
) {
3643 /* it was said several times that client write limiter does not work if client_db is disabled */
3645 ClientDelayPools
& pools(Config
.ClientDelay
.pools
);
3646 ACLFilledChecklist
ch(NULL
, NULL
, NULL
);
3648 // TODO: we check early to limit error response bandwith but we
3649 // should recheck when we can honor delay_pool_uses_indirect
3650 // TODO: we should also pass the port details for myportname here.
3651 ch
.src_addr
= params
.conn
->remote
;
3652 ch
.my_addr
= params
.conn
->local
;
3654 for (unsigned int pool
= 0; pool
< pools
.size(); ++pool
) {
3656 /* pools require explicit 'allow' to assign a client into them */
3657 if (pools
[pool
].access
) {
3658 ch
.accessList
= pools
[pool
].access
;
3659 allow_t answer
= ch
.fastCheck();
3660 if (answer
== ACCESS_ALLOWED
) {
3662 /* request client information from db after we did all checks
3663 this will save hash lookup if client failed checks */
3664 ClientInfo
* cli
= clientdbGetInfo(params
.conn
->remote
);
3667 /* put client info in FDE */
3668 fd_table
[params
.conn
->fd
].clientInfo
= cli
;
3670 /* setup write limiter for this request */
3671 const double burst
= floor(0.5 +
3672 (pools
[pool
].highwatermark
* Config
.ClientDelay
.initial
)/100.0);
3673 cli
->setWriteLimiter(pools
[pool
].rate
, burst
, pools
[pool
].highwatermark
);
3676 debugs(83, 4, HERE
<< "Delay pool " << pool
<< " skipped because ACL " << answer
);
3686 /** Create SSL connection structure and update fd_table */
3688 httpsCreate(const Comm::ConnectionPointer
&conn
, SSL_CTX
*sslContext
)
3690 SSL
*ssl
= SSL_new(sslContext
);
3693 const int ssl_error
= ERR_get_error();
3694 debugs(83, DBG_IMPORTANT
, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error
, NULL
) );
3699 SSL_set_fd(ssl
, conn
->fd
);
3700 fd_table
[conn
->fd
].ssl
= ssl
;
3701 fd_table
[conn
->fd
].read_method
= &ssl_read_method
;
3702 fd_table
[conn
->fd
].write_method
= &ssl_write_method
;
3704 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn
);
3705 fd_note(conn
->fd
, "client https start");
3710 /** negotiate an SSL connection */
3712 clientNegotiateSSL(int fd
, void *data
)
3714 ConnStateData
*conn
= (ConnStateData
*)data
;
3716 SSL
*ssl
= fd_table
[fd
].ssl
;
3719 if ((ret
= SSL_accept(ssl
)) <= 0) {
3720 int ssl_error
= SSL_get_error(ssl
, ret
);
3722 switch (ssl_error
) {
3724 case SSL_ERROR_WANT_READ
:
3725 Comm::SetSelect(fd
, COMM_SELECT_READ
, clientNegotiateSSL
, conn
, 0);
3728 case SSL_ERROR_WANT_WRITE
:
3729 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, clientNegotiateSSL
, conn
, 0);
3732 case SSL_ERROR_SYSCALL
:
3735 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Aborted by client");
3741 if (errno
== ECONNRESET
)
3744 debugs(83, hard
? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3745 fd
<< ": " << strerror(errno
) << " (" << errno
<< ")");
3752 case SSL_ERROR_ZERO_RETURN
:
3753 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd
<< ": Closed by client");
3758 debugs(83, DBG_IMPORTANT
, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
3759 fd
<< ": " << ERR_error_string(ERR_get_error(), NULL
) <<
3760 " (" << ssl_error
<< "/" << ret
<< ")");
3768 if (SSL_session_reused(ssl
)) {
3769 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl
) <<
3770 " reused on FD " << fd
<< " (" << fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<< ")");
3772 if (do_debug(83, 4)) {
3773 /* Write out the SSL session details.. actually the call below, but
3774 * OpenSSL headers do strange typecasts confusing GCC.. */
3775 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
3776 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
3777 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
);
3779 #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
3781 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3782 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3783 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3784 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3785 * Because there are two possible usable cast, if you get an error here, try the other
3786 * commented line. */
3788 PEM_ASN1_write((int(*)())i2d_SSL_SESSION
, PEM_STRING_SSL_SESSION
, debug_log
, (char *)SSL_get_session(ssl
), NULL
,NULL
,0,NULL
,NULL
);
3789 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
3793 debugs(83, 4, "With " OPENSSL_VERSION_TEXT
", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
3796 /* Note: This does not automatically fflush the log file.. */
3799 debugs(83, 2, "clientNegotiateSSL: New session " <<
3800 SSL_get_session(ssl
) << " on FD " << fd
<< " (" <<
3801 fd_table
[fd
].ipaddr
<< ":" << (int)fd_table
[fd
].remote_port
<<
3805 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<< " negotiated cipher " <<
3806 SSL_get_cipher(ssl
));
3808 client_cert
= SSL_get_peer_certificate(ssl
);
3810 if (client_cert
!= NULL
) {
3811 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3812 " client certificate: subject: " <<
3813 X509_NAME_oneline(X509_get_subject_name(client_cert
), 0, 0));
3815 debugs(83, 3, "clientNegotiateSSL: FD " << fd
<<
3816 " client certificate: issuer: " <<
3817 X509_NAME_oneline(X509_get_issuer_name(client_cert
), 0, 0));
3819 X509_free(client_cert
);
3821 debugs(83, 5, "clientNegotiateSSL: FD " << fd
<<
3822 " has no certificate.");
3825 conn
->readSomeData();
3829 * If SSL_CTX is given, starts reading the SSL handshake.
3830 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
3833 httpsEstablish(ConnStateData
*connState
, SSL_CTX
*sslContext
, Ssl::BumpMode bumpMode
)
3837 const Comm::ConnectionPointer
&details
= connState
->clientConnection
;
3839 if (sslContext
&& !(ssl
= httpsCreate(details
, sslContext
)))
3842 typedef CommCbMemFunT
<ConnStateData
, CommTimeoutCbParams
> TimeoutDialer
;
3843 AsyncCall::Pointer timeoutCall
= JobCallback(33, 5, TimeoutDialer
,
3844 connState
, ConnStateData::requestTimeout
);
3845 commSetConnTimeout(details
, Config
.Timeout
.request
, timeoutCall
);
3848 Comm::SetSelect(details
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, connState
, 0);
3850 char buf
[MAX_IPSTRLEN
];
3851 assert(bumpMode
!= Ssl::bumpNone
&& bumpMode
!= Ssl::bumpEnd
);
3852 HttpRequest::Pointer
fakeRequest(new HttpRequest
);
3853 fakeRequest
->SetHost(details
->local
.toStr(buf
, sizeof(buf
)));
3854 fakeRequest
->port
= details
->local
.port();
3855 fakeRequest
->clientConnectionManager
= connState
;
3856 fakeRequest
->client_addr
= connState
->clientConnection
->remote
;
3857 #if FOLLOW_X_FORWARDED_FOR
3858 fakeRequest
->indirect_client_addr
= connState
->clientConnection
->remote
;
3860 fakeRequest
->my_addr
= connState
->clientConnection
->local
;
3861 fakeRequest
->flags
.interceptTproxy
= ((connState
->clientConnection
->flags
& COMM_TRANSPARENT
) != 0 ) ;
3862 fakeRequest
->flags
.intercepted
= ((connState
->clientConnection
->flags
& COMM_INTERCEPTION
) != 0);
3863 fakeRequest
->myportname
= connState
->port
->name
;
3864 if (fakeRequest
->flags
.interceptTproxy
) {
3865 if (Config
.accessList
.spoof_client_ip
) {
3866 ACLFilledChecklist
checklist(Config
.accessList
.spoof_client_ip
, fakeRequest
.getRaw(), NULL
);
3867 fakeRequest
->flags
.spoofClientIp
= (checklist
.fastCheck() == ACCESS_ALLOWED
);
3869 fakeRequest
->flags
.spoofClientIp
= true;
3871 fakeRequest
->flags
.spoofClientIp
= false;
3872 debugs(33, 4, HERE
<< details
<< " try to generate a Dynamic SSL CTX");
3873 connState
->switchToHttps(fakeRequest
.getRaw(), bumpMode
);
3878 * A callback function to use with the ACLFilledChecklist callback.
3879 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
3880 * else reverts the connection to tunnel mode.
3883 httpsSslBumpAccessCheckDone(allow_t answer
, void *data
)
3885 ConnStateData
*connState
= (ConnStateData
*) data
;
3887 // if the connection is closed or closing, just return.
3888 if (!connState
->isOpen())
3891 // Require both a match and a positive bump mode to work around exceptional
3892 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3893 if (answer
== ACCESS_ALLOWED
&& answer
.kind
!= Ssl::bumpNone
) {
3894 debugs(33, 2, HERE
<< "sslBump needed for " << connState
->clientConnection
);
3895 connState
->sslBumpMode
= static_cast<Ssl::BumpMode
>(answer
.kind
);
3896 httpsEstablish(connState
, NULL
, (Ssl::BumpMode
)answer
.kind
);
3898 debugs(33, 2, HERE
<< "sslBump not needed for " << connState
->clientConnection
);
3899 connState
->sslBumpMode
= Ssl::bumpNone
;
3901 // fake a CONNECT request to force connState to tunnel
3902 static char ip
[MAX_IPSTRLEN
];
3903 static char reqStr
[MAX_IPSTRLEN
+ 80];
3904 connState
->clientConnection
->local
.toUrl(ip
, sizeof(ip
));
3905 snprintf(reqStr
, sizeof(reqStr
), "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", ip
, ip
);
3906 bool ret
= connState
->handleReadData(reqStr
, strlen(reqStr
));
3908 ret
= connState
->clientParseRequests();
3911 debugs(33, 2, HERE
<< "Failed to start fake CONNECT request for ssl bumped connection: " << connState
->clientConnection
);
3912 connState
->clientConnection
->close();
3917 /** handle a new HTTPS connection */
3919 httpsAccept(const CommAcceptCbParams
¶ms
)
3921 MasterXaction::Pointer xact
= params
.xaction
;
3922 const AnyP::PortCfgPointer s
= xact
->squidPort
;
3925 // it is possible the call or accept() was still queued when the port was reconfigured
3926 debugs(33, 2, "HTTPS accept failure: port reconfigured.");
3930 if (params
.flag
!= COMM_OK
) {
3931 // Its possible the call was still queued when the client disconnected
3932 debugs(33, 2, "httpsAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3936 debugs(33, 4, HERE
<< params
.conn
<< " accepted, starting SSL negotiation.");
3937 fd_note(params
.conn
->fd
, "client https connect");
3939 if (s
->tcp_keepalive
.enabled
) {
3940 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
3943 ++incoming_sockets_accepted
;
3945 // Socket is ready, setup the connection manager to start using it
3946 ConnStateData
*connState
= new ConnStateData(xact
);
3948 if (s
->flags
.tunnelSslBumping
) {
3949 debugs(33, 5, "httpsAccept: accept transparent connection: " << params
.conn
);
3951 if (!Config
.accessList
.ssl_bump
) {
3952 httpsSslBumpAccessCheckDone(ACCESS_DENIED
, connState
);
3956 // Create a fake HTTP request for ssl_bump ACL check,
3957 // using tproxy/intercept provided destination IP and port.
3958 HttpRequest
*request
= new HttpRequest();
3959 static char ip
[MAX_IPSTRLEN
];
3960 assert(params
.conn
->flags
& (COMM_TRANSPARENT
| COMM_INTERCEPTION
));
3961 request
->SetHost(params
.conn
->local
.toStr(ip
, sizeof(ip
)));
3962 request
->port
= params
.conn
->local
.port();
3963 request
->myportname
= s
->name
;
3965 ACLFilledChecklist
*acl_checklist
= new ACLFilledChecklist(Config
.accessList
.ssl_bump
, request
, NULL
);
3966 acl_checklist
->src_addr
= params
.conn
->remote
;
3967 acl_checklist
->my_addr
= s
->s
;
3968 acl_checklist
->nonBlockingCheck(httpsSslBumpAccessCheckDone
, connState
);
3971 SSL_CTX
*sslContext
= s
->staticSslContext
.get();
3972 httpsEstablish(connState
, sslContext
, Ssl::bumpNone
);
3976 /** handle a new FTP connection */
3978 ftpAccept(const CommAcceptCbParams
¶ms
)
3980 MasterXaction::Pointer xact
= params
.xaction
;
3981 AnyP::PortCfgPointer s
= xact
->squidPort
;
3984 // it is possible the call or accept() was still queued when the port was reconfigured
3985 debugs(33, 2, "FTP accept failure: port reconfigured.");
3989 if (params
.flag
!= COMM_OK
) {
3990 // Its possible the call was still queued when the client disconnected
3991 debugs(33, 2, "ftpAccept: " << s
->listenConn
<< ": accept failure: " << xstrerr(params
.xerrno
));
3995 debugs(33, 4, HERE
<< params
.conn
<< ": accepted");
3996 fd_note(params
.conn
->fd
, "client ftp connect");
3998 if (s
->tcp_keepalive
.enabled
) {
3999 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
4002 ++incoming_sockets_accepted
;
4004 // Socket is ready, setup the connection manager to start using it
4005 ConnStateData
*connState
= new ConnStateData(xact
);
4007 if (connState
->transparent()) {
4008 char buf
[MAX_IPSTRLEN
];
4009 connState
->clientConnection
->local
.toUrl(buf
, MAX_IPSTRLEN
);
4010 connState
->ftp
.uri
= "ftp://";
4011 connState
->ftp
.uri
.append(buf
);
4012 connState
->ftp
.uri
.append("/");
4013 debugs(33, 5, HERE
<< "FTP transparent URL: " << connState
->ftp
.uri
);
4016 FtpWriteEarlyReply(connState
, 220, "Service ready");
4018 // TODO: Merge common httpAccept() parts, applying USE_DELAY_POOLS to FTP.
4022 ConnStateData::sslCrtdHandleReplyWrapper(void *data
, const HelperReply
&reply
)
4024 ConnStateData
* state_data
= (ConnStateData
*)(data
);
4025 state_data
->sslCrtdHandleReply(reply
);
4029 ConnStateData::sslCrtdHandleReply(const HelperReply
&reply
)
4031 if (reply
.result
== HelperReply::BrokenHelper
) {
4032 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply
);
4033 } else if (!reply
.other().hasContent()) {
4034 debugs(1, DBG_IMPORTANT
, HERE
<< "\"ssl_crtd\" helper returned <NULL> reply.");
4036 Ssl::CrtdMessage
reply_message(Ssl::CrtdMessage::REPLY
);
4037 if (reply_message
.parse(reply
.other().content(), reply
.other().contentSize()) != Ssl::CrtdMessage::OK
) {
4038 debugs(33, 5, HERE
<< "Reply from ssl_crtd for " << sslConnectHostOrIp
<< " is incorrect");
4040 if (reply
.result
!= HelperReply::Okay
) {
4041 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " cannot be generated. ssl_crtd response: " << reply_message
.getBody());
4043 debugs(33, 5, HERE
<< "Certificate for " << sslConnectHostOrIp
<< " was successfully recieved from ssl_crtd");
4044 SSL_CTX
*ctx
= Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message
.getBody().c_str(), *port
);
4045 getSslContextDone(ctx
, true);
4050 getSslContextDone(NULL
);
4053 void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties
&certProperties
)
4055 certProperties
.commonName
= sslCommonName
.defined() ? sslCommonName
.termedBuf() : sslConnectHostOrIp
.termedBuf();
4057 // fake certificate adaptation requires bump-server-first mode
4058 if (!sslServerBump
) {
4059 assert(port
->signingCert
.get());
4060 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
4061 if (port
->signPkey
.get())
4062 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
4063 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
4067 // In case of an error while connecting to the secure server, use a fake
4068 // trusted certificate, with no mimicked fields and no adaptation
4069 // algorithms. There is nothing we can mimic so we want to minimize the
4070 // number of warnings the user will have to see to get to the error page.
4071 assert(sslServerBump
->entry
);
4072 if (sslServerBump
->entry
->isEmpty()) {
4073 if (X509
*mimicCert
= sslServerBump
->serverCert
.get())
4074 certProperties
.mimicCert
.resetAndLock(mimicCert
);
4076 ACLFilledChecklist
checklist(NULL
, sslServerBump
->request
.getRaw(),
4077 clientConnection
!= NULL
? clientConnection
->rfc931
: dash_str
);
4078 checklist
.sslErrors
= cbdataReference(sslServerBump
->sslErrors
);
4080 for (sslproxy_cert_adapt
*ca
= Config
.ssl_client
.cert_adapt
; ca
!= NULL
; ca
= ca
->next
) {
4081 // If the algorithm already set, then ignore it.
4082 if ((ca
->alg
== Ssl::algSetCommonName
&& certProperties
.setCommonName
) ||
4083 (ca
->alg
== Ssl::algSetValidAfter
&& certProperties
.setValidAfter
) ||
4084 (ca
->alg
== Ssl::algSetValidBefore
&& certProperties
.setValidBefore
) )
4087 if (ca
->aclList
&& checklist
.fastCheck(ca
->aclList
) == ACCESS_ALLOWED
) {
4088 const char *alg
= Ssl::CertAdaptAlgorithmStr
[ca
->alg
];
4089 const char *param
= ca
->param
;
4091 // For parameterless CN adaptation, use hostname from the
4093 if (ca
->alg
== Ssl::algSetCommonName
) {
4095 param
= sslConnectHostOrIp
.termedBuf();
4096 certProperties
.commonName
= param
;
4097 certProperties
.setCommonName
= true;
4098 } else if (ca
->alg
== Ssl::algSetValidAfter
)
4099 certProperties
.setValidAfter
= true;
4100 else if (ca
->alg
== Ssl::algSetValidBefore
)
4101 certProperties
.setValidBefore
= true;
4103 debugs(33, 5, HERE
<< "Matches certificate adaptation aglorithm: " <<
4104 alg
<< " param: " << (param
? param
: "-"));
4108 certProperties
.signAlgorithm
= Ssl::algSignEnd
;
4109 for (sslproxy_cert_sign
*sg
= Config
.ssl_client
.cert_sign
; sg
!= NULL
; sg
= sg
->next
) {
4110 if (sg
->aclList
&& checklist
.fastCheck(sg
->aclList
) == ACCESS_ALLOWED
) {
4111 certProperties
.signAlgorithm
= (Ssl::CertSignAlgorithm
)sg
->alg
;
4115 } else {// if (!sslServerBump->entry->isEmpty())
4116 // Use trusted certificate for a Squid-generated error
4117 // or the user would have to add a security exception
4118 // just to see the error page. We will close the connection
4119 // so that the trust is not extended to non-Squid content.
4120 certProperties
.signAlgorithm
= Ssl::algSignTrusted
;
4123 assert(certProperties
.signAlgorithm
!= Ssl::algSignEnd
);
4125 if (certProperties
.signAlgorithm
== Ssl::algSignUntrusted
) {
4126 assert(port
->untrustedSigningCert
.get());
4127 certProperties
.signWithX509
.resetAndLock(port
->untrustedSigningCert
.get());
4128 certProperties
.signWithPkey
.resetAndLock(port
->untrustedSignPkey
.get());
4130 assert(port
->signingCert
.get());
4131 certProperties
.signWithX509
.resetAndLock(port
->signingCert
.get());
4133 if (port
->signPkey
.get())
4134 certProperties
.signWithPkey
.resetAndLock(port
->signPkey
.get());
4136 signAlgorithm
= certProperties
.signAlgorithm
;
4140 ConnStateData::getSslContextStart()
4142 assert(areAllContextsForThisConnection());
4144 /* careful: freeAllContexts() above frees request, host, etc. */
4146 if (port
->generateHostCertificates
) {
4147 Ssl::CertificateProperties certProperties
;
4148 buildSslCertGenerationParams(certProperties
);
4149 sslBumpCertKey
= certProperties
.dbKey().c_str();
4150 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
4152 debugs(33, 5, HERE
<< "Finding SSL certificate for " << sslBumpCertKey
<< " in cache");
4153 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
4154 SSL_CTX
* dynCtx
= NULL
;
4155 Ssl::SSL_CTX_Pointer
*cachedCtx
= ssl_ctx_cache
.get(sslBumpCertKey
.termedBuf());
4156 if (cachedCtx
&& (dynCtx
= cachedCtx
->get())) {
4157 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " have found in cache");
4158 if (Ssl::verifySslCertificate(dynCtx
, certProperties
)) {
4159 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is valid");
4160 getSslContextDone(dynCtx
);
4163 debugs(33, 5, HERE
<< "Cached SSL certificate for " << sslBumpCertKey
<< " is out of date. Delete this certificate from cache");
4164 ssl_ctx_cache
.del(sslBumpCertKey
.termedBuf());
4167 debugs(33, 5, HERE
<< "SSL certificate for " << sslBumpCertKey
<< " haven't found in cache");
4172 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
<< " using ssl_crtd.");
4173 Ssl::CrtdMessage
request_message(Ssl::CrtdMessage::REQUEST
);
4174 request_message
.setCode(Ssl::CrtdMessage::code_new_certificate
);
4175 request_message
.composeRequest(certProperties
);
4176 debugs(33, 5, HERE
<< "SSL crtd request: " << request_message
.compose().c_str());
4177 Ssl::Helper::GetInstance()->sslSubmit(request_message
, sslCrtdHandleReplyWrapper
, this);
4179 } catch (const std::exception
&e
) {
4180 debugs(33, DBG_IMPORTANT
, "ERROR: Failed to compose ssl_crtd " <<
4181 "request for " << certProperties
.commonName
<<
4182 " certificate: " << e
.what() << "; will now block to " <<
4183 "generate that certificate.");
4184 // fall through to do blocking in-process generation.
4186 #endif // USE_SSL_CRTD
4188 debugs(33, 5, HERE
<< "Generating SSL certificate for " << certProperties
.commonName
);
4189 dynCtx
= Ssl::generateSslContext(certProperties
, *port
);
4190 getSslContextDone(dynCtx
, true);
4193 getSslContextDone(NULL
);
4197 ConnStateData::getSslContextDone(SSL_CTX
* sslContext
, bool isNew
)
4199 // Try to add generated ssl context to storage.
4200 if (port
->generateHostCertificates
&& isNew
) {
4202 if (signAlgorithm
== Ssl::algSignTrusted
)
4203 Ssl::addChainToSslContext(sslContext
, port
->certsToChain
.get());
4204 //else it is self-signed or untrusted do not attrach any certificate
4206 Ssl::LocalContextStorage
& ssl_ctx_cache(Ssl::TheGlobalContextStorage
.getLocalStorage(port
->s
));
4207 assert(sslBumpCertKey
.defined() && sslBumpCertKey
[0] != '\0');
4209 if (!ssl_ctx_cache
.add(sslBumpCertKey
.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext
))) {
4210 // If it is not in storage delete after using. Else storage deleted it.
4211 fd_table
[clientConnection
->fd
].dynamicSslContext
= sslContext
;
4214 debugs(33, 2, HERE
<< "Failed to generate SSL cert for " << sslConnectHostOrIp
);
4218 // If generated ssl context = NULL, try to use static ssl context.
4220 if (!port
->staticSslContext
) {
4221 debugs(83, DBG_IMPORTANT
, "Closing SSL " << clientConnection
->remote
<< " as lacking SSL context");
4222 clientConnection
->close();
4225 debugs(33, 5, HERE
<< "Using static ssl context.");
4226 sslContext
= port
->staticSslContext
.get();
4230 if (!httpsCreate(clientConnection
, sslContext
))
4233 // commSetConnTimeout() was called for this request before we switched.
4235 // Disable the client read handler until CachePeer selection is complete
4236 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
4237 Comm::SetSelect(clientConnection
->fd
, COMM_SELECT_READ
, clientNegotiateSSL
, this, 0);
4238 switchedToHttps_
= true;
4242 ConnStateData::switchToHttps(HttpRequest
*request
, Ssl::BumpMode bumpServerMode
)
4244 assert(!switchedToHttps_
);
4246 sslConnectHostOrIp
= request
->GetHost();
4247 sslCommonName
= request
->GetHost();
4249 // We are going to read new request
4250 flags
.readMore
= true;
4251 debugs(33, 5, HERE
<< "converting " << clientConnection
<< " to SSL");
4253 // If sslServerBump is set, then we have decided to deny CONNECT
4254 // and now want to switch to SSL to send the error to the client
4255 // without even peeking at the origin server certificate.
4256 if (bumpServerMode
== Ssl::bumpServerFirst
&& !sslServerBump
) {
4257 request
->flags
.sslPeek
= true;
4258 sslServerBump
= new Ssl::ServerBump(request
);
4260 // will call httpsPeeked() with certificate and connection, eventually
4261 FwdState::fwdStart(clientConnection
, sslServerBump
->entry
, sslServerBump
->request
.getRaw());
4265 // otherwise, use sslConnectHostOrIp
4266 getSslContextStart();
4270 ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection
)
4272 Must(sslServerBump
!= NULL
);
4274 if (Comm::IsConnOpen(serverConnection
)) {
4275 SSL
*ssl
= fd_table
[serverConnection
->fd
].ssl
;
4277 Ssl::X509_Pointer
serverCert(SSL_get_peer_certificate(ssl
));
4278 assert(serverCert
.get() != NULL
);
4279 sslCommonName
= Ssl::CommonHostName(serverCert
.get());
4280 debugs(33, 5, HERE
<< "HTTPS server CN: " << sslCommonName
<<
4281 " bumped: " << *serverConnection
);
4283 pinConnection(serverConnection
, NULL
, NULL
, false);
4285 debugs(33, 5, HERE
<< "bumped HTTPS server: " << sslConnectHostOrIp
);
4287 debugs(33, 5, HERE
<< "Error while bumping: " << sslConnectHostOrIp
);
4288 Ip::Address intendedDest
;
4289 intendedDest
= sslConnectHostOrIp
.termedBuf();
4290 const bool isConnectRequest
= !port
->flags
.isIntercepted();
4292 // Squid serves its own error page and closes, so we want
4293 // a CN that causes no additional browser errors. Possible
4294 // only when bumping CONNECT with a user-typed address.
4295 if (intendedDest
.isAnyAddr() || isConnectRequest
)
4296 sslCommonName
= sslConnectHostOrIp
;
4297 else if (sslServerBump
->serverCert
.get())
4298 sslCommonName
= Ssl::CommonHostName(sslServerBump
->serverCert
.get());
4300 // copy error detail from bump-server-first request to CONNECT request
4301 if (currentobject
!= NULL
&& currentobject
->http
!= NULL
&& currentobject
->http
->request
)
4302 currentobject
->http
->request
->detailError(sslServerBump
->request
->errType
, sslServerBump
->request
->errDetail
);
4305 getSslContextStart();
4308 #endif /* USE_SSL */
4310 /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4312 OpenedHttpSocket(const Comm::ConnectionPointer
&c
, const Ipc::FdNoteId portType
)
4314 if (!Comm::IsConnOpen(c
)) {
4315 Must(NHttpSockets
> 0); // we tried to open some
4316 --NHttpSockets
; // there will be fewer sockets than planned
4317 Must(HttpSockets
[NHttpSockets
] < 0); // no extra fds received
4319 if (!NHttpSockets
) // we could not open any listen sockets at all
4320 fatalf("Unable to open %s",FdNote(portType
));
4327 /// find any unused HttpSockets[] slot and store fd there or return false
4329 AddOpenedHttpSocket(const Comm::ConnectionPointer
&conn
)
4332 for (int i
= 0; i
< NHttpSockets
&& !found
; ++i
) {
4333 if ((found
= HttpSockets
[i
] < 0))
4334 HttpSockets
[i
] = conn
->fd
;
4340 clientHttpConnectionsOpen(void)
4342 AnyP::PortCfg
*s
= NULL
;
4344 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4345 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4346 debugs(1, DBG_IMPORTANT
, "WARNING: You have too many 'http_port' lines.");
4347 debugs(1, DBG_IMPORTANT
, " The limit is " << MAXTCPLISTENPORTS
<< " HTTP ports.");
4352 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4353 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4354 s
->flags
.tunnelSslBumping
= false;
4357 if (s
->flags
.tunnelSslBumping
&&
4358 !s
->staticSslContext
&&
4359 !s
->generateHostCertificates
) {
4360 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4361 s
->flags
.tunnelSslBumping
= false;
4363 if (s
->flags
.tunnelSslBumping
) {
4364 // Create ssl_ctx cache for this port.
4365 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4369 // Fill out a Comm::Connection which IPC will open as a listener for us
4370 // then pass back when active so we can start a TcpAcceptor subscription.
4371 s
->listenConn
= new Comm::Connection
;
4372 s
->listenConn
->local
= s
->s
;
4373 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) | (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4375 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4376 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4377 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept
, s
));
4378 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4380 AsyncCall::Pointer listenCall
= asyncCall(33,2, "clientListenerConnectionOpened",
4381 ListeningStartedDialer(&clientListenerConnectionOpened
, s
, Ipc::fdnHttpSocket
, sub
));
4382 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpSocket
, listenCall
);
4384 HttpSockets
[NHttpSockets
] = -1; // set in clientListenerConnectionOpened
4391 clientHttpsConnectionsOpen(void)
4395 for (s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4396 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4397 debugs(1, DBG_IMPORTANT
, "Ignoring 'https_port' lines exceeding the limit.");
4398 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " HTTPS ports.");
4402 if (!s
->staticSslContext
) {
4403 debugs(1, DBG_IMPORTANT
, "Ignoring https_port " << s
->s
<<
4404 " due to SSL initialization failure.");
4408 // TODO: merge with similar code in clientHttpConnectionsOpen()
4409 if (s
->flags
.tunnelSslBumping
&& !Config
.accessList
.ssl_bump
) {
4410 debugs(33, DBG_IMPORTANT
, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s
->protocol
<< "_port " << s
->s
);
4411 s
->flags
.tunnelSslBumping
= false;
4414 if (s
->flags
.tunnelSslBumping
&& !s
->staticSslContext
&& !s
->generateHostCertificates
) {
4415 debugs(1, DBG_IMPORTANT
, "Will not bump SSL at http_port " << s
->s
<< " due to SSL initialization failure.");
4416 s
->flags
.tunnelSslBumping
= false;
4419 if (s
->flags
.tunnelSslBumping
) {
4420 // Create ssl_ctx cache for this port.
4421 Ssl::TheGlobalContextStorage
.addLocalStorage(s
->s
, s
->dynamicCertMemCacheSize
== std::numeric_limits
<size_t>::max() ? 4194304 : s
->dynamicCertMemCacheSize
);
4424 // Fill out a Comm::Connection which IPC will open as a listener for us
4425 s
->listenConn
= new Comm::Connection
;
4426 s
->listenConn
->local
= s
->s
;
4427 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4428 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4430 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4431 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4432 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept
, s
));
4433 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4435 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4436 ListeningStartedDialer(&clientListenerConnectionOpened
,
4437 s
, Ipc::fdnHttpsSocket
, sub
));
4438 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnHttpsSocket
, listenCall
);
4439 HttpSockets
[NHttpSockets
] = -1;
4446 clientFtpConnectionsOpen(void)
4450 for (s
= Config
.Sockaddr
.ftp
; s
; s
= s
->next
) {
4451 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
4452 debugs(1, DBG_IMPORTANT
, "Ignoring 'ftp_port' lines exceeding the limit.");
4453 debugs(1, DBG_IMPORTANT
, "The limit is " << MAXTCPLISTENPORTS
<< " FTP ports.");
4457 // Fill out a Comm::Connection which IPC will open as a listener for us
4458 s
->listenConn
= new Comm::Connection
;
4459 s
->listenConn
->local
= s
->s
;
4460 s
->listenConn
->flags
= COMM_NONBLOCKING
| (s
->flags
.tproxyIntercept
? COMM_TRANSPARENT
: 0) |
4461 (s
->flags
.natIntercept
? COMM_INTERCEPTION
: 0);
4463 // setup the subscriptions such that new connections accepted by listenConn are handled by FTP
4464 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
4465 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "ftpAccept", CommAcceptCbPtrFun(ftpAccept
, s
));
4466 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
4468 AsyncCall::Pointer listenCall
= asyncCall(33, 2, "clientListenerConnectionOpened",
4469 ListeningStartedDialer(&clientListenerConnectionOpened
,
4470 s
, Ipc::fdnFtpSocket
, sub
));
4471 Ipc::StartListening(SOCK_STREAM
, IPPROTO_TCP
, s
->listenConn
, Ipc::fdnFtpSocket
, listenCall
);
4472 HttpSockets
[NHttpSockets
] = -1;
4477 /// process clientHttpConnectionsOpen result
4479 clientListenerConnectionOpened(AnyP::PortCfg
*s
, const Ipc::FdNoteId portTypeNote
, const Subscription::Pointer
&sub
)
4481 if (!OpenedHttpSocket(s
->listenConn
, portTypeNote
))
4485 Must(Comm::IsConnOpen(s
->listenConn
));
4487 // TCP: setup a job to handle accept() with subscribed handler
4488 AsyncJob::Start(new Comm::TcpAcceptor(s
->listenConn
, FdNote(portTypeNote
), sub
));
4490 debugs(1, DBG_IMPORTANT
, "Accepting " <<
4491 (s
->flags
.natIntercept
? "NAT intercepted " : "") <<
4492 (s
->flags
.tproxyIntercept
? "TPROXY intercepted " : "") <<
4493 (s
->flags
.tunnelSslBumping
? "SSL bumped " : "") <<
4494 (s
->flags
.accelSurrogate
? "reverse-proxy " : "")
4495 << FdNote(portTypeNote
) << " connections at "
4498 Must(AddOpenedHttpSocket(s
->listenConn
)); // otherwise, we have received a fd we did not ask for
4502 clientOpenListenSockets(void)
4504 clientHttpConnectionsOpen();
4506 clientHttpsConnectionsOpen();
4508 clientFtpConnectionsOpen();
4510 if (NHttpSockets
< 1)
4511 fatal("No HTTP, HTTPS or FTP ports configured");
4515 clientConnectionsClose(void)
4517 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
4518 if (s
->listenConn
!= NULL
) {
4519 debugs(1, DBG_IMPORTANT
, "Closing HTTP port " << s
->listenConn
->local
);
4520 s
->listenConn
->close();
4521 s
->listenConn
= NULL
;
4526 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.https
; s
; s
= s
->next
) {
4527 if (s
->listenConn
!= NULL
) {
4528 debugs(1, DBG_IMPORTANT
, "Closing HTTPS port " << s
->listenConn
->local
);
4529 s
->listenConn
->close();
4530 s
->listenConn
= NULL
;
4535 for (AnyP::PortCfg
*s
= Config
.Sockaddr
.ftp
; s
; s
= s
->next
) {
4536 if (s
->listenConn
!= NULL
) {
4537 debugs(1, DBG_IMPORTANT
, "Closing FTP port " << s
->listenConn
->local
);
4538 s
->listenConn
->close();
4539 s
->listenConn
= NULL
;
4543 // TODO see if we can drop HttpSockets array entirely */
4544 for (int i
= 0; i
< NHttpSockets
; ++i
) {
4545 HttpSockets
[i
] = -1;
4552 varyEvaluateMatch(StoreEntry
* entry
, HttpRequest
* request
)
4554 const char *vary
= request
->vary_headers
;
4555 int has_vary
= entry
->getReply()->header
.has(HDR_VARY
);
4556 #if X_ACCELERATOR_VARY
4559 entry
->getReply()->header
.has(HDR_X_ACCELERATOR_VARY
);
4562 if (!has_vary
|| !entry
->mem_obj
->vary_headers
) {
4564 /* Oops... something odd is going on here.. */
4565 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
4566 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4567 safe_free(request
->vary_headers
);
4572 /* This is not a varying object */
4576 /* virtual "vary" object found. Calculate the vary key and
4577 * continue the search
4579 vary
= httpMakeVaryMark(request
, entry
->getReply());
4582 request
->vary_headers
= xstrdup(vary
);
4585 /* Ouch.. we cannot handle this kind of variance */
4586 /* XXX This cannot really happen, but just to be complete */
4591 vary
= httpMakeVaryMark(request
, entry
->getReply());
4594 request
->vary_headers
= xstrdup(vary
);
4598 /* Ouch.. we cannot handle this kind of variance */
4599 /* XXX This cannot really happen, but just to be complete */
4601 } else if (strcmp(vary
, entry
->mem_obj
->vary_headers
) == 0) {
4604 /* Oops.. we have already been here and still haven't
4605 * found the requested variant. Bail out
4607 debugs(33, DBG_IMPORTANT
, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
4608 entry
->mem_obj
->url
<< "' '" << vary
<< "'");
4614 ACLFilledChecklist
*
4615 clientAclChecklistCreate(const acl_access
* acl
, ClientHttpRequest
* http
)
4617 ConnStateData
* conn
= http
->getConn();
4618 ACLFilledChecklist
*ch
= new ACLFilledChecklist(acl
, http
->request
,
4619 cbdataReferenceValid(conn
) && conn
!= NULL
&& conn
->clientConnection
!= NULL
? conn
->clientConnection
->rfc931
: dash_str
);
4622 * hack for ident ACL. It needs to get full addresses, and a place to store
4623 * the ident result on persistent connections...
4625 /* connection oriented auth also needs these two lines for it's operation. */
4629 CBDATA_CLASS_INIT(ConnStateData
);
4632 ConnStateData::transparent() const
4634 return clientConnection
!= NULL
&& (clientConnection
->flags
& (COMM_TRANSPARENT
|COMM_INTERCEPTION
));
4638 ConnStateData::reading() const
4640 return reader
!= NULL
;
4644 ConnStateData::stopReading()
4647 comm_read_cancel(clientConnection
->fd
, reader
);
4653 ConnStateData::expectRequestBody(int64_t size
)
4655 bodyPipe
= new BodyPipe(this);
4657 bodyPipe
->setBodySize(size
);
4659 startDechunkingRequest();
4664 ConnStateData::mayNeedToReadMoreBody() const
4667 return 0; // request without a body or read/produced all body bytes
4669 if (!bodyPipe
->bodySizeKnown())
4670 return -1; // probably need to read more, but we cannot be sure
4672 const int64_t needToProduce
= bodyPipe
->unproducedSize();
4673 const int64_t haveAvailable
= static_cast<int64_t>(in
.notYetUsed
);
4675 if (needToProduce
<= haveAvailable
)
4676 return 0; // we have read what we need (but are waiting for pipe space)
4678 return needToProduce
- haveAvailable
;
4682 ConnStateData::stopReceiving(const char *error
)
4684 debugs(33, 4, HERE
<< "receiving error (" << clientConnection
<< "): " << error
<<
4685 "; old sending error: " <<
4686 (stoppedSending() ? stoppedSending_
: "none"));
4688 if (const char *oldError
= stoppedReceiving()) {
4689 debugs(33, 3, HERE
<< "already stopped receiving: " << oldError
);
4690 return; // nothing has changed as far as this connection is concerned
4693 stoppedReceiving_
= error
;
4695 if (const char *sendError
= stoppedSending()) {
4696 debugs(33, 3, HERE
<< "closing because also stopped sending: " << sendError
);
4697 clientConnection
->close();
4702 ConnStateData::expectNoForwarding()
4704 if (bodyPipe
!= NULL
) {
4705 debugs(33, 4, HERE
<< "no consumer for virgin body " << bodyPipe
->status());
4706 bodyPipe
->expectNoConsumption();
4710 /// initialize dechunking state
4712 ConnStateData::startDechunkingRequest()
4714 Must(bodyPipe
!= NULL
);
4715 debugs(33, 5, HERE
<< "start dechunking" << bodyPipe
->status());
4716 assert(!in
.bodyParser
);
4717 in
.bodyParser
= new ChunkedCodingParser
;
4720 /// put parsed content into input buffer and clean up
4722 ConnStateData::finishDechunkingRequest(bool withSuccess
)
4724 debugs(33, 5, HERE
<< "finish dechunking: " << withSuccess
);
4726 if (bodyPipe
!= NULL
) {
4727 debugs(33, 7, HERE
<< "dechunked tail: " << bodyPipe
->status());
4728 BodyPipe::Pointer myPipe
= bodyPipe
;
4729 stopProducingFor(bodyPipe
, withSuccess
); // sets bodyPipe->bodySize()
4730 Must(!bodyPipe
); // we rely on it being nil after we are done with body
4732 Must(myPipe
->bodySizeKnown());
4733 ClientSocketContext::Pointer context
= getCurrentContext();
4734 if (context
!= NULL
&& context
->http
&& context
->http
->request
)
4735 context
->http
->request
->setContentLength(myPipe
->bodySize());
4739 delete in
.bodyParser
;
4740 in
.bodyParser
= NULL
;
4744 ConnStateData::In::addressToReadInto() const
4746 return buf
+ notYetUsed
;
4749 ConnStateData::In::In() : bodyParser(NULL
),
4750 buf (NULL
), notYetUsed (0), allocatedSize (0)
4753 ConnStateData::In::~In()
4756 memFreeBuf(allocatedSize
, buf
);
4757 delete bodyParser
; // TODO: pool
4761 ConnStateData::sendControlMsg(HttpControlMsg msg
)
4764 debugs(33, 3, HERE
<< "ignoring 1xx due to earlier closure");
4768 ClientSocketContext::Pointer context
= getCurrentContext();
4769 if (context
!= NULL
) {
4770 context
->writeControlMsg(msg
); // will call msg.cbSuccess
4774 debugs(33, 3, HERE
<< " closing due to missing context for 1xx");
4775 clientConnection
->close();
4778 /// Our close handler called by Comm when the pinned connection is closed
4780 ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
4782 // FwdState might repin a failed connection sooner than this close
4783 // callback is called for the failed connection.
4784 assert(pinning
.serverConnection
== io
.conn
);
4785 pinning
.closeHandler
= NULL
; // Comm unregisters handlers before calling
4786 const bool sawZeroReply
= pinning
.zeroReply
; // reset when unpinning
4789 debugs(33, 3, "Closing client connection on pinned zero reply.");
4790 clientConnection
->close();
4795 debugs(33, 5, HERE << "FTP server connection closed, closing client "
4797 clientConnection->close();
4803 ConnStateData::pinConnection(const Comm::ConnectionPointer
&pinServer
, HttpRequest
*request
, CachePeer
*aPeer
, bool auth
)
4805 char desc
[FD_DESC_SZ
];
4807 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4808 if (pinning
.serverConnection
->fd
== pinServer
->fd
)
4812 unpinConnection(); // closes pinned connection, if any, and resets fields
4814 pinning
.serverConnection
= pinServer
;
4816 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4818 // when pinning an SSL bumped connection, the request may be NULL
4819 const char *pinnedHost
= "[unknown]";
4821 pinning
.host
= xstrdup(request
->GetHost());
4822 pinning
.port
= request
->port
;
4823 pinnedHost
= pinning
.host
;
4825 pinning
.port
= pinServer
->remote
.port();
4827 pinning
.pinned
= true;
4829 pinning
.peer
= cbdataReference(aPeer
);
4830 pinning
.auth
= auth
;
4831 char stmp
[MAX_IPSTRLEN
];
4832 snprintf(desc
, FD_DESC_SZ
, "%s pinned connection for %s (%d)",
4833 (auth
|| !aPeer
) ? pinnedHost
: aPeer
->name
,
4834 clientConnection
->remote
.toUrl(stmp
,MAX_IPSTRLEN
),
4835 clientConnection
->fd
);
4836 fd_note(pinning
.serverConnection
->fd
, desc
);
4838 typedef CommCbMemFunT
<ConnStateData
, CommCloseCbParams
> Dialer
;
4839 pinning
.closeHandler
= JobCallback(33, 5,
4840 Dialer
, this, ConnStateData::clientPinnedConnectionClosed
);
4841 // remember the pinned connection so that cb does not unpin a fresher one
4842 typedef CommCloseCbParams Params
;
4843 Params
¶ms
= GetCommParams
<Params
>(pinning
.closeHandler
);
4844 params
.conn
= pinning
.serverConnection
;
4845 comm_add_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4848 const Comm::ConnectionPointer
4849 ConnStateData::validatePinnedConnection(HttpRequest
*request
, const CachePeer
*aPeer
)
4851 debugs(33, 7, HERE
<< pinning
.serverConnection
);
4854 if (!Comm::IsConnOpen(pinning
.serverConnection
))
4856 else if (pinning
.auth
&& pinning
.host
&& request
&& strcasecmp(pinning
.host
, request
->GetHost()) != 0)
4858 else if (request
&& pinning
.port
!= request
->port
)
4860 else if (pinning
.peer
&& !cbdataReferenceValid(pinning
.peer
))
4862 else if (aPeer
!= pinning
.peer
)
4866 /* The pinning info is not safe, remove any pinning info */
4870 return pinning
.serverConnection
;
4874 ConnStateData::unpinConnection()
4876 debugs(33, 3, HERE
<< pinning
.serverConnection
);
4879 cbdataReferenceDone(pinning
.peer
);
4881 if (Comm::IsConnOpen(pinning
.serverConnection
)) {
4882 if (pinning
.closeHandler
!= NULL
) {
4883 comm_remove_close_handler(pinning
.serverConnection
->fd
, pinning
.closeHandler
);
4884 pinning
.closeHandler
= NULL
;
4886 /// also close the server side socket, we should not use it for any future requests...
4887 // TODO: do not close if called from our close handler?
4888 pinning
.serverConnection
->close();
4891 safe_free(pinning
.host
);
4893 pinning
.zeroReply
= false;
4895 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4896 * connection has gone away */
4901 FtpAcceptDataConnection(const CommAcceptCbParams
¶ms
)
4903 ConnStateData
*connState
= static_cast<ConnStateData
*>(params
.data
);
4905 if (params
.flag
!= COMM_OK
) {
4906 // Its possible the call was still queued when the client disconnected
4907 debugs(33, 2, HERE
<< connState
->ftp
.dataListenConn
<< ": accept "
4908 "failure: " << xstrerr(params
.xerrno
));
4912 debugs(33, 4, "accepted " << params
.conn
);
4913 fd_note(params
.conn
->fd
, "passive client ftp data");
4914 ++incoming_sockets_accepted
;
4916 if (!connState
->clientConnection
) {
4917 debugs(33, 5, "late data connection?");
4918 FtpCloseDataConnection(connState
); // in case we are still listening
4919 params
.conn
->close();
4921 if (params
.conn
->remote
!= connState
->clientConnection
->remote
) {
4922 debugs(33, 2, "rogue data conn? ctrl: " << connState
->clientConnection
->remote
);
4923 params
.conn
->close();
4924 // Some FTP servers close control connection here, but it may make
4925 // things worse from DoS p.o.v. and no better from data stealing p.o.v.
4927 FtpCloseDataConnection(connState
);
4928 connState
->ftp
.dataConn
= params
.conn
;
4929 connState
->ftp
.uploadAvailSize
= 0;
4930 debugs(33, 7, "ready for data");
4935 FtpCloseDataConnection(ConnStateData
*conn
)
4937 if (conn
->ftp
.listener
!= NULL
) {
4938 conn
->ftp
.listener
->cancel("no longer needed");
4939 conn
->ftp
.listener
= NULL
;
4942 if (Comm::IsConnOpen(conn
->ftp
.dataListenConn
)) {
4943 debugs(33, 5, HERE
<< "FTP closing client data listen socket: " <<
4944 *conn
->ftp
.dataListenConn
);
4945 conn
->ftp
.dataListenConn
->close();
4947 conn
->ftp
.dataListenConn
= NULL
;
4949 if (conn
->ftp
.reader
!= NULL
) {
4950 // comm_read_cancel can deal with negative FDs
4951 comm_read_cancel(conn
->ftp
.dataConn
->fd
, conn
->ftp
.reader
);
4952 conn
->ftp
.reader
= NULL
;
4955 if (Comm::IsConnOpen(conn
->ftp
.dataConn
)) {
4956 debugs(33, 5, HERE
<< "FTP closing client data connection: " <<
4957 *conn
->ftp
.dataConn
);
4958 conn
->ftp
.dataConn
->close();
4960 conn
->ftp
.dataConn
= NULL
;
4963 /// Writes FTP [error] response before we fully parsed the FTP request and
4964 /// created the corresponding HTTP request wrapper for that FTP request.
4966 FtpWriteEarlyReply(ConnStateData
*connState
, const int code
, const char *msg
)
4968 debugs(33, 7, HERE
<< code
<< ' ' << msg
);
4969 assert(99 < code
&& code
< 1000);
4973 mb
.Printf("%i %s\r\n", code
, msg
);
4975 AsyncCall::Pointer call
= commCbCall(33, 5, "FtpWroteEarlyReply",
4976 CommIoCbPtrFun(&FtpWroteEarlyReply
, connState
));
4977 Comm::Write(connState
->clientConnection
, &mb
, call
);
4979 connState
->flags
.readMore
= false;
4981 // TODO: Create master transaction. Log it in FtpWroteEarlyReply.
4985 FtpWriteReply(ClientSocketContext
*context
, MemBuf
&mb
)
4987 debugs(11, 2, "FTP Client " << context
->clientConnection
);
4988 debugs(11, 2, "FTP Client REPLY:\n---------\n" << mb
.buf
<<
4991 AsyncCall::Pointer call
= commCbCall(33, 5, "FtpWroteReply",
4992 CommIoCbPtrFun(&FtpWroteReply
, context
));
4993 Comm::Write(context
->clientConnection
, &mb
, call
);
4997 FtpWriteCustomReply(ClientSocketContext
*context
, const int code
, const char *msg
, const HttpReply
*reply
)
4999 debugs(33, 7, HERE
<< code
<< ' ' << msg
);
5000 assert(99 < code
&& code
< 1000);
5002 const bool sendDetails
= reply
!= NULL
&&
5003 reply
->header
.has(HDR_FTP_STATUS
) && reply
->header
.has(HDR_FTP_REASON
);
5008 mb
.Printf("%i-%s\r\n", code
, msg
);
5009 mb
.Printf(" Server reply:\r\n");
5010 FtpPrintReply(mb
, reply
, " ");
5011 mb
.Printf("%i \r\n", code
);
5013 mb
.Printf("%i %s\r\n", code
, msg
);
5015 FtpWriteReply(context
, mb
);
5019 FtpChangeState(ConnStateData
*connState
, const ConnStateData::FtpState newState
, const char *reason
)
5022 if (connState
->ftp
.state
== newState
) {
5023 debugs(33, 3, "client state unchanged at " << connState
->ftp
.state
<<
5024 " because " << reason
);
5025 connState
->ftp
.state
= newState
;
5027 debugs(33, 3, "client state was " << connState
->ftp
.state
<<
5028 ", now " << newState
<< " because " << reason
);
5029 connState
->ftp
.state
= newState
;
5033 /** Parse an FTP request
5035 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
5036 * to 1 if the request was correctly parsed.
5037 * \param[in] connState a ConnStateData. The caller must make sure it is not null
5038 * \param[out] mehtod_p will be set as a side-effect of the parsing.
5039 * Pointed-to value will be set to Http::METHOD_NONE in case of
5041 * \param[out] http_ver will be set as a side-effect of the parsing
5042 * \return NULL on incomplete requests,
5043 * a ClientSocketContext structure on success or failure.
5045 static ClientSocketContext
*
5046 FtpParseRequest(ConnStateData
*connState
, HttpRequestMethod
*method_p
, Http::ProtocolVersion
*http_ver
)
5048 *http_ver
= Http::ProtocolVersion(1, 1);
5050 const char *const eor
=
5051 static_cast<const char *>(memchr(connState
->in
.buf
, '\n',
5052 min(connState
->in
.notYetUsed
, Config
.maxRequestHeaderSize
)));
5053 const size_t req_sz
= eor
+ 1 - connState
->in
.buf
;
5055 if (eor
== NULL
&& connState
->in
.notYetUsed
>= Config
.maxRequestHeaderSize
) {
5056 FtpChangeState(connState
, ConnStateData::FTP_ERROR
, "huge req");
5057 FtpWriteEarlyReply(connState
, 421, "Too large request");
5062 debugs(33, 5, HERE
<< "Incomplete request, waiting for end of request");
5066 connNoteUseOfBuffer(connState
, req_sz
);
5068 // skip leading whitespaces
5069 const char *boc
= connState
->in
.buf
;
5070 while (boc
< eor
&& isspace(*boc
)) ++boc
;
5072 debugs(33, 5, HERE
<< "Empty request, ignoring");
5076 const char *eoc
= boc
;
5077 while (eoc
< eor
&& !isspace(*eoc
)) ++eoc
;
5078 connState
->in
.buf
[eoc
- connState
->in
.buf
] = '\0';
5080 const char *bop
= eoc
+ 1;
5081 while (bop
< eor
&& isspace(*bop
)) ++bop
;
5083 const char *eop
= eor
- 1;
5084 while (isspace(*eop
)) --eop
;
5086 connState
->in
.buf
[eop
+ 1 - connState
->in
.buf
] = '\0';
5090 debugs(33, 7, HERE
<< "Parsed FTP command " << boc
<< " with " <<
5091 (bop
== NULL
? "no " : "") << "parameters" <<
5092 (bop
!= NULL
? ": " : "") << bop
);
5094 const String cmd
= boc
;
5095 String params
= bop
;
5097 if (connState
->ftp
.uri
.size() == 0) {
5098 // the first command must be USER
5099 if (cmd
.caseCmp("USER") != 0) {
5100 FtpWriteEarlyReply(connState
, 530, "Must login first");
5105 // We need to process USER request now because it sets request URI.
5106 if (cmd
.caseCmp("USER") == 0 &&
5107 !FtpHandleUserRequest(connState
, cmd
, params
))
5110 if (!FtpSupportedCommand(cmd
)) {
5111 FtpWriteEarlyReply(connState
, 502, "Unknown or unsupported command");
5115 *method_p
= !cmd
.caseCmp("APPE") || !cmd
.caseCmp("STOR") ||
5116 !cmd
.caseCmp("STOU") ? Http::METHOD_PUT
: Http::METHOD_GET
;
5118 assert(connState
->ftp
.uri
.size() > 0);
5119 char *uri
= xstrdup(connState
->ftp
.uri
.termedBuf());
5120 HttpRequest
*const request
=
5121 HttpRequest::CreateFromUrlAndMethod(uri
, *method_p
);
5122 if (request
== NULL
) {
5123 debugs(33, 5, HERE
<< "Invalid FTP URL: " << connState
->ftp
.uri
);
5124 FtpWriteEarlyReply(connState
, 501, "Invalid host");
5125 connState
->ftp
.uri
.clean();
5130 request
->http_ver
= *http_ver
;
5132 // Our fake Request-URIs are not distinctive enough for caching to work
5133 request
->flags
.cachable
= false; // XXX: reset later by maybeCacheable()
5134 request
->flags
.noCache
= true;
5136 request
->header
.putStr(HDR_FTP_COMMAND
, cmd
.termedBuf());
5137 request
->header
.putStr(HDR_FTP_ARGUMENTS
, params
.termedBuf() != NULL
?
5138 params
.termedBuf() : "");
5139 if (*method_p
== Http::METHOD_PUT
) {
5140 request
->header
.putStr(HDR_EXPECT
, "100-continue");
5141 request
->header
.putStr(HDR_TRANSFER_ENCODING
, "chunked");
5144 ClientHttpRequest
*const http
= new ClientHttpRequest(connState
);
5145 http
->request
= request
;
5146 HTTPMSGLOCK(http
->request
);
5147 http
->req_sz
= req_sz
;
5150 ClientSocketContext
*const result
=
5151 ClientSocketContextNew(connState
->clientConnection
, http
);
5153 StoreIOBuffer tempBuffer
;
5154 tempBuffer
.data
= result
->reqbuf
;
5155 tempBuffer
.length
= HTTP_REQBUF_SZ
;
5157 ClientStreamData newServer
= new clientReplyContext(http
);
5158 ClientStreamData newClient
= result
;
5159 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
5160 clientReplyStatus
, newServer
, clientSocketRecipient
,
5161 clientSocketDetach
, newClient
, tempBuffer
);
5163 result
->registerWithConn();
5164 result
->flags
.parsed_ok
= 1;
5165 connState
->flags
.readMore
= false;
5170 FtpHandleReply(ClientSocketContext
*context
, HttpReply
*reply
, StoreIOBuffer data
)
5172 if (context
->http
&& context
->http
->al
!= NULL
&&
5173 !context
->http
->al
->reply
&& reply
) {
5174 context
->http
->al
->reply
= reply
;
5175 HTTPMSGLOCK(context
->http
->al
->reply
);
5178 static FtpReplyHandler
*handlers
[] = {
5180 NULL
, // FTP_CONNECTED
5181 FtpHandleFeatReply
, // FTP_HANDLE_FEAT
5182 FtpHandlePasvReply
, // FTP_HANDLE_PASV
5183 FtpHandlePortReply
, // FTP_HANDLE_PORT
5184 FtpHandleDataReply
, // FTP_HANDLE_DATA_REQUEST
5185 FtpHandleUploadReply
, // FTP_HANDLE_UPLOAD_REQUEST
5186 FtpHandleErrorReply
// FTP_ERROR
5188 const ConnStateData::FtpState state
= context
->getConn()->ftp
.state
;
5189 FtpReplyHandler
*const handler
= handlers
[state
];
5191 (*handler
)(context
, reply
, data
);
5193 FtpWriteForwardedReply(context
, reply
);
5197 FtpHandleFeatReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5199 if (context
->http
->request
->errType
!= ERR_NONE
) {
5200 FtpWriteCustomReply(context
, 502, "Server does not support FEAT", reply
);
5204 HttpReply
*filteredReply
= reply
->clone();
5205 HttpHeader
&filteredHeader
= filteredReply
->header
;
5207 // Remove all unsupported commands from the response wrapper.
5208 int deletedCount
= 0;
5209 HttpHeaderPos pos
= HttpHeaderInitPos
;
5210 while (const HttpHeaderEntry
*e
= filteredHeader
.getEntry(&pos
)) {
5211 if (e
->id
== HDR_FTP_PRE
) {
5212 // assume RFC 2389 FEAT response format, quoted by Squid:
5213 // <"> SP NAME [SP PARAMS] <">
5214 if (e
->value
.size() < 4)
5216 const char *raw
= e
->value
.termedBuf();
5217 if (raw
[0] != '"' && raw
[1] != ' ')
5219 const char *beg
= raw
+ 2; // after quote and space
5220 // command name ends with (SP parameter) or quote
5221 const char *end
= beg
+ strcspn(beg
, " \"");
5222 const String cmd
= e
->value
.substr(beg
-raw
, end
-raw
);
5224 if (!FtpSupportedCommand(cmd
))
5225 filteredHeader
.delAt(pos
, deletedCount
);
5230 filteredHeader
.refreshMask();
5231 debugs(33, 5, "deleted " << deletedCount
);
5234 FtpWriteForwardedReply(context
, filteredReply
);
5238 FtpHandlePasvReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5240 if (context
->http
->request
->errType
!= ERR_NONE
) {
5241 FtpWriteCustomReply(context
, 502, "Server does not support PASV", reply
);
5245 FtpCloseDataConnection(context
->getConn());
5247 Comm::ConnectionPointer conn
= new Comm::Connection
;
5248 ConnStateData
* const connState
= context
->getConn();
5249 conn
->flags
= COMM_NONBLOCKING
;
5250 conn
->local
= connState
->transparent() ?
5251 connState
->port
->s
: context
->clientConnection
->local
;
5252 conn
->local
.port(0);
5253 const char *const note
= connState
->ftp
.uri
.termedBuf();
5254 comm_open_listener(SOCK_STREAM
, IPPROTO_TCP
, conn
, note
);
5255 if (!Comm::IsConnOpen(conn
)) {
5256 debugs(5, DBG_CRITICAL
, HERE
<< "comm_open_listener failed:" <<
5257 conn
->local
<< " error: " << errno
);
5258 FtpWriteCustomReply(context
, 451, "Internal error");
5262 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
5263 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "FtpAcceptDataConnection",
5264 CommAcceptCbPtrFun(FtpAcceptDataConnection
, connState
));
5265 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(subCall
);
5266 connState
->ftp
.listener
= subCall
.getRaw();
5267 connState
->ftp
.dataListenConn
= conn
;
5268 AsyncJob::Start(new Comm::TcpAcceptor(conn
, note
, sub
));
5270 char addr
[MAX_IPSTRLEN
];
5271 // remote server in interception setups and local address otherwise
5272 const Ip::Address
&server
= connState
->transparent() ?
5273 context
->clientConnection
->local
: conn
->local
;
5274 server
.toStr(addr
, MAX_IPSTRLEN
, AF_INET
);
5275 addr
[MAX_IPSTRLEN
- 1] = '\0';
5276 for (char *c
= addr
; *c
!= '\0'; ++c
) {
5281 // conn->fd is the client data connection (and its local port)
5282 const unsigned short port
= comm_local_port(conn
->fd
);
5283 conn
->local
.port(port
);
5285 // In interception setups, we combine remote server address with a
5286 // local port number and hope that traffic will be redirected to us.
5290 // Do not use "227 =a,b,c,d,p1,p2" format or omit parens: some nf_ct_ftp
5291 // versions block responses that use those alternative syntax rules!
5292 mb
.Printf("227 Entering Passive Mode (%s,%i,%i).\r\n",
5294 static_cast<int>(port
/ 256),
5295 static_cast<int>(port
% 256));
5297 debugs(11, 3, Raw("writing", mb
.buf
, mb
.size
));
5298 FtpWriteReply(context
, mb
);
5302 FtpHandlePortReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5304 if (context
->http
->request
->errType
!= ERR_NONE
) {
5305 FtpWriteCustomReply(context
, 502, "Server does not support PASV (converted from PORT)", reply
);
5309 FtpWriteCustomReply(context
, 200, "PORT successfully converted to PASV.");
5311 // and wait for RETR
5315 FtpHandleErrorReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5317 ConnStateData
*const connState
= context
->getConn();
5318 if (!connState
->pinning
.pinned
) // we failed to connect to server
5319 connState
->ftp
.uri
.clean();
5320 // 421: we will close due to FTP_ERROR
5321 FtpWriteErrorReply(context
, reply
, 421);
5325 FtpHandleDataReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5327 ConnStateData
*const conn
= context
->getConn();
5329 if (reply
!= NULL
&& reply
->sline
.status() != Http::scOkay
) {
5330 FtpWriteForwardedReply(context
, reply
);
5331 if (conn
&& Comm::IsConnOpen(conn
->ftp
.dataConn
)) {
5332 debugs(33, 3, "closing " << conn
->ftp
.dataConn
<< " on KO reply");
5333 FtpCloseDataConnection(conn
);
5338 if (!conn
->ftp
.dataConn
) {
5339 // We got STREAM_COMPLETE (or error) and closed the client data conn.
5340 debugs(33, 3, "ignoring FTP srv data response after clt data closure");
5344 if (!FtpCheckDataConnPost(context
))
5347 debugs(33, 7, HERE
<< data
.length
);
5349 if (data
.length
<= 0) {
5350 FtpWroteReplyData(conn
->clientConnection
, NULL
, 0, COMM_OK
, 0, context
);
5355 mb
.init(data
.length
+ 1, data
.length
+ 1);
5356 mb
.append(data
.data
, data
.length
);
5358 AsyncCall::Pointer call
= commCbCall(33, 5, "FtpWroteReplyData",
5359 CommIoCbPtrFun(&FtpWroteReplyData
, context
));
5360 Comm::Write(conn
->ftp
.dataConn
, &mb
, call
);
5362 context
->noteSentBodyBytes(data
.length
);
5366 FtpWroteReplyData(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
5368 if (errflag
== COMM_ERR_CLOSING
)
5371 ClientSocketContext
*const context
= static_cast<ClientSocketContext
*>(data
);
5372 ConnStateData
*const connState
= context
->getConn();
5374 if (errflag
!= COMM_OK
) {
5375 debugs(33, 3, HERE
<< "FTP reply data writing failed: " <<
5377 FtpCloseDataConnection(connState
);
5378 FtpWriteCustomReply(context
, 426, "Data connection error; transfer aborted");
5382 assert(context
->http
);
5383 context
->http
->out
.size
+= size
;
5385 switch (context
->socketState()) {
5387 debugs(33, 3, "Keep going");
5388 context
->pullData();
5390 case STREAM_COMPLETE
:
5391 debugs(33, 3, HERE
<< "FTP reply data transfer successfully complete");
5392 FtpWriteCustomReply(context
, 226, "Transfer complete");
5394 case STREAM_UNPLANNED_COMPLETE
:
5395 debugs(33, 3, HERE
<< "FTP reply data transfer failed: STREAM_UNPLANNED_COMPLETE");
5396 FtpWriteCustomReply(context
, 451, "Server error; transfer aborted");
5399 debugs(33, 3, HERE
<< "FTP reply data transfer failed: STREAM_FAILED");
5400 FtpWriteCustomReply(context
, 451, "Server error; transfer aborted");
5403 fatal("unreachable code");
5406 FtpCloseDataConnection(connState
);
5410 FtpHandleUploadReply(ClientSocketContext
*context
, const HttpReply
*reply
, StoreIOBuffer data
)
5412 if (!FtpCheckDataConnPost(context
))
5415 FtpWriteForwardedReply(context
, reply
);
5419 FtpWriteForwardedReply(ClientSocketContext
*context
, const HttpReply
*reply
)
5421 const AsyncCall::Pointer call
= commCbCall(33, 5, "FtpWroteReply",
5422 CommIoCbPtrFun(&FtpWroteReply
, context
));
5423 FtpWriteForwardedReply(context
, reply
, call
);
5426 /// writes FTP error response with given status and reply-derived error details
5428 FtpWriteErrorReply(ClientSocketContext
*context
, const HttpReply
*reply
, const int status
)
5433 assert(context
->http
);
5434 const HttpRequest
*request
= context
->http
->request
;
5436 if (request
->errType
!= ERR_NONE
)
5437 mb
.Printf("%i-%s\r\n", status
, errorPageName(request
->errType
));
5439 if (request
->errDetail
> 0) {
5440 // XXX: > 0 may not always mean that this is an errno
5441 mb
.Printf("%i-Error: (%d) %s\r\n", status
,
5443 strerror(request
->errDetail
));
5446 // XXX: Remove hard coded names. Use an error page template instead.
5447 const Adaptation::History::Pointer ah
= request
->adaptHistory();
5448 if (ah
!= NULL
) { // XXX: add adapt::<all_h but use lastMeta here
5449 const String info
= ah
->allMeta
.getByName("X-Response-Info");
5450 const String desc
= ah
->allMeta
.getByName("X-Response-Desc");
5452 mb
.Printf("%i-Information: %s\r\n", status
, info
.termedBuf());
5454 mb
.Printf("%i-Description: %s\r\n", status
, desc
.termedBuf());
5457 assert(reply
!= NULL
);
5458 const char *reason
= reply
->header
.has(HDR_FTP_REASON
) ?
5459 reply
->header
.getStr(HDR_FTP_REASON
):
5460 reply
->sline
.reason();
5462 mb
.Printf("%i %s\r\n", status
, reason
); // error terminating line
5464 // TODO: errorpage.cc should detect FTP client and use
5465 // configurable FTP-friendly error templates which we should
5466 // write to the client "as is" instead of hiding most of the info
5468 FtpWriteReply(context
, mb
);
5471 /// writes FTP response based on HTTP reply that is not an FTP-response wrapper
5473 FtpWriteForwardedForeign(ClientSocketContext
*context
, const HttpReply
*reply
)
5475 ConnStateData
*const connState
= context
->getConn();
5476 FtpChangeState(connState
, ConnStateData::FTP_CONNECTED
, "foreign reply");
5477 // 451: We intend to keep the control connection open.
5478 FtpWriteErrorReply(context
, reply
, 451);
5482 FtpWriteForwardedReply(ClientSocketContext
*context
, const HttpReply
*reply
, AsyncCall::Pointer call
)
5484 assert(reply
!= NULL
);
5485 const HttpHeader
&header
= reply
->header
;
5486 ConnStateData
*const connState
= context
->getConn();
5488 // adaptation and forwarding errors lack HDR_FTP_STATUS
5489 if (!header
.has(HDR_FTP_STATUS
)) {
5490 FtpWriteForwardedForeign(context
, reply
);
5494 assert(header
.has(HDR_FTP_REASON
));
5496 const int status
= header
.getInt(HDR_FTP_STATUS
);
5497 debugs(33, 7, HERE
<< "status: " << status
);
5499 if (status
== 150 && connState
->ftp
.state
==
5500 ConnStateData::FTP_HANDLE_UPLOAD_REQUEST
)
5501 connState
->readSomeFtpData();
5505 FtpPrintReply(mb
, reply
);
5507 debugs(11, 2, "FTP Client " << context
->clientConnection
);
5508 debugs(11, 2, "FTP Client REPLY:\n---------\n" << mb
.buf
<<
5511 Comm::Write(context
->clientConnection
, &mb
, call
);
5515 FtpPrintReply(MemBuf
&mb
, const HttpReply
*reply
, const char *const prefix
)
5517 const HttpHeader
&header
= reply
->header
;
5519 HttpHeaderPos pos
= HttpHeaderInitPos
;
5520 while (const HttpHeaderEntry
*e
= header
.getEntry(&pos
)) {
5521 if (e
->id
== HDR_FTP_PRE
) {
5523 if (httpHeaderParseQuotedString(e
->value
.rawBuf(), e
->value
.size(), &raw
))
5524 mb
.Printf("%s\r\n", raw
.termedBuf());
5528 if (header
.has(HDR_FTP_STATUS
)) {
5529 const char *reason
= header
.getStr(HDR_FTP_REASON
);
5530 mb
.Printf("%i %s\r\n", header
.getInt(HDR_FTP_STATUS
),
5531 (reason
? reason
: 0));
5536 FtpWroteEarlyReply(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
5538 if (errflag
== COMM_ERR_CLOSING
)
5541 if (errflag
!= COMM_OK
) {
5542 debugs(33, 3, HERE
<< "FTP reply writing failed: " << xstrerr(xerrno
));
5547 ConnStateData
*const connState
= static_cast<ConnStateData
*>(data
);
5548 ClientSocketContext::Pointer context
= connState
->getCurrentContext();
5549 if (context
!= NULL
&& context
->http
) {
5550 context
->http
->out
.size
+= size
;
5551 context
->http
->out
.headers_sz
+= size
;
5554 connState
->flags
.readMore
= true;
5555 connState
->readSomeData();
5559 FtpWroteReply(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
5561 if (errflag
== COMM_ERR_CLOSING
)
5564 if (errflag
!= COMM_OK
) {
5565 debugs(33, 3, HERE
<< "FTP reply writing failed: " <<
5571 ClientSocketContext
*const context
=
5572 static_cast<ClientSocketContext
*>(data
);
5573 ConnStateData
*const connState
= context
->getConn();
5575 assert(context
->http
);
5576 context
->http
->out
.size
+= size
;
5577 context
->http
->out
.headers_sz
+= size
;
5579 if (connState
->ftp
.state
== ConnStateData::FTP_ERROR
) {
5580 debugs(33, 5, "closing on FTP server error");
5585 const clientStream_status_t socketState
= context
->socketState();
5586 debugs(33, 5, "FTP client stream state " << socketState
);
5587 switch (socketState
) {
5588 case STREAM_UNPLANNED_COMPLETE
:
5594 case STREAM_COMPLETE
:
5595 connState
->flags
.readMore
= true;
5596 FtpChangeState(connState
, ConnStateData::FTP_CONNECTED
, "FtpWroteReply");
5597 if (connState
->in
.bodyParser
)
5598 connState
->finishDechunkingRequest(false);
5599 context
->keepaliveNextRequest();
5605 FtpHandleRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
) {
5606 if (HttpRequest
*request
= context
->http
->request
) {
5607 MemBuf
*mb
= new MemBuf
;
5610 packerToMemInit(&p
, mb
);
5614 debugs(11, 2, "FTP Client " << context
->clientConnection
);
5615 debugs(11, 2, "FTP Client REQUEST:\n---------\n" << mb
->buf
<<
5620 static std::pair
<const char *, FtpRequestHandler
*> handlers
[] = {
5621 std::make_pair("LIST", FtpHandleDataRequest
),
5622 std::make_pair("NLST", FtpHandleDataRequest
),
5623 std::make_pair("FEAT", FtpHandleFeatRequest
),
5624 std::make_pair("PASV", FtpHandlePasvRequest
),
5625 std::make_pair("PORT", FtpHandlePortRequest
),
5626 std::make_pair("RETR", FtpHandleDataRequest
)
5629 FtpRequestHandler
*handler
= NULL
;
5630 if (context
->http
->request
->method
== Http::METHOD_PUT
)
5631 handler
= FtpHandleUploadRequest
;
5633 for (size_t i
= 0; i
< sizeof(handlers
) / sizeof(*handlers
); ++i
) {
5634 if (cmd
.caseCmp(handlers
[i
].first
) == 0) {
5635 handler
= handlers
[i
].second
;
5641 return handler
!= NULL
? (*handler
)(context
, cmd
, params
) : true;
5644 /// Called to parse USER command, which is required to create an HTTP request
5645 /// wrapper. Thus, errors are handled with FtpWriteEarlyReply() here.
5647 FtpHandleUserRequest(ConnStateData
*connState
, const String
&cmd
, String
¶ms
)
5649 if (params
.size() == 0) {
5650 FtpWriteEarlyReply(connState
, 501, "Missing username");
5654 const String::size_type eou
= params
.rfind('@');
5655 if (eou
== String::npos
|| eou
+ 1 >= params
.size()) {
5656 FtpWriteEarlyReply(connState
, 501, "Missing host");
5660 static const String scheme
= "ftp://";
5661 const String login
= params
.substr(0, eou
);
5662 const String host
= params
.substr(eou
+ 1, params
.size());
5664 String uri
= scheme
;
5668 if (!connState
->ftp
.uri
.size()) {
5669 connState
->ftp
.uri
= uri
;
5670 debugs(11, 3, "set URI to " << connState
->ftp
.uri
);
5671 } else if (uri
.caseCmp(connState
->ftp
.uri
) == 0) {
5672 debugs(11, 5, "keep URI as " << uri
);
5674 debugs(11, 3, "reset URI from " << connState
->ftp
.uri
<< " to " << uri
);
5675 FtpCloseDataConnection(connState
);
5676 connState
->ftp
.readGreeting
= false;
5677 connState
->unpinConnection(); // close control connection to the server
5678 FtpChangeState(connState
, ConnStateData::FTP_BEGIN
, "URI reset");
5687 FtpHandleFeatRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
)
5689 FtpChangeState(context
->getConn(), ConnStateData::FTP_HANDLE_FEAT
, "FtpHandleFeatRequest");
5695 FtpHandlePasvRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
)
5697 if (params
.size() > 0) {
5698 FtpSetReply(context
, 501, "Unexpected parameter");
5702 FtpChangeState(context
->getConn(), ConnStateData::FTP_HANDLE_PASV
, "FtpHandlePasvRequest");
5707 #include "FtpServer.h" /* XXX: For Ftp::ParseIpPort() */
5710 FtpHandlePortRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
)
5712 // TODO: Should PORT errors trigger FtpCloseDataConnection() cleanup?
5714 if (!params
.size()) {
5715 FtpSetReply(context
, 501, "Missing parameter");
5719 Ip::Address cltAddr
;
5720 if (!Ftp::ParseIpPort(params
.termedBuf(), NULL
, cltAddr
)) {
5721 FtpSetReply(context
, 501, "Invalid parameter");
5725 ConnStateData
*const connState
= context
->getConn();
5727 assert(connState
->clientConnection
!= NULL
);
5728 assert(!connState
->clientConnection
->remote
.isAnyAddr());
5730 if (cltAddr
!= connState
->clientConnection
->remote
) {
5731 debugs(33, 2, "rogue PORT " << cltAddr
<< " request? ctrl: " << connState
->clientConnection
->remote
);
5732 // Closing the control connection would not help with attacks because
5733 // the client is evidently able to connect to us. Besides, closing
5734 // makes retrials easier for the client and more damaging to us.
5735 FtpSetReply(context
, 501, "Prohibited parameter value");
5739 FtpCloseDataConnection(context
->getConn());
5741 Comm::ConnectionPointer conn
= new Comm::Connection();
5742 conn
->remote
= cltAddr
;
5744 // Use local IP address of the control connection as the source address
5745 // of the active data connection, or some clients will refuse to accept.
5746 conn
->flags
|= COMM_DOBIND
;
5747 conn
->local
= connState
->clientConnection
->local
;
5748 // RFC 959 requires active FTP connections to originate from port 20
5749 // but that would preclude us from supporting concurrent transfers! (XXX?)
5750 conn
->local
.port(0);
5752 debugs(11, 3, "will actively connect from " << conn
->local
<< " to " <<
5755 context
->getConn()->ftp
.dataConn
= conn
;
5756 context
->getConn()->ftp
.uploadAvailSize
= 0;
5758 FtpChangeState(context
->getConn(), ConnStateData::FTP_HANDLE_PORT
, "FtpHandlePortRequest");
5760 // convert client PORT command to Squid PASV command because Squid
5761 // does not support active FTP transfers on the server side (yet?)
5762 ClientHttpRequest
*const http
= context
->http
;
5763 assert(http
!= NULL
);
5764 HttpRequest
*const request
= http
->request
;
5765 assert(request
!= NULL
);
5766 HttpHeader
&header
= request
->header
;
5767 header
.delById(HDR_FTP_COMMAND
);
5768 header
.putStr(HDR_FTP_COMMAND
, "PASV");
5769 header
.delById(HDR_FTP_ARGUMENTS
);
5770 header
.putStr(HDR_FTP_ARGUMENTS
, "");
5771 return true; // forward our fake PASV request
5775 FtpHandleDataRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
)
5777 if (!FtpCheckDataConnPre(context
))
5780 FtpChangeState(context
->getConn(), ConnStateData::FTP_HANDLE_DATA_REQUEST
, "FtpHandleDataRequest");
5786 FtpHandleUploadRequest(ClientSocketContext
*context
, String
&cmd
, String
¶ms
)
5788 if (!FtpCheckDataConnPre(context
))
5791 FtpChangeState(context
->getConn(), ConnStateData::FTP_HANDLE_UPLOAD_REQUEST
, "FtpHandleDataRequest");
5796 /// check that client data connection is ready for future I/O or at least
5797 /// has a chance of becoming ready soon.
5799 FtpCheckDataConnPre(ClientSocketContext
*context
)
5801 ConnStateData
*const connState
= context
->getConn();
5802 if (Comm::IsConnOpen(connState
->ftp
.dataConn
))
5805 if (Comm::IsConnOpen(connState
->ftp
.dataListenConn
)) {
5806 // We are still waiting for a client to connect to us after PASV.
5807 // Perhaps client's data conn handshake has not reached us yet.
5808 // After we talk to the server, FtpCheckDataConnPost() will recheck.
5809 debugs(33, 3, "expecting clt data conn " << connState
->ftp
.dataListenConn
);
5813 if (!connState
->ftp
.dataConn
|| connState
->ftp
.dataConn
->remote
.isAnyAddr()) {
5814 debugs(33, 5, "missing " << connState
->ftp
.dataConn
);
5815 // TODO: use client address and default port instead.
5816 FtpSetReply(context
, 425, "Use PORT or PASV first");
5820 // active transfer: open a connection from Squid to client
5821 AsyncCall::Pointer connector
= context
->getConn()->ftp
.connector
=
5822 commCbCall(17, 3, "FtpConnectDoneWrapper",
5823 CommConnectCbPtrFun(FtpHandleConnectDone
, context
));
5825 Comm::ConnOpener
*cs
= new Comm::ConnOpener(connState
->ftp
.dataConn
,
5827 Config
.Timeout
.connect
);
5828 AsyncJob::Start(cs
);
5829 return false; // ConnStateData::processFtpRequest waits FtpHandleConnectDone
5832 /// Check that client data connection is ready for immediate I/O.
5834 FtpCheckDataConnPost(ClientSocketContext
*context
)
5836 ConnStateData
*connState
= context
->getConn();
5838 const Comm::ConnectionPointer
&dataConn
= connState
->ftp
.dataConn
;
5839 if (dataConn
!= NULL
&& !Comm::IsConnOpen(dataConn
)) {
5840 // This check is deliberately missing from FtpCheckDataConnPre()
5841 debugs(33, 3, "missing client data conn: " << dataConn
);
5842 FtpWriteCustomReply(context
, 425, "Data connection is not established");
5843 FtpCloseDataConnection(connState
);
5850 FtpHandleConnectDone(const Comm::ConnectionPointer
&conn
, comm_err_t status
, int xerrno
, void *data
)
5852 ClientSocketContext
*context
= static_cast<ClientSocketContext
*>(data
);
5853 context
->getConn()->ftp
.connector
= NULL
;
5855 if (status
!= COMM_OK
) {
5857 FtpSetReply(context
, 425, "Cannot open data connection.");
5858 assert(context
->http
&& context
->http
->storeEntry() != NULL
);
5860 assert(context
->getConn()->ftp
.dataConn
== conn
);
5861 assert(Comm::IsConnOpen(conn
));
5862 fd_note(conn
->fd
, "active client ftp data");
5864 context
->getConn()->resumeFtpRequest(context
);
5868 FtpSetReply(ClientSocketContext
*context
, const int code
, const char *msg
)
5870 ClientHttpRequest
*const http
= context
->http
;
5871 assert(http
!= NULL
);
5872 assert(http
->storeEntry() == NULL
);
5874 HttpReply
*const reply
= new HttpReply
;
5875 reply
->sline
.set(Http::ProtocolVersion(1, 1), Http::scNoContent
);
5876 HttpHeader
&header
= reply
->header
;
5877 header
.putTime(HDR_DATE
, squid_curtime
);
5883 header
.putInt64(HDR_CONTENT_LENGTH
, 0);
5884 header
.putInt(HDR_FTP_STATUS
, code
);
5885 header
.putStr(HDR_FTP_REASON
, msg
);
5886 reply
->hdrCacheInit();
5888 setLogUri(http
, http
->uri
, true);
5890 clientStreamNode
*const node
= context
->getClientReplyContext();
5891 clientReplyContext
*const repContext
=
5892 dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
5893 assert(repContext
!= NULL
);
5896 flags
.cachable
= false; // force releaseRequest() in storeCreateEntry()
5897 flags
.noCache
= true;
5898 repContext
->createStoreEntry(http
->request
->method
, flags
);
5899 http
->storeEntry()->replaceHttpReply(reply
);
5902 /// Whether Squid FTP gateway supports a given feature (e.g., a command).
5904 FtpSupportedCommand(const String
&name
)
5906 static std::set
<std::string
> BlackList
;
5907 if (BlackList
.empty()) {
5908 /* Add FTP commands that Squid cannot gateway correctly */
5910 // IPv6 connection addresses from RFC 2428
5911 BlackList
.insert("EPRT");
5912 BlackList
.insert("EPSV");
5914 // we probably do not support AUTH TLS.* and AUTH SSL,
5915 // but let's disclaim all AUTH support to KISS, for now
5916 BlackList
.insert("AUTH");
5919 // we claim support for all commands that we do not know about
5920 return BlackList
.find(name
.termedBuf()) == BlackList
.end();