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