2 * Copyright (C) 1996-2014 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 "HttpHdrCc.h"
31 #include "ipc/FdNotes.h"
32 #include "parser/Tokenizer.h"
33 #include "servers/forward.h"
34 #include "servers/FtpServer.h"
35 #include "SquidConfig.h"
36 #include "StatCounters.h"
42 CBDATA_NAMESPACED_CLASS_INIT(Ftp
, Server
);
46 static void PrintReply(MemBuf
&mb
, const HttpReply
*reply
, const char *const prefix
= "");
47 static bool SupportedCommand(const SBuf
&name
);
48 static bool CommandHasPathParameter(const SBuf
&cmd
);
51 Ftp::Server::Server(const MasterXaction::Pointer
&xact
):
52 AsyncJob("Ftp::Server"),
54 master(new MasterState
),
66 flags
.readMore
= false; // we need to announce ourselves first
70 Ftp::Server::~Server()
72 closeDataConnection();
76 Ftp::Server::pipelinePrefetchMax() const
78 return 0; // no support for concurrent FTP requests
82 Ftp::Server::idleTimeout() const
84 return Config
.Timeout
.ftpClientIdle
;
90 ConnStateData::start();
93 char buf
[MAX_IPSTRLEN
];
94 clientConnection
->local
.toUrl(buf
, MAX_IPSTRLEN
);
97 debugs(33, 5, "FTP transparent URL: " << uri
);
100 writeEarlyReply(220, "Service ready");
103 /// schedules another data connection read if needed
105 Ftp::Server::maybeReadUploadData()
110 const size_t availSpace
= sizeof(uploadBuf
) - uploadAvailSize
;
114 debugs(33, 4, dataConn
<< ": reading FTP data...");
116 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
117 reader
= JobCallback(33, 5, Dialer
, this, Ftp::Server::readUploadData
);
118 comm_read(dataConn
, uploadBuf
+ uploadAvailSize
, availSpace
,
122 /// react to the freshly parsed request
124 Ftp::Server::doProcessRequest()
126 // zero pipelinePrefetchMax() ensures that there is only parsed request
127 ClientSocketContext::Pointer context
= getCurrentContext();
128 Must(context
!= NULL
);
129 Must(getConcurrentRequestCount() == 1);
131 ClientHttpRequest
*const http
= context
->http
;
132 assert(http
!= NULL
);
134 HttpRequest
*const request
= http
->request
;
135 Must(http
->storeEntry() || request
);
136 const bool mayForward
= !http
->storeEntry() && handleRequest(request
);
138 if (http
->storeEntry() != NULL
) {
139 debugs(33, 4, "got an immediate response");
140 clientSetKeepaliveFlag(http
);
142 } else if (mayForward
) {
143 debugs(33, 4, "forwarding request to server side");
144 assert(http
->storeEntry() == NULL
);
145 clientProcessRequest(this, Http1::RequestParserPointer(), context
.getRaw());
147 debugs(33, 4, "will resume processing later");
152 Ftp::Server::processParsedRequest(ClientSocketContext
*)
154 Must(getConcurrentRequestCount() == 1);
156 // Process FTP request asynchronously to make sure FTP
157 // data connection accept callback is fired first.
158 CallJobHere(33, 4, CbcPointer
<Server
>(this),
159 Ftp::Server
, doProcessRequest
);
162 /// imports more upload data from the data connection
164 Ftp::Server::readUploadData(const CommIoCbParams
&io
)
166 debugs(33, 5, io
.conn
<< " size " << io
.size
);
167 Must(reader
!= NULL
);
170 assert(Comm::IsConnOpen(dataConn
));
171 assert(io
.conn
->fd
== dataConn
->fd
);
173 if (io
.flag
== Comm::OK
&& bodyPipe
!= NULL
) {
175 kb_incr(&(statCounter
.client_http
.kbytes_in
), io
.size
);
177 char *const current_buf
= uploadBuf
+ uploadAvailSize
;
178 if (io
.buf
!= current_buf
)
179 memmove(current_buf
, io
.buf
, io
.size
);
180 uploadAvailSize
+= io
.size
;
182 } else if (io
.size
== 0) {
183 debugs(33, 5, io
.conn
<< " closed");
184 closeDataConnection();
185 if (uploadAvailSize
<= 0)
186 finishDechunkingRequest(true);
188 } else { // not Comm::Flags::OK or unexpected read
189 debugs(33, 5, io
.conn
<< " closed");
190 closeDataConnection();
191 finishDechunkingRequest(false);
196 /// shovel upload data from the internal buffer to the body pipe if possible
198 Ftp::Server::shovelUploadData()
200 assert(bodyPipe
!= NULL
);
202 debugs(33, 5, "handling FTP request data for " << clientConnection
);
203 const size_t putSize
= bodyPipe
->putMoreData(uploadBuf
,
206 uploadAvailSize
-= putSize
;
207 if (uploadAvailSize
> 0)
208 memmove(uploadBuf
, uploadBuf
+ putSize
, uploadAvailSize
);
211 if (Comm::IsConnOpen(dataConn
))
212 maybeReadUploadData();
213 else if (uploadAvailSize
<= 0)
214 finishDechunkingRequest(true);
218 Ftp::Server::noteMoreBodySpaceAvailable(BodyPipe::Pointer
)
224 Ftp::Server::noteBodyConsumerAborted(BodyPipe::Pointer ptr
)
226 ConnStateData::noteBodyConsumerAborted(ptr
);
227 closeDataConnection();
230 /// accept a new FTP control connection and hand it to a dedicated Server
232 Ftp::Server::AcceptCtrlConnection(const CommAcceptCbParams
¶ms
)
234 MasterXaction::Pointer xact
= params
.xaction
;
235 AnyP::PortCfgPointer s
= xact
->squidPort
;
237 // NP: it is possible the port was reconfigured when the call or accept() was queued.
239 if (params
.flag
!= Comm::OK
) {
240 // Its possible the call was still queued when the client disconnected
241 debugs(33, 2, s
->listenConn
<< ": FTP accept failure: " << xstrerr(params
.xerrno
));
245 debugs(33, 4, params
.conn
<< ": accepted");
246 fd_note(params
.conn
->fd
, "client ftp connect");
248 if (s
->tcp_keepalive
.enabled
)
249 commSetTcpKeepalive(params
.conn
->fd
, s
->tcp_keepalive
.idle
, s
->tcp_keepalive
.interval
, s
->tcp_keepalive
.timeout
);
251 ++incoming_sockets_accepted
;
253 AsyncJob::Start(new Server(xact
));
257 Ftp::StartListening()
259 for (AnyP::PortCfgPointer s
= FtpPortList
; s
!= NULL
; s
= s
->next
) {
260 if (MAXTCPLISTENPORTS
== NHttpSockets
) {
261 debugs(1, DBG_IMPORTANT
, "Ignoring ftp_port lines exceeding the" <<
262 " limit of " << MAXTCPLISTENPORTS
<< " ports.");
266 // direct new connections accepted by listenConn to Accept()
267 typedef CommCbFunPtrCallT
<CommAcceptCbPtrFun
> AcceptCall
;
268 RefCount
<AcceptCall
> subCall
= commCbCall(5, 5, "Ftp::Server::AcceptCtrlConnection",
269 CommAcceptCbPtrFun(Ftp::Server::AcceptCtrlConnection
,
270 CommAcceptCbParams(NULL
)));
271 clientStartListeningOn(s
, subCall
, Ipc::fdnFtpSocket
);
278 for (AnyP::PortCfgPointer s
= FtpPortList
; s
!= NULL
; s
= s
->next
) {
279 if (s
->listenConn
!= NULL
) {
280 debugs(1, DBG_IMPORTANT
, "Closing FTP port " << s
->listenConn
->local
);
281 s
->listenConn
->close();
282 s
->listenConn
= NULL
;
288 Ftp::Server::notePeerConnection(Comm::ConnectionPointer conn
)
291 ClientSocketContext::Pointer context
= getCurrentContext();
292 Must(context
!= NULL
);
293 ClientHttpRequest
*const http
= context
->http
;
295 HttpRequest
*const request
= http
->request
;
296 Must(request
!= NULL
);
298 // this is not an idle connection, so we do not want I/O monitoring
299 const bool monitor
= false;
301 // make FTP peer connection exclusive to our request
302 pinConnection(conn
, request
, conn
->getPeer(), false, monitor
);
306 Ftp::Server::clientPinnedConnectionClosed(const CommCloseCbParams
&io
)
308 ConnStateData::clientPinnedConnectionClosed(io
);
310 // if the server control connection is gone, reset state to login again
311 resetLogin("control connection closure");
313 // XXX: Reseting is not enough. FtpRelay::sendCommand() will not re-login
314 // because FtpRelay::serverState() is not going to be fssConnected.
317 /// clear client and server login-related state after the old login is gone
319 Ftp::Server::resetLogin(const char *reason
)
321 debugs(33, 5, "will need to re-login due to " << reason
);
322 master
->clientReadGreeting
= false;
323 changeState(fssBegin
, reason
);
326 /// computes uri member from host and, if tracked, working dir with file name
328 Ftp::Server::calcUri(const SBuf
*file
)
332 if (port
->ftp_track_dirs
&& master
->workingDir
.length()) {
333 if (master
->workingDir
[0] != '/')
335 uri
.append(master
->workingDir
);
338 if (uri
[uri
.length() - 1] != '/')
341 if (port
->ftp_track_dirs
&& file
) {
342 static const CharacterSet
Slash("/", "/");
343 Parser::Tokenizer
tok(*file
);
345 uri
.append(tok
.remaining());
349 /// Starts waiting for a data connection. Returns listening port.
350 /// On errors, responds with an error and returns zero.
352 Ftp::Server::listenForDataConnection()
354 closeDataConnection();
356 Comm::ConnectionPointer conn
= new Comm::Connection
;
357 conn
->flags
= COMM_NONBLOCKING
;
358 conn
->local
= transparent() ? port
->s
: clientConnection
->local
;
360 const char *const note
= uri
.c_str();
361 comm_open_listener(SOCK_STREAM
, IPPROTO_TCP
, conn
, note
);
362 if (!Comm::IsConnOpen(conn
)) {
363 debugs(5, DBG_CRITICAL
, "comm_open_listener failed for FTP data: " <<
364 conn
->local
<< " error: " << errno
);
365 writeCustomReply(451, "Internal error");
369 typedef CommCbMemFunT
<Server
, CommAcceptCbParams
> AcceptDialer
;
370 typedef AsyncCallT
<AcceptDialer
> AcceptCall
;
371 RefCount
<AcceptCall
> call
= static_cast<AcceptCall
*>(JobCallback(5, 5, AcceptDialer
, this, Ftp::Server::acceptDataConnection
));
372 Subscription::Pointer sub
= new CallSubscription
<AcceptCall
>(call
);
373 listener
= call
.getRaw();
374 dataListenConn
= conn
;
375 AsyncJob::Start(new Comm::TcpAcceptor(conn
, note
, sub
));
377 const unsigned int listeningPort
= comm_local_port(conn
->fd
);
378 conn
->local
.port(listeningPort
);
379 return listeningPort
;
383 Ftp::Server::acceptDataConnection(const CommAcceptCbParams
¶ms
)
385 if (params
.flag
!= Comm::OK
) {
386 // Its possible the call was still queued when the client disconnected
387 debugs(33, 2, dataListenConn
<< ": accept "
388 "failure: " << xstrerr(params
.xerrno
));
392 debugs(33, 4, "accepted " << params
.conn
);
393 fd_note(params
.conn
->fd
, "passive client ftp data");
394 ++incoming_sockets_accepted
;
396 if (!clientConnection
) {
397 debugs(33, 5, "late data connection?");
398 closeDataConnection(); // in case we are still listening
399 params
.conn
->close();
400 } else if (params
.conn
->remote
!= clientConnection
->remote
) {
401 debugs(33, 2, "rogue data conn? ctrl: " << clientConnection
->remote
);
402 params
.conn
->close();
403 // Some FTP servers close control connection here, but it may make
404 // things worse from DoS p.o.v. and no better from data stealing p.o.v.
406 closeDataConnection();
407 dataConn
= params
.conn
;
409 debugs(33, 7, "ready for data");
410 if (onDataAcceptCall
!= NULL
) {
411 AsyncCall::Pointer call
= onDataAcceptCall
;
412 onDataAcceptCall
= NULL
;
413 // If we got an upload request, start reading data from the client.
414 if (master
->serverState
== fssHandleUploadRequest
)
415 maybeReadUploadData();
417 Must(master
->serverState
== fssHandleDataRequest
);
420 mb
.Printf("150 Data connection opened.\r\n");
421 Comm::Write(clientConnection
, &mb
, call
);
427 Ftp::Server::closeDataConnection()
429 if (listener
!= NULL
) {
430 listener
->cancel("no longer needed");
434 if (Comm::IsConnOpen(dataListenConn
)) {
435 debugs(33, 5, "FTP closing client data listen socket: " <<
437 dataListenConn
->close();
439 dataListenConn
= NULL
;
441 if (reader
!= NULL
) {
442 // Comm::ReadCancel can deal with negative FDs
443 Comm::ReadCancel(dataConn
->fd
, reader
);
447 if (Comm::IsConnOpen(dataConn
)) {
448 debugs(33, 5, "FTP closing client data connection: " <<
455 /// Writes FTP [error] response before we fully parsed the FTP request and
456 /// created the corresponding HTTP request wrapper for that FTP request.
458 Ftp::Server::writeEarlyReply(const int code
, const char *msg
)
460 debugs(33, 7, code
<< ' ' << msg
);
461 assert(99 < code
&& code
< 1000);
465 mb
.Printf("%i %s\r\n", code
, msg
);
467 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
468 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteEarlyReply
);
469 Comm::Write(clientConnection
, &mb
, call
);
471 flags
.readMore
= false;
473 // TODO: Create master transaction. Log it in wroteEarlyReply().
477 Ftp::Server::writeReply(MemBuf
&mb
)
479 debugs(9, 2, "FTP Client " << clientConnection
);
480 debugs(9, 2, "FTP Client REPLY:\n---------\n" << mb
.buf
<<
483 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
484 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteReply
);
485 Comm::Write(clientConnection
, &mb
, call
);
489 Ftp::Server::writeCustomReply(const int code
, const char *msg
, const HttpReply
*reply
)
491 debugs(33, 7, code
<< ' ' << msg
);
492 assert(99 < code
&& code
< 1000);
494 const bool sendDetails
= reply
!= NULL
&&
495 reply
->header
.has(HDR_FTP_STATUS
) && reply
->header
.has(HDR_FTP_REASON
);
500 mb
.Printf("%i-%s\r\n", code
, msg
);
501 mb
.Printf(" Server reply:\r\n");
502 Ftp::PrintReply(mb
, reply
, " ");
503 mb
.Printf("%i \r\n", code
);
505 mb
.Printf("%i %s\r\n", code
, msg
);
511 Ftp::Server::changeState(const ServerState newState
, const char *reason
)
513 if (master
->serverState
== newState
) {
514 debugs(33, 3, "client state unchanged at " << master
->serverState
<<
515 " because " << reason
);
516 master
->serverState
= newState
;
518 debugs(33, 3, "client state was " << master
->serverState
<<
519 ", now " << newState
<< " because " << reason
);
520 master
->serverState
= newState
;
524 /// whether the given FTP command has a pathname parameter
526 Ftp::CommandHasPathParameter(const SBuf
&cmd
)
528 static std::set
<SBuf
> PathedCommands
;
529 if (!PathedCommands
.size()) {
530 PathedCommands
.insert(cmdMlst());
531 PathedCommands
.insert(cmdMlsd());
532 PathedCommands
.insert(cmdStat());
533 PathedCommands
.insert(cmdNlst());
534 PathedCommands
.insert(cmdList());
535 PathedCommands
.insert(cmdMkd());
536 PathedCommands
.insert(cmdRmd());
537 PathedCommands
.insert(cmdDele());
538 PathedCommands
.insert(cmdRnto());
539 PathedCommands
.insert(cmdRnfr());
540 PathedCommands
.insert(cmdAppe());
541 PathedCommands
.insert(cmdStor());
542 PathedCommands
.insert(cmdRetr());
543 PathedCommands
.insert(cmdSmnt());
544 PathedCommands
.insert(cmdCwd());
547 return PathedCommands
.find(cmd
) != PathedCommands
.end();
550 /// creates a context filled with an error message for a given early error
551 ClientSocketContext
*
552 Ftp::Server::earlyError(const EarlyErrorKind eek
)
554 /* Default values, to be updated by the switch statement below */
556 const char *reason
= "Internal error";
557 const char *errUri
= "error:ftp-internal-early-error";
562 reason
= "Huge request";
563 errUri
= "error:ftp-huge-request";
566 case eekMissingLogin
:
568 reason
= "Must login first";
569 errUri
= "error:ftp-must-login-first";
572 case eekMissingUsername
:
574 reason
= "Missing username";
575 errUri
= "error:ftp-missing-username";
580 reason
= "Missing host";
581 errUri
= "error:ftp-missing-host";
584 case eekUnsupportedCommand
:
586 reason
= "Unknown or unsupported command";
587 errUri
= "error:ftp-unsupported-command";
592 reason
= "Invalid URI";
593 errUri
= "error:ftp-invalid-uri";
596 case eekMalformedCommand
:
598 reason
= "Malformed command";
599 errUri
= "error:ftp-malformed-command";
602 // no default so that a compiler can check that we have covered all cases
605 ClientSocketContext
*context
= abortRequestParsing(errUri
);
606 clientStreamNode
*node
= context
->getClientReplyContext();
608 clientReplyContext
*repContext
= dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
611 // We cannot relay FTP scode/reason via HTTP-specific ErrorState.
612 // TODO: When/if ErrorState can handle native FTP errors, use it instead.
613 HttpReply
*reply
= Ftp::HttpReplyWrapper(scode
, reason
, Http::scBadRequest
, -1);
614 repContext
->setReplyToReply(reply
);
618 /// Parses a single FTP request on the control connection.
619 /// Returns a new ClientSocketContext on valid requests and all errors.
620 /// Returns NULL on incomplete requests that may still succeed given more data.
621 ClientSocketContext
*
622 Ftp::Server::parseOneRequest()
624 flags
.readMore
= false; // common for all but one case below
626 // OWS <command> [ RWS <parameter> ] OWS LF
628 // InlineSpaceChars are isspace(3) or RFC 959 Section 3.1.1.5.2, except
629 // for the LF character that we must exclude here (but see FullWhiteSpace).
630 static const char * const InlineSpaceChars
= " \f\r\t\v";
631 static const CharacterSet InlineSpace
= CharacterSet("Ftp::Inline", InlineSpaceChars
);
632 static const CharacterSet FullWhiteSpace
= (InlineSpace
+ CharacterSet::LF
).rename("Ftp::FWS");
633 static const CharacterSet CommandChars
= FullWhiteSpace
.complement("Ftp::Command");
634 static const CharacterSet TailChars
= CharacterSet::LF
.complement("Ftp::Tail");
636 // This set is used to ignore empty commands without allowing an attacker
637 // to keep us endlessly busy by feeding us whitespace or empty commands.
638 static const CharacterSet
&LeadingSpace
= FullWhiteSpace
;
643 Parser::Tokenizer
tok(in
.buf
);
645 (void)tok
.skipAll(LeadingSpace
); // leading OWS and empty commands
646 const bool parsed
= tok
.prefix(cmd
, CommandChars
); // required command
648 // note that the condition below will eat either RWS or trailing OWS
649 if (parsed
&& tok
.skipAll(InlineSpace
) && tok
.prefix(params
, TailChars
)) {
650 // now params may include trailing OWS
651 // TODO: Support right-trimming using CharacterSet in Tokenizer instead
652 static const SBuf
bufWhiteSpace(InlineSpaceChars
);
653 params
.trim(bufWhiteSpace
, false, true);
656 // Why limit command line and parameters size? Did not we just parse them?
657 // XXX: Our good old String cannot handle very long strings.
658 const SBuf::size_type tokenMax
= min(
659 static_cast<SBuf::size_type
>(32*1024), // conservative
660 static_cast<SBuf::size_type
>(Config
.maxRequestHeaderSize
));
661 if (cmd
.length() > tokenMax
|| params
.length() > tokenMax
) {
662 changeState(fssError
, "huge req token");
663 quitAfterError(NULL
);
664 return earlyError(eekHugeRequest
);
667 // technically, we may skip multiple NLs below, but that is OK
668 if (!parsed
|| !tok
.skipAll(CharacterSet::LF
)) { // did not find terminating LF yet
669 // we need more data, but can we buffer more?
670 if (in
.buf
.length() >= Config
.maxRequestHeaderSize
) {
671 changeState(fssError
, "huge req");
672 quitAfterError(NULL
);
673 return earlyError(eekHugeRequest
);
675 flags
.readMore
= true;
676 debugs(33, 5, "Waiting for more, up to " <<
677 (Config
.maxRequestHeaderSize
- in
.buf
.length()));
682 Must(parsed
&& cmd
.length());
683 consumeInput(tok
.parsedSize()); // TODO: Would delaying optimize copying?
685 debugs(33, 2, ">>ftp " << cmd
<< (params
.isEmpty() ? "" : " ") << params
);
687 cmd
.toUpper(); // this should speed up and simplify future comparisons
689 // interception cases do not need USER to calculate the uri
690 if (!transparent()) {
691 if (!master
->clientReadGreeting
) {
692 // the first command must be USER
693 if (!pinning
.pinned
&& cmd
!= cmdUser())
694 return earlyError(eekMissingLogin
);
697 // process USER request now because it sets FTP peer host name
698 if (cmd
== cmdUser()) {
699 if (ClientSocketContext
*errCtx
= handleUserRequest(cmd
, params
))
704 if (!Ftp::SupportedCommand(cmd
))
705 return earlyError(eekUnsupportedCommand
);
707 const HttpRequestMethod method
=
708 cmd
== cmdAppe() || cmd
== cmdStor() || cmd
== cmdStou() ?
709 Http::METHOD_PUT
: Http::METHOD_GET
;
711 const SBuf
*path
= (params
.length() && CommandHasPathParameter(cmd
)) ?
714 char *newUri
= xstrdup(uri
.c_str());
715 HttpRequest
*const request
= HttpRequest::CreateFromUrlAndMethod(newUri
, method
);
717 debugs(33, 5, "Invalid FTP URL: " << uri
);
720 return earlyError(eekInvalidUri
);
723 request
->flags
.ftpNative
= true;
724 request
->http_ver
= Http::ProtocolVersion(Ftp::ProtocolVersion().major
, Ftp::ProtocolVersion().minor
);
726 // Our fake Request-URIs are not distinctive enough for caching to work
727 request
->flags
.cachable
= false; // XXX: reset later by maybeCacheable()
728 request
->flags
.noCache
= true;
730 request
->header
.putStr(HDR_FTP_COMMAND
, cmd
.c_str());
731 request
->header
.putStr(HDR_FTP_ARGUMENTS
, params
.c_str()); // may be ""
732 if (method
== Http::METHOD_PUT
) {
733 request
->header
.putStr(HDR_EXPECT
, "100-continue");
734 request
->header
.putStr(HDR_TRANSFER_ENCODING
, "chunked");
737 ClientHttpRequest
*const http
= new ClientHttpRequest(this);
738 http
->request
= request
;
739 HTTPMSGLOCK(http
->request
);
740 http
->req_sz
= tok
.parsedSize();
743 ClientSocketContext
*const result
=
744 new ClientSocketContext(clientConnection
, http
);
746 StoreIOBuffer tempBuffer
;
747 tempBuffer
.data
= result
->reqbuf
;
748 tempBuffer
.length
= HTTP_REQBUF_SZ
;
750 ClientStreamData newServer
= new clientReplyContext(http
);
751 ClientStreamData newClient
= result
;
752 clientStreamInit(&http
->client_stream
, clientGetMoreData
, clientReplyDetach
,
753 clientReplyStatus
, newServer
, clientSocketRecipient
,
754 clientSocketDetach
, newClient
, tempBuffer
);
756 result
->flags
.parsed_ok
= 1;
761 Ftp::Server::handleReply(HttpReply
*reply
, StoreIOBuffer data
)
763 // the caller guarantees that we are dealing with the current context only
764 ClientSocketContext::Pointer context
= getCurrentContext();
765 assert(context
!= NULL
);
767 if (context
->http
&& context
->http
->al
!= NULL
&&
768 !context
->http
->al
->reply
&& reply
) {
769 context
->http
->al
->reply
= reply
;
770 HTTPMSGLOCK(context
->http
->al
->reply
);
773 static ReplyHandler handlers
[] = {
775 NULL
, // fssConnected
776 &Ftp::Server::handleFeatReply
, // fssHandleFeat
777 &Ftp::Server::handlePasvReply
, // fssHandlePasv
778 &Ftp::Server::handlePortReply
, // fssHandlePort
779 &Ftp::Server::handleDataReply
, // fssHandleDataRequest
780 &Ftp::Server::handleUploadReply
, // fssHandleUploadRequest
781 &Ftp::Server::handleEprtReply
,// fssHandleEprt
782 &Ftp::Server::handleEpsvReply
,// fssHandleEpsv
783 NULL
, // fssHandleCwd
784 NULL
, // fssHandlePass
785 NULL
, // fssHandleCdup
786 &Ftp::Server::handleErrorReply
// fssError
788 const Server
&server
= dynamic_cast<const Ftp::Server
&>(*context
->getConn());
789 if (const ReplyHandler handler
= handlers
[server
.master
->serverState
])
790 (this->*handler
)(reply
, data
);
792 writeForwardedReply(reply
);
796 Ftp::Server::handleFeatReply(const HttpReply
*reply
, StoreIOBuffer
)
798 if (getCurrentContext()->http
->request
->errType
!= ERR_NONE
) {
799 writeCustomReply(502, "Server does not support FEAT", reply
);
803 HttpReply::Pointer featReply
= Ftp::HttpReplyWrapper(211, "End", Http::scNoContent
, 0);
804 HttpHeader
const &serverReplyHeader
= reply
->header
;
806 HttpHeaderPos pos
= HttpHeaderInitPos
;
807 bool hasEPRT
= false;
808 bool hasEPSV
= false;
809 int prependSpaces
= 1;
811 featReply
->header
.putStr(HDR_FTP_PRE
, "\"211-Features:\"");
812 const int scode
= serverReplyHeader
.getInt(HDR_FTP_STATUS
);
814 while (const HttpHeaderEntry
*e
= serverReplyHeader
.getEntry(&pos
)) {
815 if (e
->id
== HDR_FTP_PRE
) {
816 // assume RFC 2389 FEAT response format, quoted by Squid:
817 // <"> SP NAME [SP PARAMS] <">
818 // but accommodate MS servers sending four SPs before NAME
820 // command name ends with (SP parameter) or quote
821 static const CharacterSet
AfterFeatNameChars("AfterFeatName", " \"");
822 static const CharacterSet FeatNameChars
= AfterFeatNameChars
.complement("FeatName");
824 Parser::Tokenizer
tok(SBuf(e
->value
.termedBuf()));
825 if (!tok
.skip('"') || !tok
.skip(' '))
828 // optional spaces; remember their number to accomodate MS servers
829 prependSpaces
= 1 + tok
.skipAll(CharacterSet::SP
);
832 if (!tok
.prefix(cmd
, FeatNameChars
))
836 if (Ftp::SupportedCommand(cmd
)) {
837 featReply
->header
.addEntry(e
->clone());
840 if (cmd
== cmdEprt())
842 else if (cmd
== cmdEpsv())
846 } // else we got a FEAT error and will only report Squid-supported features
850 snprintf(buf
, sizeof(buf
), "\"%*s\"", prependSpaces
+ 4, "EPRT");
851 featReply
->header
.putStr(HDR_FTP_PRE
, buf
);
854 snprintf(buf
, sizeof(buf
), "\"%*s\"", prependSpaces
+ 4, "EPSV");
855 featReply
->header
.putStr(HDR_FTP_PRE
, buf
);
858 featReply
->header
.refreshMask();
860 writeForwardedReply(featReply
.getRaw());
864 Ftp::Server::handlePasvReply(const HttpReply
*reply
, StoreIOBuffer
)
866 ClientSocketContext::Pointer context
= getCurrentContext();
867 assert(context
!= NULL
);
869 if (context
->http
->request
->errType
!= ERR_NONE
) {
870 writeCustomReply(502, "Server does not support PASV", reply
);
874 const unsigned short localPort
= listenForDataConnection();
878 char addr
[MAX_IPSTRLEN
];
879 // remote server in interception setups and local address otherwise
880 const Ip::Address
&server
= transparent() ?
881 clientConnection
->local
: dataListenConn
->local
;
882 server
.toStr(addr
, MAX_IPSTRLEN
, AF_INET
);
883 addr
[MAX_IPSTRLEN
- 1] = '\0';
884 for (char *c
= addr
; *c
!= '\0'; ++c
) {
889 // In interception setups, we combine remote server address with a
890 // local port number and hope that traffic will be redirected to us.
891 // Do not use "227 =a,b,c,d,p1,p2" format or omit parens: some nf_ct_ftp
892 // versions block responses that use those alternative syntax rules!
895 mb
.Printf("227 Entering Passive Mode (%s,%i,%i).\r\n",
897 static_cast<int>(localPort
/ 256),
898 static_cast<int>(localPort
% 256));
899 debugs(9, 3, Raw("writing", mb
.buf
, mb
.size
));
904 Ftp::Server::handlePortReply(const HttpReply
*reply
, StoreIOBuffer
)
906 if (getCurrentContext()->http
->request
->errType
!= ERR_NONE
) {
907 writeCustomReply(502, "Server does not support PASV (converted from PORT)", reply
);
911 writeCustomReply(200, "PORT successfully converted to PASV.");
917 Ftp::Server::handleErrorReply(const HttpReply
*reply
, StoreIOBuffer
)
919 if (!pinning
.pinned
) // we failed to connect to server
921 // 421: we will close due to fssError
922 writeErrorReply(reply
, 421);
926 Ftp::Server::handleDataReply(const HttpReply
*reply
, StoreIOBuffer data
)
928 if (reply
!= NULL
&& reply
->sline
.status() != Http::scOkay
) {
929 writeForwardedReply(reply
);
930 if (Comm::IsConnOpen(dataConn
)) {
931 debugs(33, 3, "closing " << dataConn
<< " on KO reply");
932 closeDataConnection();
938 // We got STREAM_COMPLETE (or error) and closed the client data conn.
939 debugs(33, 3, "ignoring FTP srv data response after clt data closure");
943 if (!checkDataConnPost()) {
944 writeCustomReply(425, "Data connection is not established.");
945 closeDataConnection();
949 debugs(33, 7, data
.length
);
951 if (data
.length
<= 0) {
952 replyDataWritingCheckpoint(); // skip the actual write call
957 mb
.init(data
.length
+ 1, data
.length
+ 1);
958 mb
.append(data
.data
, data
.length
);
960 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
961 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteReplyData
);
962 Comm::Write(dataConn
, &mb
, call
);
964 getCurrentContext()->noteSentBodyBytes(data
.length
);
967 /// called when we are done writing a chunk of the response data
969 Ftp::Server::wroteReplyData(const CommIoCbParams
&io
)
971 if (io
.flag
== Comm::ERR_CLOSING
)
974 if (io
.flag
!= Comm::OK
) {
975 debugs(33, 3, "FTP reply data writing failed: " << xstrerr(io
.xerrno
));
976 closeDataConnection();
977 writeCustomReply(426, "Data connection error; transfer aborted");
981 assert(getCurrentContext()->http
);
982 getCurrentContext()->http
->out
.size
+= io
.size
;
983 replyDataWritingCheckpoint();
986 /// ClientStream checks after (actual or skipped) reply data writing
988 Ftp::Server::replyDataWritingCheckpoint()
990 switch (getCurrentContext()->socketState()) {
992 debugs(33, 3, "Keep going");
993 getCurrentContext()->pullData();
995 case STREAM_COMPLETE
:
996 debugs(33, 3, "FTP reply data transfer successfully complete");
997 writeCustomReply(226, "Transfer complete");
999 case STREAM_UNPLANNED_COMPLETE
:
1000 debugs(33, 3, "FTP reply data transfer failed: STREAM_UNPLANNED_COMPLETE");
1001 writeCustomReply(451, "Server error; transfer aborted");
1004 debugs(33, 3, "FTP reply data transfer failed: STREAM_FAILED");
1005 writeCustomReply(451, "Server error; transfer aborted");
1008 fatal("unreachable code");
1011 closeDataConnection();
1015 Ftp::Server::handleUploadReply(const HttpReply
*reply
, StoreIOBuffer
)
1017 writeForwardedReply(reply
);
1018 // note that the client data connection may already be closed by now
1022 Ftp::Server::writeForwardedReply(const HttpReply
*reply
)
1024 assert(reply
!= NULL
);
1025 const HttpHeader
&header
= reply
->header
;
1026 // adaptation and forwarding errors lack HDR_FTP_STATUS
1027 if (!header
.has(HDR_FTP_STATUS
)) {
1028 writeForwardedForeign(reply
); // will get to Ftp::Server::wroteReply
1032 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
1033 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteReply
);
1034 writeForwardedReplyAndCall(reply
, call
);
1038 Ftp::Server::handleEprtReply(const HttpReply
*reply
, StoreIOBuffer
)
1040 if (getCurrentContext()->http
->request
->errType
!= ERR_NONE
) {
1041 writeCustomReply(502, "Server does not support PASV (converted from EPRT)", reply
);
1045 writeCustomReply(200, "EPRT successfully converted to PASV.");
1047 // and wait for RETR
1051 Ftp::Server::handleEpsvReply(const HttpReply
*reply
, StoreIOBuffer
)
1053 if (getCurrentContext()->http
->request
->errType
!= ERR_NONE
) {
1054 writeCustomReply(502, "Cannot connect to server", reply
);
1058 const unsigned short localPort
= listenForDataConnection();
1062 // In interception setups, we use a local port number and hope that data
1063 // traffic will be redirected to us.
1066 mb
.Printf("229 Entering Extended Passive Mode (|||%u|)\r\n", localPort
);
1068 debugs(9, 3, Raw("writing", mb
.buf
, mb
.size
));
1072 /// writes FTP error response with given status and reply-derived error details
1074 Ftp::Server::writeErrorReply(const HttpReply
*reply
, const int scode
)
1076 const HttpRequest
*request
= getCurrentContext()->http
->request
;
1082 if (request
->errType
!= ERR_NONE
)
1083 mb
.Printf("%i-%s\r\n", scode
, errorPageName(request
->errType
));
1085 if (request
->errDetail
> 0) {
1086 // XXX: > 0 may not always mean that this is an errno
1087 mb
.Printf("%i-Error: (%d) %s\r\n", scode
,
1089 strerror(request
->errDetail
));
1093 // XXX: Remove hard coded names. Use an error page template instead.
1094 const Adaptation::History::Pointer ah
= request
->adaptHistory();
1095 if (ah
!= NULL
) { // XXX: add adapt::<all_h but use lastMeta here
1096 const String info
= ah
->allMeta
.getByName("X-Response-Info");
1097 const String desc
= ah
->allMeta
.getByName("X-Response-Desc");
1099 mb
.Printf("%i-Information: %s\r\n", scode
, info
.termedBuf());
1101 mb
.Printf("%i-Description: %s\r\n", scode
, desc
.termedBuf());
1105 assert(reply
!= NULL
);
1106 const char *reason
= reply
->header
.has(HDR_FTP_REASON
) ?
1107 reply
->header
.getStr(HDR_FTP_REASON
):
1108 reply
->sline
.reason();
1110 mb
.Printf("%i %s\r\n", scode
, reason
); // error terminating line
1112 // TODO: errorpage.cc should detect FTP client and use
1113 // configurable FTP-friendly error templates which we should
1114 // write to the client "as is" instead of hiding most of the info
1119 /// writes FTP response based on HTTP reply that is not an FTP-response wrapper
1120 /// for example, internally-generated Squid "errorpages" end up here (for now)
1122 Ftp::Server::writeForwardedForeign(const HttpReply
*reply
)
1124 changeState(fssConnected
, "foreign reply");
1125 closeDataConnection();
1126 // 451: We intend to keep the control connection open.
1127 writeErrorReply(reply
, 451);
1131 Ftp::Server::writeControlMsgAndCall(ClientSocketContext
*, HttpReply
*reply
, AsyncCall::Pointer
&call
)
1133 // the caller guarantees that we are dealing with the current context only
1134 // the caller should also make sure reply->header.has(HDR_FTP_STATUS)
1135 writeForwardedReplyAndCall(reply
, call
);
1139 Ftp::Server::writeForwardedReplyAndCall(const HttpReply
*reply
, AsyncCall::Pointer
&call
)
1141 assert(reply
!= NULL
);
1142 const HttpHeader
&header
= reply
->header
;
1144 // without status, the caller must use the writeForwardedForeign() path
1145 Must(header
.has(HDR_FTP_STATUS
));
1146 Must(header
.has(HDR_FTP_REASON
));
1147 const int scode
= header
.getInt(HDR_FTP_STATUS
);
1148 debugs(33, 7, "scode: " << scode
);
1150 // Status 125 or 150 implies upload or data request, but we still check
1151 // the state in case the server is buggy.
1152 if ((scode
== 125 || scode
== 150) &&
1153 (master
->serverState
== fssHandleUploadRequest
||
1154 master
->serverState
== fssHandleDataRequest
)) {
1155 if (checkDataConnPost()) {
1156 // If the data connection is ready, start reading data (here)
1157 // and forward the response to client (further below).
1158 debugs(33, 7, "data connection established, start data transfer");
1159 if (master
->serverState
== fssHandleUploadRequest
)
1160 maybeReadUploadData();
1162 // If we are waiting to accept the data connection, keep waiting.
1163 if (Comm::IsConnOpen(dataListenConn
)) {
1164 debugs(33, 7, "wait for the client to establish a data connection");
1165 onDataAcceptCall
= call
;
1166 // TODO: Add connect timeout for passive connections listener?
1167 // TODO: Remember server response so that we can forward it?
1169 // Either the connection was establised and closed after the
1170 // data was transferred OR we failed to establish an active
1171 // data connection and already sent the error to the client.
1172 // In either case, there is nothing more to do.
1173 debugs(33, 7, "done with data OR active connection failed");
1181 Ftp::PrintReply(mb
, reply
);
1183 debugs(9, 2, "FTP Client " << clientConnection
);
1184 debugs(9, 2, "FTP Client REPLY:\n---------\n" << mb
.buf
<<
1187 Comm::Write(clientConnection
, &mb
, call
);
1191 Ftp::PrintReply(MemBuf
&mb
, const HttpReply
*reply
, const char *const)
1193 const HttpHeader
&header
= reply
->header
;
1195 HttpHeaderPos pos
= HttpHeaderInitPos
;
1196 while (const HttpHeaderEntry
*e
= header
.getEntry(&pos
)) {
1197 if (e
->id
== HDR_FTP_PRE
) {
1199 if (httpHeaderParseQuotedString(e
->value
.rawBuf(), e
->value
.size(), &raw
))
1200 mb
.Printf("%s\r\n", raw
.termedBuf());
1204 if (header
.has(HDR_FTP_STATUS
)) {
1205 const char *reason
= header
.getStr(HDR_FTP_REASON
);
1206 mb
.Printf("%i %s\r\n", header
.getInt(HDR_FTP_STATUS
),
1207 (reason
? reason
: 0));
1212 Ftp::Server::wroteEarlyReply(const CommIoCbParams
&io
)
1214 if (io
.flag
== Comm::ERR_CLOSING
)
1217 if (io
.flag
!= Comm::OK
) {
1218 debugs(33, 3, "FTP reply writing failed: " << xstrerr(io
.xerrno
));
1223 ClientSocketContext::Pointer context
= getCurrentContext();
1224 if (context
!= NULL
&& context
->http
) {
1225 context
->http
->out
.size
+= io
.size
;
1226 context
->http
->out
.headers_sz
+= io
.size
;
1229 flags
.readMore
= true;
1234 Ftp::Server::wroteReply(const CommIoCbParams
&io
)
1236 if (io
.flag
== Comm::ERR_CLOSING
)
1239 if (io
.flag
!= Comm::OK
) {
1240 debugs(33, 3, "FTP reply writing failed: " << xstrerr(io
.xerrno
));
1245 ClientSocketContext::Pointer context
= getCurrentContext();
1246 assert(context
->http
);
1247 context
->http
->out
.size
+= io
.size
;
1248 context
->http
->out
.headers_sz
+= io
.size
;
1250 if (master
->serverState
== fssError
) {
1251 debugs(33, 5, "closing on FTP server error");
1256 const clientStream_status_t socketState
= context
->socketState();
1257 debugs(33, 5, "FTP client stream state " << socketState
);
1258 switch (socketState
) {
1259 case STREAM_UNPLANNED_COMPLETE
:
1265 case STREAM_COMPLETE
:
1266 flags
.readMore
= true;
1267 changeState(fssConnected
, "Ftp::Server::wroteReply");
1269 finishDechunkingRequest(false);
1270 context
->keepaliveNextRequest();
1276 Ftp::Server::handleRequest(HttpRequest
*request
)
1278 debugs(33, 9, request
);
1281 HttpHeader
&header
= request
->header
;
1282 Must(header
.has(HDR_FTP_COMMAND
));
1283 String
&cmd
= header
.findEntry(HDR_FTP_COMMAND
)->value
;
1284 Must(header
.has(HDR_FTP_ARGUMENTS
));
1285 String
¶ms
= header
.findEntry(HDR_FTP_ARGUMENTS
)->value
;
1287 if (do_debug(9, 2)) {
1291 packerToMemInit(&p
, &mb
);
1295 debugs(9, 2, "FTP Client " << clientConnection
);
1296 debugs(9, 2, "FTP Client REQUEST:\n---------\n" << mb
.buf
<<
1300 // TODO: When HttpHeader uses SBuf, change keys to SBuf
1301 typedef std::map
<const std::string
, RequestHandler
> RequestHandlers
;
1302 static RequestHandlers handlers
;
1303 if (!handlers
.size()) {
1304 handlers
["LIST"] = &Ftp::Server::handleDataRequest
;
1305 handlers
["NLST"] = &Ftp::Server::handleDataRequest
;
1306 handlers
["MLSD"] = &Ftp::Server::handleDataRequest
;
1307 handlers
["FEAT"] = &Ftp::Server::handleFeatRequest
;
1308 handlers
["PASV"] = &Ftp::Server::handlePasvRequest
;
1309 handlers
["PORT"] = &Ftp::Server::handlePortRequest
;
1310 handlers
["RETR"] = &Ftp::Server::handleDataRequest
;
1311 handlers
["EPRT"] = &Ftp::Server::handleEprtRequest
;
1312 handlers
["EPSV"] = &Ftp::Server::handleEpsvRequest
;
1313 handlers
["CWD"] = &Ftp::Server::handleCwdRequest
;
1314 handlers
["PASS"] = &Ftp::Server::handlePassRequest
;
1315 handlers
["CDUP"] = &Ftp::Server::handleCdupRequest
;
1318 RequestHandler handler
= NULL
;
1319 if (request
->method
== Http::METHOD_PUT
)
1320 handler
= &Ftp::Server::handleUploadRequest
;
1322 const RequestHandlers::const_iterator hi
= handlers
.find(cmd
.termedBuf());
1323 if (hi
!= handlers
.end())
1324 handler
= hi
->second
;
1328 debugs(9, 7, "forwarding " << cmd
<< " as is, no post-processing");
1332 return (this->*handler
)(cmd
, params
);
1335 /// Called to parse USER command, which is required to create an HTTP request
1336 /// wrapper. W/o request, the errors are handled by returning earlyError().
1337 ClientSocketContext
*
1338 Ftp::Server::handleUserRequest(const SBuf
&, SBuf
¶ms
)
1340 if (params
.isEmpty())
1341 return earlyError(eekMissingUsername
);
1343 // find the [end of] user name
1344 const SBuf::size_type eou
= params
.rfind('@');
1345 if (eou
== SBuf::npos
|| eou
+ 1 >= params
.length())
1346 return earlyError(eekMissingHost
);
1348 // Determine the intended destination.
1349 host
= params
.substr(eou
+ 1, params
.length());
1350 // If we can parse it as raw IPv6 address, then surround with "[]".
1351 // Otherwise (domain, IPv4, [bracketed] IPv6, garbage, etc), use as is.
1352 if (host
.find(':') != SBuf::npos
) {
1353 const Ip::Address
ipa(host
.c_str());
1354 if (!ipa
.isAnyAddr()) {
1355 char ipBuf
[MAX_IPSTRLEN
];
1356 ipa
.toHostStr(ipBuf
, MAX_IPSTRLEN
);
1361 // const SBuf login = params.substr(0, eou);
1362 params
.chop(0, eou
); // leave just the login part for the peer
1365 if (master
->clientReadGreeting
)
1368 master
->workingDir
.clear();
1371 if (!master
->clientReadGreeting
) {
1372 debugs(9, 3, "set URI to " << uri
);
1373 } else if (oldUri
.caseCmp(uri
) == 0) {
1374 debugs(9, 5, "kept URI as " << oldUri
);
1376 debugs(9, 3, "reset URI from " << oldUri
<< " to " << uri
);
1377 closeDataConnection();
1378 unpinConnection(true); // close control connection to peer
1379 resetLogin("URI reset");
1382 return NULL
; // no early errors
1386 Ftp::Server::handleFeatRequest(String
&, String
&)
1388 changeState(fssHandleFeat
, "handleFeatRequest");
1393 Ftp::Server::handlePasvRequest(String
&, String
¶ms
)
1396 setReply(500, "Bad PASV command");
1400 if (params
.size() > 0) {
1401 setReply(501, "Unexpected parameter");
1405 changeState(fssHandlePasv
, "handlePasvRequest");
1406 // no need to fake PASV request via setDataCommand() in true PASV case
1410 /// [Re]initializes dataConn for active data transfers. Does not connect.
1412 Ftp::Server::createDataConnection(Ip::Address cltAddr
)
1414 assert(clientConnection
!= NULL
);
1415 assert(!clientConnection
->remote
.isAnyAddr());
1417 if (cltAddr
!= clientConnection
->remote
) {
1418 debugs(33, 2, "rogue PORT " << cltAddr
<< " request? ctrl: " << clientConnection
->remote
);
1419 // Closing the control connection would not help with attacks because
1420 // the client is evidently able to connect to us. Besides, closing
1421 // makes retrials easier for the client and more damaging to us.
1422 setReply(501, "Prohibited parameter value");
1426 closeDataConnection();
1428 Comm::ConnectionPointer conn
= new Comm::Connection();
1429 conn
->flags
|= COMM_DOBIND
;
1431 // Use local IP address of the control connection as the source address
1432 // of the active data connection, or some clients will refuse to accept.
1433 conn
->setAddrs(clientConnection
->local
, cltAddr
);
1434 // RFC 959 requires active FTP connections to originate from port 20
1435 // but that would preclude us from supporting concurrent transfers! (XXX?)
1436 conn
->local
.port(0);
1438 debugs(9, 3, "will actively connect from " << conn
->local
<< " to " <<
1442 uploadAvailSize
= 0;
1447 Ftp::Server::handlePortRequest(String
&, String
¶ms
)
1449 // TODO: Should PORT errors trigger closeDataConnection() cleanup?
1452 setReply(500, "Rejecting PORT after EPSV ALL");
1456 if (!params
.size()) {
1457 setReply(501, "Missing parameter");
1461 Ip::Address cltAddr
;
1462 if (!Ftp::ParseIpPort(params
.termedBuf(), NULL
, cltAddr
)) {
1463 setReply(501, "Invalid parameter");
1467 if (!createDataConnection(cltAddr
))
1470 changeState(fssHandlePort
, "handlePortRequest");
1472 return true; // forward our fake PASV request
1476 Ftp::Server::handleDataRequest(String
&, String
&)
1478 if (!checkDataConnPre())
1481 changeState(fssHandleDataRequest
, "handleDataRequest");
1487 Ftp::Server::handleUploadRequest(String
&, String
&)
1489 if (!checkDataConnPre())
1492 if (Config
.accessList
.forceRequestBodyContinuation
) {
1493 ClientHttpRequest
*http
= getCurrentContext()->http
;
1494 HttpRequest
*request
= http
->request
;
1495 ACLFilledChecklist
bodyContinuationCheck(Config
.accessList
.forceRequestBodyContinuation
, request
, NULL
);
1496 if (bodyContinuationCheck
.fastCheck() == ACCESS_ALLOWED
) {
1497 request
->forcedBodyContinuation
= true;
1498 if (checkDataConnPost()) {
1499 // Write control Msg
1500 writeEarlyReply(150, "Data connection opened");
1501 maybeReadUploadData();
1503 // wait for acceptDataConnection but tell it to call wroteEarlyReply
1504 // after writing "150 Data connection opened"
1505 typedef CommCbMemFunT
<Server
, CommIoCbParams
> Dialer
;
1506 AsyncCall::Pointer call
= JobCallback(33, 5, Dialer
, this, Ftp::Server::wroteEarlyReply
);
1507 onDataAcceptCall
= call
;
1512 changeState(fssHandleUploadRequest
, "handleDataRequest");
1518 Ftp::Server::handleEprtRequest(String
&, String
¶ms
)
1520 debugs(9, 3, "Process an EPRT " << params
);
1523 setReply(500, "Rejecting EPRT after EPSV ALL");
1527 if (!params
.size()) {
1528 setReply(501, "Missing parameter");
1532 Ip::Address cltAddr
;
1533 if (!Ftp::ParseProtoIpPort(params
.termedBuf(), cltAddr
)) {
1534 setReply(501, "Invalid parameter");
1538 if (!createDataConnection(cltAddr
))
1541 changeState(fssHandleEprt
, "handleEprtRequest");
1543 return true; // forward our fake PASV request
1547 Ftp::Server::handleEpsvRequest(String
&, String
¶ms
)
1549 debugs(9, 3, "Process an EPSV command with params: " << params
);
1550 if (params
.size() <= 0) {
1551 // treat parameterless EPSV as "use the protocol of the ctrl conn"
1552 } else if (params
.caseCmp("ALL") == 0) {
1553 setReply(200, "EPSV ALL ok");
1556 } else if (params
.cmp("2") == 0) {
1557 if (!Ip::EnableIpv6
) {
1558 setReply(522, "Network protocol not supported, use (1)");
1561 } else if (params
.cmp("1") != 0) {
1562 setReply(501, "Unsupported EPSV parameter");
1566 changeState(fssHandleEpsv
, "handleEpsvRequest");
1568 return true; // forward our fake PASV request
1572 Ftp::Server::handleCwdRequest(String
&, String
&)
1574 changeState(fssHandleCwd
, "handleCwdRequest");
1579 Ftp::Server::handlePassRequest(String
&, String
&)
1581 changeState(fssHandlePass
, "handlePassRequest");
1586 Ftp::Server::handleCdupRequest(String
&, String
&)
1588 changeState(fssHandleCdup
, "handleCdupRequest");
1592 // Convert user PORT, EPRT, PASV, or EPSV data command to Squid PASV command.
1593 // Squid FTP client decides what data command to use with peers.
1595 Ftp::Server::setDataCommand()
1597 ClientHttpRequest
*const http
= getCurrentContext()->http
;
1598 assert(http
!= NULL
);
1599 HttpRequest
*const request
= http
->request
;
1600 assert(request
!= NULL
);
1601 HttpHeader
&header
= request
->header
;
1602 header
.delById(HDR_FTP_COMMAND
);
1603 header
.putStr(HDR_FTP_COMMAND
, "PASV");
1604 header
.delById(HDR_FTP_ARGUMENTS
);
1605 header
.putStr(HDR_FTP_ARGUMENTS
, "");
1606 debugs(9, 5, "client data command converted to fake PASV");
1609 /// check that client data connection is ready for future I/O or at least
1610 /// has a chance of becoming ready soon.
1612 Ftp::Server::checkDataConnPre()
1614 if (Comm::IsConnOpen(dataConn
))
1617 if (Comm::IsConnOpen(dataListenConn
)) {
1618 // We are still waiting for a client to connect to us after PASV.
1619 // Perhaps client's data conn handshake has not reached us yet.
1620 // After we talk to the server, checkDataConnPost() will recheck.
1621 debugs(33, 3, "expecting clt data conn " << dataListenConn
);
1625 if (!dataConn
|| dataConn
->remote
.isAnyAddr()) {
1626 debugs(33, 5, "missing " << dataConn
);
1627 // TODO: use client address and default port instead.
1628 setReply(425, "Use PORT or PASV first");
1632 // active transfer: open a data connection from Squid to client
1633 typedef CommCbMemFunT
<Server
, CommConnectCbParams
> Dialer
;
1634 connector
= JobCallback(17, 3, Dialer
, this, Ftp::Server::connectedForData
);
1635 Comm::ConnOpener
*cs
= new Comm::ConnOpener(dataConn
, connector
,
1636 Config
.Timeout
.connect
);
1637 AsyncJob::Start(cs
);
1638 return false; // ConnStateData::processFtpRequest waits handleConnectDone
1641 /// Check that client data connection is ready for immediate I/O.
1643 Ftp::Server::checkDataConnPost() const
1645 if (!Comm::IsConnOpen(dataConn
)) {
1646 debugs(33, 3, "missing client data conn: " << dataConn
);
1652 /// Done establishing a data connection to the user.
1654 Ftp::Server::connectedForData(const CommConnectCbParams
¶ms
)
1658 if (params
.flag
!= Comm::OK
) {
1659 /* it might have been a timeout with a partially open link */
1660 if (params
.conn
!= NULL
)
1661 params
.conn
->close();
1662 setReply(425, "Cannot open data connection.");
1663 ClientSocketContext::Pointer context
= getCurrentContext();
1664 Must(context
->http
);
1665 Must(context
->http
->storeEntry() != NULL
);
1667 Must(dataConn
== params
.conn
);
1668 Must(Comm::IsConnOpen(params
.conn
));
1669 fd_note(params
.conn
->fd
, "active client ftp data");
1676 Ftp::Server::setReply(const int code
, const char *msg
)
1678 ClientSocketContext::Pointer context
= getCurrentContext();
1679 ClientHttpRequest
*const http
= context
->http
;
1680 assert(http
!= NULL
);
1681 assert(http
->storeEntry() == NULL
);
1683 HttpReply
*const reply
= Ftp::HttpReplyWrapper(code
, msg
, Http::scNoContent
, 0);
1685 setLogUri(http
, urlCanonicalClean(http
->request
));
1687 clientStreamNode
*const node
= context
->getClientReplyContext();
1688 clientReplyContext
*const repContext
=
1689 dynamic_cast<clientReplyContext
*>(node
->data
.getRaw());
1690 assert(repContext
!= NULL
);
1692 RequestFlags reqFlags
;
1693 reqFlags
.cachable
= false; // force releaseRequest() in storeCreateEntry()
1694 reqFlags
.noCache
= true;
1695 repContext
->createStoreEntry(http
->request
->method
, reqFlags
);
1696 http
->storeEntry()->replaceHttpReply(reply
);
1699 /// Whether Squid FTP Relay supports a named feature (e.g., a command).
1701 Ftp::SupportedCommand(const SBuf
&name
)
1703 static std::set
<SBuf
> BlackList
;
1704 if (BlackList
.empty()) {
1705 /* Add FTP commands that Squid cannot relay correctly. */
1707 // We probably do not support AUTH TLS.* and AUTH SSL,
1708 // but let's disclaim all AUTH support to KISS, for now.
1709 BlackList
.insert(cmdAuth());
1712 // we claim support for all commands that we do not know about
1713 return BlackList
.find(name
) == BlackList
.end();