Arduino TinyFTP
Loading...
Searching...
No Matches
FTPBasicAPI.h
1#pragma once
2
3#include "Arduino.h"
4#include "../common/FTPCommon.h"
5#include "../common/FTPLogger.h"
6
7namespace tinyftp {
8
18 public:
19 FTPBasicAPI() { FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI"); }
20
21 ~FTPBasicAPI() { FTPLogger.writeLog(LOG_DEBUG, "~FTPBasicAPI"); }
22
23 bool begin(Client *cmdPar, Client *dataPar, IPAddress &address, int port,
24 const char *username, const char *password) {
25 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI ", "open");
26 command_ptr = cmdPar;
27 data_ptr = dataPar;
28 remote_address = address;
29
30 if (!connect(address, port, command_ptr, true)) return false;
31 if (username != nullptr) {
32 const char *ok_result[] = {"331", "230", nullptr};
33 if (!cmd("USER", username, ok_result)) return false;
34 // 331: password required; 230: already logged in
35 if (strncmp(result_reply, "331", 3) == 0) {
36 const char *ok_pass[] = {"230", "202", nullptr};
37 if (!cmd("PASS", password == nullptr ? "" : password, ok_pass))
38 return false;
39 }
40 }
41
42 is_open = true;
43 const char *ok_result[] = {"200", nullptr};
44 cmd("OPTS", "UTF8", ok_result);
45
46 return true;
47 }
48
49 bool quit() {
50 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "quit");
51 const char *ok_result[] = {"221", "226", nullptr};
52 bool result = cmd("QUIT", nullptr, ok_result, false);
53 if (!result) {
54 result = cmd("BYE", nullptr, ok_result, false);
55 }
56 if (!result) {
57 result = cmd("DISCONNECT", nullptr, ok_result, false);
58 }
59 return result;
60 }
61
62 bool connected() { return is_open; }
63
64 operator bool() { return connected(); }
65
66 bool passv() {
67 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "passv");
68 bool ok = cmd("PASV", nullptr, "227");
69 if (ok) {
70 char buffer[80];
71 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::passv", result_reply);
72 // determine data port
73 int start1 = findNthInStr(result_reply, ',', 4) + 1;
74 int p1 = atoi(result_reply + start1);
75
76 snprintf(buffer, sizeof(buffer), "*** port1 -> %d ", p1);
77 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::passv", buffer);
78
79 int start2 = findNthInStr(result_reply, ',', 5) + 1;
80 int p2 = atoi(result_reply + start2);
81
82 snprintf(buffer, sizeof(buffer), "*** port2 -> %d ", p2);
83 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::passv", buffer);
84
85 int dataPort = (p1 * 256) + p2;
86 snprintf(buffer, sizeof(buffer), "*** data port: %d", dataPort);
87 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::passv", buffer);
88
89 ok = connect(remote_address, dataPort, data_ptr);
90 }
91 return ok;
92 }
93
94 bool del(const char *file) {
95 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "del");
96 return cmd("DELE", file, "250");
97 }
98
99 bool mkdir(const char *dir) {
100 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "mkdir");
101 return cmd("MKD", dir, "257");
102 }
103
104 bool rmd(const char *dir) {
105 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "rd");
106 return cmd("RMD", dir, "250");
107 }
108
109 size_t size(const char *file) {
110 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "size");
111 if (cmd("SIZE", file, "213")) {
112 return atol(result_reply + 4);
113 }
114 return 0;
115 }
116
117 ObjectType objectType(const char *file) {
118 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "objectType");
119 const char *ok_result[] = {"213", "550", nullptr};
120 ObjectType result = TypeDirectory;
121 if (cmd("SIZE", file, ok_result)) {
122 if (strncmp(result_reply, "213", 3) == 0) {
123 result = TypeFile;
124 }
125 }
126 return result;
127 }
128
129 bool abort() {
130 bool rc = true;
131 if (current_operation == RESERVED_OP) {
132 // no transfer was started: just release the data connection
133 endTransfer("abort");
134 } else if (current_operation == READ_OP || current_operation == WRITE_OP ||
135 current_operation == LS_OP) {
136 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "abort");
137 closeData();
138 setCurrentOperation(NOP);
139
140 const char *ok[] = {"426", "226", "225", nullptr};
141 rc = cmd("ABOR", nullptr, ok);
142 if (rc && strncmp(result_reply, "426", 3) == 0) {
143 // 426 (transfer aborted) is followed by the reply to the ABOR
144 const char *ok_end[] = {"226", "225", nullptr};
145 rc = checkResult(ok_end, "abort-end");
146 } else {
147 // the transfer might have completed before the ABOR: then the reply
148 // to the ABOR is still coming
149 skipReplies(FTP_ABORT_DELAY_MS);
150 }
151 }
152 return rc;
153 }
154
155 bool binary() {
156 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "binary");
157 const char *type_cmd = use_type ? "TYPE I" : "BIN";
158 return cmd(type_cmd, nullptr, "200");
159 }
160
161 bool ascii() {
162 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "ascii");
163 const char *type_cmd = use_type ? "TYPE A" : "ASC";
164 return cmd(type_cmd, nullptr, "200");
165 }
166
167 bool type(const char *txt) {
168 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "type");
169 return cmd("TYPE", txt, "200");
170 }
171
173 Client *read(const char *file_name) {
174 if (current_operation != READ_OP) {
175 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "read");
176 const char *ok[] = {"150", "125", nullptr};
177 if (!cmd("RETR", file_name, ok)) {
178 endTransfer("read failed");
179 return nullptr;
180 }
181 setCurrentOperation(READ_OP);
182 }
183 return data_ptr;
184 }
185
187 Client *write(const char *file_name, FileMode mode) {
188 if (current_operation != WRITE_OP) {
189 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "write");
190 const char *ok_write[] = {"125", "150", nullptr};
191 if (!cmd(mode == WRITE_APPEND_MODE ? "APPE" : "STOR", file_name,
192 ok_write)) {
193 endTransfer("write failed");
194 return nullptr;
195 }
196 setCurrentOperation(WRITE_OP);
197 }
198 return data_ptr;
199 }
200
202 Client *ls(const char *file_name) {
203 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "ls");
204 const char *ok[] = {"125", "150", nullptr};
205 if (!cmd("NLST", file_name, ok)) {
206 endTransfer("ls failed");
207 return nullptr;
208 }
209 setCurrentOperation(LS_OP);
210 return data_ptr;
211 }
212
215 bool dataConnected() { return data_ptr != nullptr && data_ptr->connected(); }
216
217 void closeData() {
218 FTPLogger.writeLog(LOG_INFO, "FTPBasicAPI", "closeData");
219 data_ptr->stop();
220 }
221
225 bool endTransfer(const char *tag) {
226 bool ok = true;
227 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::endTransfer", tag);
228 if (current_operation == READ_OP || current_operation == LS_OP) {
229 closeData();
230 // 426: we closed the data connection before all data was received
231 const char *ok_result[] = {"226", "250", "426", nullptr};
232 ok = checkResult(ok_result, tag, true);
233 } else if (current_operation == WRITE_OP) {
234 closeData();
235 const char *ok_result[] = {"226", "250", nullptr};
236 ok = checkResult(ok_result, tag, true);
237 } else if (current_operation == RESERVED_OP) {
238 closeData();
239 }
240 setCurrentOperation(NOP);
241 return ok;
242 }
243
245 uint32_t reserve() {
246 if (++transfer_id == 0) transfer_id = 1;
247 handles = 0;
248 setCurrentOperation(RESERVED_OP);
249 return transfer_id;
250 }
251
253 uint32_t transferId() { return transfer_id; }
254
256 bool isTransfer(uint32_t id) {
257 return id != 0 && id == transfer_id && current_operation != NOP;
258 }
259
262 void addHandle(uint32_t id) {
263 if (isTransfer(id)) handles++;
264 }
265
267 void releaseHandle(uint32_t id) {
268 if (isTransfer(id) && --handles <= 0) endTransfer("release");
269 }
270
271 void setCurrentOperation(CurrentOperation op) {
272 char msg[80];
273 snprintf(msg, sizeof(msg), "setCurrentOperation: %d", (int)op);
274 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", msg);
275 current_operation = op;
276 }
277
278 CurrentOperation currentOperation() { return current_operation; }
279
280 void flush() {
281 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI", "flush");
282 data_ptr->flush();
283 }
284
285 bool checkResult(const char *expected[], const char *command,
286 bool wait_for_data = true) {
287 result_reply[0] = '\0';
288 // nothing to consume and we do not need to wait
289 if (!wait_for_data && command_ptr->available() == 0) return true;
290
291 char result_str[FTP_RESULT_BUFFER_SIZE];
292 bool ok = readReply(result_str, sizeof(result_str));
293 if (!ok) {
294 // if we got no reply and we dont need to wait we are still ok
295 ok = !wait_for_data;
296 } else {
297 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::checkResult", result_str);
298 strncpy(result_reply, result_str, sizeof(result_reply) - 1);
299 result_reply[sizeof(result_reply) - 1] = '\0';
300 ok = isExpected(result_str, expected);
301 }
302
303 // log error
304 if (!ok) {
305 FTPLogger.writeLog(LOG_ERROR, "FTPBasicAPI::checkResult", command);
306 FTPLogger.writeLog(LOG_ERROR, "FTPBasicAPI::checkResult", result_reply);
307 }
308 return ok;
309 }
310
311 bool cmd(const char *command, const char *par, const char *expected,
312 bool wait_for_data = true) {
313 const char *expected_array[] = {expected, nullptr};
314 return cmd(command, par, expected_array, wait_for_data);
315 }
316
317 bool cmd(const char *command_str, const char *par, const char *expected[],
318 bool wait_for_data = true) {
319 char command_buffer[FTP_COMMAND_BUFFER_SIZE];
320 if (par == nullptr) {
321 snprintf(command_buffer, FTP_COMMAND_BUFFER_SIZE, "%s", command_str);
322 } else {
323 snprintf(command_buffer, FTP_COMMAND_BUFFER_SIZE, "%s %s", command_str,
324 par);
325 }
326 command_ptr->println(command_buffer);
327 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::cmd", command_buffer);
328
329 return checkResult(expected, command_buffer, wait_for_data);
330 }
331
332 void setUseTypeCommand(bool useType) { use_type = useType; }
333
334 protected:
335 // currently running op -> do we need to cancel ?
336 CurrentOperation current_operation = NOP;
337 Client *command_ptr = nullptr; // Client for commands
338 Client *data_ptr = nullptr; // Client for upload and download of files
339 IPAddress remote_address;
340 bool is_open = false;
341 bool use_type = false;
342 char result_reply[100] = {0};
343 uint32_t transfer_id = 0; // id of the current (or last) transfer
344 int handles = 0; // number of handles of the current transfer
345
348 current_operation = NOP;
349 handles = 0;
350 if (++transfer_id == 0) transfer_id = 1;
351 }
352
354 void skipReplies(unsigned long ms) {
355 char reply[FTP_RESULT_BUFFER_SIZE];
356 unsigned long start = millis();
357 while (millis() - start < ms) {
358 if (command_ptr->available() > 0) {
359 if (readReply(reply, sizeof(reply))) {
360 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::skipReplies", reply);
361 }
362 } else {
363 delay(1);
364 }
365 }
366 }
367
368 bool connect(IPAddress adr, int port, Client *client_ptr,
369 bool doCheckResult = false) {
370 char buffer[80];
371 snprintf(buffer, sizeof(buffer), "connect %d.%d.%d.%d:%d", adr[0], adr[1],
372 adr[2], adr[3], port);
373 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::connect", buffer);
374 // make sure we start with a clean state
375 if (client_ptr->connected()) client_ptr->stop();
376 for (int j = 0; j < FTP_CONNECT_RETRIES; j++) {
377 if (j > 0) delay(FTP_CONNECT_RETRY_DELAY_MS);
378 if (client_ptr->connect(adr, port)) break;
379 }
380 bool ok = client_ptr->connected();
381 if (ok && doCheckResult) {
382 const char *ok_result[] = {"220", "200", nullptr};
383 ok = checkResult(ok_result, "connect");
384 }
385 // log result
386 if (ok) {
387 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::connected", buffer);
388 } else {
389 FTPLogger.writeLog(LOG_ERROR, "FTPBasicAPI::connected", buffer);
390 }
391 return ok;
392 }
393
396 bool isExpected(const char *reply, const char *expected[]) {
397 if (expected[0] == nullptr) {
398 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::checkResult",
399 "success because of not expected result codes");
400 return true;
401 }
402 for (int j = 0; expected[j] != nullptr; j++) {
403 if (strncmp(reply, expected[j], 3) == 0) {
404 char msg[80];
405 snprintf(msg, sizeof(msg), " -> success with %s", expected[j]);
406 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::checkResult", msg);
407 return true;
408 }
409 }
410 return false;
411 }
412
415 bool readReply(char *reply, int maxLen) {
416 // skip empty lines
417 do {
418 if (!readReplyLine(reply, maxLen)) return false;
419 } while (strlen(reply) < 3);
420
421 // multi-line reply "123-..." ends with a line "123 ..."
422 if (reply[3] == '-') {
423 char line[FTP_RESULT_BUFFER_SIZE];
424 do {
425 if (!readReplyLine(line, sizeof(line))) return false;
426 FTPLogger.writeLog(LOG_DEBUG, "FTPBasicAPI::readReply", line);
427 } while (!(strncmp(line, reply, 3) == 0 && line[3] == ' '));
428 }
429 return true;
430 }
431
434 bool readReplyLine(char *str, int maxLen) {
435 int len = 0;
436 unsigned long start = millis();
437 while (true) {
438 if (command_ptr->available() > 0) {
439 int c = command_ptr->read();
440 if (c < 0) continue;
441 if (c == '\n') break;
442 if (len < maxLen - 1) str[len++] = (char)c;
443 } else if (!command_ptr->connected() ||
444 millis() - start >= FTP_REPLY_TIMEOUT_MS) {
445 str[len] = '\0';
446 FTPLogger.writeLog(LOG_ERROR, "FTPBasicAPI::readReplyLine",
447 "timeout or connection closed");
448 return false;
449 } else {
450 delay(1);
451 }
452 }
453 // For Windows we remove the \r at the end
454 if (len > 0 && str[len - 1] == '\r') len--;
455 str[len] = '\0';
456 return true;
457 }
458};
459
465 public:
466 virtual ~FTPSessionProvider() = default;
468 virtual FTPBasicAPI *idleSession() = 0;
472};
473
482 public:
483 FTPTransferHandle() = default;
484
486 : api_ptr(other.api_ptr), id(other.id) {
487 if (api_ptr != nullptr) api_ptr->addHandle(id);
488 }
489
490 FTPTransferHandle &operator=(const FTPTransferHandle &other) {
491 if (this != &other) {
492 if (other.api_ptr != nullptr) other.api_ptr->addHandle(other.id);
493 release();
494 api_ptr = other.api_ptr;
495 id = other.id;
496 }
497 return *this;
498 }
499
501
504 release();
505 api_ptr = api;
506 id = api != nullptr ? api->transferId() : 0;
507 if (api_ptr != nullptr) api_ptr->addHandle(id);
508 }
509
511 void release() {
512 if (api_ptr != nullptr) api_ptr->releaseHandle(id);
513 api_ptr = nullptr;
514 id = 0;
515 }
516
518 FTPBasicAPI *api() const {
519 return api_ptr != nullptr && api_ptr->isTransfer(id) ? api_ptr : nullptr;
520 }
521
522 protected:
523 FTPBasicAPI *api_ptr = nullptr;
524 uint32_t id = 0;
525};
526
527} // namespace tinyftp
FTPBasicAPI Implementation of Low Level FTP protocol. In order to simplify the logic we always use Pa...
Definition FTPBasicAPI.h:17
void addHandle(uint32_t id)
Definition FTPBasicAPI.h:262
uint32_t transferId()
Id of the current (or last) transfer.
Definition FTPBasicAPI.h:253
uint32_t reserve()
Reserves the session for a new transfer: returns its id.
Definition FTPBasicAPI.h:245
Client * read(const char *file_name)
Starts the download (if necessary): returns nullptr if it failed.
Definition FTPBasicAPI.h:173
bool readReplyLine(char *str, int maxLen)
Definition FTPBasicAPI.h:434
bool isExpected(const char *reply, const char *expected[])
Definition FTPBasicAPI.h:396
Client * ls(const char *file_name)
Starts the directory listing: returns nullptr if it failed.
Definition FTPBasicAPI.h:202
void skipReplies(unsigned long ms)
Consumes all replies which arrive within the indicated time.
Definition FTPBasicAPI.h:354
void resetTransfer()
Forgets the current transfer: e.g. when the connection was closed.
Definition FTPBasicAPI.h:347
void releaseHandle(uint32_t id)
Unregisters a handle: the transfer ends when the last handle is gone.
Definition FTPBasicAPI.h:267
bool endTransfer(const char *tag)
Definition FTPBasicAPI.h:225
bool isTransfer(uint32_t id)
Returns true if the transfer with the indicated id is still active.
Definition FTPBasicAPI.h:256
bool readReply(char *reply, int maxLen)
Definition FTPBasicAPI.h:415
bool dataConnected()
Definition FTPBasicAPI.h:215
Client * write(const char *file_name, FileMode mode)
Starts the upload (if necessary): returns nullptr if it failed.
Definition FTPBasicAPI.h:187
FTPSessionProvider Provides sessions on demand (implemented by the FTPClient)
Definition FTPBasicAPI.h:464
virtual FTPBasicAPI * idleSession()=0
Provides an idle, connected session (or nullptr)
virtual FTPBasicAPI * openDataSession()=0
FTPTransferHandle Counted reference to the transfer of a session: the transfer is ended and the sessi...
Definition FTPBasicAPI.h:481
void attach(FTPBasicAPI *api)
Takes part in the current transfer of the session.
Definition FTPBasicAPI.h:503
FTPBasicAPI * api() const
Provides the session while the transfer is active (or nullptr)
Definition FTPBasicAPI.h:518
void release()
Gives up this reference.
Definition FTPBasicAPI.h:511
FTP client and server functionality.
Definition FTPBasicAPI.h:7
FileMode
File Mode.
Definition FTPCommon.h:44
int findNthInStr(const char *str, char ch, int n)
Provides the position of the n-th occurrence of ch in str (or -1)
Definition FTPCommon.h:52
CurrentOperation
State of a session: RESERVED_OP means a data connection was opened (PASV) but no transfer command was...
Definition FTPCommon.h:47