2 * Copyright (C) 1996-2017 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 33 Transfer protocol servers */
12 #include "acl/FilledChecklist.h"
13 #include "base/CharacterSet.h"
14 #include "base/RefCount.h"
15 #include "base/Subscription.h"
16 #include "client_side_reply.h"
17 #include "client_side_request.h"
18 #include "clientStream.h"
19 #include "comm/ConnOpener.h"
20 #include "comm/Read.h"
21 #include "comm/TcpAcceptor.h"
22 #include "comm/Write.h"
23 #include "errorpage.h"
25 #include "ftp/Elements.h"
26 #include "ftp/Parsing.h"
28 #include "http/one/RequestParser.h"
29 #include "http/Stream.h"
30 #include "HttpHdrCc.h"
32 #include "ipc/FdNotes.h"
33 #include "parser/Tokenizer.h"
34 #include "servers/forward.h"
35 #include "servers/FtpServer.h"
36 #include "SquidConfig.h"
37 #include "StatCounters.h"
43 CBDATA_NAMESPACED_CLASS_INIT(Ftp
, Server
);
47 static void PrintReply(MemBuf
&mb
, const HttpReply
*reply
, const char *const prefix
= "");
48 static bool SupportedCommand(const SBuf
&name
);
49 static bool CommandHasPathParameter(const SBuf
&cmd
);
52 Ftp::Server::Server(const MasterXaction::Pointer
&xact
):
53 AsyncJob("Ftp::Server"),
55 master(new MasterState
),
66 waitingForOrigin(false),
67 originDataDownloadAbortedOnError(false)
69 flags
.readMore
= false; // we need to announce ourselves first
73 Ftp::Server::~Server()
75 closeDataConnection();
79 Ftp::Server::pipelinePrefetchMax() const
81 return 0; // no support for concurrent FTP requests
85 Ftp::Server::idleTimeout() const
87 return Config
.Timeout
.ftpClientIdle
;
93 ConnStateData::start();
96 char buf
[MAX_IPSTRLEN
];
97 clientConnection
->local
.toUrl(buf
, MAX_IPSTRLEN
);
100 debugs(33, 5, "FTP transparent URL: " << uri
);
103 writeEarlyReply(220, "Service ready");
106 /// schedules another data connection read if needed
108 Ftp::Server::maybeReadUploadData()
113 const size_t availSpace
= sizeof(uploadBuf
) - uploadAvailSize
;
117 debugs(33, 4, dataConn
<< ": reading FTP data...");
119 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
120 reader
= JobCallback(33, 5, Dialer
, this, Ftp::Server::readUploadData
);
121 comm_read(dataConn
, uploadBuf
+ uploadAvailSize
, availSpace
,
125 /// react to the freshly parsed request
127 Ftp::Server::doProcessRequest()
129 // zero pipelinePrefetchMax() ensures that there is only parsed request
130 Must(pipeline
.count() == 1);
131 Http::StreamPointer context
= pipeline
.front();
132 Must(context
!= nullptr);
134 ClientHttpRequest
*const http
= context
->http
;
135 assert(http
!= NULL
);
137 HttpRequest
*const request
= http
->request
;
138 Must(http
->storeEntry() || request
);
139 const bool mayForward
= !http
->storeEntry() && handleRequest(request
);
141 if (http
->storeEntry() != NULL
) {
142 debugs(33, 4, "got an immediate response");
143 clientSetKeepaliveFlag(http
);
145 } else if (mayForward
) {
146 debugs(33, 4, "forwarding request to server side");
147 assert(http
->storeEntry() == NULL
);
148 clientProcessRequest(this, Http1::RequestParserPointer(), context
.getRaw());
150 debugs(33, 4, "will resume processing later");
155 Ftp::Server::processParsedRequest(Http::StreamPointer
&)
157 Must(pipeline
.count() == 1);
159 // Process FTP request asynchronously to make sure FTP
160 // data connection accept callback is fired first.
161 CallJobHere(33, 4, CbcPointer
<Server
>(this),
162 Ftp::Server
, doProcessRequest
);
165 /// imports more upload data from the data connection
167 Ftp::Server::readUploadData(const CommIoCbParams
&io
)
169 debugs(33, 5, io
.conn
<< " size " << io
.size
);
170 Must(reader
!= NULL
);
173 assert(Comm::IsConnOpen(dataConn
));
174 assert(io
.conn
->fd
== dataConn
->fd
);
176 if (io
.flag
== Comm::OK
&& bodyPipe
!= NULL
) {
178 statCounter
.client_http
.kbytes_in
+= io
.size
;
180 char *const current_buf
= uploadBuf
+ uploadAvailSize
;
181 if (io
.buf
!= current_buf
)
182 memmove(current_buf
, io
.buf
, io
.size
);
183 uploadAvailSize
+= io
.size
;
185 } else if (io
.size
== 0) {
186 debugs(33, 5, io
.conn
<< " closed");
187 closeDataConnection();
188 if (uploadAvailSize
<= 0)
189 finishDechunkingRequest(true);
191 } else { // not Comm::Flags::OK or unexpected read
192 debugs(33, 5, io
.conn
<< " closed");
193 closeDataConnection();
194 finishDechunkingRequest(false);
199 /// shovel upload data from the internal buffer to the body pipe if possible
201 Ftp::Server::shovelUploadData()
203 assert(bodyPipe
!= NULL
);
205 debugs(33, 5, "handling FTP request data for " << clientConnection
);
206 const size_t putSize
= bodyPipe
->putMoreData(uploadBuf
,
209 uploadAvailSize
-= putSize
;
210 if (uploadAvailSize
> 0)
211 memmove(uploadBuf
, uploadBuf
+ putSize
, uploadAvailSize
);
214 if (Comm::IsConnOpen(dataConn
))
215 maybeReadUploadData();
216 else if (uploadAvailSize
<= 0)
217 finishDechunkingRequest(true);
221 Ftp::Server::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
223 if (!isOpen()) // if we are closing, nothing to do
230 Ftp::Server::noteBodyConsumerAborted(BodyPipe::Pointer ptr
)
232 if (!isOpen()) // if we are closing, nothing to do
235 ConnStateData::noteBodyConsumerAborted(ptr
);
236 closeDataConnection();
239 /// accept a new FTP control connection and hand it to a dedicated Server
241 Ftp::Server::AcceptCtrlConnection(const CommAcceptCbParams
¶ms
)
243 MasterXaction::Pointer xact
= params
.xaction
;
244 AnyP::PortCfgPointer s
= xact
->squidPort
;
246 // NP: it is possible the port was reconfigured when the call or accept() was queued.
248 if (params
.flag
!= Comm::OK
) {
249 // Its possible the call was still queued when the client disconnected
250 debugs(33, 2, s
->listenConn
<< ": FTP accept failure: " << xstrerr(params
.xerrno
));
254 debugs(33, 4, params
.conn
<< ": accepted");
255 fd_note(params
.conn
->fd
, "client ftp connect");
257 if (s
->tcp_keepalive
.enabled
)
258 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
260 ++incoming_sockets_accepted
;
262 AsyncJob::Start(new Server(xact
));
266 Ftp::StartListening()
268 for (AnyP::PortCfgPointer s
= FtpPortList
; s
!= NULL
; s
= s
->next
) {
269 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
270 debugs(1, DBG_IMPORTANT
, "Ignoring ftp_port lines exceeding the" <<
271 " limit of " << MAXTCPLISTENPORTS
<< " ports.");
275 // direct new connections accepted by listenConn to Accept()
276 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
277 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "Ftp::Server::AcceptCtrlConnection",
278 CommAcceptCbPtrFun(Ftp::Server::AcceptCtrlConnection
,
279 CommAcceptCbParams(NULL
)));
280 clientStartListeningOn(s
, subCall
, Ipc::fdnFtpSocket
);
287 for (AnyP::PortCfgPointer s
= FtpPortList
; s
!= NULL
; s
= s
->next
) {
288 if (s
->listenConn
!= NULL
) {
289 debugs(1, DBG_IMPORTANT
, "Closing FTP port " << s
->listenConn
->local
);
290 s
->listenConn
->close();
291 s
->listenConn
= NULL
;
297 Ftp::Server::notePeerConnection(Comm::ConnectionPointer conn
)
300 Http::StreamPointer context
= pipeline
.front();
301 Must(context
!= nullptr);
302 ClientHttpRequest
*const http
= context
->http
;
304 HttpRequest
*const request
= http
->request
;
305 Must(request
!= NULL
);
307 // this is not an idle connection, so we do not want I/O monitoring
308 const bool monitor
= false;
310 // make FTP peer connection exclusive to our request
311 pinConnection(conn
, request
, conn
->getPeer(), false, monitor
);
315 Ftp::Server::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
317 ConnStateData::clientPinnedConnectionClosed(io
);
319 // TODO: Keep the control connection open after fixing the reset
321 if (Comm::IsConnOpen(clientConnection
))
322 clientConnection
->close();
324 // TODO: If the server control connection is gone, reset state to login
325 // again. Reseting login alone is not enough: FtpRelay::sendCommand() will
326 // not re-login because FtpRelay::serverState() is not going to be
327 // fssConnected. Calling resetLogin() alone is also harmful because
328 // it does not reset correctly the client-to-squid control connection (eg
329 // respond if required with an error code, in all cases)
330 // resetLogin("control connection closure");
333 /// clear client and server login-related state after the old login is gone
335 Ftp::Server::resetLogin(const char *reason
)
337 debugs(33, 5, "will need to re-login due to " << reason
);
338 master
->clientReadGreeting
= false;
339 changeState(fssBegin
, reason
);
342 /// computes uri member from host and, if tracked, working dir with file name
344 Ftp::Server::calcUri(const SBuf
*file
)
348 if (port
->ftp_track_dirs
&& master
->workingDir
.length()) {
349 if (master
->workingDir
[0] != '/')
351 uri
.append(master
->workingDir
);
354 if (uri
[uri
.length() - 1] != '/')
357 if (port
->ftp_track_dirs
&& file
) {
358 static const CharacterSet
Slash("/", "/");
359 Parser::Tokenizer
tok(*file
);
361 uri
.append(tok
.remaining());
365 /// Starts waiting for a data connection. Returns listening port.
366 /// On errors, responds with an error and returns zero.
368 Ftp::Server::listenForDataConnection()
370 closeDataConnection();
372 Comm::ConnectionPointer conn
= new Comm::Connection
;
373 conn
->flags
= COMM_NONBLOCKING
;
374 conn
->local
= transparent() ? port
->s
: clientConnection
->local
;
376 const char *const note
= uri
.c_str();
377 comm_open_listener(SOCK_STREAM
, IPPROTO_TCP
, conn
, note
);
378 if (!Comm::IsConnOpen(conn
)) {
379 debugs(5, DBG_CRITICAL
, "comm_open_listener failed for FTP data: " <<
380 conn
->local
<< " error: " << errno
);
381 writeCustomReply(451, "Internal error");
385 typedef CommCbMemFunT
<Server
, CommAcceptCbParams
> AcceptDialer
;
386 typedef AsyncCallT
<AcceptDialer
> AcceptCall
;
387 RefCount
<AcceptCall
> call
= static_cast<AcceptCall
*>(JobCallback(5, 5, AcceptDialer
, this, Ftp::Server::acceptDataConnection
));
388 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(call
);
389 listener
= call
.getRaw();
390 dataListenConn
= conn
;
391 AsyncJob::Start(new Comm::TcpAcceptor(conn
, note
, sub
));
393 const unsigned int listeningPort
= comm_local_port(conn
->fd
);
394 conn
->local
.port(listeningPort
);
395 return listeningPort
;
399 Ftp::Server::acceptDataConnection(const CommAcceptCbParams
¶ms
)
401 if (params
.flag
!= Comm::OK
) {
402 // Its possible the call was still queued when the client disconnected
403 debugs(33, 2, dataListenConn
<< ": accept "
404 "failure: " << xstrerr(params
.xerrno
));
408 debugs(33, 4, "accepted " << params
.conn
);
409 fd_note(params
.conn
->fd
, "passive client ftp data");
410 ++incoming_sockets_accepted
;
412 if (!clientConnection
) {
413 debugs(33, 5, "late data connection?");
414 closeDataConnection(); // in case we are still listening
415 params
.conn
->close();
416 } else if (params
.conn
->remote
!= clientConnection
->remote
) {
417 debugs(33, 2, "rogue data conn? ctrl: " << clientConnection
->remote
);
418 params
.conn
->close();
419 // Some FTP servers close control connection here, but it may make
420 // things worse from DoS p.o.v. and no better from data stealing p.o.v.
422 closeDataConnection();
423 dataConn
= params
.conn
;
425 debugs(33, 7, "ready for data");
426 if (onDataAcceptCall
!= NULL
) {
427 AsyncCall::Pointer call
= onDataAcceptCall
;
428 onDataAcceptCall
= NULL
;
429 // If we got an upload request, start reading data from the client.
430 if (master
->serverState
== fssHandleUploadRequest
)
431 maybeReadUploadData();
433 Must(master
->serverState
== fssHandleDataRequest
);
436 mb
.appendf("150 Data connection opened.\r\n");
437 Comm::Write(clientConnection
, &mb
, call
);
443 Ftp::Server::closeDataConnection()
445 if (listener
!= NULL
) {
446 listener
->cancel("no longer needed");
450 if (Comm::IsConnOpen(dataListenConn
)) {
451 debugs(33, 5, "FTP closing client data listen socket: " <<
453 dataListenConn
->close();
455 dataListenConn
= NULL
;
457 if (reader
!= NULL
) {
458 // Comm::ReadCancel can deal with negative FDs
459 Comm::ReadCancel(dataConn
->fd
, reader
);
463 if (Comm::IsConnOpen(dataConn
)) {
464 debugs(33, 5, "FTP closing client data connection: " <<
471 /// Writes FTP [error] response before we fully parsed the FTP request and
472 /// created the corresponding HTTP request wrapper for that FTP request.
474 Ftp::Server::writeEarlyReply(const int code
, const char *msg
)
476 debugs(33, 7, code
<< ' ' << msg
);
477 assert(99 < code
&& code
< 1000);
481 mb
.appendf("%i %s\r\n", code
, msg
);
483 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
484 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteEarlyReply
);
485 Comm::Write(clientConnection
, &mb
, call
);
487 flags
.readMore
= false;
489 // TODO: Create master transaction. Log it in wroteEarlyReply().
493 Ftp::Server::writeReply(MemBuf
&mb
)
495 debugs(9, 2, "FTP Client " << clientConnection
);
496 debugs(9, 2, "FTP Client REPLY:\n---------\n" << mb
.buf
<<
499 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
500 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteReply
);
501 Comm::Write(clientConnection
, &mb
, call
);
505 Ftp::Server::writeCustomReply(const int code
, const char *msg
, const HttpReply
*reply
)
507 debugs(33, 7, code
<< ' ' << msg
);
508 assert(99 < code
&& code
< 1000);
510 const bool sendDetails
= reply
!= NULL
&&
511 reply
->header
.has(Http::HdrType::FTP_STATUS
) && reply
->header
.has(Http::HdrType::FTP_REASON
);
516 mb
.appendf("%i-%s\r\n", code
, msg
);
517 mb
.appendf(" Server reply:\r\n");
518 Ftp::PrintReply(mb
, reply
, " ");
519 mb
.appendf("%i \r\n", code
);
521 mb
.appendf("%i %s\r\n", code
, msg
);
527 Ftp::Server::changeState(const ServerState newState
, const char *reason
)
529 if (master
->serverState
== newState
) {
530 debugs(33, 3, "client state unchanged at " << master
->serverState
<<
531 " because " << reason
);
532 master
->serverState
= newState
;
534 debugs(33, 3, "client state was " << master
->serverState
<<
535 ", now " << newState
<< " because " << reason
);
536 master
->serverState
= newState
;
540 /// whether the given FTP command has a pathname parameter
542 Ftp::CommandHasPathParameter(const SBuf
&cmd
)
544 static std::set
<SBuf
> PathedCommands
;
545 if (!PathedCommands
.size()) {
546 PathedCommands
.insert(cmdMlst());
547 PathedCommands
.insert(cmdMlsd());
548 PathedCommands
.insert(cmdStat());
549 PathedCommands
.insert(cmdNlst());
550 PathedCommands
.insert(cmdList());
551 PathedCommands
.insert(cmdMkd());
552 PathedCommands
.insert(cmdRmd());
553 PathedCommands
.insert(cmdDele());
554 PathedCommands
.insert(cmdRnto());
555 PathedCommands
.insert(cmdRnfr());
556 PathedCommands
.insert(cmdAppe());
557 PathedCommands
.insert(cmdStor());
558 PathedCommands
.insert(cmdRetr());
559 PathedCommands
.insert(cmdSmnt());
560 PathedCommands
.insert(cmdCwd());
563 return PathedCommands
.find(cmd
) != PathedCommands
.end();
566 /// creates a context filled with an error message for a given early error
568 Ftp::Server::earlyError(const EarlyErrorKind eek
)
570 /* Default values, to be updated by the switch statement below */
572 const char *reason
= "Internal error";
573 const char *errUri
= "error:ftp-internal-early-error";
576 case EarlyErrorKind::HugeRequest
:
578 reason
= "Huge request";
579 errUri
= "error:ftp-huge-request";
582 case EarlyErrorKind::MissingLogin
:
584 reason
= "Must login first";
585 errUri
= "error:ftp-must-login-first";
588 case EarlyErrorKind::MissingUsername
:
590 reason
= "Missing username";
591 errUri
= "error:ftp-missing-username";
594 case EarlyErrorKind::MissingHost
:
596 reason
= "Missing host";
597 errUri
= "error:ftp-missing-host";
600 case EarlyErrorKind::UnsupportedCommand
:
602 reason
= "Unknown or unsupported command";
603 errUri
= "error:ftp-unsupported-command";
606 case EarlyErrorKind::InvalidUri
:
608 reason
= "Invalid URI";
609 errUri
= "error:ftp-invalid-uri";
612 case EarlyErrorKind::MalformedCommand
:
614 reason
= "Malformed command";
615 errUri
= "error:ftp-malformed-command";
618 // no default so that a compiler can check that we have covered all cases
621 Http::Stream
*context
= abortRequestParsing(errUri
);
622 clientStreamNode
*node
= context
->getClientReplyContext();
624 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
627 // We cannot relay FTP scode/reason via HTTP-specific ErrorState.
628 // TODO: When/if ErrorState can handle native FTP errors, use it instead.
629 HttpReply
*reply
= Ftp::HttpReplyWrapper(scode
, reason
, Http::scBadRequest
, -1);
630 repContext
->setReplyToReply(reply
);
634 /// Parses a single FTP request on the control connection.
635 /// Returns a new Http::Stream on valid requests and all errors.
636 /// Returns NULL on incomplete requests that may still succeed given more data.
638 Ftp::Server::parseOneRequest()
640 flags
.readMore
= false; // common for all but one case below
642 // OWS <command> [ RWS <parameter> ] OWS LF
644 // InlineSpaceChars are isspace(3) or RFC 959 Section 3.1.1.5.2, except
645 // for the LF character that we must exclude here (but see FullWhiteSpace).
646 static const char * const InlineSpaceChars
= " \f\r\t\v";
647 static const CharacterSet InlineSpace
= CharacterSet("Ftp::Inline", InlineSpaceChars
);
648 static const CharacterSet FullWhiteSpace
= (InlineSpace
+ CharacterSet::LF
).rename("Ftp::FWS");
649 static const CharacterSet CommandChars
= FullWhiteSpace
.complement("Ftp::Command");
650 static const CharacterSet TailChars
= CharacterSet::LF
.complement("Ftp::Tail");
652 // This set is used to ignore empty commands without allowing an attacker
653 // to keep us endlessly busy by feeding us whitespace or empty commands.
654 static const CharacterSet
&LeadingSpace
= FullWhiteSpace
;
659 Parser::Tokenizer
tok(inBuf
);
661 (void)tok
.skipAll(LeadingSpace
); // leading OWS and empty commands
662 const bool parsed
= tok
.prefix(cmd
, CommandChars
); // required command
664 // note that the condition below will eat either RWS or trailing OWS
665 if (parsed
&& tok
.skipAll(InlineSpace
) && tok
.prefix(params
, TailChars
)) {
666 // now params may include trailing OWS
667 // TODO: Support right-trimming using CharacterSet in Tokenizer instead
668 static const SBuf
bufWhiteSpace(InlineSpaceChars
);
669 params
.trim(bufWhiteSpace
, false, true);
672 // Why limit command line and parameters size? Did not we just parse them?
673 // XXX: Our good old String cannot handle very long strings.
674 const SBuf::size_type tokenMax
= min(
675 static_cast<SBuf::size_type
>(32*1024), // conservative
676 static_cast<SBuf::size_type
>(Config
.maxRequestHeaderSize
));
677 if (cmd
.length() > tokenMax
|| params
.length() > tokenMax
) {
678 changeState(fssError
, "huge req token");
679 quitAfterError(NULL
);
680 return earlyError(EarlyErrorKind::HugeRequest
);
683 // technically, we may skip multiple NLs below, but that is OK
684 if (!parsed
|| !tok
.skipAll(CharacterSet::LF
)) { // did not find terminating LF yet
685 // we need more data, but can we buffer more?
686 if (inBuf
.length() >= Config
.maxRequestHeaderSize
) {
687 changeState(fssError
, "huge req");
688 quitAfterError(NULL
);
689 return earlyError(EarlyErrorKind::HugeRequest
);
691 flags
.readMore
= true;
692 debugs(33, 5, "Waiting for more, up to " <<
693 (Config
.maxRequestHeaderSize
- inBuf
.length()));
698 Must(parsed
&& cmd
.length());
699 consumeInput(tok
.parsedSize()); // TODO: Would delaying optimize copying?
701 debugs(33, 2, ">>ftp " << cmd
<< (params
.isEmpty() ? "" : " ") << params
);
703 cmd
.toUpper(); // this should speed up and simplify future comparisons
705 // interception cases do not need USER to calculate the uri
706 if (!transparent()) {
707 if (!master
->clientReadGreeting
) {
708 // the first command must be USER
709 if (!pinning
.pinned
&& cmd
!= cmdUser())
710 return earlyError(EarlyErrorKind::MissingLogin
);
713 // process USER request now because it sets FTP peer host name
714 if (cmd
== cmdUser()) {
715 if (Http::Stream
*errCtx
= handleUserRequest(cmd
, params
))
720 if (!Ftp::SupportedCommand(cmd
))
721 return earlyError(EarlyErrorKind::UnsupportedCommand
);
723 const HttpRequestMethod method
=
724 cmd
== cmdAppe() || cmd
== cmdStor() || cmd
== cmdStou() ?
725 Http::METHOD_PUT
: Http::METHOD_GET
;
727 const SBuf
*path
= (params
.length() && CommandHasPathParameter(cmd
)) ?
730 char *newUri
= xstrdup(uri
.c_str());
731 HttpRequest
*const request
= HttpRequest::CreateFromUrl(newUri
, method
);
733 debugs(33, 5, "Invalid FTP URL: " << uri
);
736 return earlyError(EarlyErrorKind::InvalidUri
);
739 request
->flags
.ftpNative
= true;
740 request
->http_ver
= Http::ProtocolVersion(Ftp::ProtocolVersion().major
, Ftp::ProtocolVersion().minor
);
742 // Our fake Request-URIs are not distinctive enough for caching to work
743 request
->flags
.cachable
= false; // XXX: reset later by maybeCacheable()
744 request
->flags
.noCache
= true;
746 request
->header
.putStr(Http::HdrType::FTP_COMMAND
, cmd
.c_str());
747 request
->header
.putStr(Http::HdrType::FTP_ARGUMENTS
, params
.c_str()); // may be ""
748 if (method
== Http::METHOD_PUT
) {
749 request
->header
.putStr(Http::HdrType::EXPECT
, "100-continue");
750 request
->header
.putStr(Http::HdrType::TRANSFER_ENCODING
, "chunked");
753 ClientHttpRequest
*const http
= new ClientHttpRequest(this);
754 http
->request
= request
;
755 HTTPMSGLOCK(http
->request
);
756 http
->req_sz
= tok
.parsedSize();
759 Http::Stream
*const result
=
760 new Http::Stream(clientConnection
, http
);
762 StoreIOBuffer tempBuffer
;
763 tempBuffer
.data
= result
->reqbuf
;
764 tempBuffer
.length
= HTTP_REQBUF_SZ
;
766 ClientStreamData newServer
= new clientReplyContext(http
);
767 ClientStreamData newClient
= result
;
768 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
769 clientReplyStatus
, newServer
, clientSocketRecipient
,
770 clientSocketDetach
, newClient
, tempBuffer
);
772 result
->flags
.parsed_ok
= 1;
777 Ftp::Server::handleReply(HttpReply
*reply
, StoreIOBuffer data
)
779 // the caller guarantees that we are dealing with the current context only
780 Http::StreamPointer context
= pipeline
.front();
781 assert(context
!= nullptr);
783 if (context
->http
&& context
->http
->al
!= NULL
&&
784 !context
->http
->al
->reply
&& reply
) {
785 context
->http
->al
->reply
= reply
;
786 HTTPMSGLOCK(context
->http
->al
->reply
);
789 static ReplyHandler handlers
[] = {
791 NULL
, // fssConnected
792 &Ftp::Server::handleFeatReply
, // fssHandleFeat
793 &Ftp::Server::handlePasvReply
, // fssHandlePasv
794 &Ftp::Server::handlePortReply
, // fssHandlePort
795 &Ftp::Server::handleDataReply
, // fssHandleDataRequest
796 &Ftp::Server::handleUploadReply
, // fssHandleUploadRequest
797 &Ftp::Server::handleEprtReply
,// fssHandleEprt
798 &Ftp::Server::handleEpsvReply
,// fssHandleEpsv
799 NULL
, // fssHandleCwd
800 NULL
, // fssHandlePass
801 NULL
, // fssHandleCdup
802 &Ftp::Server::handleErrorReply
// fssError
805 const Server
&server
= dynamic_cast<const Ftp::Server
&>(*context
->getConn());
806 if (const ReplyHandler handler
= handlers
[server
.master
->serverState
])
807 (this->*handler
)(reply
, data
);
809 writeForwardedReply(reply
);
810 } catch (const std::exception
&e
) {
812 throw TexcHere(e
.what());
817 Ftp::Server::handleFeatReply(const HttpReply
*reply
, StoreIOBuffer
)
819 if (pipeline
.front()->http
->request
->errType
!= ERR_NONE
) {
820 writeCustomReply(502, "Server does not support FEAT", reply
);
825 HttpReply::Pointer featReply
= Ftp::HttpReplyWrapper(211, "End", Http::scNoContent
, 0);
826 HttpHeader
const &serverReplyHeader
= reply
->header
;
828 HttpHeaderPos pos
= HttpHeaderInitPos
;
829 bool hasEPRT
= false;
830 bool hasEPSV
= false;
831 int prependSpaces
= 1;
833 featReply
->header
.putStr(Http::HdrType::FTP_PRE
, "\"211-Features:\"");
834 const int scode
= serverReplyHeader
.getInt(Http::HdrType::FTP_STATUS
);
836 while (const HttpHeaderEntry
*e
= serverReplyHeader
.getEntry(&pos
)) {
837 if (e
->id
== Http::HdrType::FTP_PRE
) {
838 // assume RFC 2389 FEAT response format, quoted by Squid:
839 // <"> SP NAME [SP PARAMS] <">
840 // but accommodate MS servers sending four SPs before NAME
842 // command name ends with (SP parameter) or quote
843 static const CharacterSet
AfterFeatNameChars("AfterFeatName", " \"");
844 static const CharacterSet FeatNameChars
= AfterFeatNameChars
.complement("FeatName");
846 Parser::Tokenizer
tok(SBuf(e
->value
.termedBuf()));
847 if (!tok
.skip('"') || !tok
.skip(' '))
850 // optional spaces; remember their number to accomodate MS servers
851 prependSpaces
= 1 + tok
.skipAll(CharacterSet::SP
);
854 if (!tok
.prefix(cmd
, FeatNameChars
))
858 if (Ftp::SupportedCommand(cmd
)) {
859 featReply
->header
.addEntry(e
->clone());
862 if (cmd
== cmdEprt())
864 else if (cmd
== cmdEpsv())
868 } // else we got a FEAT error and will only report Squid-supported features
872 snprintf(buf
, sizeof(buf
), "\"%*s\"", prependSpaces
+ 4, "EPRT");
873 featReply
->header
.putStr(Http::HdrType::FTP_PRE
, buf
);
876 snprintf(buf
, sizeof(buf
), "\"%*s\"", prependSpaces
+ 4, "EPSV");
877 featReply
->header
.putStr(Http::HdrType::FTP_PRE
, buf
);
880 featReply
->header
.refreshMask();
882 writeForwardedReply(featReply
.getRaw());
886 Ftp::Server::handlePasvReply(const HttpReply
*reply
, StoreIOBuffer
)
888 const Http::StreamPointer
context(pipeline
.front());
889 assert(context
!= nullptr);
891 if (context
->http
->request
->errType
!= ERR_NONE
) {
892 writeCustomReply(502, "Server does not support PASV", reply
);
896 const unsigned short localPort
= listenForDataConnection();
900 char addr
[MAX_IPSTRLEN
];
901 // remote server in interception setups and local address otherwise
902 const Ip::Address
&server
= transparent() ?
903 clientConnection
->local
: dataListenConn
->local
;
904 server
.toStr(addr
, MAX_IPSTRLEN
, AF_INET
);
905 addr
[MAX_IPSTRLEN
- 1] = '\0';
906 for (char *c
= addr
; *c
!= '\0'; ++c
) {
911 // In interception setups, we combine remote server address with a
912 // local port number and hope that traffic will be redirected to us.
913 // Do not use "227 =a,b,c,d,p1,p2" format or omit parens: some nf_ct_ftp
914 // versions block responses that use those alternative syntax rules!
917 mb
.appendf("227 Entering Passive Mode (%s,%i,%i).\r\n",
919 static_cast<int>(localPort
/ 256),
920 static_cast<int>(localPort
% 256));
921 debugs(9, 3, Raw("writing", mb
.buf
, mb
.size
));
926 Ftp::Server::handlePortReply(const HttpReply
*reply
, StoreIOBuffer
)
928 if (pipeline
.front()->http
->request
->errType
!= ERR_NONE
) {
929 writeCustomReply(502, "Server does not support PASV (converted from PORT)", reply
);
933 writeCustomReply(200, "PORT successfully converted to PASV.");
939 Ftp::Server::handleErrorReply(const HttpReply
*reply
, StoreIOBuffer
)
941 if (!pinning
.pinned
) // we failed to connect to server
943 // 421: we will close due to fssError
944 writeErrorReply(reply
, 421);
948 Ftp::Server::handleDataReply(const HttpReply
*reply
, StoreIOBuffer data
)
950 if (reply
!= NULL
&& reply
->sline
.status() != Http::scOkay
) {
951 writeForwardedReply(reply
);
952 if (Comm::IsConnOpen(dataConn
)) {
953 debugs(33, 3, "closing " << dataConn
<< " on KO reply");
954 closeDataConnection();
960 // We got STREAM_COMPLETE (or error) and closed the client data conn.
961 debugs(33, 3, "ignoring FTP srv data response after clt data closure");
965 if (!checkDataConnPost()) {
966 writeCustomReply(425, "Data connection is not established.");
967 closeDataConnection();
971 debugs(33, 7, data
.length
);
973 if (data
.length
<= 0) {
974 replyDataWritingCheckpoint(); // skip the actual write call
979 mb
.init(data
.length
+ 1, data
.length
+ 1);
980 mb
.append(data
.data
, data
.length
);
982 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
983 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteReplyData
);
984 Comm::Write(dataConn
, &mb
, call
);
986 pipeline
.front()->noteSentBodyBytes(data
.length
);
989 /// called when we are done writing a chunk of the response data
991 Ftp::Server::wroteReplyData(const CommIoCbParams
&io
)
993 if (io
.flag
== Comm::ERR_CLOSING
)
996 if (io
.flag
!= Comm::OK
) {
997 debugs(33, 3, "FTP reply data writing failed: " << xstrerr(io
.xerrno
));
998 userDataCompletionCheckpoint(426);
1002 assert(pipeline
.front()->http
);
1003 pipeline
.front()->http
->out
.size
+= io
.size
;
1004 replyDataWritingCheckpoint();
1007 /// ClientStream checks after (actual or skipped) reply data writing
1009 Ftp::Server::replyDataWritingCheckpoint()
1011 switch (pipeline
.front()->socketState()) {
1013 debugs(33, 3, "Keep going");
1014 pipeline
.front()->pullData();
1016 case STREAM_COMPLETE
:
1017 debugs(33, 3, "FTP reply data transfer successfully complete");
1018 userDataCompletionCheckpoint(226);
1020 case STREAM_UNPLANNED_COMPLETE
:
1021 debugs(33, 3, "FTP reply data transfer failed: STREAM_UNPLANNED_COMPLETE");
1022 userDataCompletionCheckpoint(451);
1025 userDataCompletionCheckpoint(451);
1026 debugs(33, 3, "FTP reply data transfer failed: STREAM_FAILED");
1029 fatal("unreachable code");
1034 Ftp::Server::handleUploadReply(const HttpReply
*reply
, StoreIOBuffer
)
1036 writeForwardedReply(reply
);
1037 // note that the client data connection may already be closed by now
1041 Ftp::Server::writeForwardedReply(const HttpReply
*reply
)
1045 if (waitingForOrigin
) {
1046 Must(delayedReply
== NULL
);
1047 delayedReply
= reply
;
1051 const HttpHeader
&header
= reply
->header
;
1052 // adaptation and forwarding errors lack Http::HdrType::FTP_STATUS
1053 if (!header
.has(Http::HdrType::FTP_STATUS
)) {
1054 writeForwardedForeign(reply
); // will get to Ftp::Server::wroteReply
1058 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
1059 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteReply
);
1060 writeForwardedReplyAndCall(reply
, call
);
1064 Ftp::Server::handleEprtReply(const HttpReply
*reply
, StoreIOBuffer
)
1066 if (pipeline
.front()->http
->request
->errType
!= ERR_NONE
) {
1067 writeCustomReply(502, "Server does not support PASV (converted from EPRT)", reply
);
1071 writeCustomReply(200, "EPRT successfully converted to PASV.");
1073 // and wait for RETR
1077 Ftp::Server::handleEpsvReply(const HttpReply
*reply
, StoreIOBuffer
)
1079 if (pipeline
.front()->http
->request
->errType
!= ERR_NONE
) {
1080 writeCustomReply(502, "Cannot connect to server", reply
);
1084 const unsigned short localPort
= listenForDataConnection();
1088 // In interception setups, we use a local port number and hope that data
1089 // traffic will be redirected to us.
1092 mb
.appendf("229 Entering Extended Passive Mode (|||%u|)\r\n", localPort
);
1094 debugs(9, 3, Raw("writing", mb
.buf
, mb
.size
));
1098 /// writes FTP error response with given status and reply-derived error details
1100 Ftp::Server::writeErrorReply(const HttpReply
*reply
, const int scode
)
1102 const HttpRequest
*request
= pipeline
.front()->http
->request
;
1108 if (request
->errType
!= ERR_NONE
)
1109 mb
.appendf("%i-%s\r\n", scode
, errorPageName(request
->errType
));
1111 if (request
->errDetail
> 0) {
1112 // XXX: > 0 may not always mean that this is an errno
1113 mb
.appendf("%i-Error: (%d) %s\r\n", scode
,
1115 strerror(request
->errDetail
));
1119 // XXX: Remove hard coded names. Use an error page template instead.
1120 const Adaptation::History::Pointer ah
= request
->adaptHistory();
1121 if (ah
!= NULL
) { // XXX: add adapt::<all_h but use lastMeta here
1122 const String info
= ah
->allMeta
.getByName("X-Response-Info");
1123 const String desc
= ah
->allMeta
.getByName("X-Response-Desc");
1125 mb
.appendf("%i-Information: %s\r\n", scode
, info
.termedBuf());
1127 mb
.appendf("%i-Description: %s\r\n", scode
, desc
.termedBuf());
1132 const char *reason
= reply
->header
.has(Http::HdrType::FTP_REASON
) ?
1133 reply
->header
.getStr(Http::HdrType::FTP_REASON
):
1134 reply
->sline
.reason();
1136 mb
.appendf("%i %s\r\n", scode
, reason
); // error terminating line
1138 // TODO: errorpage.cc should detect FTP client and use
1139 // configurable FTP-friendly error templates which we should
1140 // write to the client "as is" instead of hiding most of the info
1145 /// writes FTP response based on HTTP reply that is not an FTP-response wrapper
1146 /// for example, internally-generated Squid "errorpages" end up here (for now)
1148 Ftp::Server::writeForwardedForeign(const HttpReply
*reply
)
1150 changeState(fssConnected
, "foreign reply");
1151 closeDataConnection();
1152 // 451: We intend to keep the control connection open.
1153 writeErrorReply(reply
, 451);
1157 Ftp::Server::writeControlMsgAndCall(HttpReply
*reply
, AsyncCall::Pointer
&call
)
1159 // the caller guarantees that we are dealing with the current context only
1160 // the caller should also make sure reply->header.has(Http::HdrType::FTP_STATUS)
1161 writeForwardedReplyAndCall(reply
, call
);
1166 Ftp::Server::writeForwardedReplyAndCall(const HttpReply
*reply
, AsyncCall::Pointer
&call
)
1168 assert(reply
!= NULL
);
1169 const HttpHeader
&header
= reply
->header
;
1171 // without status, the caller must use the writeForwardedForeign() path
1172 Must(header
.has(Http::HdrType::FTP_STATUS
));
1173 Must(header
.has(Http::HdrType::FTP_REASON
));
1174 const int scode
= header
.getInt(Http::HdrType::FTP_STATUS
);
1175 debugs(33, 7, "scode: " << scode
);
1177 // Status 125 or 150 implies upload or data request, but we still check
1178 // the state in case the server is buggy.
1179 if ((scode
== 125 || scode
== 150) &&
1180 (master
->serverState
== fssHandleUploadRequest
||
1181 master
->serverState
== fssHandleDataRequest
)) {
1182 if (checkDataConnPost()) {
1183 // If the data connection is ready, start reading data (here)
1184 // and forward the response to client (further below).
1185 debugs(33, 7, "data connection established, start data transfer");
1186 if (master
->serverState
== fssHandleUploadRequest
)
1187 maybeReadUploadData();
1189 // If we are waiting to accept the data connection, keep waiting.
1190 if (Comm::IsConnOpen(dataListenConn
)) {
1191 debugs(33, 7, "wait for the client to establish a data connection");
1192 onDataAcceptCall
= call
;
1193 // TODO: Add connect timeout for passive connections listener?
1194 // TODO: Remember server response so that we can forward it?
1196 // Either the connection was establised and closed after the
1197 // data was transferred OR we failed to establish an active
1198 // data connection and already sent the error to the client.
1199 // In either case, there is nothing more to do.
1200 debugs(33, 7, "done with data OR active connection failed");
1208 Ftp::PrintReply(mb
, reply
);
1210 debugs(9, 2, "FTP Client " << clientConnection
);
1211 debugs(9, 2, "FTP Client REPLY:\n---------\n" << mb
.buf
<<
1214 Comm::Write(clientConnection
, &mb
, call
);
1218 Ftp::PrintReply(MemBuf
&mb
, const HttpReply
*reply
, const char *const)
1220 const HttpHeader
&header
= reply
->header
;
1222 HttpHeaderPos pos
= HttpHeaderInitPos
;
1223 while (const HttpHeaderEntry
*e
= header
.getEntry(&pos
)) {
1224 if (e
->id
== Http::HdrType::FTP_PRE
) {
1226 if (httpHeaderParseQuotedString(e
->value
.rawBuf(), e
->value
.size(), &raw
))
1227 mb
.appendf("%s\r\n", raw
.termedBuf());
1231 if (header
.has(Http::HdrType::FTP_STATUS
)) {
1232 const char *reason
= header
.getStr(Http::HdrType::FTP_REASON
);
1233 mb
.appendf("%i %s\r\n", header
.getInt(Http::HdrType::FTP_STATUS
),
1234 (reason
? reason
: 0));
1239 Ftp::Server::wroteEarlyReply(const CommIoCbParams
&io
)
1241 if (io
.flag
== Comm::ERR_CLOSING
)
1244 if (io
.flag
!= Comm::OK
) {
1245 debugs(33, 3, "FTP reply writing failed: " << xstrerr(io
.xerrno
));
1250 Http::StreamPointer context
= pipeline
.front();
1251 if (context
!= nullptr && context
->http
) {
1252 context
->http
->out
.size
+= io
.size
;
1253 context
->http
->out
.headers_sz
+= io
.size
;
1256 flags
.readMore
= true;
1261 Ftp::Server::wroteReply(const CommIoCbParams
&io
)
1263 if (io
.flag
== Comm::ERR_CLOSING
)
1266 if (io
.flag
!= Comm::OK
) {
1267 debugs(33, 3, "FTP reply writing failed: " << xstrerr(io
.xerrno
));
1272 Http::StreamPointer context
= pipeline
.front();
1273 assert(context
->http
);
1274 context
->http
->out
.size
+= io
.size
;
1275 context
->http
->out
.headers_sz
+= io
.size
;
1277 if (master
->serverState
== fssError
) {
1278 debugs(33, 5, "closing on FTP server error");
1283 const clientStream_status_t socketState
= context
->socketState();
1284 debugs(33, 5, "FTP client stream state " << socketState
);
1285 switch (socketState
) {
1286 case STREAM_UNPLANNED_COMPLETE
:
1292 case STREAM_COMPLETE
:
1293 flags
.readMore
= true;
1294 changeState(fssConnected
, "Ftp::Server::wroteReply");
1296 finishDechunkingRequest(false);
1297 context
->finished();
1304 Ftp::Server::handleRequest(HttpRequest
*request
)
1306 debugs(33, 9, request
);
1309 HttpHeader
&header
= request
->header
;
1310 Must(header
.has(Http::HdrType::FTP_COMMAND
));
1311 String
&cmd
= header
.findEntry(Http::HdrType::FTP_COMMAND
)->value
;
1312 Must(header
.has(Http::HdrType::FTP_ARGUMENTS
));
1313 String
¶ms
= header
.findEntry(Http::HdrType::FTP_ARGUMENTS
)->value
;
1315 if (Debug::Enabled(9, 2)) {
1320 debugs(9, 2, "FTP Client " << clientConnection
);
1321 debugs(9, 2, "FTP Client REQUEST:\n---------\n" << mb
.buf
<<
1325 // TODO: When HttpHeader uses SBuf, change keys to SBuf
1326 typedef std::map
<const std::string
, RequestHandler
> RequestHandlers
;
1327 static RequestHandlers handlers
;
1328 if (!handlers
.size()) {
1329 handlers
["LIST"] = &Ftp::Server::handleDataRequest
;
1330 handlers
["NLST"] = &Ftp::Server::handleDataRequest
;
1331 handlers
["MLSD"] = &Ftp::Server::handleDataRequest
;
1332 handlers
["FEAT"] = &Ftp::Server::handleFeatRequest
;
1333 handlers
["PASV"] = &Ftp::Server::handlePasvRequest
;
1334 handlers
["PORT"] = &Ftp::Server::handlePortRequest
;
1335 handlers
["RETR"] = &Ftp::Server::handleDataRequest
;
1336 handlers
["EPRT"] = &Ftp::Server::handleEprtRequest
;
1337 handlers
["EPSV"] = &Ftp::Server::handleEpsvRequest
;
1338 handlers
["CWD"] = &Ftp::Server::handleCwdRequest
;
1339 handlers
["PASS"] = &Ftp::Server::handlePassRequest
;
1340 handlers
["CDUP"] = &Ftp::Server::handleCdupRequest
;
1343 RequestHandler handler
= NULL
;
1344 if (request
->method
== Http::METHOD_PUT
)
1345 handler
= &Ftp::Server::handleUploadRequest
;
1347 const RequestHandlers::const_iterator hi
= handlers
.find(cmd
.termedBuf());
1348 if (hi
!= handlers
.end())
1349 handler
= hi
->second
;
1353 debugs(9, 7, "forwarding " << cmd
<< " as is, no post-processing");
1357 return (this->*handler
)(cmd
, params
);
1360 /// Called to parse USER command, which is required to create an HTTP request
1361 /// wrapper. W/o request, the errors are handled by returning earlyError().
1363 Ftp::Server::handleUserRequest(const SBuf
&, SBuf
¶ms
)
1365 if (params
.isEmpty())
1366 return earlyError(EarlyErrorKind::MissingUsername
);
1368 // find the [end of] user name
1369 const SBuf::size_type eou
= params
.rfind('@');
1370 if (eou
== SBuf::npos
|| eou
+ 1 >= params
.length())
1371 return earlyError(EarlyErrorKind::MissingHost
);
1373 // Determine the intended destination.
1374 host
= params
.substr(eou
+ 1, params
.length());
1375 // If we can parse it as raw IPv6 address, then surround with "[]".
1376 // Otherwise (domain, IPv4, [bracketed] IPv6, garbage, etc), use as is.
1377 if (host
.find(':') != SBuf::npos
) {
1378 const Ip::Address
ipa(host
.c_str());
1379 if (!ipa
.isAnyAddr()) {
1380 char ipBuf
[MAX_IPSTRLEN
];
1381 ipa
.toHostStr(ipBuf
, MAX_IPSTRLEN
);
1386 // const SBuf login = params.substr(0, eou);
1387 params
.chop(0, eou
); // leave just the login part for the peer
1390 if (master
->clientReadGreeting
)
1393 master
->workingDir
.clear();
1396 if (!master
->clientReadGreeting
) {
1397 debugs(9, 3, "set URI to " << uri
);
1398 } else if (oldUri
.caseCmp(uri
) == 0) {
1399 debugs(9, 5, "kept URI as " << oldUri
);
1401 debugs(9, 3, "reset URI from " << oldUri
<< " to " << uri
);
1402 closeDataConnection();
1403 unpinConnection(true); // close control connection to peer
1404 resetLogin("URI reset");
1407 return NULL
; // no early errors
1411 Ftp::Server::handleFeatRequest(String
&, String
&)
1413 changeState(fssHandleFeat
, "handleFeatRequest");
1418 Ftp::Server::handlePasvRequest(String
&, String
¶ms
)
1421 setReply(500, "Bad PASV command");
1425 if (params
.size() > 0) {
1426 setReply(501, "Unexpected parameter");
1430 changeState(fssHandlePasv
, "handlePasvRequest");
1431 // no need to fake PASV request via setDataCommand() in true PASV case
1435 /// [Re]initializes dataConn for active data transfers. Does not connect.
1437 Ftp::Server::createDataConnection(Ip::Address cltAddr
)
1439 assert(clientConnection
!= NULL
);
1440 assert(!clientConnection
->remote
.isAnyAddr());
1442 if (cltAddr
!= clientConnection
->remote
) {
1443 debugs(33, 2, "rogue PORT " << cltAddr
<< " request? ctrl: " << clientConnection
->remote
);
1444 // Closing the control connection would not help with attacks because
1445 // the client is evidently able to connect to us. Besides, closing
1446 // makes retrials easier for the client and more damaging to us.
1447 setReply(501, "Prohibited parameter value");
1451 closeDataConnection();
1453 Comm::ConnectionPointer conn
= new Comm::Connection();
1454 conn
->flags
|= COMM_DOBIND
;
1456 // Use local IP address of the control connection as the source address
1457 // of the active data connection, or some clients will refuse to accept.
1458 conn
->setAddrs(clientConnection
->local
, cltAddr
);
1459 // RFC 959 requires active FTP connections to originate from port 20
1460 // but that would preclude us from supporting concurrent transfers! (XXX?)
1461 conn
->local
.port(0);
1463 debugs(9, 3, "will actively connect from " << conn
->local
<< " to " <<
1467 uploadAvailSize
= 0;
1472 Ftp::Server::handlePortRequest(String
&, String
¶ms
)
1474 // TODO: Should PORT errors trigger closeDataConnection() cleanup?
1477 setReply(500, "Rejecting PORT after EPSV ALL");
1481 if (!params
.size()) {
1482 setReply(501, "Missing parameter");
1486 Ip::Address cltAddr
;
1487 if (!Ftp::ParseIpPort(params
.termedBuf(), NULL
, cltAddr
)) {
1488 setReply(501, "Invalid parameter");
1492 if (!createDataConnection(cltAddr
))
1495 changeState(fssHandlePort
, "handlePortRequest");
1497 return true; // forward our fake PASV request
1501 Ftp::Server::handleDataRequest(String
&, String
&)
1503 if (!checkDataConnPre())
1506 master
->userDataDone
= 0;
1507 originDataDownloadAbortedOnError
= false;
1509 changeState(fssHandleDataRequest
, "handleDataRequest");
1515 Ftp::Server::handleUploadRequest(String
&, String
&)
1517 if (!checkDataConnPre())
1520 if (Config
.accessList
.forceRequestBodyContinuation
) {
1521 ClientHttpRequest
*http
= pipeline
.front()->http
;
1522 HttpRequest
*request
= http
->request
;
1523 ACLFilledChecklist
bodyContinuationCheck(Config
.accessList
.forceRequestBodyContinuation
, request
, NULL
);
1524 if (bodyContinuationCheck
.fastCheck() == ACCESS_ALLOWED
) {
1525 request
->forcedBodyContinuation
= true;
1526 if (checkDataConnPost()) {
1527 // Write control Msg
1528 writeEarlyReply(150, "Data connection opened");
1529 maybeReadUploadData();
1531 // wait for acceptDataConnection but tell it to call wroteEarlyReply
1532 // after writing "150 Data connection opened"
1533 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
1534 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteEarlyReply
);
1535 onDataAcceptCall
= call
;
1540 changeState(fssHandleUploadRequest
, "handleDataRequest");
1546 Ftp::Server::handleEprtRequest(String
&, String
¶ms
)
1548 debugs(9, 3, "Process an EPRT " << params
);
1551 setReply(500, "Rejecting EPRT after EPSV ALL");
1555 if (!params
.size()) {
1556 setReply(501, "Missing parameter");
1560 Ip::Address cltAddr
;
1561 if (!Ftp::ParseProtoIpPort(params
.termedBuf(), cltAddr
)) {
1562 setReply(501, "Invalid parameter");
1566 if (!createDataConnection(cltAddr
))
1569 changeState(fssHandleEprt
, "handleEprtRequest");
1571 return true; // forward our fake PASV request
1575 Ftp::Server::handleEpsvRequest(String
&, String
¶ms
)
1577 debugs(9, 3, "Process an EPSV command with params: " << params
);
1578 if (params
.size() <= 0) {
1579 // treat parameterless EPSV as "use the protocol of the ctrl conn"
1580 } else if (params
.caseCmp("ALL") == 0) {
1581 setReply(200, "EPSV ALL ok");
1584 } else if (params
.cmp("2") == 0) {
1585 if (!Ip::EnableIpv6
) {
1586 setReply(522, "Network protocol not supported, use (1)");
1589 } else if (params
.cmp("1") != 0) {
1590 setReply(501, "Unsupported EPSV parameter");
1594 changeState(fssHandleEpsv
, "handleEpsvRequest");
1596 return true; // forward our fake PASV request
1600 Ftp::Server::handleCwdRequest(String
&, String
&)
1602 changeState(fssHandleCwd
, "handleCwdRequest");
1607 Ftp::Server::handlePassRequest(String
&, String
&)
1609 changeState(fssHandlePass
, "handlePassRequest");
1614 Ftp::Server::handleCdupRequest(String
&, String
&)
1616 changeState(fssHandleCdup
, "handleCdupRequest");
1620 // Convert user PORT, EPRT, PASV, or EPSV data command to Squid PASV command.
1621 // Squid FTP client decides what data command to use with peers.
1623 Ftp::Server::setDataCommand()
1625 ClientHttpRequest
*const http
= pipeline
.front()->http
;
1626 assert(http
!= NULL
);
1627 HttpRequest
*const request
= http
->request
;
1628 assert(request
!= NULL
);
1629 HttpHeader
&header
= request
->header
;
1630 header
.delById(Http::HdrType::FTP_COMMAND
);
1631 header
.putStr(Http::HdrType::FTP_COMMAND
, "PASV");
1632 header
.delById(Http::HdrType::FTP_ARGUMENTS
);
1633 header
.putStr(Http::HdrType::FTP_ARGUMENTS
, "");
1634 debugs(9, 5, "client data command converted to fake PASV");
1637 /// check that client data connection is ready for future I/O or at least
1638 /// has a chance of becoming ready soon.
1640 Ftp::Server::checkDataConnPre()
1642 if (Comm::IsConnOpen(dataConn
))
1645 if (Comm::IsConnOpen(dataListenConn
)) {
1646 // We are still waiting for a client to connect to us after PASV.
1647 // Perhaps client's data conn handshake has not reached us yet.
1648 // After we talk to the server, checkDataConnPost() will recheck.
1649 debugs(33, 3, "expecting clt data conn " << dataListenConn
);
1653 if (!dataConn
|| dataConn
->remote
.isAnyAddr()) {
1654 debugs(33, 5, "missing " << dataConn
);
1655 // TODO: use client address and default port instead.
1656 setReply(425, "Use PORT or PASV first");
1660 // active transfer: open a data connection from Squid to client
1661 typedef CommCbMemFunT
<Server
, CommConnectCbParams
> Dialer
;
1662 connector
= JobCallback(17, 3, Dialer
, this, Ftp::Server::connectedForData
);
1663 Comm::ConnOpener
*cs
= new Comm::ConnOpener(dataConn
, connector
,
1664 Config
.Timeout
.connect
);
1665 AsyncJob::Start(cs
);
1666 return false; // ConnStateData::processFtpRequest waits handleConnectDone
1669 /// Check that client data connection is ready for immediate I/O.
1671 Ftp::Server::checkDataConnPost() const
1673 if (!Comm::IsConnOpen(dataConn
)) {
1674 debugs(33, 3, "missing client data conn: " << dataConn
);
1680 /// Done establishing a data connection to the user.
1682 Ftp::Server::connectedForData(const CommConnectCbParams
¶ms
)
1686 if (params
.flag
!= Comm::OK
) {
1687 /* it might have been a timeout with a partially open link */
1688 if (params
.conn
!= NULL
)
1689 params
.conn
->close();
1690 setReply(425, "Cannot open data connection.");
1691 Http::StreamPointer context
= pipeline
.front();
1692 Must(context
->http
);
1693 Must(context
->http
->storeEntry() != NULL
);
1695 Must(dataConn
== params
.conn
);
1696 Must(Comm::IsConnOpen(params
.conn
));
1697 fd_note(params
.conn
->fd
, "active client ftp data");
1704 Ftp::Server::setReply(const int code
, const char *msg
)
1706 Http::StreamPointer context
= pipeline
.front();
1707 ClientHttpRequest
*const http
= context
->http
;
1708 assert(http
!= NULL
);
1709 assert(http
->storeEntry() == NULL
);
1711 HttpReply
*const reply
= Ftp::HttpReplyWrapper(code
, msg
, Http::scNoContent
, 0);
1713 setLogUri(http
, urlCanonicalClean(http
->request
));
1715 clientStreamNode
*const node
= context
->getClientReplyContext();
1716 clientReplyContext
*const repContext
=
1717 dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1718 assert(repContext
!= NULL
);
1720 RequestFlags reqFlags
;
1721 reqFlags
.cachable
= false; // force releaseRequest() in storeCreateEntry()
1722 reqFlags
.noCache
= true;
1723 repContext
->createStoreEntry(http
->request
->method
, reqFlags
);
1724 http
->storeEntry()->replaceHttpReply(reply
);
1728 Ftp::Server::callException(const std::exception
&e
)
1730 debugs(33, 2, "FTP::Server job caught: " << e
.what());
1731 closeDataConnection();
1732 unpinConnection(true);
1733 if (Comm::IsConnOpen(clientConnection
))
1734 clientConnection
->close();
1735 AsyncJob::callException(e
);
1739 Ftp::Server::startWaitingForOrigin()
1741 if (!isOpen()) // if we are closing, nothing to do
1744 debugs(33, 5, "waiting for Ftp::Client data transfer to end");
1745 waitingForOrigin
= true;
1749 Ftp::Server::stopWaitingForOrigin(int originStatus
)
1751 Must(waitingForOrigin
);
1752 waitingForOrigin
= false;
1754 if (!isOpen()) // if we are closing, nothing to do
1757 // if we have already decided how to respond, respond now
1759 HttpReply::Pointer reply
= delayedReply
;
1760 delayedReply
= nullptr;
1761 writeForwardedReply(reply
.getRaw());
1762 return; // do not completeDataDownload() after an earlier response
1765 if (master
->serverState
!= fssHandleDataRequest
)
1768 // completeDataDownload() could be waitingForOrigin in fssHandleDataRequest
1769 // Depending on which side has finished downloading first, either trust
1770 // master->userDataDone status or set originDataDownloadAbortedOnError:
1771 if (master
->userDataDone
) {
1772 // We finished downloading before Ftp::Client. Most likely, the
1773 // adaptation shortened the origin response or we hit an error.
1774 // Our status (stored in master->userDataDone) is more informative.
1775 // Use master->userDataDone; avoid originDataDownloadAbortedOnError.
1776 completeDataDownload();
1778 debugs(33, 5, "too early to write the response");
1779 // Ftp::Client naturally finished downloading before us. Set
1780 // originDataDownloadAbortedOnError to overwrite future
1781 // master->userDataDone and relay Ftp::Client error, if there was
1782 // any, to the user.
1783 originDataDownloadAbortedOnError
= (originStatus
>= 400);
1787 void Ftp::Server::userDataCompletionCheckpoint(int finalStatusCode
)
1789 Must(!master
->userDataDone
);
1790 master
->userDataDone
= finalStatusCode
;
1793 finishDechunkingRequest(false);
1795 if (waitingForOrigin
) {
1796 // The completeDataDownload() is not called here unconditionally
1797 // because we want to signal the FTP user that we are not fully
1798 // done processing its data stream, even though all data bytes
1799 // have been sent or received already.
1800 debugs(33, 5, "Transfering from FTP server is not complete");
1804 // Adjust our reply if the server aborted with an error before we are done.
1805 if (master
->userDataDone
== 226 && originDataDownloadAbortedOnError
) {
1806 debugs(33, 5, "Transfering from FTP server terminated with an error, adjust status code");
1807 master
->userDataDone
= 451;
1809 completeDataDownload();
1812 void Ftp::Server::completeDataDownload()
1814 writeCustomReply(master
->userDataDone
, master
->userDataDone
== 226 ? "Transfer complete" : "Server error; transfer aborted");
1815 closeDataConnection();
1818 /// Whether Squid FTP Relay supports a named feature (e.g., a command).
1820 Ftp::SupportedCommand(const SBuf
&name
)
1822 static std::set
<SBuf
> BlackList
;
1823 if (BlackList
.empty()) {
1824 /* Add FTP commands that Squid cannot relay correctly. */
1826 // We probably do not support AUTH TLS.* and AUTH SSL,
1827 // but let's disclaim all AUTH support to KISS, for now.
1828 BlackList
.insert(cmdAuth());
1831 // we claim support for all commands that we do not know about
1832 return BlackList
.find(name
) == BlackList
.end();