10#if defined(ESP32) && defined(FS_H)
14using SDClass = fs::FS;
23#define FTP_DATA_PORT 50009
26#ifndef FTP_DATA_TIMEOUT
27#define FTP_DATA_TIMEOUT 5000
30#ifndef FTP_SERVER_MAX_SESSIONS
31#define FTP_SERVER_MAX_SESSIONS 4
34#ifndef FTP_SERVER_BUFFER_SIZE
35#define FTP_SERVER_BUFFER_SIZE 512
38#ifndef FTP_SERVER_MAX_LINE
39#define FTP_SERVER_MAX_LINE 512
52#if defined(FILE_READ) && defined(FILE_WRITE)
54#define FTP_FILE_APPEND FILE_APPEND
56#define FTP_FILE_APPEND FILE_WRITE
82template <
typename TServer,
typename TStorage>
86 using ClientType =
decltype(std::declval<TServer&>().accept());
91 : server(port), dataPort(dataPort), storage(storage) {
92 commands = {{
"USER", &FTPServer::onUSER,
false},
93 {
"PASS", &FTPServer::onPASS,
false},
94 {
"LIST", &FTPServer::onLIST},
95 {
"NLST", &FTPServer::onNLST},
96 {
"PWD", &FTPServer::onPWD},
97 {
"CWD", &FTPServer::onCWD},
98 {
"CD", &FTPServer::onCWD},
99 {
"CDUP", &FTPServer::onCDUP},
100 {
"SYST", &FTPServer::onSYST},
101 {
"TYPE", &FTPServer::onTYPE},
102 {
"BIN", &FTPServer::onBIN},
103 {
"ASC", &FTPServer::onASC},
104 {
"NOOP", &FTPServer::onNOOP},
105 {
"PASV", &FTPServer::onPASV},
106 {
"EPSV", &FTPServer::onEPSV},
107 {
"PORT", &FTPServer::onPORT},
108 {
"HELP", &FTPServer::onHELP,
false},
109 {
"RETR", &FTPServer::onRETR},
110 {
"STOR", &FTPServer::onSTOR},
111 {
"APPE", &FTPServer::onAPPE},
112 {
"ABOR", &FTPServer::onABOR},
113 {
"DELE", &FTPServer::onDELE},
114 {
"MKD", &FTPServer::onMKD},
115 {
"RMD", &FTPServer::onRMD},
116 {
"RNFR", &FTPServer::onRNFR},
117 {
"RNTO", &FTPServer::onRNTO},
118 {
"SIZE", &FTPServer::onSIZE},
119 {
"FEAT", &FTPServer::onFEAT,
false},
120 {
"OPTS", &FTPServer::onOPTS,
false},
121 {
"QUIT", &FTPServer::onQUIT,
false}};
126 for (
auto&
s : sessions) {
127 if (
s.active) closeSession(
s);
129 s.dataServer =
nullptr;
134 FTPServer& operator=(
const FTPServer&) =
delete;
139 for (
auto&
entry : users) {
141 entry.password = password;
145 users.push_back({
user, password});
162 Serial.println(
"Warning: No FTP users defined. Server is open to all.");
170 for (
auto&
s : sessions) {
178 for (
auto&
s : sessions) {
188 bool needsAuth =
true) {
189 for (
auto&
entry : commands) {
191 entry.handler = handler;
192 entry.builtin =
nullptr;
197 entry.handler = handler;
198 commands.push_back(
entry);
202 enum class DataMode { None, Passive, Active };
203 enum class Transfer { None, Retr, Stor, List };
204 enum class OpenMode { Read, Write, Append };
214 template <
typename S>
216 ->
decltype(fs->open(
path,
"r")) {
217 return fs->open(
path, mode == OpenMode::Read ?
"r"
218 : mode == OpenMode::Write ?
"w"
225#ifdef FTP_FILE_APPEND
227 template <
typename S>
233 case OpenMode::Append:
237 if (fs->exists(
path)) fs->remove(
path);
245 decltype(
openIn(std::declval<TStorage*>(),
"", OpenMode::Read, 0));
253 bool lineReady =
false;
254 bool isLoggedIn =
false;
258 DataMode dataMode = DataMode::None;
262 bool dataServerStarted =
false;
264 Transfer transfer = Transfer::None;
265 bool waitingForData =
false;
266 DataMode transferMode = DataMode::None;
267 const char* transferMsg =
"";
268 unsigned long lastActivity = 0;
271 bool listDetails =
false;
272 bool listSingle =
false;
274 size_t bufferLen = 0;
275 size_t bufferPos = 0;
281 CommandEntry(
const char* name, Handler builtin,
bool needsAuth =
true)
282 : name(name), builtin(builtin), needsAuth(needsAuth) {}
294 std::vector<CommandEntry> commands;
299 std::vector<User> users;
301 bool hasPassiveIP =
false;
304 bool hasUsers() {
return !users.empty(); }
313 for (
auto&
entry : users) {
314 if (
entry.name == name &&
entry.password ==
pwd)
return true;
322 if (
s.dataServer ==
nullptr)
s.dataServer =
new TServer(dataPort + index);
323 return *
s.dataServer;
328 auto client = server.accept();
330 for (
auto&
s : sessions) {
333 reply(
s,
"220 Welcome to TinyFTP");
338 "421 Too many connections, try again later");
348 s.isLoggedIn = !hasUsers();
352 s.dataMode = DataMode::None;
353 s.transfer = Transfer::None;
356 void closeSession(Session&
s) {
360 s.isLoggedIn =
false;
362 s.dataMode = DataMode::None;
370 if (
s.lineReady && (
s.transfer == Transfer::None || isAbort(
s.line))) {
380 if (
s.transfer == Transfer::None && !
s.lineReady &&
381 s.control.available() == 0 && !
s.control.
connected()) {
388 while (
s.control.available() > 0) {
396 if (
c >= 0x80)
continue;
400 if (
s.line.length() > 0 && !
s.control.
connected())
s.lineReady =
true;
403 static bool isAbort(
String line) {
405 return line.equalsIgnoreCase(
"ABOR");
410 int end = cmd.indexOf(
' ');
411 String verb = end < 0 ? cmd : cmd.substring(0, end);
413 if (!
verb.equalsIgnoreCase(
"RNTO"))
s.renameFrom =
"";
414 for (
auto&
entry : commands) {
416 if (
entry.needsAuth && !
s.isLoggedIn) {
417 reply(
s,
"530 Not logged in");
420 if (
entry.builtin !=
nullptr)
return (this->*
entry.builtin)(
s, cmd);
421 return entry.handler(
s.control, cmd);
424 return onUnknown(
s, cmd);
429 int start = cmd.indexOf(
' ');
430 if (
start < 0)
return "";
440 std::vector<String>
parts;
444 if (end < 0) end =
path.length();
448 }
else if (
part.length() > 0 &&
part !=
".") {
453 if (
parts.empty())
return "/";
462 int pos =
result.lastIndexOf(
'/');
467 template <
typename C>
472 template <
typename C>
477 FileType openFile(
const char* path, OpenMode mode) {
478 return openIn(storage, path, mode, 0);
482 template <
typename S>
485 return fs->rename(
from,
to);
487 template <
typename S>
488 static bool renameIn(
S*,
const char*,
const char*,
long) {
491 template <
typename S>
492 static auto canRename(S* fs,
int) ->
decltype(fs->rename(
"",
""), bool()) {
495 template <
typename S>
496 static bool canRename(S*,
long) {
502 auto file = openFile(
path.c_str(), OpenMode::Read);
503 bool result = file && file.isDirectory();
504 if (file) file.close();
512 if (!
s.dataServerStarted) {
514 s.dataServerStarted =
true;
522 if (
s.dataMode == DataMode::None) {
523 reply(
s,
"425 Use PORT or PASV first");
526 s.transferMode =
s.dataMode;
527 s.dataMode = DataMode::None;
528 s.transfer = transfer;
530 s.waitingForData =
true;
535 if (
s.transferMode == DataMode::Active) {
536 if (!
s.data.connect(
s.activeIP,
s.activePort)) {
537 reply(
s,
"425 Can't open data connection");
546 void dataConnected(Session&
s) {
547 s.waitingForData =
false;
554 if (
s.waitingForData) {
558 }
else if (
millis() -
s.lastActivity >= dataTimeout) {
559 reply(
s,
"425 Can't open data connection");
564 switch (
s.transfer) {
579 void stepRetr(Session&
s) {
580 if (
s.bufferPos >=
s.bufferLen) {
581 int len =
s.file.available() ?
s.file.
read(
s.buffer,
sizeof(
s.buffer))
591 s.data.
write(s.buffer + s.bufferPos, s.bufferLen - s.bufferPos);
592 s.bufferPos += written;
594 s.lastActivity = millis();
595 }
else if (!s.data.connected() ||
596 millis() - s.lastActivity >= dataTimeout) {
597 endTransfer(s,
"426 Connection closed; transfer aborted");
601 void stepStor(Session& s) {
602 int len = s.data.available();
605 len =
static_cast<Client&
>(s.data).read(
606 s.buffer, min((
size_t)len,
sizeof(s.buffer)));
607 if (len > 0) s.file.
write(s.buffer, len);
608 s.lastActivity = millis();
609 }
else if (!s.data.connected() ||
610 millis() - s.lastActivity >= dataTimeout) {
618 printListEntry(
s.data,
s.file,
s.listDetails);
622 auto entry =
s.file.openNextFile();
627 printListEntry(
s.data,
entry,
s.listDetails);
645 if (
s.file)
s.file.close();
647 s.transfer = Transfer::None;
648 s.waitingForData =
false;
651 template <
typename F>
654 data.print(
entry.isDirectory() ?
"drwxr-xr-x" :
"-rw-r--r--");
655 data.print(
" 1 owner group ");
657 data.print(
" Jan 1 00:00 ");
663 bool checkStorage(Session& s) {
664 if (!storage)
reply(s,
"550 Storage not available");
665 return storage !=
nullptr;
668 bool list(Session& s,
const String& cmd,
bool details) {
669 if (!checkStorage(s))
return true;
671 if (arg.startsWith(
"-")) arg =
"";
673 auto dir = openFile(path.c_str(), OpenMode::Read);
675 reply(s,
"550 No such file or directory");
678 s.listDetails = details;
679 s.listSingle = !dir.isDirectory();
680 s.file = std::move(dir);
682 "150 Here comes the directory listing")) {
690 if (!checkStorage(
s))
return true;
692 auto file = openFile(
path.c_str(), mode);
694 reply(
s,
"550 Cannot open file for writing");
697 s.file = std::move(file);
698 if (!
beginTransfer(
s, Transfer::Stor,
"150 Ready to receive data")) {
705 bool onUSER(Session&
s,
const String& cmd) {
708 s.isLoggedIn = !hasUsers();
709 reply(
s,
"331 Username OK, enter password");
712 bool onPASS(Session& s,
const String& cmd) {
713 if (hasUsers() && s.userName.length() == 0) {
714 reply(s,
"503 Login with USER first");
718 if (!hasUsers() || isValidLogin(s.userName, pwd)) {
719 reply(s,
"230 User logged in");
723 reply(s,
"530 Login incorrect");
724 s.isLoggedIn =
false;
728 bool onLIST(Session& s,
const String& cmd) {
return list(s, cmd,
true); }
729 bool onNLST(Session& s,
const String& cmd) {
return list(s, cmd,
false); }
730 bool onCWD(Session& s,
const String& cmd) {
731 if (!checkStorage(s))
return true;
733 auto dir = openFile(path.c_str(), OpenMode::Read);
734 if (dir && dir.isDirectory()) {
736 reply(s,
"250 Directory changed to " + path);
738 reply(s,
"550 Not a directory");
740 if (dir) dir.close();
743 bool onCDUP(Session& s,
const String& ) {
return onCWD(s,
"CWD .."); }
744 bool onPWD(Session& s,
const String& ) {
745 reply(s,
"257 \"" + s.currentDir +
"\" is current directory");
748 bool onSYST(Session& s,
const String& ) {
749 reply(s,
"215 UNIX Type: L8");
752 bool onTYPE(Session& s,
const String& cmd) {
756 bool onBIN(Session& s,
const String& ) {
757 reply(s,
"200 Type set to I");
760 bool onASC(Session& s,
const String& ) {
761 reply(s,
"200 Type set to A");
764 bool onNOOP(Session& s,
const String& ) {
765 reply(s,
"200 NOOP ok");
768 bool onPASV(Session& s,
const String& ) {
770 IPAddress ip = hasPassiveIP ? passiveIP :
localIPOf(s.control, 0);
771 uint16_t port = dataPort + s.index;
772 s.dataMode = DataMode::Passive;
774 snprintf(msg,
sizeof(msg),
775 "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d)", ip[0], ip[1],
776 ip[2], ip[3], port >> 8, port & 0xFF);
780 bool onEPSV(Session& s,
const String& ) {
782 s.dataMode = DataMode::Passive;
784 snprintf(msg,
sizeof(msg),
"229 Entering Extended Passive Mode (|||%d|)",
789 bool onPORT(Session& s,
const String& cmd) {
792 if (sscanf(arg.c_str(),
"%d,%d,%d,%d,%d,%d", &v[0], &v[1], &v[2], &v[3],
793 &v[4], &v[5]) != 6) {
794 reply(s,
"501 Syntax error in parameters");
797 for (
int j = 0; j < 6; j++) {
798 if (v[j] < 0 || v[j] > 255) {
799 reply(s,
"501 Syntax error in parameters");
803 s.activeIP = IPAddress(v[0], v[1], v[2], v[3]);
804 s.activePort = (v[4] << 8) | v[5];
805 s.dataMode = DataMode::Active;
806 reply(s,
"200 PORT command successful");
809 bool onHELP(Session& s,
const String& ) {
810 reply(s,
"214-The following commands are recognized:");
812 for (
auto& entry : commands) {
817 reply(s,
"214 Help OK.");
820 bool onRETR(Session& s,
const String& cmd) {
821 if (!checkStorage(s))
return true;
823 auto file = openFile(path.c_str(), OpenMode::Read);
824 if (!file || file.isDirectory()) {
825 reply(s,
"550 File not found");
826 if (file) file.close();
829 s.file = std::move(file);
831 "150 Opening data connection for file transfer")) {
836 bool onSTOR(Session& s,
const String& cmd) {
837 return store(s, cmd, OpenMode::Write);
839 bool onAPPE(Session& s,
const String& cmd) {
840 return store(s, cmd, OpenMode::Append);
842 bool onABOR(Session& s,
const String& ) {
843 if (s.transfer != Transfer::None) {
845 reply(s,
"426 Transfer aborted");
846 reply(s,
"226 Abort successful");
848 reply(s,
"225 No transfer to abort");
852 bool onDELE(Session& s,
const String& cmd) {
853 if (!checkStorage(s))
return true;
855 if (!storage->exists(path.c_str()) ||
isDirectory(path)) {
856 reply(s,
"550 File not found");
857 }
else if (storage->remove(path.c_str())) {
858 reply(s,
"250 File deleted");
860 reply(s,
"550 Delete failed");
864 bool onMKD(Session& s,
const String& cmd) {
865 if (!checkStorage(s))
return true;
868 if (arg.length() == 0) {
869 reply(s,
"501 Missing directory name");
870 }
else if (storage->exists(path.c_str())) {
871 reply(s,
"550 Already exists");
872 }
else if (storage->mkdir(path.c_str())) {
873 reply(s,
"257 \"" + path +
"\" created");
875 reply(s,
"550 Create directory failed");
879 bool onRMD(Session& s,
const String& cmd) {
880 if (!checkStorage(s))
return true;
883 reply(s,
"550 Not a directory");
884 }
else if (storage->rmdir(path.c_str())) {
885 reply(s,
"250 Directory removed");
887 for (
auto& other : sessions) {
888 if (other.currentDir == path ||
889 other.currentDir.startsWith(path +
"/")) {
890 other.currentDir =
"/";
894 reply(s,
"550 Remove directory failed");
898 bool onRNFR(Session& s,
const String& cmd) {
899 if (!checkStorage(s))
return true;
900 if (!canRename(storage, 0)) {
901 reply(s,
"502 Rename not supported by storage");
905 if (path ==
"/" || !storage->exists(path.c_str())) {
906 reply(s,
"550 File not found");
909 reply(s,
"350 Ready for destination name");
913 bool onRNTO(Session& s,
const String& cmd) {
914 if (s.renameFrom.length() == 0) {
915 reply(s,
"503 Bad sequence of commands");
918 String from = s.renameFrom;
921 if (storage->exists(path.c_str())) {
922 reply(s,
"553 Destination already exists");
923 }
else if (
renameIn(storage, from.c_str(), path.c_str(), 0)) {
924 reply(s,
"250 Rename successful");
926 reply(s,
"553 Rename failed");
930 bool onSIZE(Session& s,
const String& cmd) {
931 if (!checkStorage(s))
return true;
933 auto file = openFile(path.c_str(), OpenMode::Read);
934 if (!file || file.isDirectory()) {
935 reply(s,
"550 File not found");
937 reply(s,
"213 " + String((
unsigned long)file.size()));
939 if (file) file.close();
942 bool onFEAT(Session& s,
const String& ) {
943 reply(s,
"211-Features:");
951 bool onOPTS(Session& s,
const String& cmd) {
953 if (arg.equalsIgnoreCase(
"UTF8 ON") || arg.equalsIgnoreCase(
"UTF8")) {
954 reply(s,
"200 UTF8 mode enabled");
956 reply(s,
"501 Option not supported");
960 bool onQUIT(Session& s,
const String& ) {
961 reply(s,
"221 Goodbye");
962 s.isLoggedIn =
false;
965 bool onUnknown(Session& s,
const String& ) {
966 reply(s,
"502 Command not implemented");
Client * read(const char *file_name)
Starts the download (if necessary): returns nullptr if it failed.
Definition FTPBasicAPI.h:173
Client * write(const char *file_name, FileMode mode)
Starts the upload (if necessary): returns nullptr if it failed.
Definition FTPBasicAPI.h:187
Simple, extensible FTP server for Arduino using a templated server and storage backend.
Definition FTPServer.h:83
static String baseName(const char *name)
Provides the file name without the directory.
Definition FTPServer.h:460
void closeTransfer(Session &s)
Closes the data connection and the file.
Definition FTPServer.h:640
void addUser(const char *user, const char *password)
Definition FTPServer.h:138
void startDataServer(Session &s)
Definition FTPServer.h:510
decltype(std::declval< TServer & >().accept()) ClientType
Client type returned by the server.
Definition FTPServer.h:86
String resolvePath(Session &s, const String &arg)
Definition FTPServer.h:438
void stepTransfer(Session &s)
Processes one step of the running transfer.
Definition FTPServer.h:553
void step(Session &s)
Processes one step of a connection.
Definition FTPServer.h:366
bool isDirectory(const String &path)
Checks if the path is an existing directory.
Definition FTPServer.h:501
void setDataTimeout(uint32_t timeoutMs)
Defines the timeout in ms for opening and idling on data connections.
Definition FTPServer.h:156
bool processCommand(Session &s, const String &cmd)
Dispatches a command line: returns false to disconnect.
Definition FTPServer.h:409
int connectionCount()
Number of connected FTP clients.
Definition FTPServer.h:176
void startSession(Session &s, ClientType &client)
Resets the per connection state.
Definition FTPServer.h:343
void acceptClient()
Accepts a new client connection.
Definition FTPServer.h:327
decltype(openIn(std::declval< TStorage * >(), "", OpenMode::Read, 0)) FileType
File type of the storage.
Definition FTPServer.h:245
void begin()
Starts the FTP server.
Definition FTPServer.h:159
bool beginTransfer(Session &s, Transfer transfer, const char *msg)
Definition FTPServer.h:521
static auto openIn(S *fs, const char *path, OpenMode mode, int) -> decltype(fs->open(path, "r"))
Opens a file with a storage which supports mode strings (e.g. fs::FS)
Definition FTPServer.h:215
TServer & dataServer(int index)
Provides the passive data server of the connection.
Definition FTPServer.h:320
static auto renameIn(S *fs, const char *from, const char *to, int) -> decltype(fs->rename(from, to), bool())
Renames a file if the storage supports it.
Definition FTPServer.h:483
void doLoop()
Definition FTPServer.h:168
bool store(Session &s, const String &cmd, OpenMode mode)
Uploads a file (STOR or APPE)
Definition FTPServer.h:689
void stepList(Session &s)
Sends one entry of the directory listing.
Definition FTPServer.h:616
FTPServer(uint16_t port=FTP_PORT, TStorage *storage=nullptr, uint16_t dataPort=FTP_DATA_PORT)
Constructor: initializes server and storage backend.
Definition FTPServer.h:89
static auto localIPOf(C &client, int) -> decltype(IPAddress(client.localIP()))
Local IP of the control connection if the client type supports it.
Definition FTPServer.h:468
void setPassiveIP(IPAddress ip)
Definition FTPServer.h:150
void readLine(Session &s)
Collects the characters of the next command line.
Definition FTPServer.h:387
static String argument(const String &cmd)
Provides the parameter of a command line.
Definition FTPServer.h:428
void endTransfer(Session &s, const char *msg)
Ends the transfer and reports the result.
Definition FTPServer.h:632
void reply(Session &s, const String &msg)
Definition FTPServer.h:308
void addCommand(const char *name, std::function< bool(Client &, const String &)> handler, bool needsAuth=true)
Definition FTPServer.h:186
static auto openIn(S *fs, const char *path, OpenMode mode, long) -> decltype(fs->open(path, FILE_READ))
Opens a file with the SD API modes (FILE_READ, FILE_WRITE...)
Definition FTPServer.h:228
FTPSession An FTPBasicAPI which owns its command and data connections.
Definition FTPSession.h:17
bool connected()
Returns true if logged in and the command connection is still alive.
Definition FTPSession.h:43
bool begin(IPAddress &address, int port, const char *username, const char *password)
Opens the command connection and logs in.
Definition FTPSession.h:27
FTP client and server functionality.
Definition FTPBasicAPI.h:7
Definition FTPServer.h:280
State of a client connection.
Definition FTPServer.h:248
Definition FTPServer.h:289