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