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