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-2019 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.6
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  strcpy(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  memset(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  memset(&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  //Debug message
257  TRACE_INFO("Starting FTP server...\r\n");
258 
259  //Make sure the FTP server context is valid
260  if(context == NULL)
262 
263  //Create the FTP server task
264  task = osCreateTask("FTP Server", (OsTaskCode) ftpServerTask,
266 
267  //Unable to create the task?
268  if(task == OS_INVALID_HANDLE)
269  return ERROR_OUT_OF_RESOURCES;
270 
271  //Successful processing
272  return NO_ERROR;
273 }
274 
275 
276 /**
277  * @brief Set home directory
278  * @param[in] connection Pointer to the client connection
279  * @param[in] homeDir NULL-terminated string specifying the home directory
280  * @return Error code
281  **/
282 
284  const char_t *homeDir)
285 {
286  //Check parameters
287  if(connection == NULL || homeDir == NULL)
289 
290  //Set home directory
291  pathCombine(connection->homeDir, homeDir, FTP_SERVER_MAX_HOME_DIR_LEN);
292 
293  //Clean the resulting path
294  pathCanonicalize(connection->homeDir);
295  pathRemoveSlash(connection->homeDir);
296 
297  //Set current directory
298  strcpy(connection->currentDir, connection->homeDir);
299 
300  //Successful processing
301  return NO_ERROR;
302 }
303 
304 
305 /**
306  * @brief FTP server task
307  * @param[in] context Pointer to the FTP server context
308  **/
309 
311 {
312  error_t error;
313  uint_t i;
314  systime_t time;
315  systime_t timeout;
316  FtpClientConnection *connection;
317 
318 #if (NET_RTOS_SUPPORT == ENABLED)
319  //Task prologue
320  osEnterTask();
321 
322  //Process events
323  while(1)
324  {
325 #endif
326  //Set polling timeout
327  timeout = FTP_SERVER_TICK_INTERVAL;
328 
329  //Clear event descriptor set
330  memset(context->eventDesc, 0, sizeof(context->eventDesc));
331 
332  //Specify the events the application is interested in
333  for(i = 0; i < context->settings.maxConnections; i++)
334  {
335  //Point to the structure describing the current connection
336  connection = &context->connections[i];
337 
338  //Check whether the control connection is active
339  if(connection->controlChannel.socket != NULL)
340  {
341  //Register the events related to the control connection
343  &context->eventDesc[2 * i]);
344 
345  //Check whether the socket is ready for I/O operation
346  if(context->eventDesc[2 * i].eventFlags != 0)
347  {
348  //No need to poll the underlying socket for incoming traffic
349  timeout = 0;
350  }
351  }
352 
353  //Check whether the data connection is active
354  if(connection->dataChannel.socket != NULL)
355  {
356  //Register the events related to the data connection
358  &context->eventDesc[2 * i + 1]);
359 
360  //Check whether the socket is ready for I/O operation
361  if(context->eventDesc[2 * i + 1].eventFlags != 0)
362  {
363  //No need to poll the underlying socket for incoming traffic
364  timeout = 0;
365  }
366  }
367  }
368 
369  //Accept connection request events
370  context->eventDesc[2 * i].socket = context->socket;
371  context->eventDesc[2 * i].eventMask = SOCKET_EVENT_RX_READY;
372 
373  //Wait for one of the set of sockets to become ready to perform I/O
374  error = socketPoll(context->eventDesc,
375  2 * context->settings.maxConnections + 1, &context->event, timeout);
376 
377  //Get current time
378  time = osGetSystemTime();
379 
380  //Check status code
381  if(error == NO_ERROR || error == ERROR_TIMEOUT)
382  {
383  //Event-driven processing
384  for(i = 0; i < context->settings.maxConnections; i++)
385  {
386  //Point to the structure describing the current connection
387  connection = &context->connections[i];
388 
389  //Check whether the control connection is active
390  if(connection->controlChannel.socket != NULL)
391  {
392  //Check whether the control socket is to ready to perform I/O
393  if(context->eventDesc[2 * i].eventFlags)
394  {
395  //Update time stamp
396  connection->timestamp = time;
397 
398  //Control connection event handler
400  context->eventDesc[2 * i].eventFlags);
401  }
402  }
403 
404  //Check whether the data connection is active
405  if(connection->dataChannel.socket != NULL)
406  {
407  //Check whether the data socket is ready to perform I/O
408  if(context->eventDesc[2 * i + 1].eventFlags)
409  {
410  //Update time stamp
411  connection->timestamp = time;
412 
413  //Data connection event handler
415  context->eventDesc[2 * i + 1].eventFlags);
416  }
417  }
418  }
419 
420  //Check the state of the listening socket
421  if(context->eventDesc[2 * i].eventFlags & SOCKET_EVENT_RX_READY)
422  {
423  //Accept connection request
425  }
426  }
427 
428  //Handle periodic operations
429  ftpServerTick(context);
430 
431 #if (NET_RTOS_SUPPORT == ENABLED)
432  }
433 #endif
434 }
435 
436 
437 /**
438  * @brief Release FTP server context
439  * @param[in] context Pointer to the FTP server context
440  **/
441 
443 {
444  uint_t i;
445 
446  //Make sure the FTP server context is valid
447  if(context != NULL)
448  {
449  //Loop through the connection table
450  for(i = 0; i < context->settings.maxConnections; i++)
451  {
452  //Close client connection
453  ftpServerCloseConnection(&context->connections[i]);
454  }
455 
456  //Close listening socket
457  socketClose(context->socket);
458 
459 #if (FTP_SERVER_TLS_SUPPORT == ENABLED && TLS_TICKET_SUPPORT == ENABLED)
460  //Release ticket encryption context
461  tlsFreeTicketContext(&context->tlsTicketContext);
462 #endif
463 
464  //Free previously allocated resources
465  osDeleteEvent(&context->event);
466 
467  //Clear FTP server context
468  memset(context, 0, sizeof(FtpServerContext));
469  }
470 }
471 
472 #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:355
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
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:822
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
error_t ftpServerSetHomeDir(FtpClientConnection *connection, const char_t *homeDir)
Set home directory.
Definition: ftp_server.c:283
NetInterface * interface
Underlying network interface.
Definition: ftp_server.h:346
uint16_t dataPort
FTP data port number.
Definition: ftp_server.h:348
@ SOCKET_TYPE_STREAM
Definition: socket.h:77
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:244
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:310
@ ERROR_OPEN_FAILED
Definition: error.h:74
const IpAddr IP_ADDR_ANY
Definition: ip.c:45
void pathCanonicalize(char_t *path)
Simplify a path.
Definition: path.c:112
error_t socketSetRxBufferSize(Socket *socket, size_t size)
Specify the size of the receive buffer.
Definition: socket.c:278
FtpServerCheckPasswordCallback checkPasswordCallback
Password verification callback function.
Definition: ftp_server.h:362
@ ERROR_INVALID_PARAMETER
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:94
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:95
#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:882
#define socketBindToInterface
Definition: net_legacy.h:270
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
@ ERROR_TIMEOUT
Definition: error.h:94
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
@ SOCKET_EVENT_RX_READY
Definition: socket.h:160
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)
FtpServerDisconnectCallback disconnectCallback
Disconnection callback function.
Definition: ftp_server.h:357
@ FTP_SERVER_MODE_PLAINTEXT
Definition: ftp_server.h:249
#define FtpClientConnection
Definition: ftp_server.h:207
#define FTP_SERVER_PASSIVE_PORT_MAX
Definition: ftp_server.h:179
void ftpServerDeinit(FtpServerContext *context)
Release FTP server context.
Definition: ftp_server.c:442
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 FTP_DATA_PORT
Definition: ftp_server.h:194
@ SOCKET_IP_PROTO_TCP
Definition: socket.h:92
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:219
void ftpServerProcessDataChannelEvents(FtpClientConnection *connection, uint_t eventFlags)
Data connection event handler.
FTP control connection.
uint32_t systime_t
Definition: compiler_port.h:46
@ NO_ERROR
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:444