Arduino TinyFTP
Loading...
Searching...
No Matches
FTPServer.h
1#pragma once
2#include <Arduino.h>
3#include <Client.h>
4#include <IPAddress.h>
5
6#include <functional>
7#include <utility>
8#include <vector>
9
10#if defined(ESP32) && defined(FS_H)
11// on the ESP32 all file systems (SD, LittleFS, SPIFFS...) are a fs::FS: we do
12// not include FS.h ourself, so that its FILE_READ/FILE_WRITE do not conflict
13// with other file systems (e.g. TinyFATFS)
14using SDClass = fs::FS;
15#endif
16
17// Default port for FTP
18#ifndef FTP_PORT
19#define FTP_PORT 21
20#endif
21// Default port used for passive data connections
22#ifndef FTP_DATA_PORT
23#define FTP_DATA_PORT 50009
24#endif
25// Default timeout in ms for establishing and idling on data connections
26#ifndef FTP_DATA_TIMEOUT
27#define FTP_DATA_TIMEOUT 5000
28#endif
29// Max number of FTP clients which can be connected at the same time
30#ifndef FTP_SERVER_MAX_SESSIONS
31#define FTP_SERVER_MAX_SESSIONS 4
32#endif
33// Size of the transfer buffer of each connection
34#ifndef FTP_SERVER_BUFFER_SIZE
35#define FTP_SERVER_BUFFER_SIZE 512
36#endif
37// Max length of a command line
38#ifndef FTP_SERVER_MAX_LINE
39#define FTP_SERVER_MAX_LINE 512
40#endif
41
42// File modes of storages with the SD API (e.g. SD.h, TinyFATFS): their header
43// must be included before FTPServer.h.
44//
45// FTP_FILE_APPEND is only defined if FILE_READ and FILE_WRITE are available.
46// This is not always the case: e.g. a sketch which only uses CallbackFS or
47// LittleFS (with mode strings) does not include any header which defines
48// them. We can't provide default values, because the modes are platform
49// specific (e.g. uint8_t flags for SD and TinyFATFS, "r"/"w" strings for the
50// ESP32 FS.h). FTP_FILE_APPEND is a private name, so that it does not conflict
51// with a FILE_APPEND which is defined by a header that is included later.
52#if defined(FILE_READ) && defined(FILE_WRITE)
53#ifdef FILE_APPEND
54#define FTP_FILE_APPEND FILE_APPEND
55#else
56#define FTP_FILE_APPEND FILE_WRITE // FILE_WRITE appends with the SD library
57#endif
58#endif
59
60namespace tinyftp {
61
82template <typename TServer, typename TStorage>
83class FTPServer {
84 public:
86 using ClientType = decltype(std::declval<TServer&>().accept());
87
89 FTPServer(uint16_t port = FTP_PORT, TStorage* storage = nullptr,
90 uint16_t dataPort = FTP_DATA_PORT)
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}};
122 for (int j = 0; j < FTP_SERVER_MAX_SESSIONS; j++) sessions[j].index = j;
123 }
124
125 ~FTPServer() {
126 for (auto& s : sessions) {
127 if (s.active) closeSession(s);
128 delete s.dataServer;
129 s.dataServer = nullptr;
130 }
131 }
132
133 FTPServer(const FTPServer&) = delete;
134 FTPServer& operator=(const FTPServer&) = delete;
135
138 void addUser(const char* user, const char* password) {
139 for (auto& entry : users) {
140 if (entry.name == user) {
141 entry.password = password;
142 return;
143 }
144 }
145 users.push_back({user, password});
146 }
147
151 passiveIP = ip;
152 hasPassiveIP = true;
153 }
154
157
159 void begin() {
160 server.begin();
161 if (!hasUsers()) {
162 Serial.println("Warning: No FTP users defined. Server is open to all.");
163 }
164 }
165
168 void doLoop() {
169 acceptClient();
170 for (auto& s : sessions) {
171 if (s.active) step(s);
172 }
173 }
174
177 int result = 0;
178 for (auto& s : sessions) {
179 if (s.active) result++;
180 }
181 return result;
182 }
183
186 void addCommand(const char* name,
187 std::function<bool(Client&, const String&)> handler,
188 bool needsAuth = true) {
189 for (auto& entry : commands) {
190 if (strcasecmp(entry.name, name) == 0) {
191 entry.handler = handler;
192 entry.builtin = nullptr;
193 return;
194 }
195 }
196 CommandEntry entry{name, nullptr, needsAuth};
197 entry.handler = handler;
198 commands.push_back(entry);
199 }
200
201 protected:
202 enum class DataMode { None, Passive, Active };
203 enum class Transfer { None, Retr, Stor, List };
204 enum class OpenMode { Read, Write, Append };
205
206 // The storage is opened with one of the following openIn() overloads, which
207 // are selected with SFINAE: the 0 argument prefers the int overload (mode
208 // strings) if the storage supports open(path, "r"); otherwise the long
209 // overload (SD API modes) is used. If neither matches, the compiler reports
210 // that there is no matching openIn(): then include the header of your
211 // storage (e.g. SD.h) before FTPServer.h.
212
214 template <typename S>
215 static auto openIn(S* fs, const char* path, OpenMode mode, int)
216 -> decltype(fs->open(path, "r")) {
217 return fs->open(path, mode == OpenMode::Read ? "r"
218 : mode == OpenMode::Write ? "w"
219 : "a");
220 }
221 // Only available with the SD API modes: we can't drop the #ifdef, because
222 // FILE_READ does not depend on the template parameter, so the compiler
223 // checks it when it reads the template, even if this overload is never
224 // used. Without the SD API modes the sketch would not compile.
225#ifdef FTP_FILE_APPEND
227 template <typename S>
228 static auto openIn(S* fs, const char* path, OpenMode mode, long)
229 -> decltype(fs->open(path, FILE_READ)) {
230 switch (mode) {
231 case OpenMode::Read:
232 return fs->open(path, FILE_READ);
233 case OpenMode::Append:
234 return fs->open(path, FTP_FILE_APPEND);
235 default:
236 // FILE_WRITE might append: make sure that we replace the file
237 if (fs->exists(path)) fs->remove(path);
238 return fs->open(path, FILE_WRITE);
239 }
240 }
241#endif
242
244 using FileType =
245 decltype(openIn(std::declval<TStorage*>(), "", OpenMode::Read, 0));
246
248 struct Session {
249 int index = 0;
250 bool active = false;
251 ClientType control;
252 String line; // command line which is being received
253 bool lineReady = false;
254 bool isLoggedIn = false;
255 String userName; // name provided by USER
256 String currentDir = "/";
257 String renameFrom;
258 DataMode dataMode = DataMode::None;
259 IPAddress activeIP;
260 uint16_t activePort = 0;
261 TServer* dataServer = nullptr; // passive data port of this connection
262 bool dataServerStarted = false;
263 // running transfer
264 Transfer transfer = Transfer::None;
265 bool waitingForData = false; // data connection not open yet
266 DataMode transferMode = DataMode::None;
267 const char* transferMsg = ""; // 150 reply when the data connection opens
268 unsigned long lastActivity = 0;
269 ClientType data;
270 FileType file;
271 bool listDetails = false;
272 bool listSingle = false; // list a single file instead of a directory
274 size_t bufferLen = 0;
275 size_t bufferPos = 0;
276 };
277
278 using Handler = bool (FTPServer::*)(Session&, const String&);
279
281 CommandEntry(const char* name, Handler builtin, bool needsAuth = true)
282 : name(name), builtin(builtin), needsAuth(needsAuth) {}
283 const char* name;
284 Handler builtin; // or custom handler
285 bool needsAuth;
286 std::function<bool(Client&, const String&)> handler;
287 };
288
289 struct User {
290 String name;
291 String password;
292 };
293
294 std::vector<CommandEntry> commands;
295 TServer server;
296 uint16_t dataPort;
297 TStorage* storage;
299 std::vector<User> users;
300 IPAddress passiveIP;
301 bool hasPassiveIP = false;
302 uint32_t dataTimeout = FTP_DATA_TIMEOUT;
303
304 bool hasUsers() { return !users.empty(); }
305
308 void reply(Session& s, const String& msg) {
309 static_cast<Client&>(s.control).println(msg);
310 }
311
312 bool isValidLogin(const String& name, const String& pwd) {
313 for (auto& entry : users) {
314 if (entry.name == name && entry.password == pwd) return true;
315 }
316 return false;
317 }
318
320 TServer& dataServer(int index) {
321 Session& s = sessions[index];
322 if (s.dataServer == nullptr) s.dataServer = new TServer(dataPort + index);
323 return *s.dataServer;
324 }
325
328 auto client = server.accept();
329 if (!client) return;
330 for (auto& s : sessions) {
331 if (!s.active) {
333 reply(s, "220 Welcome to TinyFTP");
334 return;
335 }
336 }
337 static_cast<Client&>(client).println(
338 "421 Too many connections, try again later");
339 client.stop();
340 }
341
344 s.active = true;
345 s.control = client;
346 s.line = "";
347 s.lineReady = false;
348 s.isLoggedIn = !hasUsers();
349 s.userName = "";
350 s.currentDir = "/";
351 s.renameFrom = "";
352 s.dataMode = DataMode::None;
353 s.transfer = Transfer::None;
354 }
355
356 void closeSession(Session& s) {
357 if (s.transfer != Transfer::None) closeTransfer(s);
358 s.control.stop();
359 s.active = false;
360 s.isLoggedIn = false;
361 s.userName = "";
362 s.dataMode = DataMode::None;
363 }
364
366 void step(Session& s) {
367 if (s.transfer != Transfer::None) stepTransfer(s);
368 if (!s.lineReady) readLine(s);
369 // during a transfer we only process ABOR: the other commands wait
370 if (s.lineReady && (s.transfer == Transfer::None || isAbort(s.line))) {
371 String cmd = s.line;
372 s.line = "";
373 s.lineReady = false;
374 cmd.trim();
375 if (cmd.length() > 0 && !processCommand(s, cmd)) {
376 closeSession(s);
377 return;
378 }
379 }
380 if (s.transfer == Transfer::None && !s.lineReady &&
381 s.control.available() == 0 && !s.control.connected()) {
382 closeSession(s);
383 }
384 }
385
388 while (s.control.available() > 0) {
389 int c = s.control.read();
390 if (c < 0) break;
391 if (c == '\n') {
392 s.lineReady = true;
393 return;
394 }
395 // ignore telnet control characters (e.g. sent before ABOR)
396 if (c >= 0x80) continue;
397 if (s.line.length() < FTP_SERVER_MAX_LINE) s.line += (char)c;
398 }
399 // last line without line feed
400 if (s.line.length() > 0 && !s.control.connected()) s.lineReady = true;
401 }
402
403 static bool isAbort(String line) {
404 line.trim();
405 return line.equalsIgnoreCase("ABOR");
406 }
407
409 bool processCommand(Session& s, const String& cmd) {
410 int end = cmd.indexOf(' ');
411 String verb = end < 0 ? cmd : cmd.substring(0, end);
412 // RNTO must directly follow RNFR
413 if (!verb.equalsIgnoreCase("RNTO")) s.renameFrom = "";
414 for (auto& entry : commands) {
415 if (verb.equalsIgnoreCase(entry.name)) {
416 if (entry.needsAuth && !s.isLoggedIn) {
417 reply(s, "530 Not logged in");
418 return true; // stay connected
419 }
420 if (entry.builtin != nullptr) return (this->*entry.builtin)(s, cmd);
421 return entry.handler(s.control, cmd);
422 }
423 }
424 return onUnknown(s, cmd);
425 }
426
428 static String argument(const String& cmd) {
429 int start = cmd.indexOf(' ');
430 if (start < 0) return "";
431 String result = cmd.substring(start + 1);
432 result.trim();
433 return result;
434 }
435
439 String path = arg.startsWith("/") ? arg : s.currentDir + "/" + arg;
440 std::vector<String> parts;
441 int start = 0;
442 while (start <= (int)path.length()) {
443 int end = path.indexOf('/', start);
444 if (end < 0) end = path.length();
445 String part = path.substring(start, end);
446 if (part == "..") {
447 if (!parts.empty()) parts.pop_back();
448 } else if (part.length() > 0 && part != ".") {
449 parts.push_back(part);
450 }
451 start = end + 1;
452 }
453 if (parts.empty()) return "/";
455 for (auto& part : parts) result += "/" + part;
456 return result;
457 }
458
460 static String baseName(const char* name) {
461 String result = name;
462 int pos = result.lastIndexOf('/');
463 return pos < 0 ? result : result.substring(pos + 1);
464 }
465
467 template <typename C>
468 static auto localIPOf(C& client, int)
469 -> decltype(IPAddress(client.localIP())) {
470 return client.localIP();
471 }
472 template <typename C>
473 static IPAddress localIPOf(C&, long) {
474 return IPAddress(0, 0, 0, 0);
475 }
476
477 FileType openFile(const char* path, OpenMode mode) {
478 return openIn(storage, path, mode, 0);
479 }
480
482 template <typename S>
483 static auto renameIn(S* fs, const char* from, const char* to, int)
484 -> decltype(fs->rename(from, to), bool()) {
485 return fs->rename(from, to);
486 }
487 template <typename S>
488 static bool renameIn(S*, const char*, const char*, long) {
489 return false;
490 }
491 template <typename S>
492 static auto canRename(S* fs, int) -> decltype(fs->rename("", ""), bool()) {
493 return true;
494 }
495 template <typename S>
496 static bool canRename(S*, long) {
497 return false;
498 }
499
501 bool isDirectory(const String& path) {
502 auto file = openFile(path.c_str(), OpenMode::Read);
503 bool result = file && file.isDirectory();
504 if (file) file.close();
505 return result;
506 }
507
511 TServer& ds = dataServer(s.index);
512 if (!s.dataServerStarted) {
513 ds.begin();
514 s.dataServerStarted = true;
515 }
516 for (auto stale = ds.accept(); stale; stale = ds.accept()) stale.stop();
517 }
518
521 bool beginTransfer(Session& s, Transfer transfer, const char* msg) {
522 if (s.dataMode == DataMode::None) {
523 reply(s, "425 Use PORT or PASV first");
524 return false;
525 }
526 s.transferMode = s.dataMode;
527 s.dataMode = DataMode::None; // one transfer per PASV/PORT
528 s.transfer = transfer;
529 s.transferMsg = msg;
530 s.waitingForData = true;
531 s.lastActivity = millis();
532 s.bufferLen = 0;
533 s.bufferPos = 0;
534 s.data = ClientType();
535 if (s.transferMode == DataMode::Active) {
536 if (!s.data.connect(s.activeIP, s.activePort)) {
537 reply(s, "425 Can't open data connection");
539 return false;
540 }
541 dataConnected(s);
542 }
543 return true;
544 }
545
546 void dataConnected(Session& s) {
547 s.waitingForData = false;
548 s.lastActivity = millis();
549 reply(s, s.transferMsg);
550 }
551
554 if (s.waitingForData) {
555 s.data = dataServer(s.index).accept();
556 if (s.data) {
557 dataConnected(s);
558 } else if (millis() - s.lastActivity >= dataTimeout) {
559 reply(s, "425 Can't open data connection");
561 }
562 return;
563 }
564 switch (s.transfer) {
565 case Transfer::Retr:
566 stepRetr(s);
567 break;
568 case Transfer::Stor:
569 stepStor(s);
570 break;
571 case Transfer::List:
572 stepList(s);
573 break;
574 default:
575 break;
576 }
577 }
578
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))
582 : 0;
583 if (len <= 0) {
584 endTransfer(s, "226 Transfer complete");
585 return;
586 }
587 s.bufferLen = len;
588 s.bufferPos = 0;
589 }
590 size_t written =
591 s.data.write(s.buffer + s.bufferPos, s.bufferLen - s.bufferPos);
592 s.bufferPos += written;
593 if (written > 0) {
594 s.lastActivity = millis();
595 } else if (!s.data.connected() ||
596 millis() - s.lastActivity >= dataTimeout) {
597 endTransfer(s, "426 Connection closed; transfer aborted");
598 }
599 }
600
601 void stepStor(Session& s) {
602 int len = s.data.available();
603 if (len > 0) {
604 // read via Client: some client types hide read(buf, len)
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) {
611 endTransfer(s, "226 Transfer complete");
612 }
613 }
614
617 if (s.listSingle) {
618 printListEntry(s.data, s.file, s.listDetails);
619 endTransfer(s, "226 Transfer complete");
620 return;
621 }
622 auto entry = s.file.openNextFile();
623 if (!entry) {
624 endTransfer(s, "226 Transfer complete");
625 return;
626 }
627 printListEntry(s.data, entry, s.listDetails);
628 entry.close();
629 }
630
632 void endTransfer(Session& s, const char* msg) {
633 // close the file first, so that it is complete when the client gets the
634 // reply
636 reply(s, msg);
637 }
638
641 if (s.data) {
642 s.data.flush();
643 s.data.stop();
644 }
645 if (s.file) s.file.close();
646 s.file = FileType();
647 s.transfer = Transfer::None;
648 s.waitingForData = false;
649 }
650
651 template <typename F>
652 void printListEntry(Client& data, F& entry, bool details) {
653 if (details) {
654 data.print(entry.isDirectory() ? "drwxr-xr-x" : "-rw-r--r--");
655 data.print(" 1 owner group ");
656 data.print(entry.isDirectory() ? 0 : (unsigned long)entry.size());
657 data.print(" Jan 1 00:00 ");
658 }
659 data.print(baseName(entry.name()));
660 data.print("\r\n");
661 }
662
663 bool checkStorage(Session& s) {
664 if (!storage) reply(s, "550 Storage not available");
665 return storage != nullptr;
666 }
667
668 bool list(Session& s, const String& cmd, bool details) {
669 if (!checkStorage(s)) return true;
670 String arg = argument(cmd);
671 if (arg.startsWith("-")) arg = ""; // ignore options like -a
672 String path = resolvePath(s, arg);
673 auto dir = openFile(path.c_str(), OpenMode::Read);
674 if (!dir) {
675 reply(s, "550 No such file or directory");
676 return true;
677 }
678 s.listDetails = details;
679 s.listSingle = !dir.isDirectory();
680 s.file = std::move(dir);
681 if (!beginTransfer(s, Transfer::List,
682 "150 Here comes the directory listing")) {
683 closeTransfer(s);
684 }
685 return true;
686 }
687
689 bool store(Session& s, const String& cmd, OpenMode mode) {
690 if (!checkStorage(s)) return true;
692 auto file = openFile(path.c_str(), mode);
693 if (!file) {
694 reply(s, "550 Cannot open file for writing");
695 return true;
696 }
697 s.file = std::move(file);
698 if (!beginTransfer(s, Transfer::Stor, "150 Ready to receive data")) {
700 }
701 return true;
702 }
703
704 // Each command handler returns true to continue, false to disconnect
705 bool onUSER(Session& s, const String& cmd) {
706 // a new USER restarts the login
707 s.userName = argument(cmd);
708 s.isLoggedIn = !hasUsers();
709 reply(s, "331 Username OK, enter password");
710 return true;
711 }
712 bool onPASS(Session& s, const String& cmd) {
713 if (hasUsers() && s.userName.length() == 0) {
714 reply(s, "503 Login with USER first");
715 return true;
716 }
717 String pwd = argument(cmd);
718 if (!hasUsers() || isValidLogin(s.userName, pwd)) {
719 reply(s, "230 User logged in");
720 s.isLoggedIn = true;
721 return true;
722 } else {
723 reply(s, "530 Login incorrect");
724 s.isLoggedIn = false;
725 return false; // disconnect on wrong password
726 }
727 }
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;
732 String path = resolvePath(s, argument(cmd));
733 auto dir = openFile(path.c_str(), OpenMode::Read);
734 if (dir && dir.isDirectory()) {
735 s.currentDir = path;
736 reply(s, "250 Directory changed to " + path);
737 } else {
738 reply(s, "550 Not a directory");
739 }
740 if (dir) dir.close();
741 return true;
742 }
743 bool onCDUP(Session& s, const String& /*cmd*/) { return onCWD(s, "CWD .."); }
744 bool onPWD(Session& s, const String& /*cmd*/) {
745 reply(s, "257 \"" + s.currentDir + "\" is current directory");
746 return true;
747 }
748 bool onSYST(Session& s, const String& /*cmd*/) {
749 reply(s, "215 UNIX Type: L8");
750 return true;
751 }
752 bool onTYPE(Session& s, const String& cmd) {
753 reply(s, "200 Type set to " + argument(cmd));
754 return true;
755 }
756 bool onBIN(Session& s, const String& /*cmd*/) {
757 reply(s, "200 Type set to I");
758 return true;
759 }
760 bool onASC(Session& s, const String& /*cmd*/) {
761 reply(s, "200 Type set to A");
762 return true;
763 }
764 bool onNOOP(Session& s, const String& /*cmd*/) {
765 reply(s, "200 NOOP ok");
766 return true;
767 }
768 bool onPASV(Session& s, const String& /*cmd*/) {
770 IPAddress ip = hasPassiveIP ? passiveIP : localIPOf(s.control, 0);
771 uint16_t port = dataPort + s.index;
772 s.dataMode = DataMode::Passive;
773 char msg[80];
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);
777 reply(s, msg);
778 return true;
779 }
780 bool onEPSV(Session& s, const String& /*cmd*/) {
782 s.dataMode = DataMode::Passive;
783 char msg[80];
784 snprintf(msg, sizeof(msg), "229 Entering Extended Passive Mode (|||%d|)",
785 dataPort + s.index);
786 reply(s, msg);
787 return true;
788 }
789 bool onPORT(Session& s, const String& cmd) {
790 int v[6];
791 String arg = argument(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");
795 return true;
796 }
797 for (int j = 0; j < 6; j++) {
798 if (v[j] < 0 || v[j] > 255) {
799 reply(s, "501 Syntax error in parameters");
800 return true;
801 }
802 }
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");
807 return true;
808 }
809 bool onHELP(Session& s, const String& /*cmd*/) {
810 reply(s, "214-The following commands are recognized:");
811 String names;
812 for (auto& entry : commands) {
813 names += " ";
814 names += entry.name;
815 }
816 reply(s, names);
817 reply(s, "214 Help OK.");
818 return true;
819 }
820 bool onRETR(Session& s, const String& cmd) {
821 if (!checkStorage(s)) return true;
822 String path = resolvePath(s, argument(cmd));
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();
827 return true;
828 }
829 s.file = std::move(file);
830 if (!beginTransfer(s, Transfer::Retr,
831 "150 Opening data connection for file transfer")) {
832 closeTransfer(s);
833 }
834 return true;
835 }
836 bool onSTOR(Session& s, const String& cmd) {
837 return store(s, cmd, OpenMode::Write);
838 }
839 bool onAPPE(Session& s, const String& cmd) {
840 return store(s, cmd, OpenMode::Append);
841 }
842 bool onABOR(Session& s, const String& /*cmd*/) {
843 if (s.transfer != Transfer::None) {
844 closeTransfer(s);
845 reply(s, "426 Transfer aborted");
846 reply(s, "226 Abort successful");
847 } else {
848 reply(s, "225 No transfer to abort");
849 }
850 return true;
851 }
852 bool onDELE(Session& s, const String& cmd) {
853 if (!checkStorage(s)) return true;
854 String path = resolvePath(s, argument(cmd));
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");
859 } else {
860 reply(s, "550 Delete failed");
861 }
862 return true;
863 }
864 bool onMKD(Session& s, const String& cmd) {
865 if (!checkStorage(s)) return true;
866 String arg = argument(cmd);
867 String path = resolvePath(s, arg);
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");
874 } else {
875 reply(s, "550 Create directory failed");
876 }
877 return true;
878 }
879 bool onRMD(Session& s, const String& cmd) {
880 if (!checkStorage(s)) return true;
881 String path = resolvePath(s, argument(cmd));
882 if (path == "/" || !isDirectory(path)) {
883 reply(s, "550 Not a directory");
884 } else if (storage->rmdir(path.c_str())) {
885 reply(s, "250 Directory removed");
886 // the directory might be the current directory of any connection
887 for (auto& other : sessions) {
888 if (other.currentDir == path ||
889 other.currentDir.startsWith(path + "/")) {
890 other.currentDir = "/";
891 }
892 }
893 } else {
894 reply(s, "550 Remove directory failed");
895 }
896 return true;
897 }
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");
902 return true;
903 }
904 String path = resolvePath(s, argument(cmd));
905 if (path == "/" || !storage->exists(path.c_str())) {
906 reply(s, "550 File not found");
907 } else {
908 s.renameFrom = path;
909 reply(s, "350 Ready for destination name");
910 }
911 return true;
912 }
913 bool onRNTO(Session& s, const String& cmd) {
914 if (s.renameFrom.length() == 0) {
915 reply(s, "503 Bad sequence of commands");
916 return true;
917 }
918 String from = s.renameFrom;
919 s.renameFrom = "";
920 String path = resolvePath(s, argument(cmd));
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");
925 } else {
926 reply(s, "553 Rename failed");
927 }
928 return true;
929 }
930 bool onSIZE(Session& s, const String& cmd) {
931 if (!checkStorage(s)) return true;
932 String path = resolvePath(s, argument(cmd));
933 auto file = openFile(path.c_str(), OpenMode::Read);
934 if (!file || file.isDirectory()) {
935 reply(s, "550 File not found");
936 } else {
937 reply(s, "213 " + String((unsigned long)file.size()));
938 }
939 if (file) file.close();
940 return true;
941 }
942 bool onFEAT(Session& s, const String& /*cmd*/) {
943 reply(s, "211-Features:");
944 reply(s, " EPSV");
945 reply(s, " PASV");
946 reply(s, " SIZE");
947 reply(s, " UTF8");
948 reply(s, "211 End");
949 return true;
950 }
951 bool onOPTS(Session& s, const String& cmd) {
952 String arg = argument(cmd);
953 if (arg.equalsIgnoreCase("UTF8 ON") || arg.equalsIgnoreCase("UTF8")) {
954 reply(s, "200 UTF8 mode enabled");
955 } else {
956 reply(s, "501 Option not supported");
957 }
958 return true;
959 }
960 bool onQUIT(Session& s, const String& /*cmd*/) {
961 reply(s, "221 Goodbye");
962 s.isLoggedIn = false;
963 return false;
964 }
965 bool onUnknown(Session& s, const String& /*cmd*/) {
966 reply(s, "502 Command not implemented");
967 return true;
968 }
969};
970
971} // namespace tinyftp
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