ftp_server.c
Go to the documentation of this file.
1 /**
2  * @file ftp_server.c
3  * @brief FTP server (File Transfer Protocol)
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2024 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @section Description
28  *
29  * File Transfer Protocol (FTP) is a standard network protocol used to
30  * transfer files from one host to another host over a TCP-based network.
31  * Refer to the following RFCs for complete details:
32  * - RFC 959: File Transfer Protocol (FTP)
33  * - RFC 3659: Extensions to FTP
34  * - RFC 2428: FTP Extensions for IPv6 and NATs
35  *
36  * @author Oryx Embedded SARL (www.oryx-embedded.com)
37  * @version 2.4.0
38  **/
39 
40 //Switch to the appropriate trace level
41 #define TRACE_LEVEL FTP_TRACE_LEVEL
42 
43 //Dependencies
44 #include "ftp/ftp_server.h"
45 #include "ftp/ftp_server_control.h"
46 #include "ftp/ftp_server_data.h"
47 #include "ftp/ftp_server_misc.h"
48 #include "path.h"
49 #include "debug.h"
50 
51 //Check TCP/IP stack configuration
52 #if (FTP_SERVER_SUPPORT == ENABLED)
53 
54 
55 /**
56  * @brief Initialize settings with default values
57  * @param[out] settings Structure that contains FTP server settings
58  **/
59 
61 {
62  //Default task parameters
63  settings->task = OS_TASK_DEFAULT_PARAMS;
65  settings->task.priority = FTP_SERVER_PRIORITY;
66 
67  //The FTP server is not bound to any interface
68  settings->interface = NULL;
69 
70  //FTP command port number
71  settings->port = FTP_PORT;
72  //FTP data port number
73  settings->dataPort = FTP_DATA_PORT;
74 
75  //Passive port range
78 
79  //Public IPv4 address to be used in PASV replies
81 
82  //Default security mode (no security)
83  settings->mode = FTP_SERVER_MODE_PLAINTEXT;
84 
85  //Client connections
86  settings->maxConnections = 0;
87  settings->connections = NULL;
88 
89  //Set root directory
90  osStrcpy(settings->rootDir, "/");
91 
92  //Connection callback function
93  settings->connectCallback = NULL;
94  //Disconnection callback function
95  settings->disconnectCallback = NULL;
96 
97 #if (FTP_SERVER_TLS_SUPPORT == ENABLED)
98  //TLS initialization callback function
99  settings->tlsInitCallback = NULL;
100 #endif
101 
102  //User verification callback function
103  settings->checkUserCallback = NULL;
104  //Password verification callback function
105  settings->checkPasswordCallback = NULL;
106  //Callback used to retrieve file permissions
107  settings->getFilePermCallback = NULL;
108  //Unknown command callback function
109  settings->unknownCommandCallback = NULL;
110 }
111 
112 
113 /**
114  * @brief FTP server initialization
115  * @param[in] context Pointer to the FTP server context
116  * @param[in] settings FTP server specific settings
117  * @return Error code
118  **/
119 
121  const FtpServerSettings *settings)
122 {
123  error_t error;
124  uint_t i;
125 
126  //Debug message
127  TRACE_INFO("Initializing FTP server...\r\n");
128 
129  //Ensure the parameters are valid
130  if(context == NULL || settings == NULL)
132 
133  //Sanity check
134  if(settings->passivePortMax <= settings->passivePortMin)
135  {
137  }
138 
139  //Invalid number of client connections?
140  if(settings->maxConnections < 1 ||
142  {
144  }
145 
146  //Invalid pointer?
147  if(settings->connections == NULL)
149 
150  //Clear the FTP server context
151  osMemset(context, 0, sizeof(FtpServerContext));
152 
153  //Initialize task parameters
154  context->taskParams = settings->task;
155  context->taskId = OS_INVALID_TASK_ID;
156 
157  //Save user settings
158  context->settings = *settings;
159  //Client connections
160  context->connections = settings->connections;
161 
162  //Clean the root directory path
163  pathCanonicalize(context->settings.rootDir);
164  pathRemoveSlash(context->settings.rootDir);
165 
166  //Loop through client connections
167  for(i = 0; i < context->settings.maxConnections; i++)
168  {
169  //Initialize the structure representing the client connection
170  osMemset(&context->connections[i], 0, sizeof(FtpClientConnection));
171  }
172 
173  //Initialize status code
174  error = NO_ERROR;
175 
176  //Create an event object to poll the state of sockets
177  if(!osCreateEvent(&context->event))
178  {
179  //Failed to create event
180  error = ERROR_OUT_OF_RESOURCES;
181  }
182 
183 #if (FTP_SERVER_TLS_SUPPORT == ENABLED && TLS_TICKET_SUPPORT == ENABLED)
184  //Check status code
185  if(!error)
186  {
187  //Initialize ticket encryption context
188  error = tlsInitTicketContext(&context->tlsTicketContext);
189  }
190 #endif
191 
192  //Any error to report?
193  if(error)
194  {
195  //Clean up side effects
196  ftpServerDeinit(context);
197  }
198 
199  //Return status code
200  return error;
201 }
202 
203 
204 /**
205  * @brief Start FTP server
206  * @param[in] context Pointer to the FTP server context
207  * @return Error code
208  **/
209 
211 {
212  error_t error;
213 
214  //Make sure the FTP server context is valid
215  if(context == NULL)
217 
218  //Debug message
219  TRACE_INFO("Starting FTP server...\r\n");
220 
221  //Make sure the FTP server is not already running
222  if(context->running)
223  return ERROR_ALREADY_RUNNING;
224 
225  //Start of exception handling block
226  do
227  {
228  //Open a TCP socket
230  //Failed to open socket?
231  if(context->socket == NULL)
232  {
233  //Report an error
234  error = ERROR_OPEN_FAILED;
235  break;
236  }
237 
238  //Force the socket to operate in non-blocking mode
239  error = socketSetTimeout(context->socket, 0);
240  //Any error to report?
241  if(error)
242  break;
243 
244  //Adjust the size of the TX buffer
245  error = socketSetTxBufferSize(context->socket,
247  //Any error to report?
248  if(error)
249  break;
250 
251  //Adjust the size of the RX buffer
252  error = socketSetRxBufferSize(context->socket,
254  //Any error to report?
255  if(error)
256  break;
257 
258  //Associate the socket with the relevant interface
259  error = socketBindToInterface(context->socket,
260  context->settings.interface);
261  //Any error to report?
262  if(error)
263  break;
264 
265  //The FTP server listens for connection requests on port 21
266  error = socketBind(context->socket, &IP_ADDR_ANY,
267  context->settings.port);
268  //Any error to report?
269  if(error)
270  break;
271 
272  //Place socket in listening state
273  error = socketListen(context->socket, FTP_SERVER_BACKLOG);
274  //Any failure to report?
275  if(error)
276  break;
277 
278  //Start the FTP server
279  context->stop = FALSE;
280  context->running = TRUE;
281 
282  //Create a task
283  context->taskId = osCreateTask("FTP Server", (OsTaskCode) ftpServerTask,
284  context, &context->taskParams);
285 
286  //Failed to create task?
287  if(context->taskId == OS_INVALID_TASK_ID)
288  {
289  //Report an error
290  error = ERROR_OUT_OF_RESOURCES;
291  break;
292  }
293 
294  //End of exception handling block
295  } while(0);
296 
297  //Any error to report?
298  if(error)
299  {
300  //Clean up side effects
301  context->running = FALSE;
302 
303  //Close listening socket
304  socketClose(context->socket);
305  context->socket = NULL;
306  }
307 
308  //Return status code
309  return error;
310 }
311 
312 
313 /**
314  * @brief Stop FTP server
315  * @param[in] context Pointer to the FTP server context
316  * @return Error code
317  **/
318 
320 {
321  uint_t i;
322 
323  //Make sure the FTP server context is valid
324  if(context == NULL)
326 
327  //Debug message
328  TRACE_INFO("Stopping FTP server...\r\n");
329 
330  //Check whether the FTP server is running
331  if(context->running)
332  {
333  //Stop the FTP server
334  context->stop = TRUE;
335  //Send a signal to the task to abort any blocking operation
336  osSetEvent(&context->event);
337 
338  //Wait for the task to terminate
339  while(context->running)
340  {
341  osDelayTask(1);
342  }
343 
344  //Loop through the connection table
345  for(i = 0; i < context->settings.maxConnections; i++)
346  {
347  //Close client connection
348  ftpServerCloseConnection(&context->connections[i]);
349  }
350 
351  //Close listening socket
352  socketClose(context->socket);
353  context->socket = NULL;
354  }
355 
356  //Successful processing
357  return NO_ERROR;
358 }
359 
360 
361 /**
362  * @brief Set home directory
363  * @param[in] connection Pointer to the client connection
364  * @param[in] homeDir NULL-terminated string specifying the home directory
365  * @return Error code
366  **/
367 
369  const char_t *homeDir)
370 {
371  //Check parameters
372  if(connection == NULL || homeDir == NULL)
374 
375  //Set home directory
376  pathCombine(connection->homeDir, homeDir, FTP_SERVER_MAX_HOME_DIR_LEN);
377 
378  //Clean the resulting path
379  pathCanonicalize(connection->homeDir);
380  pathRemoveSlash(connection->homeDir);
381 
382  //Set current directory
383  osStrcpy(connection->currentDir, connection->homeDir);
384 
385  //Successful processing
386  return NO_ERROR;
387 }
388 
389 
390 /**
391  * @brief FTP server task
392  * @param[in] context Pointer to the FTP server context
393  **/
394 
396 {
397  error_t error;
398  uint_t i;
399  systime_t time;
400  systime_t timeout;
401  FtpClientConnection *connection;
402 
403 #if (NET_RTOS_SUPPORT == ENABLED)
404  //Task prologue
405  osEnterTask();
406 
407  //Process events
408  while(1)
409  {
410 #endif
411  //Set polling timeout
412  timeout = FTP_SERVER_TICK_INTERVAL;
413 
414  //Clear event descriptor set
415  osMemset(context->eventDesc, 0, sizeof(context->eventDesc));
416 
417  //Specify the events the application is interested in
418  for(i = 0; i < context->settings.maxConnections; i++)
419  {
420  //Point to the structure describing the current connection
421  connection = &context->connections[i];
422 
423  //Check whether the control connection is active
424  if(connection->controlChannel.socket != NULL)
425  {
426  //Register the events related to the control connection
428  &context->eventDesc[2 * i]);
429 
430  //Check whether the socket is ready for I/O operation
431  if(context->eventDesc[2 * i].eventFlags != 0)
432  {
433  //No need to poll the underlying socket for incoming traffic
434  timeout = 0;
435  }
436  }
437 
438  //Check whether the data connection is active
439  if(connection->dataChannel.socket != NULL)
440  {
441  //Register the events related to the data connection
443  &context->eventDesc[2 * i + 1]);
444 
445  //Check whether the socket is ready for I/O operation
446  if(context->eventDesc[2 * i + 1].eventFlags != 0)
447  {
448  //No need to poll the underlying socket for incoming traffic
449  timeout = 0;
450  }
451  }
452  }
453 
454  //Accept connection request events
455  context->eventDesc[2 * i].socket = context->socket;
456  context->eventDesc[2 * i].eventMask = SOCKET_EVENT_RX_READY;
457 
458  //Wait for one of the set of sockets to become ready to perform I/O
459  error = socketPoll(context->eventDesc,
460  2 * context->settings.maxConnections + 1, &context->event, timeout);
461 
462  //Get current time
463  time = osGetSystemTime();
464 
465  //Check status code
466  if(error == NO_ERROR || error == ERROR_TIMEOUT ||
467  error == ERROR_WAIT_CANCELED)
468  {
469  //Stop request?
470  if(context->stop)
471  {
472  //Stop FTP server operation
473  context->running = FALSE;
474  //Task epilogue
475  osExitTask();
476  //Kill ourselves
478  }
479 
480  //Event-driven processing
481  for(i = 0; i < context->settings.maxConnections; i++)
482  {
483  //Point to the structure describing the current connection
484  connection = &context->connections[i];
485 
486  //Check whether the control connection is active
487  if(connection->controlChannel.socket != NULL)
488  {
489  //Check whether the control socket is to ready to perform I/O
490  if(context->eventDesc[2 * i].eventFlags)
491  {
492  //Update time stamp
493  connection->timestamp = time;
494 
495  //Control connection event handler
497  context->eventDesc[2 * i].eventFlags);
498  }
499  }
500 
501  //Check whether the data connection is active
502  if(connection->dataChannel.socket != NULL)
503  {
504  //Check whether the data socket is ready to perform I/O
505  if(context->eventDesc[2 * i + 1].eventFlags)
506  {
507  //Update time stamp
508  connection->timestamp = time;
509 
510  //Data connection event handler
512  context->eventDesc[2 * i + 1].eventFlags);
513  }
514  }
515  }
516 
517  //Check the state of the listening socket
518  if(context->eventDesc[2 * i].eventFlags & SOCKET_EVENT_RX_READY)
519  {
520  //Accept connection request
522  }
523  }
524 
525  //Handle periodic operations
526  ftpServerTick(context);
527 
528 #if (NET_RTOS_SUPPORT == ENABLED)
529  }
530 #endif
531 }
532 
533 
534 /**
535  * @brief Release FTP server context
536  * @param[in] context Pointer to the FTP server context
537  **/
538 
540 {
541  //Make sure the FTP server context is valid
542  if(context != NULL)
543  {
544  //Free previously allocated resources
545  osDeleteEvent(&context->event);
546 
547 #if (FTP_SERVER_TLS_SUPPORT == ENABLED && TLS_TICKET_SUPPORT == ENABLED)
548  //Release ticket encryption context
549  tlsFreeTicketContext(&context->tlsTicketContext);
550 #endif
551 
552  //Clear FTP server context
553  osMemset(context, 0, sizeof(FtpServerContext));
554  }
555 }
556 
557 #endif
unsigned int uint_t
Definition: compiler_port.h:50
char char_t
Definition: compiler_port.h:48
Debugging facilities.
#define TRACE_INFO(...)
Definition: debug.h:95
uint32_t time
error_t
Error codes.
Definition: error.h:43
@ ERROR_WAIT_CANCELED
Definition: error.h:73
@ ERROR_ALREADY_RUNNING
Definition: error.h:292
@ ERROR_TIMEOUT
Definition: error.h:95
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
@ ERROR_OPEN_FAILED
Definition: error.h:75
@ NO_ERROR
Success.
Definition: error.h:44
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
void ftpServerTask(FtpServerContext *context)
FTP server task.
Definition: ftp_server.c:395
error_t ftpServerStart(FtpServerContext *context)
Start FTP server.
Definition: ftp_server.c:210
error_t ftpServerInit(FtpServerContext *context, const FtpServerSettings *settings)
FTP server initialization.
Definition: ftp_server.c:120
error_t ftpServerStop(FtpServerContext *context)
Stop FTP server.
Definition: ftp_server.c:319
void ftpServerGetDefaultSettings(FtpServerSettings *settings)
Initialize settings with default values.
Definition: ftp_server.c:60
error_t ftpServerSetHomeDir(FtpClientConnection *connection, const char_t *homeDir)
Set home directory.
Definition: ftp_server.c:368
void ftpServerDeinit(FtpServerContext *context)
Release FTP server context.
Definition: ftp_server.c:539
FTP server (File Transfer Protocol)
#define FTP_SERVER_PASSIVE_PORT_MAX
Definition: ftp_server.h:179
#define FTP_SERVER_TICK_INTERVAL
Definition: ftp_server.h:81
#define FTP_PORT
Definition: ftp_server.h:197
#define FTP_SERVER_MIN_TCP_BUFFER_SIZE
Definition: ftp_server.h:137
#define FTP_SERVER_MAX_HOME_DIR_LEN
Definition: ftp_server.h:116
#define FTP_SERVER_PRIORITY
Definition: ftp_server.h:62
#define FTP_SERVER_PASSIVE_PORT_MIN
Definition: ftp_server.h:172
#define FTP_SERVER_BACKLOG
Definition: ftp_server.h:88
@ FTP_SERVER_MODE_PLAINTEXT
Definition: ftp_server.h:255
#define FTP_DATA_PORT
Definition: ftp_server.h:199
#define FtpClientConnection
Definition: ftp_server.h:212
#define FTP_SERVER_STACK_SIZE
Definition: ftp_server.h:55
#define FTP_SERVER_MAX_CONNECTIONS
Definition: ftp_server.h:67
#define FtpServerContext
Definition: ftp_server.h:208
void ftpServerRegisterControlChannelEvents(FtpClientConnection *connection, SocketEventDesc *eventDesc)
Register control connection events.
void ftpServerProcessControlChannelEvents(FtpClientConnection *connection, uint_t eventFlags)
Control connection event handler.
void ftpServerAcceptControlChannel(FtpServerContext *context)
Accept control connection.
FTP control connection.
void ftpServerRegisterDataChannelEvents(FtpClientConnection *connection, SocketEventDesc *eventDesc)
Register data connection events.
void ftpServerProcessDataChannelEvents(FtpClientConnection *connection, uint_t eventFlags)
Data connection event handler.
FTP data connection.
void ftpServerCloseConnection(FtpClientConnection *connection)
Close client connection properly.
void ftpServerTick(FtpServerContext *context)
Handle periodic operations.
Helper functions for FTP server.
const IpAddr IP_ADDR_ANY
Definition: ip.c:51
#define IPV4_UNSPECIFIED_ADDR
Definition: ipv4.h:110
#define socketBindToInterface
Definition: net_legacy.h:193
#define osMemset(p, value, length)
Definition: os_port.h:135
#define TRUE
Definition: os_port.h:50
#define FALSE
Definition: os_port.h:46
#define osStrcpy(s1, s2)
Definition: os_port.h:207
void osDeleteEvent(OsEvent *event)
Delete an event object.
const OsTaskParameters OS_TASK_DEFAULT_PARAMS
void osDelayTask(systime_t delay)
Delay routine.
OsTaskId osCreateTask(const char_t *name, OsTaskCode taskCode, void *arg, const OsTaskParameters *params)
Create a task.
void osDeleteTask(OsTaskId taskId)
Delete a task.
systime_t osGetSystemTime(void)
Retrieve system time.
bool_t osCreateEvent(OsEvent *event)
Create an event object.
void osSetEvent(OsEvent *event)
Set the specified event object to the signaled state.
void(* OsTaskCode)(void *arg)
Task routine.
#define osEnterTask()
#define OS_SELF_TASK_ID
#define OS_INVALID_TASK_ID
uint32_t systime_t
System time.
#define osExitTask()
void pathCombine(char_t *path, const char_t *more, size_t maxLen)
Concatenate two paths.
Definition: path.c:370
void pathCanonicalize(char_t *path)
Simplify a path.
Definition: path.c:150
void pathRemoveSlash(char_t *path)
Remove the trailing slash from a given path.
Definition: path.c:340
Path manipulation helper functions.
error_t socketBind(Socket *socket, const IpAddr *localIpAddr, uint16_t localPort)
Associate a local address with a socket.
Definition: socket.c:778
error_t socketPoll(SocketEventDesc *eventDesc, uint_t size, OsEvent *extEvent, systime_t timeout)
Wait for one of a set of sockets to become ready to perform I/O.
Definition: socket.c:1592
error_t socketListen(Socket *socket, uint_t backlog)
Place a socket in the listening state.
Definition: socket.c:875
Socket * socketOpen(uint_t type, uint_t protocol)
Create a socket (UDP or TCP)
Definition: socket.c:125
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:148
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:1517
error_t socketSetRxBufferSize(Socket *socket, size_t size)
Specify the size of the TCP receive buffer.
Definition: socket.c:699
error_t socketSetTxBufferSize(Socket *socket, size_t size)
Specify the size of the TCP send buffer.
Definition: socket.c:663
@ SOCKET_IP_PROTO_TCP
Definition: socket.h:100
@ SOCKET_TYPE_STREAM
Definition: socket.h:85
@ SOCKET_EVENT_RX_READY
Definition: socket.h:169
FTP server settings.
Definition: ftp_server.h:351
FtpServerConnectCallback connectCallback
Connection callback function.
Definition: ftp_server.h:363
FtpServerCheckPasswordCallback checkPasswordCallback
Password verification callback function.
Definition: ftp_server.h:369
uint16_t passivePortMin
Passive port range (lower value)
Definition: ftp_server.h:356
OsTaskParameters task
Task parameters.
Definition: ftp_server.h:352
Ipv4Addr publicIpv4Addr
Public IPv4 address to be used in PASV replies.
Definition: ftp_server.h:358
uint16_t dataPort
FTP data port number.
Definition: ftp_server.h:355
FtpClientConnection * connections
Client connections.
Definition: ftp_server.h:361
char_t rootDir[FTP_SERVER_MAX_ROOT_DIR_LEN+1]
Root directory.
Definition: ftp_server.h:362
FtpServerTlsInitCallback tlsInitCallback
TLS initialization callback function.
Definition: ftp_server.h:366
FtpServerCheckUserCallback checkUserCallback
User verification callback function.
Definition: ftp_server.h:368
uint16_t passivePortMax
Passive port range (upper value)
Definition: ftp_server.h:357
FtpServerDisconnectCallback disconnectCallback
Disconnection callback function.
Definition: ftp_server.h:364
uint16_t port
FTP command port number.
Definition: ftp_server.h:354
uint_t mode
Security modes.
Definition: ftp_server.h:359
uint_t maxConnections
Maximum number of client connections.
Definition: ftp_server.h:360
FtpServerGetFilePermCallback getFilePermCallback
Callback used to retrieve file permissions.
Definition: ftp_server.h:370
FtpServerUnknownCommandCallback unknownCommandCallback
Unknown command callback function.
Definition: ftp_server.h:371
NetInterface * interface
Underlying network interface.
Definition: ftp_server.h:353
error_t tlsInitTicketContext(TlsTicketContext *ticketContext)
Initialize ticket encryption context.
Definition: tls_ticket.c:49
void tlsFreeTicketContext(TlsTicketContext *ticketContext)
Properly dispose ticket encryption context.
Definition: tls_ticket.c:448