├── FTPClient.cpp ├── FTPClient.h ├── FTPCommon.cpp ├── FTPCommon.h ├── FTPServer.cpp ├── FTPServer.h ├── LICENSE ├── README.md ├── esp32compat └── PolledTimeout.h ├── esp8266compat └── PolledTimeout.h ├── examples ├── FTPClientSample │ └── FTPClientSample.ino └── FTPServerSample │ ├── LittleFSSample │ └── LittleFSSample.ino │ └── SPIFFSSample │ └── SPIFFSSample.ino ├── library.json └── library.properties /FTPClient.cpp: -------------------------------------------------------------------------------- 1 | #include "FTPClient.h" 2 | 3 | FTPClient::FTPClient(FS &_FSImplementation) : FTPCommon(_FSImplementation) 4 | { 5 | // set aTimeout to never expire, will be used later by ::waitFor(...) 6 | aTimeout.resetToNeverExpires(); 7 | } 8 | 9 | void FTPClient::begin(const ServerInfo &theServer) 10 | { 11 | _server = &theServer; 12 | } 13 | 14 | const FTPClient::Status &FTPClient::transfer(const String &localFileName, const String &remoteFileName, TransferType direction) 15 | { 16 | _serverStatus.result = PROGRESS; 17 | if (ftpState >= cIdle) 18 | { 19 | _remoteFileName = remoteFileName; 20 | _direction = direction; 21 | 22 | if (direction & FTP_GET_NONBLOCKING) 23 | file = THEFS.open(localFileName, "w"); 24 | else if (direction & FTP_PUT_NONBLOCKING) 25 | file = THEFS.open(localFileName, "r"); 26 | 27 | if (!file) 28 | { 29 | _serverStatus.result = ERROR; 30 | _serverStatus.code = errorLocalFile; 31 | _serverStatus.desc = F("Local file error"); 32 | } 33 | else 34 | { 35 | ftpState = cConnect; 36 | if (direction & 0x80) 37 | { 38 | while (ftpState <= cQuit) 39 | { 40 | handleFTP(); 41 | delay(25); 42 | } 43 | } 44 | } 45 | } 46 | else 47 | { 48 | // return error code with status "in PROGRESS" 49 | _serverStatus.code = errorAlreadyInProgress; 50 | } 51 | return _serverStatus; 52 | } 53 | 54 | const FTPClient::Status &FTPClient::check() 55 | { 56 | return _serverStatus; 57 | } 58 | 59 | void FTPClient::handleFTP() 60 | { 61 | if (_server == nullptr) 62 | { 63 | _serverStatus.result = TransferResult::ERROR; 64 | _serverStatus.code = errorUninitialized; 65 | _serverStatus.desc = F("begin() not called"); 66 | } 67 | else if (ftpState > cIdle) 68 | { 69 | _serverStatus.result = TransferResult::ERROR; 70 | } 71 | else if (cConnect == ftpState) 72 | { 73 | _serverStatus.code = errorConnectionFailed; 74 | _serverStatus.desc = F("No connection to FTP server"); 75 | if (controlConnect()) 76 | { 77 | FTP_DEBUG_MSG("Connection to %s:%u established", control.remoteIP().toString().c_str(), control.remotePort()); 78 | _serverStatus.result = TransferResult::PROGRESS; 79 | ftpState = cGreet; 80 | } 81 | else 82 | { 83 | ftpState = cError; 84 | } 85 | } 86 | else if (cGreet == ftpState) 87 | { 88 | if (waitFor(220 /* 220 (vsFTPd version) */, F("No server greeting"))) 89 | { 90 | FTP_DEBUG_MSG(">>> USER %s", _server->login.c_str()); 91 | control.printf_P(PSTR("USER %s\n"), _server->login.c_str()); 92 | ftpState = cUser; 93 | } 94 | } 95 | else if (cUser == ftpState) 96 | { 97 | if (waitFor(331 /* 331 Password */)) 98 | { 99 | FTP_DEBUG_MSG(">>> PASS %s", _server->password.c_str()); 100 | control.printf_P(PSTR("PASS %s\n"), _server->password.c_str()); 101 | ftpState = cPassword; 102 | } 103 | } 104 | else if (cPassword == ftpState) 105 | { 106 | if (waitFor(230 /* 230 Login successful*/)) 107 | { 108 | FTP_DEBUG_MSG(">>> PASV"); 109 | control.printf_P(PSTR("PASV\n")); 110 | ftpState = cPassive; 111 | } 112 | } 113 | else if (cPassive == ftpState) 114 | { 115 | if (waitFor(227 /* 227 Entering Passive Mode (ip,ip,ip,ip,port,port) */)) 116 | { 117 | bool parseOK = false; 118 | // find () 119 | uint8_t bracketOpen = _serverStatus.desc.indexOf(F("(")); 120 | uint8_t bracketClose = _serverStatus.desc.indexOf(F(")")); 121 | if (bracketOpen && (bracketClose > bracketOpen)) 122 | { 123 | FTP_DEBUG_MSG("Parsing PASV response %s", _serverStatus.desc.c_str()); 124 | _serverStatus.desc[bracketClose] = '\0'; 125 | if (parseDataIpPort(_serverStatus.desc.c_str() + bracketOpen + 1)) 126 | { 127 | // catch ip=0.0.0.0 and replace with the control.remoteIP() 128 | if (dataIP.toString() == F("0.0.0.0")) 129 | { 130 | dataIP = control.remoteIP(); 131 | } 132 | parseOK = true; 133 | ftpState = cData; 134 | } 135 | } 136 | if (!parseOK) 137 | { 138 | _serverStatus.code = errorServerResponse; 139 | _serverStatus.desc = F("FTP server response not understood."); 140 | } 141 | } 142 | } 143 | else if (cData == ftpState) 144 | { 145 | // open data connection 146 | if (dataConnect() < 0) 147 | { 148 | _serverStatus.code = errorDataConnectionFailed; 149 | _serverStatus.desc = F("No data connection to FTP server"); 150 | ftpState = cError; 151 | } 152 | else 153 | { 154 | FTP_DEBUG_MSG("Data connection to %s:%u established", data.remoteIP().toString().c_str(), data.remotePort()); 155 | millisBeginTrans = millis(); 156 | bytesTransfered = 0; 157 | ftpState = cTransfer; 158 | if (allocateBuffer() == 0) 159 | { 160 | _serverStatus.code = errorMemory; 161 | _serverStatus.desc = F("No memory for transfer buffer"); 162 | ftpState = cError; 163 | } 164 | if (_direction & FTP_PUT_NONBLOCKING) 165 | { 166 | FTP_DEBUG_MSG(">>> STOR %s", _remoteFileName.c_str()); 167 | control.printf_P(PSTR("STOR %s\n"), _remoteFileName.c_str()); 168 | } 169 | else if (_direction & FTP_GET_NONBLOCKING) 170 | { 171 | FTP_DEBUG_MSG(">>> RETR %s", _remoteFileName.c_str()); 172 | control.printf_P(PSTR("RETR %s\n"), _remoteFileName.c_str()); 173 | } 174 | } 175 | } 176 | else if (cTransfer == ftpState) 177 | { 178 | bool res = true; 179 | if (_direction & FTP_PUT_NONBLOCKING) 180 | { 181 | res = doFiletoNetwork(); 182 | } 183 | else 184 | { 185 | res = doNetworkToFile(); 186 | } 187 | if (!res || !data.connected()) 188 | { 189 | ftpState = cFinish; 190 | } 191 | } 192 | else if (cFinish == ftpState) 193 | { 194 | closeTransfer(); 195 | ftpState = cQuit; 196 | } 197 | else if (cQuit == ftpState) 198 | { 199 | FTP_DEBUG_MSG(">>> QUIT"); 200 | control.printf_P(PSTR("QUIT\n")); 201 | _serverStatus.result = OK; 202 | ftpState = cIdle; 203 | } 204 | else if (cIdle == ftpState) 205 | { 206 | stop(); 207 | } 208 | } 209 | 210 | int8_t FTPClient::controlConnect() 211 | { 212 | if (_server->validateCA) 213 | { 214 | FTP_DEBUG_MSG("Ignoring CA verification - FTP only"); 215 | } 216 | control.connect(_server->servername.c_str(), _server->port); 217 | FTP_DEBUG_MSG("Connection to %s:%d ... %s", _server->servername.c_str(), _server->port, control.connected() ? PSTR("OK") : PSTR("failed")); 218 | if (control.connected()) 219 | return 1; 220 | return -1; 221 | } 222 | 223 | bool FTPClient::waitFor(const int16_t respCode, const String &errorString, uint32_t timeOutMs) 224 | { 225 | // initalize waiting 226 | if (!aTimeout.canExpire()) 227 | { 228 | aTimeout.reset(timeOutMs); 229 | _serverStatus.desc.clear(); 230 | } 231 | else 232 | { 233 | // timeout 234 | if (aTimeout.expired()) 235 | { 236 | aTimeout.resetToNeverExpires(); 237 | FTP_DEBUG_MSG("Waiting for code %u - timeout!", respCode); 238 | _serverStatus.code = errorTimeout; 239 | if (errorString) 240 | { 241 | _serverStatus.desc = errorString; 242 | } 243 | else 244 | { 245 | _serverStatus.desc = F("timeout"); 246 | } 247 | ftpState = cTimeout; 248 | return false; 249 | } 250 | 251 | // check for bytes from the client 252 | while (control.available()) 253 | { 254 | char c = control.read(); 255 | //FTP_DEBUG_MSG("readChar() line='%s' <= %c", _serverStatus.desc.c_str(), c); 256 | if (c == '\n' || c == '\r') 257 | { 258 | // filter out empty lines 259 | _serverStatus.desc.trim(); 260 | if (0 == _serverStatus.desc.length()) 261 | continue; 262 | 263 | // line complete, evaluate code 264 | _serverStatus.code = atoi(_serverStatus.desc.c_str()); 265 | if (respCode != _serverStatus.code) 266 | { 267 | ftpState = cError; 268 | FTP_DEBUG_MSG("Waiting for code %u but SMTP server replies: %s", respCode, _serverStatus.desc.c_str()); 269 | } 270 | else 271 | { 272 | FTP_DEBUG_MSG("Waiting for code %u success, SMTP server replies: %s", respCode, _serverStatus.desc.c_str()); 273 | } 274 | 275 | aTimeout.resetToNeverExpires(); 276 | return (respCode == _serverStatus.code); 277 | } 278 | else 279 | { 280 | // just add the char 281 | _serverStatus.desc += c; 282 | } 283 | } 284 | } 285 | return false; 286 | } 287 | -------------------------------------------------------------------------------- /FTPClient.h: -------------------------------------------------------------------------------- 1 | /** \mainpage FTPClient library 2 | * 3 | * MIT license 4 | * written by Daniel Plasa: 5 | * Inspired by https://github.com/danbicks and his code posted in https://github.com/esp8266/Arduino/issues/1183#issuecomment-634556135 6 | * 7 | * The Client supports two ways of getting/putting files: 8 | * a) blocking, returns only after transfer complete (or error) 9 | * b) non-blocking, returns immedeate. call check() for status of process 10 | * 11 | * When using non-blocking mode, be sure to call update() frequently, e.g. in loop(). 12 | */ 13 | 14 | #ifndef FTP_CLIENT_H 15 | #define FTP_CLIENT_H 16 | 17 | /******************************************************************************* 18 | ** ** 19 | ** DEFINITIONS FOR FTP SERVER/CLIENT ** 20 | ** ** 21 | *******************************************************************************/ 22 | #include 23 | #include "FTPCommon.h" 24 | 25 | class FTPClient : public FTPCommon 26 | { 27 | public: 28 | struct ServerInfo 29 | { 30 | ServerInfo(const String &_l, const String &_pw, const String &_sn, uint16_t _p = 21, bool v = false) : login(_l), password(_pw), servername(_sn), port(_p), validateCA(v) {} 31 | ServerInfo() = default; 32 | String login; 33 | String password; 34 | String servername; 35 | uint16_t port; 36 | bool authTLS = false; 37 | bool validateCA = false; 38 | }; 39 | 40 | typedef enum 41 | { 42 | OK, 43 | PROGRESS, 44 | ERROR, 45 | } TransferResult; 46 | 47 | static constexpr int16_t errorLocalFile = -1; 48 | static constexpr int16_t errorAlreadyInProgress = -2; 49 | static constexpr int16_t errorConnectionFailed = -3; 50 | static constexpr int16_t errorServerResponse = -4; 51 | static constexpr int16_t errorDataConnectionFailed = -5; 52 | static constexpr int16_t errorUninitialized = -6; 53 | static constexpr int16_t errorTimeout = -7; 54 | static constexpr int16_t errorMemory = -8; 55 | 56 | typedef struct 57 | { 58 | TransferResult result; 59 | int16_t code; 60 | String desc; 61 | } Status; 62 | 63 | typedef enum 64 | { 65 | FTP_PUT = 1 | 0x80, 66 | FTP_GET = 2 | 0x80, 67 | FTP_PUT_NONBLOCKING = FTP_PUT & 0x7f, 68 | FTP_GET_NONBLOCKING = FTP_GET & 0x7f, 69 | } TransferType; 70 | 71 | // contruct an instance of the FTP Client using a 72 | // given FS object, e.g. SPIFFS or LittleFS 73 | FTPClient(FS &_FSImplementation); 74 | 75 | // initialize FTP Client with the ftp server's credentials 76 | void begin(const ServerInfo &server); 77 | 78 | // transfer a file (nonblocking via handleFTP() ) 79 | const Status &transfer(const String &localFileName, const String &remoteFileName, TransferType direction = FTP_GET); 80 | 81 | // check status 82 | const Status &check(); 83 | 84 | // call freqently (e.g. in loop()), when using non-blocking mode 85 | void handleFTP(); 86 | 87 | protected: 88 | typedef enum 89 | { 90 | cConnect = 0, 91 | cGreet, 92 | cUser, 93 | cPassword, 94 | cPassive, 95 | cData, 96 | cTransfer, 97 | cFinish, 98 | cQuit, 99 | cIdle, 100 | cTimeout, 101 | cError 102 | } internalState; 103 | internalState ftpState = cIdle; 104 | Status _serverStatus; 105 | uint32_t waitUntil = 0; 106 | const ServerInfo *_server = nullptr; 107 | 108 | String _remoteFileName; 109 | TransferType _direction; 110 | 111 | int8_t controlConnect(); // connects to ServerInfo, returns -1: no connection possible, +1: connection established 112 | 113 | bool waitFor(const int16_t respCode, const String &errorString = (const char*)NULL, uint32_t timeOut = 10000); 114 | }; 115 | 116 | #endif // FTP_CLIENT_H 117 | -------------------------------------------------------------------------------- /FTPCommon.cpp: -------------------------------------------------------------------------------- 1 | #include "FTPCommon.h" 2 | 3 | FTPCommon::FTPCommon(FS &_FSImplementation) : THEFS(_FSImplementation), sTimeOutMs(FTP_TIME_OUT * 60 * 1000), aTimeout(FTP_TIME_OUT * 60 * 1000) 4 | { 5 | } 6 | 7 | FTPCommon::~FTPCommon() 8 | { 9 | stop(); 10 | } 11 | 12 | void FTPCommon::stop() 13 | { 14 | control.stop(); 15 | data.stop(); 16 | file.close(); 17 | freeBuffer(); 18 | } 19 | 20 | void FTPCommon::setTimeout(uint32_t timeoutMs) 21 | { 22 | sTimeOutMs = timeoutMs; 23 | } 24 | 25 | // 26 | // allocate a big buffer for file transfers 27 | // 28 | uint16_t FTPCommon::allocateBuffer(uint16_t desiredBytes) 29 | { 30 | #if (defined ESP8266) 31 | uint16_t maxBlock = ESP.getMaxFreeBlockSize() / 2; 32 | 33 | if (desiredBytes > maxBlock) 34 | desiredBytes = maxBlock; 35 | #endif 36 | while (fileBuffer == NULL && desiredBytes > 0) 37 | { 38 | fileBuffer = (uint8_t *)malloc(desiredBytes); 39 | if (NULL == fileBuffer) 40 | { 41 | FTP_DEBUG_MSG("Cannot allocate buffer for file transfer, re-trying"); 42 | // try with less bytes 43 | desiredBytes--; 44 | } 45 | else 46 | { 47 | fileBufferSize = desiredBytes; 48 | } 49 | } 50 | return fileBufferSize; 51 | } 52 | 53 | void FTPCommon::freeBuffer() 54 | { 55 | free(fileBuffer); 56 | fileBuffer = NULL; 57 | } 58 | 59 | int8_t FTPCommon::dataConnect() 60 | { 61 | // open our own data connection 62 | data.stop(); 63 | FTP_DEBUG_MSG("Open data connection to %s:%u", dataIP.toString().c_str(), dataPort); 64 | data.connect(dataIP, dataPort); 65 | return data.connected() ? 1 : -1; 66 | } 67 | 68 | bool FTPCommon::parseDataIpPort(const char *p) 69 | { 70 | // parse IP and data port of "ip,ip,ip,ip,port,port" 71 | uint8_t parsecount = 0; 72 | uint8_t tmp[6]; 73 | while (parsecount < sizeof(tmp)) 74 | { 75 | tmp[parsecount++] = atoi(p); 76 | p = strchr(p, ','); 77 | if (NULL == p || *(++p) == '\0') 78 | break; 79 | } 80 | if (parsecount >= sizeof(tmp)) 81 | { 82 | // copy first 4 bytes = IP 83 | for (uint8_t i = 0; i < 4; ++i) 84 | dataIP[i] = tmp[i]; 85 | // data port is 5,6 86 | dataPort = tmp[4] * 256 + tmp[5]; 87 | return true; 88 | } 89 | return false; 90 | } 91 | 92 | bool FTPCommon::doFiletoNetwork() 93 | { 94 | // data connection lost or no more bytes to transfer? 95 | if (!data.connected() || (bytesTransfered >= file.size())) 96 | { 97 | return false; 98 | } 99 | 100 | // how many bytes to transfer left? 101 | uint32_t nb = (file.size() - bytesTransfered); 102 | if (nb > fileBufferSize) 103 | nb = fileBufferSize; 104 | 105 | // transfer the file 106 | FTP_DEBUG_MSG("Transfer %d bytes fs->net", nb); 107 | nb = file.readBytes((char *)fileBuffer, nb); 108 | if (nb > 0) 109 | { 110 | data.write(fileBuffer, nb); 111 | bytesTransfered += nb; 112 | } 113 | 114 | return (nb > 0); 115 | } 116 | 117 | bool FTPCommon::doNetworkToFile() 118 | { 119 | // Avoid blocking by never reading more bytes than are available 120 | int16_t navail = data.available(); 121 | 122 | if (navail > 0) 123 | { 124 | if (navail > fileBufferSize) 125 | navail = fileBufferSize; 126 | FTP_DEBUG_MSG("Transfer %d bytes net->FS", navail); 127 | navail = data.read(fileBuffer, navail); 128 | file.write(fileBuffer, navail); 129 | bytesTransfered += navail; 130 | } 131 | 132 | if (!data.connected() && (navail <= 0)) 133 | { 134 | // connection closed or no more bytes to read 135 | return false; 136 | } 137 | else 138 | { 139 | // inidcate, we need to be called again 140 | return true; 141 | } 142 | } 143 | 144 | void FTPCommon::closeTransfer() 145 | { 146 | data.stop(); 147 | file.close(); 148 | freeBuffer(); 149 | } 150 | -------------------------------------------------------------------------------- /FTPCommon.h: -------------------------------------------------------------------------------- 1 | #ifndef FTP_COMMON_H 2 | #define FTP_COMMON_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #ifdef ESP8266 10 | #include "esp8266compat/PolledTimeout.h" 11 | using esp8266Pool::polledTimeout::oneShotMs; // import the type to the local namespace 12 | #define BUFFERSIZE TCP_MSS 13 | #define PRINTu32 "lu" 14 | #elif defined ESP32 15 | #include "esp32compat/PolledTimeout.h" 16 | using esp32Pool::polledTimeout::oneShotMs; 17 | #define BUFFERSIZE CONFIG_TCP_MSS 18 | #define PRINTu32 "u" 19 | #endif 20 | 21 | #define FTP_SERVER_VERSION "0.9.7-20200529" 22 | 23 | #define FTP_CTRL_PORT 21 // Command port on which server is listening 24 | #define FTP_DATA_PORT_PASV 50009 // Data port in passive mode 25 | #define FTP_TIME_OUT 5 // Disconnect client after 5 minutes of inactivity 26 | #define FTP_CMD_SIZE 127 // allow max. 127 chars in a received command 27 | 28 | // Use ESP8266 Core Debug functionality 29 | #ifdef DEBUG_ESP_PORT 30 | #define FTP_DEBUG_MSG(fmt, ...) \ 31 | do \ 32 | { \ 33 | DEBUG_ESP_PORT.printf_P(PSTR("[FTP] " fmt "\n"), ##__VA_ARGS__); \ 34 | yield(); \ 35 | } while (0) 36 | #else 37 | #define FTP_DEBUG_MSG(...) 38 | #endif 39 | 40 | #define FTP_CMD(CMD) (FTP_CMD_LE_##CMD) // make command 41 | #define FTP_CMD_LE_USER 0x52455355 // "USER" as uint32_t (little endian) 42 | #define FTP_CMD_BE_USER 0x55534552 // "USER" as uint32_t (big endian) 43 | #define FTP_CMD_LE_PASS 0x53534150 // "PASS" as uint32_t (little endian) 44 | #define FTP_CMD_BE_PASS 0x50415353 // "PASS" as uint32_t (big endian) 45 | #define FTP_CMD_LE_QUIT 0x54495551 // "QUIT" as uint32_t (little endian) 46 | #define FTP_CMD_BE_QUIT 0x51554954 // "QUIT" as uint32_t (big endian) 47 | #define FTP_CMD_LE_CDUP 0x50554443 // "CDUP" as uint32_t (little endian) 48 | #define FTP_CMD_BE_CDUP 0x43445550 // "CDUP" as uint32_t (big endian) 49 | #define FTP_CMD_LE_CWD 0x00445743 // "CWD" as uint32_t (little endian) 50 | #define FTP_CMD_BE_CWD 0x43574400 // "CWD" as uint32_t (big endian) 51 | #define FTP_CMD_LE_PWD 0x00445750 // "PWD" as uint32_t (little endian) 52 | #define FTP_CMD_BE_PWD 0x50574400 // "PWD" as uint32_t (big endian) 53 | #define FTP_CMD_LE_MODE 0x45444f4d // "MODE" as uint32_t (little endian) 54 | #define FTP_CMD_BE_MODE 0x4d4f4445 // "MODE" as uint32_t (big endian) 55 | #define FTP_CMD_LE_PASV 0x56534150 // "PASV" as uint32_t (little endian) 56 | #define FTP_CMD_BE_PASV 0x50415356 // "PASV" as uint32_t (big endian) 57 | #define FTP_CMD_LE_PORT 0x54524f50 // "PORT" as uint32_t (little endian) 58 | #define FTP_CMD_BE_PORT 0x504f5254 // "PORT" as uint32_t (big endian) 59 | #define FTP_CMD_LE_STRU 0x55525453 // "STRU" as uint32_t (little endian) 60 | #define FTP_CMD_BE_STRU 0x53545255 // "STRU" as uint32_t (big endian) 61 | #define FTP_CMD_LE_TYPE 0x45505954 // "TYPE" as uint32_t (little endian) 62 | #define FTP_CMD_BE_TYPE 0x54595045 // "TYPE" as uint32_t (big endian) 63 | #define FTP_CMD_LE_ABOR 0x524f4241 // "ABOR" as uint32_t (little endian) 64 | #define FTP_CMD_BE_ABOR 0x41424f52 // "ABOR" as uint32_t (big endian) 65 | #define FTP_CMD_LE_DELE 0x454c4544 // "DELE" as uint32_t (little endian) 66 | #define FTP_CMD_BE_DELE 0x44454c45 // "DELE" as uint32_t (big endian) 67 | #define FTP_CMD_LE_LIST 0x5453494c // "LIST" as uint32_t (little endian) 68 | #define FTP_CMD_BE_LIST 0x4c495354 // "LIST" as uint32_t (big endian) 69 | #define FTP_CMD_LE_MLSD 0x44534c4d // "MLSD" as uint32_t (little endian) 70 | #define FTP_CMD_BE_MLSD 0x4d4c5344 // "MLSD" as uint32_t (big endian) 71 | #define FTP_CMD_LE_NLST 0x54534c4e // "NLST" as uint32_t (little endian) 72 | #define FTP_CMD_BE_NLST 0x4e4c5354 // "NLST" as uint32_t (big endian) 73 | #define FTP_CMD_LE_NOOP 0x504f4f4e // "NOOP" as uint32_t (little endian) 74 | #define FTP_CMD_BE_NOOP 0x4e4f4f50 // "NOOP" as uint32_t (big endian) 75 | #define FTP_CMD_LE_RETR 0x52544552 // "RETR" as uint32_t (little endian) 76 | #define FTP_CMD_BE_RETR 0x52455452 // "RETR" as uint32_t (big endian) 77 | #define FTP_CMD_LE_STOR 0x524f5453 // "STOR" as uint32_t (little endian) 78 | #define FTP_CMD_BE_STOR 0x53544f52 // "STOR" as uint32_t (big endian) 79 | #define FTP_CMD_LE_MKD 0x00444b4d // "MKD" as uint32_t (little endian) 80 | #define FTP_CMD_BE_MKD 0x4d4b4400 // "MKD" as uint32_t (big endian) 81 | #define FTP_CMD_LE_RMD 0x00444d52 // "RMD" as uint32_t (little endian) 82 | #define FTP_CMD_BE_RMD 0x524d4400 // "RMD" as uint32_t (big endian) 83 | #define FTP_CMD_LE_RNFR 0x52464e52 // "RNFR" as uint32_t (little endian) 84 | #define FTP_CMD_BE_RNFR 0x524e4652 // "RNFR" as uint32_t (big endian) 85 | #define FTP_CMD_LE_RNTO 0x4f544e52 // "RNTO" as uint32_t (little endian) 86 | #define FTP_CMD_BE_RNTO 0x524e544f // "RNTO" as uint32_t (big endian) 87 | #define FTP_CMD_LE_FEAT 0x54414546 // "FEAT" as uint32_t (little endian) 88 | #define FTP_CMD_BE_FEAT 0x46454154 // "FEAT" as uint32_t (big endian) 89 | #define FTP_CMD_LE_MDTM 0x4d54444d // "MDTM" as uint32_t (little endian) 90 | #define FTP_CMD_BE_MDTM 0x4d44544d // "MDTM" as uint32_t (big endian) 91 | #define FTP_CMD_LE_SIZE 0x455a4953 // "SIZE" as uint32_t (little endian) 92 | #define FTP_CMD_BE_SIZE 0x53495a45 // "SIZE" as uint32_t (big endian) 93 | #define FTP_CMD_LE_SITE 0x45544953 // "SITE" as uint32_t (little endian) 94 | #define FTP_CMD_BE_SITE 0x53495445 // "SITE" as uint32_t (big endian) 95 | #define FTP_CMD_LE_SYST 0x54535953 // "SYST" as uint32_t (little endian) 96 | #define FTP_CMD_BE_SYST 0x53595354 // "SYST" as uint32_t (big endian) 97 | 98 | class FTPCommon 99 | { 100 | public: 101 | // contruct an instance of the FTP Server or Client using a 102 | // given FS object, e.g. SPIFFS or LittleFS 103 | FTPCommon(FS &_FSImplementation); 104 | virtual ~FTPCommon(); 105 | 106 | // stops the FTP Server or Client, i.e. stops control and data connections 107 | virtual void stop(); 108 | 109 | // set disconnect timeout in millisecords 110 | void setTimeout(uint32_t timeoutMs = FTP_TIME_OUT * 60 * 1000); 111 | 112 | // needs to be called frequently (e.g. in loop() ) 113 | // to process ftp requests 114 | virtual void handleFTP() = 0; 115 | 116 | protected: 117 | WiFiClient control; 118 | WiFiClient data; 119 | 120 | File file; 121 | FS &THEFS; 122 | 123 | IPAddress dataIP; // IP address for PORT (active) mode 124 | uint16_t dataPort = // holds our PASV port number or the port number provided by PORT 125 | FTP_DATA_PORT_PASV; 126 | virtual int8_t dataConnect(); // connects to dataIP:dataPort, returns -1: no data connection possible, +1: data connection established 127 | bool parseDataIpPort(const char *p); 128 | 129 | uint32_t sTimeOutMs; // disconnect timeout 130 | oneShotMs aTimeout; // timeout from esp8266 core library 131 | 132 | bool doFiletoNetwork(); 133 | bool doNetworkToFile(); 134 | virtual void closeTransfer(); 135 | 136 | uint16_t allocateBuffer(uint16_t desiredBytes = BUFFERSIZE); // allocate buffer for transfer 137 | void freeBuffer(); 138 | uint8_t *fileBuffer = NULL; // pointer to buffer for file transfer (by allocateBuffer) 139 | uint16_t fileBufferSize; // size of buffer 140 | 141 | uint32_t millisBeginTrans; // store time of beginning of a transaction 142 | uint32_t bytesTransfered; // bytes transfered 143 | }; 144 | 145 | #endif // FTP_COMMON_H 146 | -------------------------------------------------------------------------------- /FTPServer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * FTP Server for ESP8266/ESP32 3 | * based on FTP Serveur for Arduino Due and Ethernet shield (W5100) or WIZ820io (W5200) 4 | * based on Jean-Michel Gallego's work 5 | * modified to work with esp8266 SPIFFS by David Paiva david@nailbuster.com 6 | * modified to work with esp8266 LitteFS by Daniel Plasa dplasa@gmail.com 7 | * Also done some code reworks and all string contants are now in flash memory 8 | * by using F(), PSTR() ... on the string literals. 9 | * 10 | * This program is free software: you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation, either version 3 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * This program is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU General Public License 21 | * along with this program. If not, see . 22 | */ 23 | 24 | #include "FTPServer.h" 25 | 26 | #ifdef ESP8266 27 | #include 28 | #elif defined ESP32 29 | #include 30 | #endif 31 | 32 | #include "FTPCommon.h" 33 | #include 34 | #include 35 | 36 | WiFiServer controlServer(FTP_CTRL_PORT); 37 | WiFiServer dataServer(FTP_DATA_PORT_PASV); 38 | 39 | // some constants 40 | static const char aSpace[] PROGMEM = " "; 41 | static const char aSlash[] PROGMEM = "/"; 42 | 43 | // constructor 44 | FTPServer::FTPServer(FS &_FSImplementation) : FTPCommon(_FSImplementation) 45 | { 46 | aTimeout.resetToNeverExpires(); 47 | } 48 | 49 | void FTPServer::begin(const String &uname, const String &pword) 50 | { 51 | _FTP_USER = uname; 52 | _FTP_PASS = pword; 53 | 54 | iniVariables(); 55 | 56 | // Tells the ftp server to begin listening for incoming connections 57 | controlServer.begin(); 58 | dataServer.begin(); 59 | } 60 | 61 | void FTPServer::stop() 62 | { 63 | abortTransfer(); 64 | disconnectClient(false); 65 | controlServer.stop(); 66 | dataServer.stop(); 67 | 68 | FTPCommon::stop(); 69 | } 70 | 71 | void FTPServer::iniVariables() 72 | { 73 | // Default Data connection is Active 74 | dataPassiveConn = true; 75 | 76 | // Set the root directory 77 | cwd = FPSTR(aSlash); 78 | 79 | // init internal status vars 80 | cmdState = cInit; 81 | transferState = tIdle; 82 | rnFrom.clear(); 83 | 84 | // reset control connection input buffer, clear previous command 85 | cmdLine.clear(); 86 | cmdString.clear(); 87 | parameters.clear(); 88 | command = 0; 89 | 90 | // free any used fileBuffer 91 | freeBuffer(); 92 | } 93 | 94 | void FTPServer::handleFTP() 95 | { 96 | // 97 | // control connection state sequence is 98 | // cInit 99 | // | 100 | // V 101 | // cWait 102 | // | 103 | // V 104 | // cCheck -----------+ 105 | // | | (no username but password set) 106 | // V | 107 | // cUserId ----------+---+ 108 | // | | | 109 | // +<--------------+ | 110 | // V | (no password set) 111 | // cPassword | 112 | // | | 113 | // +<------------------+ 114 | // V 115 | // cLoginOk 116 | // | 117 | // V 118 | // cProcess 119 | // 120 | if (cmdState == cInit) 121 | { 122 | if (control.connected()) 123 | { 124 | abortTransfer(); 125 | disconnectClient(false); 126 | } 127 | iniVariables(); 128 | cmdState = cWait; 129 | } 130 | else if (cmdState == cWait) // FTP control server waiting for connection 131 | { 132 | if (controlServer.hasClient()) 133 | { 134 | control = controlServer.available(); 135 | 136 | // wait 10s for login command 137 | aTimeout.reset(10 * 1000); 138 | cmdState = cCheck; 139 | } 140 | } 141 | 142 | else if (cmdState == cCheck) // FTP control server check/setup control connection 143 | { 144 | if (control.connected()) // A client connected, say "220 Hello client!" 145 | { 146 | FTP_DEBUG_MSG("control server got connection from %s:%d", 147 | control.remoteIP().toString().c_str(), control.remotePort()); 148 | 149 | sendMessage_P(220, PSTR("(espFTP " FTP_SERVER_VERSION ")")); 150 | 151 | if (_FTP_USER.length()) 152 | { 153 | cmdState = cUserId; 154 | } 155 | else if (_FTP_PASS.length()) 156 | { 157 | cmdState = cPassword; 158 | } 159 | else 160 | { 161 | cmdState = cLoginOk; 162 | } 163 | } 164 | } 165 | 166 | else if (cmdState == cLoginOk) // tell client "Login ok!" 167 | { 168 | sendMessage_P(230, PSTR("Login successful.")); 169 | aTimeout.reset(sTimeOutMs); 170 | cmdState = cProcess; 171 | } 172 | 173 | // 174 | // all other command states need to process commands froms control connection 175 | // 176 | else if (readChar() > 0) 177 | { 178 | // enforce USER than PASS commands before anything else except the FEAT command 179 | // that should be supported to indicate server features even before login 180 | if ((FTP_CMD(FEAT) != command) && (((cmdState == cUserId) && (FTP_CMD(USER) != command)) || 181 | ((cmdState == cPassword) && (FTP_CMD(PASS) != command)))) 182 | { 183 | sendMessage_P(530, PSTR("Please login with USER and PASS.")); 184 | FTP_DEBUG_MSG("ignoring before login: command %s [%x], params='%s'", cmdString.c_str(), command, parameters.c_str()); 185 | command = 0; 186 | return; 187 | } 188 | 189 | // process the command 190 | int8_t rc = processCommand(); 191 | // returns 192 | // -1 : command processing indicates, we have to close control (e.g. QUIT) 193 | // 0 : not yet finished, just call processCommend() again 194 | // 1 : finished 195 | if (rc < 0) 196 | { 197 | cmdState = cInit; 198 | } 199 | if (rc > 0) 200 | { 201 | // clear current command, so readChar() can fetch the next command 202 | command = 0; 203 | 204 | // command was successful, update command state 205 | if (cmdState == cUserId) 206 | { 207 | if (_FTP_PASS.length()) 208 | { 209 | // wait 10s for PASS command 210 | aTimeout.reset(10 * 1000); 211 | sendMessage_P(331, PSTR("Please specify the password.")); 212 | cmdState = cPassword; 213 | } 214 | else 215 | { 216 | cmdState = cLoginOk; 217 | } 218 | } 219 | else if (cmdState == cPassword) 220 | { 221 | cmdState = cLoginOk; 222 | } 223 | else 224 | { 225 | aTimeout.reset(sTimeOutMs); 226 | } 227 | } 228 | } 229 | 230 | // 231 | // general connection handling 232 | // (if we have an established control connection) 233 | // 234 | if (cmdState >= cCheck) 235 | { 236 | // detect lost/closed by remote connections 237 | if (!control.connected() || !control) 238 | { 239 | cmdState = cInit; 240 | FTP_DEBUG_MSG("client lost or disconnected"); 241 | } 242 | 243 | // check for timeout 244 | if (aTimeout.expired()) 245 | { 246 | sendMessage_P(530, PSTR("Timeout.")); 247 | cmdState = cInit; 248 | } 249 | 250 | // handle data file transfer 251 | if (transferState == tRetrieve) // Retrieve data 252 | { 253 | if (!doFiletoNetwork()) 254 | { 255 | closeTransfer(); 256 | transferState = tIdle; 257 | } 258 | } 259 | else if (transferState == tStore) // Store data 260 | { 261 | if (!doNetworkToFile()) 262 | { 263 | closeTransfer(); 264 | transferState = tIdle; 265 | } 266 | } 267 | } 268 | } 269 | 270 | void FTPServer::disconnectClient(bool gracious) 271 | { 272 | FTP_DEBUG_MSG("Disconnecting client"); 273 | abortTransfer(); 274 | if (gracious) 275 | { 276 | sendMessage_P(221, PSTR("Goodbye.")); 277 | } 278 | else 279 | { 280 | sendMessage_P(231, PSTR("Service terminated.")); 281 | } 282 | control.stop(); 283 | } 284 | 285 | int8_t FTPServer::processCommand() 286 | { 287 | // assume successful operation by default 288 | int8_t rc = 1; 289 | 290 | // make the full path of parameters (even if this makes no sense for all commands) 291 | String path = getFileName(parameters, true); 292 | FTP_DEBUG_MSG("processing: command %s [%x], params='%s' (cwd='%s')", cmdString.c_str(), command, parameters.c_str(), cwd.c_str()); 293 | 294 | /////////////////////////////////////// 295 | // // 296 | // ACCESS CONTROL COMMANDS // 297 | // // 298 | /////////////////////////////////////// 299 | 300 | // 301 | // USER - Provide username 302 | // 303 | if (FTP_CMD(USER) == command) 304 | { 305 | if (_FTP_USER.length() && (_FTP_USER != parameters)) 306 | { 307 | sendMessage_P(430, PSTR("User not found.")); 308 | command = 0; 309 | rc = 0; 310 | } 311 | else 312 | { 313 | FTP_DEBUG_MSG("USER ok"); 314 | } 315 | } 316 | 317 | // 318 | // PASS - Provide password 319 | // 320 | else if (FTP_CMD(PASS) == command) 321 | { 322 | if (_FTP_PASS.length() && (_FTP_PASS != parameters)) 323 | { 324 | sendMessage_P(430, PSTR("Password invalid.")); 325 | command = 0; 326 | rc = 0; 327 | } 328 | else 329 | { 330 | FTP_DEBUG_MSG("PASS ok"); 331 | } 332 | } 333 | 334 | // 335 | // QUIT 336 | // 337 | else if (FTP_CMD(QUIT) == command) 338 | { 339 | disconnectClient(); 340 | rc = -1; 341 | } 342 | 343 | // 344 | // NOOP 345 | // 346 | else if (FTP_CMD(NOOP) == command) 347 | { 348 | sendMessage_P(200, PSTR("Zzz...")); 349 | } 350 | 351 | // 352 | // CDUP - Change to Parent Directory 353 | // 354 | else if (FTP_CMD(CDUP) == command) 355 | { 356 | // up one level 357 | cwd = getPathName("", false); 358 | sendMessage_P(250, PSTR("Directory successfully changed to \"%s\"."), cwd.c_str()); 359 | } 360 | 361 | // 362 | // CWD - Change Working Directory 363 | // 364 | else if (FTP_CMD(CWD) == command) 365 | { 366 | if (parameters == F(".")) // 'CWD .' is the same as PWD command 367 | { 368 | command = FTP_CMD(PWD); // make CWD a PWD command ;-) 369 | rc = 0; // indicate we need another processCommand() call 370 | } 371 | else if (parameters == F("..")) // 'CWD ..' is the same as CDUP command 372 | { 373 | command = FTP_CMD(CDUP); // make CWD a CDUP command ;-) 374 | rc = 0; // indicate we need another processCommand() call 375 | } 376 | else 377 | { 378 | #if (defined esp8266FTPServer_SPIFFS) 379 | // SPIFFS has no directories, it's always ok 380 | cwd = path; 381 | sendMessage_P(250, PSTR("Directory successfully changed.")); 382 | #else 383 | // check if directory exists 384 | file = THEFS.open(path, "r"); 385 | if (file.isDirectory()) 386 | { 387 | cwd = path; 388 | sendMessage_P(250, PSTR("Directory successfully changed.")); 389 | } 390 | else 391 | { 392 | sendMessage_P(550, PSTR("Failed to change directory.")); 393 | } 394 | file.close(); 395 | #endif 396 | } 397 | } 398 | 399 | // 400 | // PWD - Print Directory 401 | // 402 | else if (FTP_CMD(PWD) == command) 403 | { 404 | sendMessage_P(257, PSTR("\"%s\" is the current directory."), cwd.c_str()); 405 | } 406 | 407 | /////////////////////////////////////// 408 | // // 409 | // TRANSFER PARAMETER COMMANDS // 410 | // // 411 | /////////////////////////////////////// 412 | 413 | // 414 | // MODE - Transfer Mode 415 | // 416 | else if (FTP_CMD(MODE) == command) 417 | { 418 | if (parameters == F("S")) 419 | sendMessage_P(504, PSTR("Only S(tream) mode is suported")); 420 | else 421 | sendMessage_P(200, PSTR("Mode set to S.")); 422 | } 423 | 424 | // 425 | // PASV - Passive data connection management 426 | // 427 | else if (FTP_CMD(PASV) == command) 428 | { 429 | // stop a possible previous data connection 430 | data.stop(); 431 | // tell client to open data connection to our ip:dataPort 432 | dataPort = FTP_DATA_PORT_PASV; 433 | dataPassiveConn = true; 434 | String ip = control.localIP().toString(); 435 | ip.replace(".", ","); 436 | sendMessage_P(227, PSTR("Entering Passive Mode (%s,%d,%d)."), ip.c_str(), dataPort >> 8, dataPort & 255); 437 | //sendMessage_P(227, PSTR("Entering Passive Mode (0,0,0,0,%d,%d)."), dataPort >> 8, dataPort & 255); 438 | } 439 | 440 | // 441 | // PORT - Data Port, Active data connection management 442 | // 443 | else if (FTP_CMD(PORT) == command) 444 | { 445 | if (data) 446 | data.stop(); 447 | 448 | if (parseDataIpPort(parameters.c_str())) 449 | { 450 | dataPassiveConn = false; 451 | sendMessage_P(200, PSTR("PORT command successful")); 452 | FTP_DEBUG_MSG("Data connection management Active, using %s:%u", dataIP.toString().c_str(), dataPort); 453 | } 454 | else 455 | { 456 | sendMessage_P(501, PSTR("Cannot interpret parameters.")); 457 | } 458 | } 459 | 460 | // 461 | // STRU - File Structure 462 | // 463 | else if (FTP_CMD(STRU) == command) 464 | { 465 | if (parameters == F("F")) 466 | sendMessage_P(504, PSTR("Only F(ile) is suported")); 467 | else 468 | sendMessage_P(200, PSTR("Structure set to F.")); 469 | } 470 | 471 | // 472 | // TYPE - Data Type 473 | // 474 | else if (FTP_CMD(TYPE) == command) 475 | { 476 | if (parameters == F("A")) 477 | sendMessage_P(200, PSTR("TYPE is now ASII.")); 478 | else if (parameters == F("I")) 479 | sendMessage_P(200, PSTR("TYPE is now 8-bit Binary.")); 480 | else 481 | sendMessage_P(504, PSTR("Unrecognised TYPE.")); 482 | } 483 | 484 | /////////////////////////////////////// 485 | // // 486 | // FTP SERVICE COMMANDS // 487 | // // 488 | /////////////////////////////////////// 489 | 490 | // 491 | // ABOR - Abort 492 | // 493 | else if (FTP_CMD(ABOR) == command) 494 | { 495 | abortTransfer(); 496 | sendMessage_P(226, PSTR("Data connection closed")); 497 | } 498 | 499 | // 500 | // DELE - Delete a File 501 | // 502 | else if (FTP_CMD(DELE) == command) 503 | { 504 | if (parameters.length() == 0) 505 | sendMessage_P(501, PSTR("No file name")); 506 | else 507 | { 508 | if (!THEFS.exists(path)) 509 | { 510 | sendMessage_P(550, PSTR("Delete operation failed, file '%s' not found."), path.c_str()); 511 | } 512 | else if (THEFS.remove(path)) 513 | { 514 | sendMessage_P(250, PSTR("Delete operation successful.")); 515 | } 516 | else 517 | { 518 | sendMessage_P(450, PSTR("Delete operation failed.")); 519 | } 520 | } 521 | } 522 | 523 | // 524 | // LIST - List directory contents 525 | // MLSD - Listing for Machine Processing (see RFC 3659) 526 | // NLST - Name List 527 | // 528 | else if ((FTP_CMD(LIST) == command) || (FTP_CMD(MLSD) == command) || (FTP_CMD(NLST) == command)) 529 | { 530 | rc = dataConnect(); // returns -1: no data connection, 0: need more time, 1: data ok 531 | if (rc < 0) 532 | { 533 | sendMessage_P(425, PSTR("No data connection")); 534 | rc = 1; // mark command as processed 535 | } 536 | else if (rc > 0) 537 | { 538 | sendMessage_P(150, PSTR("Accepted data connection")); 539 | uint16_t dirCount = 0; 540 | 541 | // filter out possible command parameters like "-a", given by some clients 542 | // like FuseFS 543 | int8_t dashPos = path.lastIndexOf(F("-")); 544 | if (dashPos > 0) 545 | { 546 | path.remove(dashPos); 547 | } 548 | FTP_DEBUG_MSG("Listing content of '%s'", path.c_str()); 549 | #if (defined ESP8266) 550 | Dir dir = THEFS.openDir(path); 551 | while (dir.next()) 552 | { 553 | file = dir.openFile("r"); 554 | #elif (defined ESP32) 555 | File dir = THEFS.open(path); 556 | file = dir.openNextFile(); 557 | while (file) 558 | { 559 | #endif 560 | bool isDir = file.isDirectory(); 561 | String fn = file.name(); 562 | uint32_t fs = file.size(); 563 | String fileTime = makeDateTimeStr(file.getLastWrite()); 564 | file.close(); 565 | dashPos = fn.lastIndexOf(F("/")); 566 | if (dashPos >= 0) 567 | { 568 | fn.remove(0, dashPos + 1); 569 | } 570 | 571 | if (FTP_CMD(LIST) == command) 572 | { 573 | // unixperms type userid groupid size time & date name 574 | // drwxrwsr-x 2 111 117 4096 Apr 01 12:45 aDirectory 575 | // -rw-rw-r-- 1 111 117 875315 Mar 23 17:29 aFile 576 | data.printf_P(PSTR("%crw%cr-%cr-%c %c 0 0 %8" PRINTu32 " %s %s\r\n"), 577 | isDir ? 'd' : '-', 578 | isDir ? 'x' : '-', 579 | isDir ? 'x' : '-', 580 | isDir ? 'x' : '-', 581 | isDir ? '2' : '1', 582 | isDir ? 0 : fs, 583 | fileTime.c_str(), 584 | fn.c_str()); 585 | //data.printf_P(PSTR("+r,s%lu\r\n,\t%s\r\n"), (uint32_t)dir.fileSize(), fn.c_str()); 586 | } 587 | else if (FTP_CMD(MLSD) == command) 588 | { 589 | // "modify=20170122163911;type=dir;UNIX.group=0;UNIX.mode=0775;UNIX.owner=0; dirname" 590 | // "modify=20170121000817;size=12;type=file;UNIX.group=0;UNIX.mode=0644;UNIX.owner=0; filename" 591 | data.printf_P(PSTR("modify=%s;UNIX.group=0;UNIX.owner=0;UNIX.mode="), fileTime.c_str()); 592 | if (isDir) 593 | { 594 | data.printf_P(PSTR("0755;type=dir; ")); 595 | } 596 | else 597 | { 598 | data.printf_P(PSTR("0644;size=%" PRINTu32 ";type=file; "), fs); 599 | } 600 | data.printf_P(PSTR("%s\r\n"), fn.c_str()); 601 | } 602 | else if (FTP_CMD(NLST) == command) 603 | { 604 | data.println(fn); 605 | } 606 | ++dirCount; 607 | #if (defined ESP32) 608 | file = dir.openNextFile(); 609 | #endif 610 | } 611 | 612 | if (FTP_CMD(MLSD) == command) 613 | { 614 | control.println(F("226-options: -a -l\r\n")); 615 | } 616 | sendMessage_P(226, PSTR("%d matches total"), dirCount); 617 | } 618 | data.stop(); 619 | } 620 | 621 | // 622 | // RETR - Retrieve 623 | // 624 | else if (FTP_CMD(RETR) == command) 625 | { 626 | if (parameters.length() == 0) 627 | { 628 | sendMessage_P(501, PSTR("No file name")); 629 | } 630 | else 631 | { 632 | // open the file if not opened before (when re-running processCommand() since data connetion needs time) 633 | if (!file) 634 | file = THEFS.open(path, "r"); 635 | if (!file) 636 | { 637 | sendMessage_P(550, PSTR("File \"%s\" not found."), parameters.c_str()); 638 | } 639 | else if (file.isDirectory()) 640 | { 641 | sendMessage_P(450, PSTR("Cannot open file \"%s\"."), parameters.c_str()); 642 | } 643 | else 644 | { 645 | rc = dataConnect(); // returns -1: no data connection, 0: need more time, 1: data ok 646 | if (rc < 0) 647 | { 648 | sendMessage_P(425, PSTR("No data connection")); 649 | rc = 1; // mark command as processed 650 | } 651 | else if (rc > 0) 652 | { 653 | transferState = tRetrieve; 654 | millisBeginTrans = millis(); 655 | bytesTransfered = 0; 656 | uint32_t fs = file.size(); 657 | if (allocateBuffer()) 658 | { 659 | FTP_DEBUG_MSG("Sending file '%s' (%lu bytes)", path.c_str(), fs); 660 | sendMessage_P(150, PSTR("%lu bytes to download"), fs); 661 | } 662 | else 663 | { 664 | closeTransfer(); 665 | sendMessage_P(451, PSTR("Internal error. Not enough memory.")); 666 | } 667 | } 668 | } 669 | } 670 | } 671 | 672 | // 673 | // STOR - Store 674 | // 675 | else if (FTP_CMD(STOR) == command) 676 | { 677 | if (parameters.length() == 0) 678 | { 679 | sendMessage_P(501, PSTR("No file name.")); 680 | } 681 | else 682 | { 683 | FTP_DEBUG_MSG("STOR '%s'", path.c_str()); 684 | if (!file) 685 | { 686 | file = THEFS.open(path, "w"); // open file, truncate it if already exists 687 | file.close(); // this performs a sync on LittleFS so that the actual 688 | // space used by the file in FS gets released 689 | file = THEFS.open(path, "w"); // re-open file for writing 690 | } 691 | if (!file) 692 | { 693 | sendMessage_P(451, PSTR("Cannot open/create \"%s\""), path.c_str()); 694 | } 695 | else 696 | { 697 | rc = dataConnect(); // returns -1: no data connection, 0: need more time, 1: data ok 698 | if (rc < 0) 699 | { 700 | sendMessage_P(425, PSTR("No data connection")); 701 | file.close(); 702 | rc = 1; // mark command as processed 703 | } 704 | else if (rc > 0) 705 | { 706 | transferState = tStore; 707 | millisBeginTrans = millis(); 708 | bytesTransfered = 0; 709 | if (allocateBuffer()) 710 | { 711 | FTP_DEBUG_MSG("Receiving file '%s' => %s", parameters.c_str(), path.c_str()); 712 | sendMessage_P(150, PSTR("Connected to port %d"), dataPort); 713 | } 714 | else 715 | { 716 | closeTransfer(); 717 | sendMessage_P(451, PSTR("Internal error. Not enough memory.")); 718 | } 719 | } 720 | } 721 | } 722 | } 723 | 724 | // 725 | // MKD - Make Directory 726 | // 727 | else if (FTP_CMD(MKD) == command) 728 | { 729 | #if (defined esp8266FTPServer_SPIFFS) 730 | sendMessage_P(550, "Create directory operation failed."); //not support on SPIFFS 731 | #else 732 | FTP_DEBUG_MSG("mkdir(%s)", path.c_str()); 733 | if (THEFS.mkdir(path)) 734 | { 735 | sendMessage_P(257, PSTR("\"%s\" created."), path.c_str()); 736 | } 737 | else 738 | { 739 | sendMessage_P(550, PSTR("Create directory operation failed.")); 740 | } 741 | #endif 742 | } 743 | 744 | // 745 | // RMD - Remove a Directory 746 | // 747 | else if (FTP_CMD(RMD) == command) 748 | { 749 | #if (defined esp8266FTPServer_SPIFFS) 750 | sendMessage_P(550, "Remove directory operation failed."); //not support on SPIFFS 751 | #else 752 | // check directory for files 753 | #if (defined ESP8266) 754 | Dir dir = THEFS.openDir(path); 755 | if (dir.next()) 756 | { 757 | #elif (defined ESP32) 758 | File dir = THEFS.open(path); 759 | file = dir.openNextFile(); 760 | if (file) 761 | { 762 | file.close(); 763 | #endif 764 | //only delete if dir is empty! 765 | sendMessage_P(550, PSTR("Remove directory operation failed, directory is not empty.")); 766 | } 767 | else 768 | { 769 | THEFS.rmdir(path); 770 | sendMessage_P(250, PSTR("Remove directory operation successful.")); 771 | } 772 | #endif 773 | } 774 | // 775 | // RNFR - Rename From 776 | // 777 | else if (FTP_CMD(RNFR) == command) 778 | { 779 | if (parameters.length() == 0) 780 | sendMessage_P(501, PSTR("No file name")); 781 | else 782 | { 783 | if (!THEFS.exists(path)) 784 | sendMessage_P(550, PSTR("File \"%s\" not found."), path.c_str()); 785 | else 786 | { 787 | sendMessage_P(350, PSTR("RNFR accepted - file \"%s\" exists, ready for destination"), path.c_str()); 788 | rnFrom = path; 789 | } 790 | } 791 | } 792 | // 793 | // RNTO - Rename To 794 | // 795 | else if (FTP_CMD(RNTO) == command) 796 | { 797 | if (rnFrom.length() == 0) 798 | sendMessage_P(503, PSTR("Need RNFR before RNTO")); 799 | else if (parameters.length() == 0) 800 | sendMessage_P(501, PSTR("No file name")); 801 | else if (THEFS.exists(path)) 802 | sendMessage_P(553, PSTR("\"%s\" already exists."), parameters.c_str()); 803 | else 804 | { 805 | FTP_DEBUG_MSG("Renaming '%s' to '%s'", rnFrom.c_str(), path.c_str()); 806 | if (THEFS.rename(rnFrom, path)) 807 | sendMessage_P(250, PSTR("File successfully renamed or moved")); 808 | else 809 | sendMessage_P(451, PSTR("Rename/move failure.")); 810 | } 811 | rnFrom.clear(); 812 | } 813 | 814 | /////////////////////////////////////// 815 | // // 816 | // EXTENSIONS COMMANDS (RFC 3659) // 817 | // // 818 | /////////////////////////////////////// 819 | 820 | // 821 | // FEAT - New Features 822 | // 823 | else if (FTP_CMD(FEAT) == command) 824 | { 825 | control.print(F("211-Features:\r\n MLSD\r\n MDTM\r\n SITE\r\n SIZE\r\n211 End.\r\n")); 826 | command = 0; // clear command code and 827 | rc = 0; // return 0 to prevent progression of state machine in case FEAT was a command before login 828 | } 829 | 830 | // 831 | // MDTM - File Modification Time (see RFC 3659) 832 | // 833 | else if (FTP_CMD(MDTM) == command) 834 | { 835 | file = THEFS.open(path, "r"); 836 | if ((!file) || (0 == parameters.length())) 837 | { 838 | sendMessage_P(550, PSTR("Unable to retrieve time")); 839 | } 840 | else 841 | { 842 | sendMessage_P(213, PSTR("%s"), makeDateTimeStr(file.getLastWrite()).c_str()); 843 | } 844 | file.close(); 845 | } 846 | 847 | // 848 | // SIZE - Size of the file 849 | // 850 | else if (FTP_CMD(SIZE) == command) 851 | { 852 | file = THEFS.open(path, "r"); 853 | if ((!file) || (0 == parameters.length())) 854 | { 855 | sendMessage_P(450, PSTR("Cannot open file.")); 856 | } 857 | else 858 | { 859 | sendMessage_P(213, PSTR("%lu"), (uint32_t)file.size()); 860 | } 861 | file.close(); 862 | } 863 | 864 | // 865 | // SITE - System command 866 | // 867 | else if (FTP_CMD(SITE) == command) 868 | { 869 | sendMessage_P(550, PSTR("SITE %s command not implemented."), parameters.c_str()); 870 | } 871 | 872 | // 873 | // SYST - System information 874 | // 875 | else if (FTP_CMD(SYST) == command) 876 | { 877 | sendMessage_P(215, PSTR("UNIX Type: L8")); 878 | } 879 | 880 | // 881 | // Unrecognized commands ... 882 | // 883 | else 884 | { 885 | FTP_DEBUG_MSG("Unknown command: %s, params: '%s')", cmdString.c_str(), parameters.c_str()); 886 | sendMessage_P(500, PSTR("unknown command \"%s\""), cmdString.c_str()); 887 | } 888 | 889 | return rc; 890 | } 891 | 892 | int8_t FTPServer::dataConnect() 893 | { 894 | int8_t rc = 1; // assume success 895 | 896 | if (!dataPassiveConn) 897 | { 898 | // active mode 899 | // open our own data connection 900 | return FTPCommon::dataConnect(); 901 | } 902 | else 903 | { 904 | // passive mode 905 | // wait for data connection from the client 906 | if (!data.connected()) 907 | { 908 | if (dataServer.hasClient()) 909 | { 910 | data.stop(); 911 | data = dataServer.available(); 912 | FTP_DEBUG_MSG("Got incoming (passive) data connection from %s:%u", data.remoteIP().toString().c_str(), data.remotePort()); 913 | } 914 | else 915 | { 916 | // give me more time waiting for a data connection 917 | rc = 0; 918 | } 919 | } 920 | } 921 | return rc; 922 | } 923 | 924 | void FTPServer::closeTransfer() 925 | { 926 | uint32_t deltaT = (int32_t)(millis() - millisBeginTrans); 927 | if (deltaT > 0 && bytesTransfered > 0) 928 | { 929 | sendMessage_P(226, PSTR("File successfully transferred, %lu ms, %f kB/s."), deltaT, float(bytesTransfered) / deltaT); 930 | } 931 | else 932 | sendMessage_P(226, PSTR("File successfully transferred")); 933 | 934 | FTPCommon::closeTransfer(); 935 | } 936 | 937 | void FTPServer::abortTransfer() 938 | { 939 | if (transferState > tIdle) 940 | { 941 | file.close(); 942 | data.stop(); 943 | sendMessage_P(426, PSTR("Transfer aborted")); 944 | } 945 | freeBuffer(); 946 | transferState = tIdle; 947 | } 948 | 949 | // Read a char from client connected to ftp server 950 | // 951 | // returns: 952 | // -1 if cmdLine too long 953 | // 0 cmdLine still incomplete (no \r or \n received yet) 954 | // 1 cmdLine processed, command and parameters available 955 | 956 | int8_t FTPServer::readChar() 957 | { 958 | // only read/parse, if the previous command has been fully processed! 959 | if (command) 960 | return 1; 961 | 962 | while (control.available()) 963 | { 964 | char c = control.read(); 965 | // FTP_DEBUG_MSG("readChar() cmdLine='%s' <= %c", cmdLine.c_str(), c); 966 | 967 | // substitute '\' with '/' 968 | if (c == '\\') 969 | c = '/'; 970 | 971 | // nl detected? then process line 972 | if (c == '\n' || c == '\r') 973 | { 974 | cmdLine.trim(); 975 | 976 | // but only if we got at least chars in the line! 977 | if (0 == cmdLine.length()) 978 | break; 979 | 980 | // search for space between command and parameters 981 | int pos = cmdLine.indexOf(FPSTR(aSpace)); 982 | if (pos > 0) 983 | { 984 | parameters = cmdLine.substring(pos + 1); 985 | parameters.trim(); 986 | cmdLine.remove(pos); 987 | } 988 | else 989 | { 990 | parameters.remove(0); 991 | } 992 | cmdString = cmdLine; 993 | 994 | // convert command to upper case 995 | cmdString.toUpperCase(); 996 | 997 | // convert the (up to 4 command chars to numerical value) 998 | command = *(const uint32_t *)cmdString.c_str(); 999 | 1000 | // clear cmdline 1001 | cmdLine.clear(); 1002 | // FTP_DEBUG_MSG("readChar() success, cmdString='%s' [%x], params='%s'", cmdString.c_str(), command, parameters.c_str()); 1003 | return 1; 1004 | } 1005 | else 1006 | { 1007 | // just add char 1008 | cmdLine += c; 1009 | if (cmdLine.length() > FTP_CMD_SIZE) 1010 | { 1011 | cmdLine.clear(); 1012 | sendMessage_P(500, PSTR("Line too long")); 1013 | } 1014 | } 1015 | } 1016 | return 0; 1017 | } 1018 | 1019 | // Get the complete path from cwd + parameters or complete filename from cwd + parameters 1020 | // 1021 | // 3 possible cases: parameters can be absolute path, relative path or only the name 1022 | // 1023 | // returns: 1024 | // path WITHOUT file-/dirname (fullname=false) 1025 | // full path WITH file-/dirname (fullname=true) 1026 | String FTPServer::getPathName(const String ¶m, bool fullname) 1027 | { 1028 | String tmp; 1029 | 1030 | // is param an absoulte path? 1031 | if (param[0] == '/') 1032 | { 1033 | tmp = param; 1034 | } 1035 | else 1036 | { 1037 | // start with cwd 1038 | tmp = cwd; 1039 | 1040 | // if param != "" then add param 1041 | if (param.length()) 1042 | { 1043 | if (!tmp.endsWith(FPSTR(aSlash))) 1044 | tmp += '/'; 1045 | tmp += param; 1046 | } 1047 | // => tmp becomes cdw [ + '/' + param ] 1048 | } 1049 | 1050 | // strip filename 1051 | if (!fullname) 1052 | { 1053 | // search rightmost '/' 1054 | int lastslash = tmp.lastIndexOf(FPSTR(aSlash)); 1055 | if (lastslash >= 0) 1056 | { 1057 | tmp.remove(lastslash); 1058 | } 1059 | } 1060 | // sanetize: 1061 | // "" -> "/" 1062 | // "/some/path/" => "/some/path" 1063 | while (tmp.length() > 1 && tmp.endsWith(FPSTR(aSlash))) 1064 | tmp.remove(cwd.length() - 1); 1065 | if (tmp.length() == 0) 1066 | tmp += '/'; 1067 | return tmp; 1068 | } 1069 | 1070 | // Get the [complete] file name from cwd + parameters 1071 | // 1072 | // 3 possible cases: parameters can be absolute path, relative path or only the filename 1073 | // 1074 | // returns: 1075 | // filename or filename with complete path 1076 | String FTPServer::getFileName(const String ¶m, bool fullFilePath) 1077 | { 1078 | // build the filename with full path 1079 | String tmp = getPathName(param, true); 1080 | 1081 | if (!fullFilePath) 1082 | { 1083 | // strip path 1084 | // search rightmost '/' 1085 | int lastslash = tmp.lastIndexOf(FPSTR(aSlash)); 1086 | if (lastslash > 0) 1087 | { 1088 | tmp.remove(0, lastslash); 1089 | } 1090 | } 1091 | 1092 | return tmp; 1093 | } 1094 | 1095 | // 1096 | // Formats printable String from a time_t timestamp 1097 | // 1098 | String FTPServer::makeDateTimeStr(time_t ft) 1099 | { 1100 | String tmp; 1101 | // a buffer with enough space for the formats 1102 | char buf[25]; 1103 | char *b = buf; 1104 | 1105 | // break down the provided file time 1106 | struct tm _tm; 1107 | gmtime_r(&ft, &_tm); 1108 | 1109 | if (FTP_CMD(MLSD) == command) 1110 | { 1111 | // "%Y%m%d%H%M%S", e.g. "20200517123400" 1112 | strftime(b, sizeof(buf), "%Y%m%d%H%M%S", &_tm); 1113 | } 1114 | else if (FTP_CMD(LIST) == command) 1115 | { 1116 | // "%h %d %H:%M", e.g. "May 17 12:34" for file dates of the current year 1117 | // "%h %d %Y" , e.g. "May 17 2019" for file dates of any other years 1118 | 1119 | // just convert both ways, select later what's to be shown 1120 | // buf becomes "May 17 2019May 17 12:34" 1121 | strftime(b, sizeof(buf), "%h %d %H:%M%h %d %Y", &_tm); 1122 | 1123 | // check for a year != year from now 1124 | int fileYear = _tm.tm_year; 1125 | time_t nowTime = time(NULL); 1126 | gmtime_r(&nowTime, &_tm); 1127 | if (fileYear == _tm.tm_year) 1128 | { 1129 | // cut off 2nd half - year variant 1130 | b[12] = '\0'; 1131 | } 1132 | else 1133 | { 1134 | // skip 1st half - time variant 1135 | b += 12; 1136 | } 1137 | } 1138 | tmp = b; 1139 | return tmp; 1140 | } 1141 | 1142 | // 1143 | // send "code formatted string" + CR-LF 1144 | // 1145 | void FTPServer::sendMessage_P(int16_t code, PGM_P fmt, ...) 1146 | { 1147 | FTP_DEBUG_MSG(">>> %d %s", code, fmt); 1148 | 1149 | int size = 0; 1150 | char *p = NULL; 1151 | va_list ap; 1152 | 1153 | /* Determine required size for a string buffer */ 1154 | va_start(ap, fmt); 1155 | size = vsnprintf(p, size, fmt, ap); 1156 | va_end(ap); 1157 | 1158 | if (size > 0) 1159 | { 1160 | p = (char *)malloc(++size); // increase +1 for '\0' 1161 | if (p) 1162 | { 1163 | va_start(ap, fmt); 1164 | size = vsnprintf(p, size, fmt, ap); 1165 | va_end(ap); 1166 | 1167 | if (size > 0) 1168 | { 1169 | control.printf_P(PSTR("%d %s\r\n"), code, p); 1170 | } 1171 | free(p); 1172 | } 1173 | } 1174 | } 1175 | -------------------------------------------------------------------------------- /FTPServer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * FTP SERVER FOR ESP8266/ESP32 3 | * based on FTP Serveur for Arduino Due and Ethernet shield (W5100) or WIZ820io (W5200) 4 | * based on Jean-Michel Gallego's work 5 | * modified to work with esp8266 SPIFFS by David Paiva (david@nailbuster.com) 6 | * modified to work with esp8266 LitteFS by Daniel Plasa dplasa@gmail.com 7 | * Also done some code reworks and all string contants are now in flash memory 8 | * by using F(), PSTR() ... on the string literals. 9 | * 10 | * This program is free software: you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation, either version 3 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * This program is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU General Public License 21 | * along with this program. If not, see . 22 | */ 23 | 24 | #ifndef FTP_SERVER_H 25 | #define FTP_SERVER_H 26 | 27 | /******************************************************************************* 28 | ** ** 29 | ** DEFINITIONS FOR FTP SERVER/CLIENT ** 30 | ** ** 31 | *******************************************************************************/ 32 | #include "FTPCommon.h" 33 | 34 | class FTPServer : public FTPCommon 35 | { 36 | public: 37 | // contruct an instance of the FTP server using a 38 | // given FS object, e.g. SPIFFS or LittleFS 39 | FTPServer(FS &_FSImplementation); 40 | 41 | // starts the FTP server with username and password, 42 | // either one can be empty to enable anonymous ftp 43 | void begin(const String &uname, const String &pword); 44 | 45 | // stops the FTP server 46 | void stop(); 47 | 48 | // needs to be called frequently (e.g. in loop() ) 49 | // to process ftp requests 50 | void handleFTP(); 51 | 52 | private: 53 | enum internalState 54 | { 55 | cInit = 0, 56 | cWait, 57 | cCheck, 58 | cUserId, 59 | cPassword, 60 | cLoginOk, 61 | cProcess, 62 | 63 | tIdle, 64 | tRetrieve, 65 | tStore 66 | }; 67 | 68 | void iniVariables(); 69 | void disconnectClient(bool gracious = true); 70 | int8_t processCommand(); 71 | virtual void closeTransfer(); 72 | void abortTransfer(); 73 | 74 | virtual int8_t dataConnect(); 75 | 76 | void sendMessage_P(int16_t code, PGM_P fmt, ...); 77 | String getPathName(const String ¶m, bool includeLast = false); 78 | String getFileName(const String ¶m, bool fullFilePath = false); 79 | String makeDateTimeStr(time_t fileTime); 80 | int8_t readChar(); 81 | 82 | // server specific 83 | bool dataPassiveConn = true; // PASV (passive) mode is our default 84 | String _FTP_USER; // usename 85 | String _FTP_PASS; // password 86 | uint32_t command; // numeric command code of command sent by the client 87 | String cmdLine; // command line as read from client 88 | String cmdString; // command as textual representation 89 | String parameters; // parameters sent by client 90 | String cwd; // the current directory 91 | String rnFrom; // previous command was RNFR, this is the source file name 92 | 93 | internalState cmdState, // state of ftp control connection 94 | transferState; // state of ftp data connection 95 | }; 96 | 97 | #endif // FTP_SERVER_H 98 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | (This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.) 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | {description} 474 | Copyright (C) {year} {fullname} 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | {signature of Ty Coon}, 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FTPServer and FTPClient 2 | Simple FTP Server and Client for the esp8266/esp32 with SPIFFS and LittleFS support. 3 | 4 | I've modified a FTP Server from arduino/wifi shield to work with the esp8266 and the esp32. This allows you to FTP into your esp8266/esp32 and access/modify files and directories on the FS. SPIFFS's approach to directories is somewhat limited (everything is a file albeit it's name may contain '/'-es). LittleFS (which is not yet available for the esp32) however has full directory support. 5 | So with a FTP Server working on SPIFFS there will be no create/modify directory support but with LittleFS there is! 6 | The code ist tested it with command line ftp and Filezilla. 7 | 8 | The FTP Client is pretty much straight forward. It can upload (put, STOR) a file to a FTP Server or download (get, RETR) a file from a FTP Server. Both ways can be done blocking or non-blocking. 9 | 10 | ## Features 11 | * Server supports both active and passive mode 12 | * Client uses passive mode 13 | * Client/Server both support LittleFS and SPIFFS 14 | * Server (fully) supports directories with LittleFS 15 | * Client supports directories with either filesystem 16 | since both FS will just auto-create missing Directories 17 | when accessing files. 18 | 19 | ## Limitations 20 | * Server only allows **one** ftp control and **one** data connection at a time. You need to setup Filezilla (or other clients) to respect that, i.e. only allow **1** connection. (In FileZilla go to File/Site Manager then select your site. In Transfer Settings, check "Limit number of simultaneous connections" and set the maximum to 1.) This limitation is also the reason why FuseFS based clients (e.g. curlftpfs) seem to work (i.e. listing directories) but will fail on file operations as they try to open a second control connection for that. 21 | 22 | * It does not yet support encryption 23 | 24 | ## Compatibility 25 | This library was tested against the 2.7.1 version of the esp8266 Arduino core library and the 1.0.4 version of the esp32 Arduino core. 26 | 27 | ## Server Usage 28 | 29 | ### Construct an FTPServer 30 | Select the desired FS via the contructor 31 | ```cpp 32 | #include 33 | #include 34 | 35 | FTPServer ftpSrv(LittleFS); // construct with LittleFS 36 | // or 37 | FTPServer ftpSrv(SPIFFS); // construct with SPIFFS if you need to for backward compatibility 38 | ``` 39 | 40 | ### Set username/password 41 | ```cpp 42 | ftpSrv.begin("username", "password"); 43 | ``` 44 | 45 | ### Handle by calling frequently 46 | ```cpp 47 | ftpSrv.handleFTP(); // place this in e.g. loop() 48 | ``` 49 | 50 | ## Client Usage 51 | 52 | ### Construct an FTPClient 53 | Select the desired FS via the contructor 54 | ```cpp 55 | #include 56 | #include 57 | 58 | FTPClient ftpClient(LittleFS); // construct with LittleFS 59 | // or 60 | FTPClient ftpClient(SPIFFS); // construct with SPIFFS if you need to for backward compatibility 61 | ``` 62 | 63 | ### Provide username, password, server, port... 64 | ```cpp 65 | // struct ServerInfo 66 | // { 67 | // String login; 68 | // String password; 69 | // String servername; 70 | // uint16_t port; 71 | // }; 72 | 73 | ServerInfo ftpServerInfo ("username", "password", "server_name_or_ip", 21); 74 | ftpClient.begin(ftpServerInfo); 75 | ``` 76 | 77 | ### Transfer a file 78 | ```cpp 79 | ftpClient.transfer("local_file_path", "remote_file_path", FTPClient::FTP_GET); // get a file blocking 80 | ftpClient.transfer("local_file_path", "remote_file_path", FTPClient::FTP_PUT_NONBLOCKING); // put a file non-blocking 81 | ``` 82 | ### Handle non-blocking transfers by calling frequently 83 | ```cpp 84 | ftpClient.handleFTP(); // place this in e.g. loop() 85 | ``` 86 | 87 | ## Notes 88 | * I forked the Server from https://github.com/nailbuster/esp8266FTPServer which itself was forked from: https://github.com/gallegojm/Arduino-Ftp-Server/tree/master/FtpServer 89 | * Inspiration for the Client was taken from https://github.com/danbicks and his code posted in https://github.com/esp8266/Arduino/issues/1183#issuecomment-634556135 90 | -------------------------------------------------------------------------------- /esp32compat/PolledTimeout.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | /* 5 | PolledTimeout.h - Encapsulation of a polled Timeout 6 | 7 | Copyright (c) 2018 Daniel Salazar. All rights reserved. 8 | This file is part of the esp8266 core for Arduino environment. 9 | 10 | This library is free software; you can redistribute it and/or 11 | modify it under the terms of the GNU Lesser General Public 12 | License as published by the Free Software Foundation; either 13 | version 2.1 of the License, or (at your option) any later version. 14 | 15 | This library is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 18 | Lesser General Public License for more details. 19 | 20 | You should have received a copy of the GNU Lesser General Public 21 | License along with this library; if not, write to the Free Software 22 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 23 | */ 24 | 25 | #include 26 | 27 | #include 28 | 29 | namespace esp32Pool 30 | { 31 | 32 | 33 | namespace polledTimeout 34 | { 35 | 36 | namespace YieldPolicy 37 | { 38 | 39 | struct DoNothing 40 | { 41 | static void execute() {} 42 | }; 43 | 44 | struct YieldOrSkip 45 | { 46 | static void execute() {delay(0);} 47 | }; 48 | 49 | template 50 | struct YieldAndDelayMs 51 | { 52 | static void execute() {delay(delayMs);} 53 | }; 54 | 55 | } //YieldPolicy 56 | 57 | namespace TimePolicy 58 | { 59 | 60 | struct TimeSourceMillis 61 | { 62 | // time policy in milli-seconds based on millis() 63 | 64 | using timeType = decltype(millis()); 65 | static timeType time() {return millis();} 66 | static constexpr timeType ticksPerSecond = 1000; 67 | static constexpr timeType ticksPerSecondMax = 1000; 68 | }; 69 | 70 | template 71 | // "second_th" units of timeType for one second 72 | struct TimeUnit 73 | { 74 | using timeType = typename TimeSourceType::timeType; 75 | 76 | #if __GNUC__ < 5 77 | // gcc-4.8 cannot compile the constexpr-only version of this function 78 | // using #defines instead luckily works 79 | static constexpr timeType computeRangeCompensation () 80 | { 81 | #define number_of_secondTh_in_one_tick ((1.0 * second_th) / ticksPerSecond) 82 | #define fractional (number_of_secondTh_in_one_tick - (long)number_of_secondTh_in_one_tick) 83 | 84 | return ({ 85 | fractional == 0? 86 | 1: // no need for compensation 87 | (number_of_secondTh_in_one_tick / fractional) + 0.5; // scalar multiplier allowing exact division 88 | }); 89 | 90 | #undef number_of_secondTh_in_one_tick 91 | #undef fractional 92 | } 93 | #else 94 | static constexpr timeType computeRangeCompensation () 95 | { 96 | return ({ 97 | constexpr double number_of_secondTh_in_one_tick = (1.0 * second_th) / ticksPerSecond; 98 | constexpr double fractional = number_of_secondTh_in_one_tick - (long)number_of_secondTh_in_one_tick; 99 | fractional == 0? 100 | 1: // no need for compensation 101 | (number_of_secondTh_in_one_tick / fractional) + 0.5; // scalar multiplier allowing exact division 102 | }); 103 | } 104 | #endif 105 | 106 | static constexpr timeType ticksPerSecond = TimeSourceType::ticksPerSecond; 107 | static constexpr timeType ticksPerSecondMax = TimeSourceType::ticksPerSecondMax; 108 | static constexpr timeType rangeCompensate = computeRangeCompensation(); 109 | static constexpr timeType user2UnitMultiplierMax = (ticksPerSecondMax * rangeCompensate) / second_th; 110 | static constexpr timeType user2UnitMultiplier = (ticksPerSecond * rangeCompensate) / second_th; 111 | static constexpr timeType user2UnitDivider = rangeCompensate; 112 | // std::numeric_limits::max() is reserved 113 | static constexpr timeType timeMax = (std::numeric_limits::max() - 1) / user2UnitMultiplierMax; 114 | 115 | static timeType toTimeTypeUnit (const timeType userUnit) {return (userUnit * user2UnitMultiplier) / user2UnitDivider;} 116 | static timeType toUserUnit (const timeType internalUnit) {return (internalUnit * user2UnitDivider) / user2UnitMultiplier;} 117 | static timeType time () {return TimeSourceType::time();} 118 | }; 119 | 120 | using TimeMillis = TimeUnit< TimeSourceMillis, 1000 >; 121 | 122 | } //TimePolicy 123 | 124 | template 125 | class timeoutTemplate 126 | { 127 | public: 128 | using timeType = typename TimePolicyT::timeType; 129 | static_assert(std::is_unsigned::value == true, "timeType must be unsigned"); 130 | 131 | static constexpr timeType alwaysExpired = 0; 132 | static constexpr timeType neverExpires = std::numeric_limits::max(); 133 | static constexpr timeType rangeCompensate = TimePolicyT::rangeCompensate; //debug 134 | 135 | timeoutTemplate(const timeType userTimeout) 136 | { 137 | reset(userTimeout); 138 | } 139 | 140 | IRAM_ATTR // fast 141 | bool expired() 142 | { 143 | YieldPolicyT::execute(); //in case of DoNothing: gets optimized away 144 | if(PeriodicT) //in case of false: gets optimized away 145 | return expiredRetrigger(); 146 | return expiredOneShot(); 147 | } 148 | 149 | IRAM_ATTR // fast 150 | operator bool() 151 | { 152 | return expired(); 153 | } 154 | 155 | bool canExpire () const 156 | { 157 | return !_neverExpires; 158 | } 159 | 160 | bool canWait () const 161 | { 162 | return _timeout != alwaysExpired; 163 | } 164 | 165 | IRAM_ATTR // called from ISR 166 | void reset(const timeType newUserTimeout) 167 | { 168 | reset(); 169 | _timeout = TimePolicyT::toTimeTypeUnit(newUserTimeout); 170 | _neverExpires = (newUserTimeout < 0) || (newUserTimeout > timeMax()); 171 | } 172 | 173 | IRAM_ATTR // called from ISR 174 | void reset() 175 | { 176 | _start = TimePolicyT::time(); 177 | } 178 | 179 | void resetToNeverExpires () 180 | { 181 | _timeout = alwaysExpired + 1; // because canWait() has precedence 182 | _neverExpires = true; 183 | } 184 | 185 | timeType getTimeout() const 186 | { 187 | return TimePolicyT::toUserUnit(_timeout); 188 | } 189 | 190 | static constexpr timeType timeMax() 191 | { 192 | return TimePolicyT::timeMax; 193 | } 194 | 195 | private: 196 | 197 | IRAM_ATTR // fast 198 | bool checkExpired(const timeType internalUnit) const 199 | { 200 | // canWait() is not checked here 201 | // returns "can expire" and "time expired" 202 | return (!_neverExpires) && ((internalUnit - _start) >= _timeout); 203 | } 204 | 205 | protected: 206 | 207 | IRAM_ATTR // fast 208 | bool expiredRetrigger() 209 | { 210 | if (!canWait()) 211 | return true; 212 | 213 | timeType current = TimePolicyT::time(); 214 | if(checkExpired(current)) 215 | { 216 | unsigned long n = (current - _start) / _timeout; //how many _timeouts periods have elapsed, will usually be 1 (current - _start >= _timeout) 217 | _start += n * _timeout; 218 | return true; 219 | } 220 | return false; 221 | } 222 | 223 | IRAM_ATTR // fast 224 | bool expiredOneShot() const 225 | { 226 | // returns "always expired" or "has expired" 227 | return !canWait() || checkExpired(TimePolicyT::time()); 228 | } 229 | 230 | timeType _timeout; 231 | timeType _start; 232 | bool _neverExpires; 233 | }; 234 | 235 | // standard versions (based on millis()) 236 | // timeMax() is 49.7 days ((2^32)-2 ms) 237 | 238 | using oneShotMs = polledTimeout::timeoutTemplate; 239 | using periodicMs = polledTimeout::timeoutTemplate; 240 | 241 | 242 | } //polledTimeout 243 | 244 | 245 | /* A 1-shot timeout that auto-yields when in CONT can be built as follows: 246 | * using oneShotYieldMs = esp32::polledTimeout::timeoutTemplate; 247 | * 248 | * Other policies can be implemented by the user, e.g.: simple yield that panics in SYS, and the polledTimeout types built as needed as shown above, without modifying this file. 249 | */ 250 | 251 | }//esp32 252 | 253 | -------------------------------------------------------------------------------- /esp8266compat/PolledTimeout.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | /* 5 | PolledTimeout.h - Encapsulation of a polled Timeout 6 | 7 | Copyright (c) 2018 Daniel Salazar. All rights reserved. 8 | This file is part of the esp8266 core for Arduino environment. 9 | 10 | This library is free software; you can redistribute it and/or 11 | modify it under the terms of the GNU Lesser General Public 12 | License as published by the Free Software Foundation; either 13 | version 2.1 of the License, or (at your option) any later version. 14 | 15 | This library is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 18 | Lesser General Public License for more details. 19 | 20 | You should have received a copy of the GNU Lesser General Public 21 | License along with this library; if not, write to the Free Software 22 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 23 | */ 24 | 25 | #include 26 | 27 | #include 28 | 29 | namespace esp8266Pool 30 | { 31 | 32 | 33 | namespace polledTimeout 34 | { 35 | 36 | namespace YieldPolicy 37 | { 38 | 39 | struct DoNothing 40 | { 41 | static void execute() {} 42 | }; 43 | 44 | struct YieldOrSkip 45 | { 46 | static void execute() {delay(0);} 47 | }; 48 | 49 | template 50 | struct YieldAndDelayMs 51 | { 52 | static void execute() {delay(delayMs);} 53 | }; 54 | 55 | } //YieldPolicy 56 | 57 | namespace TimePolicy 58 | { 59 | 60 | struct TimeSourceMillis 61 | { 62 | // time policy in milli-seconds based on millis() 63 | 64 | using timeType = decltype(millis()); 65 | static timeType time() {return millis();} 66 | static constexpr timeType ticksPerSecond = 1000; 67 | static constexpr timeType ticksPerSecondMax = 1000; 68 | }; 69 | 70 | struct TimeSourceCycles 71 | { 72 | // time policy based on ESP.getCycleCount() 73 | // this particular time measurement is intended to be called very often 74 | // (every loop, every yield) 75 | 76 | using timeType = decltype(ESP.getCycleCount()); 77 | static timeType time() {return ESP.getCycleCount();} 78 | static constexpr timeType ticksPerSecond = F_CPU; // 80'000'000 or 160'000'000 Hz 79 | static constexpr timeType ticksPerSecondMax = 160000000; // 160MHz 80 | }; 81 | 82 | template 83 | // "second_th" units of timeType for one second 84 | struct TimeUnit 85 | { 86 | using timeType = typename TimeSourceType::timeType; 87 | 88 | #if __GNUC__ < 5 89 | // gcc-4.8 cannot compile the constexpr-only version of this function 90 | // using #defines instead luckily works 91 | static constexpr timeType computeRangeCompensation () 92 | { 93 | #define number_of_secondTh_in_one_tick ((1.0 * second_th) / ticksPerSecond) 94 | #define fractional (number_of_secondTh_in_one_tick - (long)number_of_secondTh_in_one_tick) 95 | 96 | return ({ 97 | fractional == 0? 98 | 1: // no need for compensation 99 | (number_of_secondTh_in_one_tick / fractional) + 0.5; // scalar multiplier allowing exact division 100 | }); 101 | 102 | #undef number_of_secondTh_in_one_tick 103 | #undef fractional 104 | } 105 | #else 106 | static constexpr timeType computeRangeCompensation () 107 | { 108 | return ({ 109 | constexpr double number_of_secondTh_in_one_tick = (1.0 * second_th) / ticksPerSecond; 110 | constexpr double fractional = number_of_secondTh_in_one_tick - (long)number_of_secondTh_in_one_tick; 111 | fractional == 0? 112 | 1: // no need for compensation 113 | (number_of_secondTh_in_one_tick / fractional) + 0.5; // scalar multiplier allowing exact division 114 | }); 115 | } 116 | #endif 117 | 118 | static constexpr timeType ticksPerSecond = TimeSourceType::ticksPerSecond; 119 | static constexpr timeType ticksPerSecondMax = TimeSourceType::ticksPerSecondMax; 120 | static constexpr timeType rangeCompensate = computeRangeCompensation(); 121 | static constexpr timeType user2UnitMultiplierMax = (ticksPerSecondMax * rangeCompensate) / second_th; 122 | static constexpr timeType user2UnitMultiplier = (ticksPerSecond * rangeCompensate) / second_th; 123 | static constexpr timeType user2UnitDivider = rangeCompensate; 124 | // std::numeric_limits::max() is reserved 125 | static constexpr timeType timeMax = (std::numeric_limits::max() - 1) / user2UnitMultiplierMax; 126 | 127 | static timeType toTimeTypeUnit (const timeType userUnit) {return (userUnit * user2UnitMultiplier) / user2UnitDivider;} 128 | static timeType toUserUnit (const timeType internalUnit) {return (internalUnit * user2UnitDivider) / user2UnitMultiplier;} 129 | static timeType time () {return TimeSourceType::time();} 130 | }; 131 | 132 | using TimeMillis = TimeUnit< TimeSourceMillis, 1000 >; 133 | using TimeFastMillis = TimeUnit< TimeSourceCycles, 1000 >; 134 | using TimeFastMicros = TimeUnit< TimeSourceCycles, 1000000 >; 135 | using TimeFastNanos = TimeUnit< TimeSourceCycles, 1000000000 >; 136 | 137 | } //TimePolicy 138 | 139 | template 140 | class timeoutTemplate 141 | { 142 | public: 143 | using timeType = typename TimePolicyT::timeType; 144 | static_assert(std::is_unsigned::value == true, "timeType must be unsigned"); 145 | 146 | static constexpr timeType alwaysExpired = 0; 147 | static constexpr timeType neverExpires = std::numeric_limits::max(); 148 | static constexpr timeType rangeCompensate = TimePolicyT::rangeCompensate; //debug 149 | 150 | timeoutTemplate(const timeType userTimeout) 151 | { 152 | reset(userTimeout); 153 | } 154 | 155 | IRAM_ATTR // fast 156 | bool expired() 157 | { 158 | YieldPolicyT::execute(); //in case of DoNothing: gets optimized away 159 | if(PeriodicT) //in case of false: gets optimized away 160 | return expiredRetrigger(); 161 | return expiredOneShot(); 162 | } 163 | 164 | IRAM_ATTR // fast 165 | operator bool() 166 | { 167 | return expired(); 168 | } 169 | 170 | bool canExpire () const 171 | { 172 | return !_neverExpires; 173 | } 174 | 175 | bool canWait () const 176 | { 177 | return _timeout != alwaysExpired; 178 | } 179 | 180 | IRAM_ATTR // called from ISR 181 | void reset(const timeType newUserTimeout) 182 | { 183 | reset(); 184 | _timeout = TimePolicyT::toTimeTypeUnit(newUserTimeout); 185 | _neverExpires = (newUserTimeout < 0) || (newUserTimeout > timeMax()); 186 | } 187 | 188 | IRAM_ATTR // called from ISR 189 | void reset() 190 | { 191 | _start = TimePolicyT::time(); 192 | } 193 | 194 | void resetToNeverExpires () 195 | { 196 | _timeout = alwaysExpired + 1; // because canWait() has precedence 197 | _neverExpires = true; 198 | } 199 | 200 | timeType getTimeout() const 201 | { 202 | return TimePolicyT::toUserUnit(_timeout); 203 | } 204 | 205 | static constexpr timeType timeMax() 206 | { 207 | return TimePolicyT::timeMax; 208 | } 209 | 210 | private: 211 | 212 | IRAM_ATTR // fast 213 | bool checkExpired(const timeType internalUnit) const 214 | { 215 | // canWait() is not checked here 216 | // returns "can expire" and "time expired" 217 | return (!_neverExpires) && ((internalUnit - _start) >= _timeout); 218 | } 219 | 220 | protected: 221 | 222 | IRAM_ATTR // fast 223 | bool expiredRetrigger() 224 | { 225 | if (!canWait()) 226 | return true; 227 | 228 | timeType current = TimePolicyT::time(); 229 | if(checkExpired(current)) 230 | { 231 | unsigned long n = (current - _start) / _timeout; //how many _timeouts periods have elapsed, will usually be 1 (current - _start >= _timeout) 232 | _start += n * _timeout; 233 | return true; 234 | } 235 | return false; 236 | } 237 | 238 | IRAM_ATTR // fast 239 | bool expiredOneShot() const 240 | { 241 | // returns "always expired" or "has expired" 242 | return !canWait() || checkExpired(TimePolicyT::time()); 243 | } 244 | 245 | timeType _timeout; 246 | timeType _start; 247 | bool _neverExpires; 248 | }; 249 | 250 | // legacy type names, deprecated (unit is milliseconds) 251 | 252 | using oneShot = polledTimeout::timeoutTemplate /*__attribute__((deprecated("use oneShotMs")))*/; 253 | using periodic = polledTimeout::timeoutTemplate /*__attribute__((deprecated("use periodicMs")))*/; 254 | 255 | // standard versions (based on millis()) 256 | // timeMax() is 49.7 days ((2^32)-2 ms) 257 | 258 | using oneShotMs = polledTimeout::timeoutTemplate; 259 | using periodicMs = polledTimeout::timeoutTemplate; 260 | 261 | // Time policy based on ESP.getCycleCount(), and intended to be called very often: 262 | // "Fast" versions sacrifices time range for improved precision and reduced execution time (by 86%) 263 | // (cpu cycles for ::expired(): 372 (millis()) vs 52 (ESP.getCycleCount())) 264 | // timeMax() values: 265 | // Ms: max is 26843 ms (26.8 s) 266 | // Us: max is 26843545 us (26.8 s) 267 | // Ns: max is 1073741823 ns ( 1.07 s) 268 | // (time policy based on ESP.getCycleCount() is intended to be called very often) 269 | 270 | using oneShotFastMs = polledTimeout::timeoutTemplate; 271 | using periodicFastMs = polledTimeout::timeoutTemplate; 272 | using oneShotFastUs = polledTimeout::timeoutTemplate; 273 | using periodicFastUs = polledTimeout::timeoutTemplate; 274 | using oneShotFastNs = polledTimeout::timeoutTemplate; 275 | using periodicFastNs = polledTimeout::timeoutTemplate; 276 | 277 | } //polledTimeout 278 | 279 | 280 | /* A 1-shot timeout that auto-yields when in CONT can be built as follows: 281 | * using oneShotYieldMs = esp8266::polledTimeout::timeoutTemplate; 282 | * 283 | * Other policies can be implemented by the user, e.g.: simple yield that panics in SYS, and the polledTimeout types built as needed as shown above, without modifying this file. 284 | */ 285 | 286 | }//esp8266 287 | 288 | -------------------------------------------------------------------------------- /examples/FTPClientSample/FTPClientSample.ino: -------------------------------------------------------------------------------- 1 | /* 2 | This is an example sketch to show the use of the FTP Client. 3 | 4 | Please replace 5 | YOUR_SSID and YOUR_PASS 6 | with your WiFi's values and compile. 7 | 8 | If you want to see debugging output of the FTP Client, please 9 | select select an Serial Port in the Arduino IDE menu Tools->Debug Port 10 | 11 | Send L via Serial Monitor, to display the contents of the FS 12 | Send F via Serial Monitor, to fromat the FS 13 | Send G via Serial Monitor, to GET a file from a FTP Server 14 | 15 | This example is provided as Public Domain 16 | Daniel Plasa 17 | 18 | */ 19 | #include 20 | #include 21 | #include 22 | 23 | const char *ssid PROGMEM = "YOUR_SSID"; 24 | const char *password PROGMEM = "YOUR_PASS"; 25 | 26 | // tell the FTP Client to use LittleFS 27 | FTPClient ftpClient(LittleFS); 28 | 29 | // provide FTP servers credentials and servername 30 | FTPClient::ServerInfo ftpServerInfo("user", "password", "hostname_or_ip"); 31 | 32 | void setup(void) 33 | { 34 | Serial.begin(74880); 35 | WiFi.begin(ssid, password); 36 | 37 | bool fsok = LittleFS.begin(); 38 | Serial.printf_P(PSTR("FS init: %s\n"), fsok ? PSTR("ok") : PSTR("fail!")); 39 | 40 | // Wait for connection 41 | while (WiFi.status() != WL_CONNECTED) 42 | { 43 | delay(500); 44 | Serial.printf_P(PSTR(".")); 45 | } 46 | Serial.printf_P(PSTR("\nConnected to %s, IP address is %s\n"), ssid, WiFi.localIP().toString().c_str()); 47 | 48 | ftpClient.begin(ftpServerInfo); 49 | } 50 | 51 | enum consoleaction 52 | { 53 | show, 54 | get, 55 | put, 56 | wait, 57 | format, 58 | list 59 | }; 60 | consoleaction action = show; 61 | 62 | String fileName; 63 | bool transferStarted = false; 64 | uint32_t startTime; 65 | 66 | void loop() 67 | { 68 | // this is all you need 69 | // make sure to call handleFTP() frequently 70 | ftpClient.handleFTP(); 71 | 72 | // 73 | // Code below just to debug in Serial Monitor 74 | // 75 | if (action == show) 76 | { 77 | Serial.printf_P(PSTR("Enter 'F' to format, 'L' to list the contents of the FS, 'G'/'P' + File to GET/PUT from/to FTP Server\n")); 78 | action = wait; 79 | } 80 | else if (action == wait) 81 | { 82 | if (transferStarted ) 83 | { 84 | const FTPClient::Status &r = ftpClient.check(); 85 | if (r.result == FTPClient::OK) 86 | { 87 | Serial.printf_P(PSTR("Transfer complete, took %lu ms\n"), millis() - startTime); 88 | transferStarted = false; 89 | } 90 | else if (r.result == FTPClient::ERROR) 91 | { 92 | Serial.printf_P(PSTR("Transfer failed after %lu ms, code: %u, descr=%s\n"), millis() - startTime, ftpClient.check().code, ftpClient.check().desc.c_str()); 93 | transferStarted = false; 94 | } 95 | } 96 | 97 | if (Serial.available()) 98 | { 99 | char c = Serial.read(); 100 | if (c == 'F') 101 | action = format; 102 | else if (c == 'L') 103 | action = list; 104 | else if (c == 'G') 105 | { 106 | action = get; 107 | fileName = Serial.readStringUntil('\n'); 108 | fileName.trim(); 109 | } 110 | else if (c == 'P') 111 | { 112 | action = put; 113 | fileName = Serial.readStringUntil('\n'); 114 | fileName.trim(); 115 | } 116 | else if (!(c == '\n' || c == '\r')) 117 | action = show; 118 | } 119 | } 120 | 121 | else if (action == format) 122 | { 123 | startTime = millis(); 124 | LittleFS.format(); 125 | Serial.printf_P(PSTR("FS format done, took %lu ms!\n"), millis() - startTime); 126 | action = show; 127 | } 128 | 129 | else if ((action == get) || (action == put)) 130 | { 131 | startTime = millis(); 132 | ftpClient.transfer(fileName, fileName, action == get ? 133 | FTPClient::FTP_GET_NONBLOCKING : FTPClient::FTP_PUT_NONBLOCKING); 134 | Serial.printf_P(PSTR("transfer started, took %lu ms!\n"), millis() - startTime); 135 | transferStarted = true; 136 | action = show; 137 | } 138 | 139 | else if (action == list) 140 | { 141 | Serial.printf_P(PSTR("Listing contents...\n")); 142 | uint16_t fileCount = listDir("", "/"); 143 | Serial.printf_P(PSTR("%d files/dirs total\n"), fileCount); 144 | action = show; 145 | } 146 | } 147 | 148 | uint16_t listDir(String indent, String path) 149 | { 150 | uint16_t dirCount = 0; 151 | Dir dir = LittleFS.openDir(path); 152 | while (dir.next()) 153 | { 154 | ++dirCount; 155 | if (dir.isDirectory()) 156 | { 157 | Serial.printf_P(PSTR("%s%s [Dir]\n"), indent.c_str(), dir.fileName().c_str()); 158 | dirCount += listDir(indent + " ", path + dir.fileName() + "/"); 159 | } 160 | else 161 | Serial.printf_P(PSTR("%s%-16s (%ld Bytes)\n"), indent.c_str(), dir.fileName().c_str(), (uint32_t)dir.fileSize()); 162 | } 163 | return dirCount; 164 | } 165 | -------------------------------------------------------------------------------- /examples/FTPServerSample/LittleFSSample/LittleFSSample.ino: -------------------------------------------------------------------------------- 1 | /* 2 | This is an example sketch to show the use of the espFTP server. 3 | 4 | Please replace 5 | YOUR_SSID and YOUR_PASS 6 | with your WiFi's values and compile. 7 | 8 | If you want to see debugging output of the FTP server, please 9 | select select an Serial Port in the Arduino IDE menu Tools->Debug Port 10 | 11 | Send L via Serial Monitor, to display the contents of the FS 12 | Send F via Serial Monitor, to fromat the FS 13 | 14 | This example is provided as Public Domain 15 | Daniel Plasa 16 | 17 | */ 18 | #if (defined ESP32) 19 | #error "No LittlFS on the ESP32" 20 | #endif 21 | 22 | #include 23 | #include 24 | #include 25 | #define BAUDRATE 74880 26 | 27 | const char *ssid PROGMEM = "YOUR_SSID"; 28 | const char *password PROGMEM = "YOUR_PASS"; 29 | 30 | // tell the FtpServer to use LittleFS 31 | FTPServer ftpSrv(LittleFS); 32 | 33 | void setup(void) 34 | { 35 | Serial.begin(BAUDRATE); 36 | WiFi.begin(ssid, password); 37 | 38 | bool fsok = LittleFS.begin(); 39 | Serial.printf_P(PSTR("FS init: %s\n"), fsok ? PSTR("ok") : PSTR("fail!")); 40 | 41 | // Wait for connection 42 | while (WiFi.status() != WL_CONNECTED) 43 | { 44 | delay(500); 45 | Serial.printf_P(PSTR(".")); 46 | } 47 | Serial.printf_P(PSTR("\nConnected to %s, IP address is %s\n"), ssid, WiFi.localIP().toString().c_str()); 48 | 49 | // setup the ftp server with username and password 50 | // ports are defined in FTPCommon.h, default is 51 | // 21 for the control connection 52 | // 50009 for the data connection (passive mode by default) 53 | ftpSrv.begin(F("ftp"), F("ftp")); //username, password for ftp. set ports in ESP8266FtpServer.h (default 21, 50009 for PASV) 54 | } 55 | 56 | enum consoleaction 57 | { 58 | show, 59 | wait, 60 | format, 61 | list 62 | }; 63 | consoleaction action = show; 64 | uint16_t listDir(String indent, String path); 65 | 66 | void loop(void) 67 | { 68 | // this is all you need 69 | // make sure to call handleFTP() frequently 70 | ftpSrv.handleFTP(); 71 | 72 | // 73 | // Code below just to debug in Serial Monitor 74 | // 75 | if (action == show) 76 | { 77 | Serial.printf_P(PSTR("Enter 'F' to format, 'L' to list the contents of the FS\n")); 78 | action = wait; 79 | } 80 | else if (action == wait) 81 | { 82 | if (Serial.available()) 83 | { 84 | char c = Serial.read(); 85 | if (c == 'F') 86 | action = format; 87 | else if (c == 'L') 88 | action = list; 89 | else if (!(c == '\n' || c == '\r')) 90 | action = show; 91 | } 92 | } 93 | else if (action == format) 94 | { 95 | uint32_t startTime = millis(); 96 | LittleFS.format(); 97 | Serial.printf_P(PSTR("FS format done, took %lu ms!\n"), millis() - startTime); 98 | action = show; 99 | } 100 | else if (action == list) 101 | { 102 | Serial.printf_P(PSTR("Listing contents...\n")); 103 | uint16_t fileCount = listDir("", "/"); 104 | Serial.printf_P(PSTR("%d files/dirs total\n"), fileCount); 105 | action = show; 106 | } 107 | } 108 | 109 | uint16_t listDir(String indent, String path) 110 | { 111 | uint16_t dirCount = 0; 112 | Dir dir = LittleFS.openDir(path); 113 | while (dir.next()) 114 | { 115 | ++dirCount; 116 | if (dir.isDirectory()) 117 | { 118 | Serial.printf_P(PSTR("%s%s [Dir]\n"), indent.c_str(), dir.fileName().c_str()); 119 | dirCount += listDir(indent + " ", path + dir.fileName() + "/"); 120 | } 121 | else 122 | Serial.printf_P(PSTR("%s%-16s (%ld Bytes)\n"), indent.c_str(), dir.fileName().c_str(), (uint32_t)dir.fileSize()); 123 | } 124 | return dirCount; 125 | } 126 | -------------------------------------------------------------------------------- /examples/FTPServerSample/SPIFFSSample/SPIFFSSample.ino: -------------------------------------------------------------------------------- 1 | /* 2 | This is an example sketch to show the use of the espFTP server. 3 | 4 | Please replace 5 | YOUR_SSID and YOUR_PASS 6 | with your WiFi's values and compile. 7 | 8 | If you want to see debugging output of the FTP server, please 9 | select select an Serial Port in the Arduino IDE menu Tools->Debug Port 10 | 11 | Send L via Serial Monitor, to display the contents of the FS 12 | Send F via Serial Monitor, to fromat the FS 13 | 14 | This example is provided as Public Domain 15 | Daniel Plasa 16 | 17 | */ 18 | #if (defined ESP32) 19 | #include 20 | #include 21 | #define BAUDRATE 115200 22 | #elif (defined ESP8266) 23 | #include 24 | #include 25 | #define BAUDRATE 74880 26 | #endif 27 | 28 | #include 29 | 30 | const char *ssid = "YOUR_SSID"; 31 | const char *password = "YOUR_PASS"; 32 | 33 | // Since SPIFFS is becoming deprecated but might still be in 34 | // use in your Projects, tell the FtpServer to use SPIFFS 35 | FTPServer ftpSrv(SPIFFS); 36 | 37 | void setup(void) 38 | { 39 | Serial.begin(BAUDRATE); 40 | WiFi.begin(ssid, password); 41 | 42 | bool fsok = SPIFFS.begin(); 43 | Serial.printf_P(PSTR("FS init: %s\n"), fsok ? PSTR("ok") : PSTR("fail!")); 44 | 45 | // Wait for connection 46 | while (WiFi.status() != WL_CONNECTED) 47 | { 48 | delay(500); 49 | Serial.printf_P(PSTR(".")); 50 | } 51 | Serial.printf_P(PSTR("\nConnected to %s, IP address is %s\n"), ssid, WiFi.localIP().toString().c_str()); 52 | 53 | // setup the ftp server with username and password 54 | // ports are defined in FTPCommon.h, default is 55 | // 21 for the control connection 56 | // 50009 for the data connection (passive mode by default) 57 | ftpSrv.begin(F("ftp"), F("ftp")); 58 | } 59 | 60 | enum consoleaction 61 | { 62 | show, 63 | wait, 64 | format, 65 | list 66 | }; 67 | 68 | consoleaction action = show; 69 | 70 | void loop(void) 71 | { 72 | // this is all you need 73 | // make sure to call handleFTP() frequently 74 | ftpSrv.handleFTP(); 75 | 76 | // 77 | // Code below just for debugging in Serial Monitor 78 | // 79 | if (action == show) 80 | { 81 | Serial.printf_P(PSTR("Enter 'F' to format, 'L' to list the contents of the FS\n")); 82 | action = wait; 83 | } 84 | else if (action == wait) 85 | { 86 | if (Serial.available()) 87 | { 88 | char c = Serial.read(); 89 | if (c == 'F') 90 | action = format; 91 | else if (c == 'L') 92 | action = list; 93 | else if (!(c == '\n' || c == '\r')) 94 | action = show; 95 | } 96 | } 97 | else if (action == format) 98 | { 99 | uint32_t startTime = millis(); 100 | SPIFFS.format(); 101 | Serial.printf_P(PSTR("FS format done, took %lu ms!\n"), millis() - startTime); 102 | action = show; 103 | } 104 | else if (action == list) 105 | { 106 | Serial.printf_P(PSTR("Listing contents...\n")); 107 | uint16_t dirCount = ListDir("/"); 108 | Serial.printf_P(PSTR("%d files total\n"), dirCount); 109 | action = show; 110 | } 111 | } 112 | 113 | #if (defined ESP8266) 114 | uint16_t ListDir(const char *path) 115 | { 116 | uint16_t dirCount = 0; 117 | Dir dir = SPIFFS.openDir(path, "r"); 118 | while (dir.next()) 119 | { 120 | ++dirCount; 121 | Serial.printf_P(PSTR("%6ld %s\n"), (uint32_t)dir.fileSize(), dir.fileName().c_str()); 122 | } 123 | return dirCount; 124 | } 125 | #elif (defined ESP32) 126 | uint16_t ListDir(const char *path) 127 | { 128 | uint16_t dirCount = 0; 129 | File root = SPIFFS.open(path); 130 | if (!root) 131 | { 132 | Serial.println(F("failed to open root")); 133 | return 0; 134 | } 135 | if (!root.isDirectory()) 136 | { 137 | Serial.println(F("/ not a directory")); 138 | return 0; 139 | } 140 | 141 | File file = root.openNextFile(); 142 | while (file) 143 | { 144 | ++dirCount; 145 | if (file.isDirectory()) 146 | { 147 | Serial.print(F(" DIR : ")); 148 | Serial.println(file.name()); 149 | dirCount += ListDir(file.name()); 150 | } 151 | else 152 | { 153 | Serial.print(F(" FILE: ")); 154 | Serial.print(file.name()); 155 | Serial.print(F("\tSIZE: ")); 156 | Serial.println(file.size()); 157 | } 158 | file = root.openNextFile(); 159 | } 160 | return dirCount; 161 | } 162 | #endif -------------------------------------------------------------------------------- /library.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "FTP", 3 | "description": "Simple FTP Server and Client for using SPIFFS or LittleFS", 4 | "keywords": "esp8266, ftp, spiffs, littlefs", 5 | "authors": 6 | { 7 | "name": "Daniel Plasa", 8 | "email": "dplasa@gmail.com" 9 | }, 10 | "repository": 11 | { 12 | "type": "git", 13 | "url": "https://github.com/dplasa/FTPClientServer" 14 | }, 15 | "frameworks": "Arduino", 16 | "platforms": "*" 17 | } 18 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=FtpClientServer 2 | version=0.9.9 3 | author=Daniel Plasa 4 | maintainer=dplasa@gmail.com 5 | sentence=Simple FTP server for SPIFFS and LittleFS on esp8266/esp32 6 | paragraph=Simple FTP server for SPIFFS and LittleFS on esp8266/esp32 7 | category=Communication 8 | url= 9 | architectures=esp8266,esp32,arduino-esp32 10 | --------------------------------------------------------------------------------