ftp_server_control.c
Go to the documentation of this file.
1 /**
2  * @file ftp_server_control.c
3  * @brief FTP control connection
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  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.5.2
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL FTP_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "ftp/ftp_server.h"
38 #include "ftp/ftp_server_control.h"
40 #include "ftp/ftp_server_misc.h"
41 #include "path.h"
42 #include "debug.h"
43 
44 //Check TCP/IP stack configuration
45 #if (FTP_SERVER_SUPPORT == ENABLED)
46 
47 
48 /**
49  * @brief Register control connection events
50  * @param[in] connection Pointer to the client connection
51  * @param[in] eventDesc Socket events to be registered
52  **/
53 
55  SocketEventDesc *eventDesc)
56 {
57  //Check the state of the control connection
58  if(connection->controlChannel.state == FTP_CHANNEL_STATE_CONNECT_TLS)
59  {
60 #if (FTP_SERVER_TLS_SUPPORT == ENABLED)
61  //Any data pending in the send buffer?
62  if(tlsIsTxReady(connection->controlChannel.tlsContext))
63  {
64  //Wait until there is more room in the send buffer
65  eventDesc->socket = connection->controlChannel.socket;
66  eventDesc->eventMask = SOCKET_EVENT_TX_READY;
67  }
68  else
69  {
70  //Wait for data to be available for reading
71  eventDesc->socket = connection->controlChannel.socket;
72  eventDesc->eventMask = SOCKET_EVENT_RX_READY;
73  }
74 #endif
75  }
76  else if(connection->responseLen > 0)
77  {
78  //Wait until there is more room in the send buffer
79  eventDesc->socket = connection->controlChannel.socket;
80  eventDesc->eventMask = SOCKET_EVENT_TX_READY;
81  }
82  else if(connection->controlChannel.state == FTP_CHANNEL_STATE_AUTH_TLS_2)
83  {
84 #if (FTP_SERVER_TLS_SUPPORT == ENABLED)
85  //Any data pending in the send buffer?
86  if(tlsIsTxReady(connection->controlChannel.tlsContext))
87  {
88  //Wait until there is more room in the send buffer
89  eventDesc->socket = connection->controlChannel.socket;
90  eventDesc->eventMask = SOCKET_EVENT_TX_READY;
91  }
92  else
93  {
94  //Wait for data to be available for reading
95  eventDesc->socket = connection->controlChannel.socket;
96  eventDesc->eventMask = SOCKET_EVENT_RX_READY;
97  }
98 #endif
99  }
100  else if(connection->controlChannel.state == FTP_CHANNEL_STATE_WAIT_ACK)
101  {
102  //Wait for all the data to be transmitted and acknowledged
103  eventDesc->socket = connection->controlChannel.socket;
104  eventDesc->eventMask = SOCKET_EVENT_TX_ACKED;
105  }
106  else if(connection->controlChannel.state == FTP_CHANNEL_STATE_SHUTDOWN_TX)
107  {
108  //Wait for the FIN to be acknowledged
109  eventDesc->socket = connection->controlChannel.socket;
110  eventDesc->eventMask = SOCKET_EVENT_TX_SHUTDOWN;
111  }
112  else if(connection->controlChannel.state == FTP_CHANNEL_STATE_SHUTDOWN_RX)
113  {
114  //Wait for a FIN to be received
115  eventDesc->socket = connection->controlChannel.socket;
116  eventDesc->eventMask = SOCKET_EVENT_RX_SHUTDOWN;
117  }
118  else
119  {
120 #if (FTP_SERVER_TLS_SUPPORT == ENABLED)
121  //Any data pending in the receive buffer?
122  if(connection->controlChannel.tlsContext != NULL &&
123  tlsIsRxReady(connection->controlChannel.tlsContext))
124  {
125  //No need to poll the underlying socket for incoming traffic
126  eventDesc->eventFlags = SOCKET_EVENT_RX_READY;
127  }
128  else
129 #endif
130  {
131  //Wait for data to be available for reading
132  eventDesc->socket = connection->controlChannel.socket;
133  eventDesc->eventMask = SOCKET_EVENT_RX_READY;
134  }
135  }
136 }
137 
138 
139 /**
140  * @brief Control connection event handler
141  * @param[in] connection Pointer to the client connection
142  * @param[in] eventFlags Event to be processed
143  **/
144 
146  uint_t eventFlags)
147 {
148  error_t error;
149  size_t n;
150  FtpServerContext *context;
151 
152  //Point to the FTP server context
153  context = connection->context;
154 
155 #if (FTP_SERVER_TLS_SUPPORT == ENABLED)
156  //TLS session establishment in progress?
157  if(connection->controlChannel.state == FTP_CHANNEL_STATE_CONNECT_TLS ||
158  connection->controlChannel.state == FTP_CHANNEL_STATE_AUTH_TLS_2)
159  {
160  //Perform TLS handshake
161  error = ftpServerEstablishSecureChannel(&connection->controlChannel);
162 
163  //Check status code
164  if(error == NO_ERROR)
165  {
166  //Update the state of the control connection
167  connection->controlChannel.state = FTP_CHANNEL_STATE_IDLE;
168  }
169  else if(error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
170  {
171  }
172  else
173  {
174  //Close connection with the client
175  ftpServerCloseConnection(connection);
176  }
177  }
178  else
179 #endif
180  {
181  //Check event flags
182  if(eventFlags == SOCKET_EVENT_TX_READY)
183  {
184  //Transmit data
185  error = ftpServerWriteChannel(&connection->controlChannel,
186  connection->response + connection->responsePos,
187  connection->responseLen, &n, 0);
188 
189  //Check status code
190  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
191  {
192  //Advance data pointer
193  connection->responsePos += n;
194  //Number of bytes still available in the response buffer
195  connection->responseLen -= n;
196 
197  //Check whether the AUTH response has been transmitted
198  if(connection->responseLen == 0 &&
199  connection->controlChannel.state == FTP_CHANNEL_STATE_AUTH_TLS_1)
200  {
201  //TLS initialization
202  error = ftpServerOpenSecureChannel(context,
203  &connection->controlChannel, FTP_SERVER_TLS_TX_BUFFER_SIZE,
205 
206  //Check status code
207  if(!error)
208  {
209  //Perform TLS handshake
210  connection->controlChannel.state = FTP_CHANNEL_STATE_AUTH_TLS_2;
211  }
212  else
213  {
214  //Close connection with the client
215  ftpServerCloseConnection(connection);
216  }
217  }
218  }
219  else
220  {
221  //Close connection with the client
222  ftpServerCloseConnection(connection);
223  }
224  }
225  else if(eventFlags == SOCKET_EVENT_RX_READY)
226  {
227  //Receive data
228  error = ftpServerReadChannel(&connection->controlChannel,
229  connection->command + connection->commandLen,
230  FTP_SERVER_MAX_LINE_LEN - connection->commandLen, &n, 0);
231 
232  //Check status code
233  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
234  {
235  //Number of bytes available in the command buffer
236  connection->commandLen += n;
237  //Process incoming command
238  ftpServerProcessCommand(connection);
239  }
240  else if(error == ERROR_END_OF_STREAM)
241  {
242  //Gracefully disconnect from the remote host
243  connection->controlChannel.state = FTP_CHANNEL_STATE_WAIT_ACK;
244  }
245  else
246  {
247  //Close connection with the client
248  ftpServerCloseConnection(connection);
249  }
250  }
251  else if(eventFlags == SOCKET_EVENT_TX_ACKED)
252  {
253  //Disable transmission
254  socketShutdown(connection->controlChannel.socket, SOCKET_SD_SEND);
255  //Next state
256  connection->controlChannel.state = FTP_CHANNEL_STATE_SHUTDOWN_TX;
257  }
258  else if(eventFlags == SOCKET_EVENT_TX_SHUTDOWN)
259  {
260  //Disable reception
261  socketShutdown(connection->controlChannel.socket, SOCKET_SD_RECEIVE);
262  //Next state
263  connection->controlChannel.state = FTP_CHANNEL_STATE_SHUTDOWN_RX;
264  }
265  else if(eventFlags == SOCKET_EVENT_RX_SHUTDOWN)
266  {
267  //Properly close connection
268  ftpServerCloseConnection(connection);
269  }
270  }
271 }
272 
273 
274 /**
275  * @brief Accept control connection
276  * @param[in] context Pointer to the FTP server context
277  **/
278 
280 {
281  error_t error;
282  uint_t i;
283  Socket *socket;
284  IpAddr clientIpAddr;
285  uint16_t clientPort;
286  FtpClientConnection *connection;
287 
288  //Accept incoming connection
289  socket = socketAccept(context->socket, &clientIpAddr, &clientPort);
290 
291  //Make sure the socket handle is valid
292  if(socket != NULL)
293  {
294  //Force the socket to operate in non-blocking mode
296 
297  //Initialize pointer
298  connection = NULL;
299 
300  //Loop through the connection table
301  for(i = 0; i < context->maxConnections; i++)
302  {
303  //Check the state of the current connection
304  if(context->connections[i].controlChannel.state == FTP_CHANNEL_STATE_CLOSED &&
305  context->connections[i].dataChannel.state == FTP_CHANNEL_STATE_CLOSED)
306  {
307  //The current entry is free
308  connection = &context->connections[i];
309  break;
310  }
311  }
312 
313  //If the connection table runs out of space, then the client's connection
314  //request is rejected
315  if(connection != NULL)
316  {
317  //Clear the structure describing the connection
318  osMemset(connection, 0, sizeof(FtpClientConnection));
319 
320  //Attach FTP server context
321  connection->context = context;
322  //Underlying network interface
323  connection->interface = socketGetInterface(socket);
324  //Save socket handle
325  connection->controlChannel.socket = socket;
326  //Initialize time stamp
327  connection->timestamp = osGetSystemTime();
328 
329  //Set default user's root directory
330  pathCopy(connection->rootDir, context->rootDir,
332 
333  //Set default user's home directory
334  pathCopy(connection->currentDir, context->rootDir,
336 
337  //Format greeting message
338  osStrcpy(connection->response, "220 Service ready for new user\r\n");
339 
340  //Any registered callback?
341  if(context->connectCallback != NULL)
342  {
343  //Invoke user callback function
344  error = context->connectCallback(connection, &clientIpAddr,
345  clientPort);
346  }
347  else
348  {
349  //No callback function defined
350  error = NO_ERROR;
351  }
352 
353  //Check status code
354  if(!error)
355  {
356  //Debug message
357  TRACE_INFO("FTP Server: Control connection established with client %s port %"
358  PRIu16 "...\r\n", ipAddrToString(&clientIpAddr, NULL), clientPort);
359 
360  //Debug message
361  TRACE_DEBUG("FTP server: %s", connection->response);
362 
363  //Number of bytes in the response buffer
364  connection->responseLen = osStrlen(connection->response);
365  connection->responsePos = 0;
366 
367  //Implicit TLS mode supported by the server?
368  if((context->mode & FTP_SERVER_MODE_IMPLICIT_TLS) != 0)
369  {
370  //TLS initialization
371  error = ftpServerOpenSecureChannel(context,
372  &connection->controlChannel, FTP_SERVER_TLS_TX_BUFFER_SIZE,
374 
375  //Check status code
376  if(!error)
377  {
378  //Perform TLS handshake
379  connection->controlChannel.state = FTP_CHANNEL_STATE_CONNECT_TLS;
380  }
381  else
382  {
383  //Close connection with the client
384  ftpServerCloseConnection(connection);
385  }
386  }
387  else
388  {
389  //Enter default state
390  connection->controlChannel.state = FTP_CHANNEL_STATE_IDLE;
391  }
392  }
393  else
394  {
395  //The connection attempt has been refused
396  osMemset(connection, 0, sizeof(FtpClientConnection));
397  }
398  }
399  else
400  {
401  //The connection table runs out of space
402  error = ERROR_OUT_OF_RESOURCES;
403  }
404 
405  //Check status code
406  if(error)
407  {
408  //Debug message
409  TRACE_INFO("FTP Server: Connection refused with client %s port %"
410  PRIu16 "...\r\n", ipAddrToString(&clientIpAddr, NULL), clientPort);
411 
412  //The FTP server cannot accept the incoming connection request
414  }
415  }
416 }
417 
418 
419 /**
420  * @brief Close control connection
421  * @param[in] connection Pointer to the client connection
422  **/
423 
425 {
426  IpAddr clientIpAddr;
427  uint16_t clientPort;
428  FtpServerContext *context;
429 
430  //Point to the FTP server context
431  context = connection->context;
432 
433  //Check whether the control connection is active
434  if(connection->controlChannel.socket != NULL)
435  {
436  //Retrieve the address of the peer to which a socket is connected
437  socketGetRemoteAddr(connection->controlChannel.socket, &clientIpAddr,
438  &clientPort);
439 
440  //Debug message
441  TRACE_INFO("FTP server: Closing control connection with client %s port %"
442  PRIu16 "...\r\n", ipAddrToString(&clientIpAddr, NULL), clientPort);
443 
444  //Any registered callback?
445  if(context->disconnectCallback != NULL)
446  {
447  //Invoke user callback function
448  context->disconnectCallback(connection, &clientIpAddr, clientPort);
449  }
450 
451 #if (FTP_SERVER_TLS_SUPPORT == ENABLED)
452  //Valid TLS context?
453  if(connection->controlChannel.tlsContext != NULL)
454  {
455  //Release TLS context
456  tlsFree(connection->controlChannel.tlsContext);
457  connection->controlChannel.tlsContext = NULL;
458  }
459 #endif
460 
461  //Valid socket?
462  if(connection->controlChannel.socket != NULL)
463  {
464  //Close control connection
465  socketClose(connection->controlChannel.socket);
466  connection->controlChannel.socket = NULL;
467  }
468 
469  //Mark the connection as closed
470  connection->controlChannel.state = FTP_CHANNEL_STATE_CLOSED;
471  }
472 }
473 
474 #endif
#define FtpServerContext
Definition: ftp_server.h:201
Path manipulation helper functions.
FTP server (command processing)
@ ERROR_WOULD_BLOCK
Definition: error.h:96
IP network address.
Definition: ip.h:90
@ FTP_CHANNEL_STATE_IDLE
Definition: ftp_server.h:222
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:2071
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
#define FTP_SERVER_MAX_PATH_LEN
Definition: ftp_server.h:123
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:804
Transport protocol abstraction layer.
#define osStrlen(s)
Definition: os_port.h:168
@ ERROR_END_OF_STREAM
Definition: error.h:211
#define FTP_SERVER_MAX_ROOT_DIR_LEN
Definition: ftp_server.h:109
error_t socketGetRemoteAddr(Socket *socket, IpAddr *remoteIpAddr, uint16_t *remotePort)
Retrieve the address of the peer to which a socket is connected.
Definition: socket.c:1994
Helper functions for FTP server.
Structure describing socket events.
Definition: socket.h:432
@ FTP_CHANNEL_STATE_CLOSED
Definition: ftp_server.h:219
@ FTP_CHANNEL_STATE_AUTH_TLS_1
Definition: ftp_server.h:226
@ SOCKET_SD_SEND
Definition: socket.h:160
@ FTP_CHANNEL_STATE_WAIT_ACK
Definition: ftp_server.h:236
error_t
Error codes.
Definition: error.h:43
int_t socket(int_t family, int_t type, int_t protocol)
Create a socket that is bound to a specific transport service provider.
Definition: bsd_socket.c:65
@ SOCKET_EVENT_TX_READY
Definition: socket.h:175
@ FTP_CHANNEL_STATE_AUTH_TLS_2
Definition: ftp_server.h:227
@ FTP_CHANNEL_STATE_SHUTDOWN_TX
Definition: ftp_server.h:237
void ftpServerAcceptControlChannel(FtpServerContext *context)
Accept control connection.
bool_t tlsIsTxReady(TlsContext *context)
Check whether some data is ready for transmission.
Definition: tls.c:2355
@ SOCKET_EVENT_RX_SHUTDOWN
Definition: socket.h:180
void ftpServerCloseConnection(FtpClientConnection *connection)
Close client connection properly.
error_t ftpServerEstablishSecureChannel(FtpServerChannel *channel)
Establish secure connection.
@ FTP_CHANNEL_STATE_SHUTDOWN_RX
Definition: ftp_server.h:238
error_t socketShutdown(Socket *socket, uint_t how)
Disable reception, transmission, or both.
Definition: socket.c:2029
#define TRACE_INFO(...)
Definition: debug.h:105
error_t ftpServerOpenSecureChannel(FtpServerContext *context, FtpServerChannel *channel, size_t txBufferSize, size_t rxBufferSize)
Open secure connection.
uint_t eventFlags
Returned events.
Definition: socket.h:435
Socket * socketAccept(Socket *socket, IpAddr *clientIpAddr, uint16_t *clientPort)
Permit an incoming connection attempt on a socket.
Definition: socket.c:1456
#define FTP_SERVER_TLS_TX_BUFFER_SIZE
Definition: ftp_server.h:144
bool_t tlsIsRxReady(TlsContext *context)
Check whether some data is available in the receive buffer.
Definition: tls.c:2389
#define TRACE_DEBUG(...)
Definition: debug.h:119
@ ERROR_TIMEOUT
Definition: error.h:95
@ SOCKET_EVENT_TX_ACKED
Definition: socket.h:177
@ SOCKET_EVENT_RX_READY
Definition: socket.h:179
uint8_t n
@ SOCKET_EVENT_TX_SHUTDOWN
Definition: socket.h:178
void ftpServerProcessCommand(FtpClientConnection *connection)
FTP command processing.
@ SOCKET_SD_RECEIVE
Definition: socket.h:159
#define Socket
Definition: socket.h:36
NetInterface * socketGetInterface(Socket *socket)
Retrieve the underlying interface.
Definition: socket.c:1298
void ftpServerCloseControlChannel(FtpClientConnection *connection)
Close control connection.
void ftpServerRegisterControlChannelEvents(FtpClientConnection *connection, SocketEventDesc *eventDesc)
Register control connection events.
error_t ftpServerReadChannel(FtpServerChannel *channel, void *data, size_t size, size_t *received, uint_t flags)
Receive data using the relevant transport protocol.
FTP server (File Transfer Protocol)
#define FTP_SERVER_MIN_TLS_RX_BUFFER_SIZE
Definition: ftp_server.h:151
#define FTP_SERVER_MAX_LINE_LEN
Definition: ftp_server.h:95
#define FtpClientConnection
Definition: ftp_server.h:205
void tlsFree(TlsContext *context)
Release TLS context.
Definition: tls.c:2596
error_t ftpServerWriteChannel(FtpServerChannel *channel, const void *data, size_t length, size_t *written, uint_t flags)
Send data using the relevant transport protocol.
Socket * socket
Handle to a socket to monitor.
Definition: socket.h:433
unsigned int uint_t
Definition: compiler_port.h:57
#define osMemset(p, value, length)
Definition: os_port.h:138
TCP/IP stack core.
#define osStrcpy(s1, s2)
Definition: os_port.h:210
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:148
FTP control connection.
@ FTP_CHANNEL_STATE_CONNECT_TLS
Definition: ftp_server.h:220
uint_t eventMask
Requested events.
Definition: socket.h:434
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
void pathCopy(char_t *dest, const char_t *src, size_t maxLen)
Copy a path.
Definition: path.c:141
@ FTP_SERVER_MODE_IMPLICIT_TLS
Definition: ftp_server.h:249
systime_t osGetSystemTime(void)
Retrieve system time.
void ftpServerProcessControlChannelEvents(FtpClientConnection *connection, uint_t eventFlags)
Control connection event handler.