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