tftp_server.c
Go to the documentation of this file.
1 /**
2  * @file tftp_server.c
3  * @brief TFTP server
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  * @section Description
28  *
29  * TFTP is a very simple protocol used to transfer files. Refer to the
30  * following RFCs for complete details:
31  * - RFC 1123: Requirements for Internet Hosts
32  * - RFC 1350: The TFTP Protocol (Revision 2)
33  * - RFC 1782: TFTP Option Extension
34  * - RFC 1783: TFTP Blocksize Option
35  * - RFC 1784: TFTP Timeout Interval and Transfer Size Options
36  *
37  * @author Oryx Embedded SARL (www.oryx-embedded.com)
38  * @version 2.5.0
39  **/
40 
41 //Switch to the appropriate trace level
42 #define TRACE_LEVEL TFTP_TRACE_LEVEL
43 
44 //Dependencies
45 #include "core/net.h"
46 #include "tftp/tftp_server.h"
47 #include "tftp/tftp_server_misc.h"
48 #include "debug.h"
49 
50 //Check TCP/IP stack configuration
51 #if (TFTP_SERVER_SUPPORT == ENABLED)
52 
53 
54 /**
55  * @brief Initialize settings with default values
56  * @param[out] settings Structure that contains TFTP server settings
57  **/
58 
60 {
61  //Default task parameters
62  settings->task = OS_TASK_DEFAULT_PARAMS;
65 
66  //The TFTP server is not bound to any interface
67  settings->interface = NULL;
68 
69  //TFTP port number
70  settings->port = TFTP_PORT;
71 
72  //Open file callback function
73  settings->openFileCallback = NULL;
74  //Write file callback function
75  settings->writeFileCallback = NULL;
76  //Read file callback function
77  settings->readFileCallback = NULL;
78  //Close file callback function
79  settings->closeFileCallback = NULL;
80 }
81 
82 
83 /**
84  * @brief TFTP server initialization
85  * @param[in] context Pointer to the TFTP server context
86  * @param[in] settings TFTP server specific settings
87  * @return Error code
88  **/
89 
91  const TftpServerSettings *settings)
92 {
93  error_t error;
94 
95  //Debug message
96  TRACE_INFO("Initializing TFTP server...\r\n");
97 
98  //Ensure the parameters are valid
99  if(context == NULL || settings == NULL)
101 
102  //Clear the TFTP server context
103  osMemset(context, 0, sizeof(TftpServerContext));
104 
105  //Initialize task parameters
106  context->taskParams = settings->task;
107  context->taskId = OS_INVALID_TASK_ID;
108 
109  //Save user settings
110  context->settings = *settings;
111 
112  //Initialize status code
113  error = NO_ERROR;
114 
115  //Create an event object to poll the state of sockets
116  if(!osCreateEvent(&context->event))
117  {
118  //Failed to create event
119  error = ERROR_OUT_OF_RESOURCES;
120  }
121 
122  //Check status code
123  if(error)
124  {
125  //Clean up side effects
126  tftpServerDeinit(context);
127  }
128 
129  //Return status code
130  return error;
131 }
132 
133 
134 /**
135  * @brief Start TFTP server
136  * @param[in] context Pointer to the TFTP server context
137  * @return Error code
138  **/
139 
141 {
142  error_t error;
143 
144  //Make sure the TFTP server context is valid
145  if(context == NULL)
147 
148  //Debug message
149  TRACE_INFO("Starting TFTP server...\r\n");
150 
151  //Make sure the TFTP server is not already running
152  if(context->running)
153  return ERROR_ALREADY_RUNNING;
154 
155  //Start of exception handling block
156  do
157  {
158  //Open a UDP socket
160  //Failed to open socket?
161  if(context->socket == NULL)
162  {
163  //Report an error
164  error = ERROR_OPEN_FAILED;
165  break;
166  }
167 
168  //Associate the socket with the relevant interface
169  error = socketBindToInterface(context->socket,
170  context->settings.interface);
171  //Unable to bind the socket to the desired interface?
172  if(error)
173  break;
174 
175  //The TFTP server listens for connection requests on port 69
176  error = socketBind(context->socket, &IP_ADDR_ANY, context->settings.port);
177  //Unable to bind the socket to the desired port?
178  if(error)
179  break;
180 
181  //Start the TFTP server
182  context->stop = FALSE;
183  context->running = TRUE;
184 
185  //Create a task
186  context->taskId = osCreateTask("TFTP Server", (OsTaskCode) tftpServerTask,
187  context, &context->taskParams);
188 
189  //Failed to create task?
190  if(context->taskId == OS_INVALID_TASK_ID)
191  {
192  //Report an error
193  error = ERROR_OUT_OF_RESOURCES;
194  break;
195  }
196 
197  //End of exception handling block
198  } while(0);
199 
200  //Any error to report?
201  if(error)
202  {
203  //Clean up side effects
204  context->running = FALSE;
205 
206  //Close the UDP socket
207  socketClose(context->socket);
208  context->socket = NULL;
209  }
210 
211  //Return status code
212  return error;
213 }
214 
215 
216 /**
217  * @brief Stop TFTP server
218  * @param[in] context Pointer to the TFTP server context
219  * @return Error code
220  **/
221 
223 {
224  uint_t i;
225 
226  //Make sure the TFTP server context is valid
227  if(context == NULL)
229 
230  //Debug message
231  TRACE_INFO("Stopping TFTP server...\r\n");
232 
233  //Check whether the TFTP server is running
234  if(context->running)
235  {
236 #if (NET_RTOS_SUPPORT == ENABLED)
237  //Stop the TFTP server
238  context->stop = TRUE;
239  //Send a signal to the task to abort any blocking operation
240  osSetEvent(&context->event);
241 
242  //Wait for the task to terminate
243  while(context->running)
244  {
245  osDelayTask(1);
246  }
247 #endif
248 
249  //Loop through the connection table
250  for(i = 0; i < TFTP_SERVER_MAX_CONNECTIONS; i++)
251  {
252  //Close client connection
253  tftpServerCloseConnection(&context->connection[i]);
254  }
255 
256  //Close the UDP socket
257  socketClose(context->socket);
258  context->socket = NULL;
259  }
260 
261  //Successful processing
262  return NO_ERROR;
263 }
264 
265 
266 /**
267  * @brief TFTP server task
268  * @param[in] context Pointer to the TFTP server context
269  **/
270 
272 {
273  error_t error;
274  uint_t i;
275  TftpClientConnection *connection;
276 
277 #if (NET_RTOS_SUPPORT == ENABLED)
278  //Task prologue
279  osEnterTask();
280 
281  //Process events
282  while(1)
283  {
284 #endif
285  //Clear event descriptor set
286  osMemset(context->eventDesc, 0, sizeof(context->eventDesc));
287 
288  //Specify the events the application is interested in
289  for(i = 0; i < TFTP_SERVER_MAX_CONNECTIONS; i++)
290  {
291  //Point to the structure describing the current connection
292  connection = &context->connection[i];
293 
294  //Loop through active connections only
295  if(connection->state != TFTP_STATE_CLOSED)
296  {
297  //Wait for a packet to be received
298  context->eventDesc[i].socket = connection->socket;
299  context->eventDesc[i].eventMask = SOCKET_EVENT_RX_READY;
300  }
301  }
302 
303  //The TFTP server listens for connection requests on port 69
304  context->eventDesc[i].socket = context->socket;
305  context->eventDesc[i].eventMask = SOCKET_EVENT_RX_READY;
306 
307  //Wait for one of the set of sockets to become ready to perform I/O
308  error = socketPoll(context->eventDesc, TFTP_SERVER_MAX_CONNECTIONS + 1,
309  &context->event, TFTP_SERVER_TICK_INTERVAL);
310 
311  //Check status code
312  if(error == NO_ERROR || error == ERROR_TIMEOUT ||
313  error == ERROR_WAIT_CANCELED)
314  {
315  //Stop request?
316  if(context->stop)
317  {
318  //Stop TFTP server operation
319  context->running = FALSE;
320  //Task epilogue
321  osExitTask();
322  //Kill ourselves
324  }
325 
326  //Event-driven processing
327  for(i = 0; i < TFTP_SERVER_MAX_CONNECTIONS; i++)
328  {
329  //Point to the structure describing the current connection
330  connection = &context->connection[i];
331 
332  //Loop through active connections only
333  if(connection->state != TFTP_STATE_CLOSED)
334  {
335  //Check whether a packet has been received
336  if((context->eventDesc[i].eventFlags & SOCKET_EVENT_RX_READY) != 0)
337  {
338  //Process incoming packet
339  tftpServerProcessPacket(context, connection);
340  }
341  }
342  }
343 
344  //Any connection request received on port 69?
345  if((context->eventDesc[i].eventFlags & SOCKET_EVENT_RX_READY) != 0)
346  {
347  //Accept connection request
348  tftpServerAcceptRequest(context);
349  }
350  }
351 
352  //Handle periodic operations
353  tftpServerTick(context);
354 
355 #if (NET_RTOS_SUPPORT == ENABLED)
356  }
357 #endif
358 }
359 
360 
361 /**
362  * @brief Release TFTP server context
363  * @param[in] context Pointer to the TFTP server context
364  **/
365 
367 {
368  //Make sure the TFTP server context is valid
369  if(context != NULL)
370  {
371  //Free previously allocated resources
372  osDeleteEvent(&context->event);
373 
374  //Clear TFTP server context
375  osMemset(context, 0, sizeof(TftpServerContext));
376  }
377 }
378 
379 #endif
OsTaskId osCreateTask(const char_t *name, OsTaskCode taskCode, void *arg, const OsTaskParameters *params)
Create a task.
@ SOCKET_IP_PROTO_UDP
Definition: socket.h:108
error_t socketBind(Socket *socket, const IpAddr *localIpAddr, uint16_t localPort)
Associate a local address with a socket.
Definition: socket.c:1321
void tftpServerProcessPacket(TftpServerContext *context, TftpClientConnection *connection)
Process incoming packet.
#define osExitTask()
#define TFTP_SERVER_TICK_INTERVAL
Definition: tftp_server.h:66
TftpServerCloseFileCallback closeFileCallback
Close file callback function.
Definition: tftp_server.h:179
error_t tftpServerInit(TftpServerContext *context, const TftpServerSettings *settings)
TFTP server initialization.
Definition: tftp_server.c:90
#define TRUE
Definition: os_port.h:50
uint16_t port
TFTP port number.
Definition: tftp_server.h:175
void tftpServerCloseConnection(TftpClientConnection *connection)
Close client connection.
NetInterface * interface
Underlying network interface.
Definition: tftp_server.h:174
#define OS_INVALID_TASK_ID
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:2067
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
#define TftpServerContext
Definition: tftp_server.h:113
@ SOCKET_TYPE_DGRAM
Definition: socket.h:93
void tftpServerTask(TftpServerContext *context)
TFTP server task.
Definition: tftp_server.c:271
void tftpServerDeinit(TftpServerContext *context)
Release TFTP server context.
Definition: tftp_server.c:366
#define OS_SELF_TASK_ID
TFTP server.
TftpServerReadFileCallback readFileCallback
Read file callback function.
Definition: tftp_server.h:178
TftpServerWriteFileCallback writeFileCallback
Write file callback function.
Definition: tftp_server.h:177
@ ERROR_OPEN_FAILED
Definition: error.h:75
const IpAddr IP_ADDR_ANY
Definition: ip.c:53
void osDeleteTask(OsTaskId taskId)
Delete a task.
#define FALSE
Definition: os_port.h:46
OsTaskParameters task
Task parameters.
Definition: tftp_server.h:173
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
error_t
Error codes.
Definition: error.h:43
void(* OsTaskCode)(void *arg)
Task routine.
void osDeleteEvent(OsEvent *event)
Delete an event object.
error_t tftpServerStart(TftpServerContext *context)
Start TFTP server.
Definition: tftp_server.c:140
const OsTaskParameters OS_TASK_DEFAULT_PARAMS
TftpServerOpenFileCallback openFileCallback
Open file callback function.
Definition: tftp_server.h:176
#define TRACE_INFO(...)
Definition: debug.h:105
#define TFTP_SERVER_MAX_CONNECTIONS
Definition: tftp_server.h:59
Socket * socketOpen(uint_t type, uint_t protocol)
Create a socket (UDP or TCP)
Definition: socket.c:125
#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:2154
void tftpServerTick(TftpServerContext *context)
Handle periodic operations.
#define socketBindToInterface
Definition: net_legacy.h:193
@ TFTP_STATE_CLOSED
Definition: tftp_server.h:127
@ ERROR_TIMEOUT
Definition: error.h:95
void tftpServerAcceptRequest(TftpServerContext *context)
Accept connection request.
#define TFTP_PORT
Definition: tftp_common.h:38
@ SOCKET_EVENT_RX_READY
Definition: socket.h:179
#define TFTP_SERVER_PRIORITY
Definition: tftp_server.h:54
@ ERROR_WAIT_CANCELED
Definition: error.h:73
bool_t osCreateEvent(OsEvent *event)
Create an event object.
#define TftpClientConnection
Definition: tftp_server.h:109
Helper functions for TFTP server.
void osDelayTask(systime_t delay)
Delay routine.
void osSetEvent(OsEvent *event)
Set the specified event object to the signaled state.
TFTP server settings.
Definition: tftp_server.h:172
error_t tftpServerStop(TftpServerContext *context)
Stop TFTP server.
Definition: tftp_server.c:222
#define TFTP_SERVER_STACK_SIZE
Definition: tftp_server.h:47
unsigned int uint_t
Definition: compiler_port.h:57
#define osMemset(p, value, length)
Definition: os_port.h:138
TCP/IP stack core.
void tftpServerGetDefaultSettings(TftpServerSettings *settings)
Initialize settings with default values.
Definition: tftp_server.c:59
@ ERROR_ALREADY_RUNNING
Definition: error.h:294
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.