sftp_server.c
Go to the documentation of this file.
1 /**
2  * @file sftp_server.c
3  * @brief SFTP server
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2019-2024 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneSSH 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.0
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL SFTP_TRACE_LEVEL
33 
34 //Dependencies
35 #include "ssh/ssh.h"
36 #include "sftp/sftp_server.h"
37 #include "sftp/sftp_server_misc.h"
38 #include "path.h"
39 #include "debug.h"
40 
41 //Check SSH stack configuration
42 #if (SFTP_SERVER_SUPPORT == ENABLED)
43 
44 
45 /**
46  * @brief Initialize settings with default values
47  * @param[out] settings Structure that contains SFTP server settings
48  **/
49 
51 {
52  //Default task parameters
53  settings->task = OS_TASK_DEFAULT_PARAMS;
56 
57  //SSH server context
58  settings->sshServerContext = NULL;
59 
60  //SFTP sessions
61  settings->numSessions = 0;
62  settings->sessions = NULL;
63 
64  //File objects
65  settings->numFileObjects = 0;
66  settings->fileObjects = NULL;
67 
68  //Root directory
69  settings->rootDir = NULL;
70 
71  //User verification callback function
72  settings->checkUserCallback = NULL;
73  //Callback used to retrieve file permissions
74  settings->getFilePermCallback = NULL;
75 }
76 
77 
78 /**
79  * @brief Initialize SFTP server context
80  * @param[in] context Pointer to the SFTP server context
81  * @param[in] settings SFTP server specific settings
82  * @return Error code
83  **/
84 
86  const SftpServerSettings *settings)
87 {
88  error_t error;
89  uint_t i;
90 
91  //Debug message
92  TRACE_INFO("Initializing SFTP server...\r\n");
93 
94  //Ensure the parameters are valid
95  if(context == NULL || settings == NULL)
97 
98  //Invalid SFTP sessions?
99  if(settings->sessions == NULL || settings->numSessions < 1 ||
101  {
103  }
104 
105  //Invalid file objects?
106  if(settings->fileObjects == NULL || settings->numFileObjects < 1)
107  {
109  }
110 
111  //Invalid root directory?
112  if(settings->rootDir == NULL ||
114  {
116  }
117 
118  //Initialize status code
119  error = NO_ERROR;
120 
121  //Clear SFTP server context
122  osMemset(context, 0, sizeof(SftpServerContext));
123 
124  //Initialize task parameters
125  context->taskParams = settings->task;
126  context->taskId = OS_INVALID_TASK_ID;
127 
128  //Save user settings
129  context->sshServerContext = settings->sshServerContext;
130  context->numSessions = settings->numSessions;
131  context->sessions = settings->sessions;
132  context->numFileObjects = settings->numFileObjects;
133  context->fileObjects = settings->fileObjects;
134  context->checkUserCallback = settings->checkUserCallback;
135  context->getFilePermCallback = settings->getFilePermCallback;
136 
137  //Set root directory
138  osStrcpy(context->rootDir, settings->rootDir);
139 
140  //Clean the root directory path
141  pathCanonicalize(context->rootDir);
142  pathRemoveSlash(context->rootDir);
143 
144  //Loop through SFTP sessions
145  for(i = 0; i < context->numSessions; i++)
146  {
147  //Initialize the structure representing the SFTP session
148  osMemset(&context->sessions[i], 0, sizeof(SftpServerSession));
149  }
150 
151  //Loop through file objects
152  for(i = 0; i < context->numFileObjects; i++)
153  {
154  //Initialize the structure representing a file object
155  osMemset(&context->fileObjects[i], 0, sizeof(SftpFileObject));
156  }
157 
158  //Create an event object to poll the state of channels
159  if(!osCreateEvent(&context->event))
160  {
161  //Report an error
162  error = ERROR_OUT_OF_RESOURCES;
163  }
164 
165  //Check status code
166  if(error)
167  {
168  //Clean up side effects
169  sftpServerDeinit(context);
170  }
171 
172  //Return status code
173  return error;
174 }
175 
176 
177 /**
178  * @brief Start SFTP server
179  * @param[in] context Pointer to the SFTP server context
180  * @return Error code
181  **/
182 
184 {
185  error_t error;
186 
187  //Make sure the SFTP server context is valid
188  if(context == NULL)
190 
191  //Debug message
192  TRACE_INFO("Starting SFTP server...\r\n");
193 
194  //Make sure the SFTP server is not already running
195  if(context->running)
196  return ERROR_ALREADY_RUNNING;
197 
198  //Register channel request processing callback
199  error = sshServerRegisterChannelRequestCallback(context->sshServerContext,
201 
202  //Check status code
203  if(!error)
204  {
205  //Start the SFTP server
206  context->stop = FALSE;
207  context->running = TRUE;
208 
209  //Create a task
210  context->taskId = osCreateTask("SFTP Server", (OsTaskCode) sftpServerTask,
211  context, &context->taskParams);
212 
213  //Failed to create task?
214  if(context->taskId == OS_INVALID_TASK_ID)
215  {
216  error = ERROR_OUT_OF_RESOURCES;
217  }
218  }
219 
220  //Any error to report?
221  if(error)
222  {
223  //Clean up side effects
224  context->running = FALSE;
225 
226  //Unregister channel request processing callback
227  sshServerUnregisterChannelRequestCallback(context->sshServerContext,
229  }
230 
231  //Return status code
232  return error;
233 }
234 
235 
236 /**
237  * @brief Stop SFTP server
238  * @param[in] context Pointer to the SFTP server context
239  * @return Error code
240  **/
241 
243 {
244  uint_t i;
245 
246  //Make sure the SFTP server context is valid
247  if(context == NULL)
249 
250  //Debug message
251  TRACE_INFO("Stopping SFTP server...\r\n");
252 
253  //Check whether the SFTP server is running
254  if(context->running)
255  {
256  //Unregister channel request processing callback
257  sshServerUnregisterChannelRequestCallback(context->sshServerContext,
259 
260  //Stop the SFTP server
261  context->stop = TRUE;
262  //Send a signal to the task to abort any blocking operation
263  osSetEvent(&context->event);
264 
265  //Wait for the task to terminate
266  while(context->running)
267  {
268  osDelayTask(1);
269  }
270 
271  //Loop through SFTP sessions
272  for(i = 0; i < context->numSessions; i++)
273  {
274  //Active session?
275  if(context->sessions[i].state != SFTP_SERVER_SESSION_STATE_CLOSED)
276  {
277  //Close SFTP session
278  sftpServerCloseSession(&context->sessions[i]);
279  }
280  }
281  }
282 
283  //Successful processing
284  return NO_ERROR;
285 }
286 
287 
288 /**
289  * @brief Set user's root directory
290  * @param[in] session Handle referencing an SFTP session
291  * @param[in] rootDir NULL-terminated string specifying the root directory
292  * @return Error code
293  **/
294 
296 {
297  SftpServerContext *context;
298 
299  //Check parameters
300  if(session == NULL || rootDir == NULL)
302 
303  //Point to the SFTP server context
304  context = session->context;
305 
306  //Set user's root directory
307  pathCopy(session->rootDir, context->rootDir, SFTP_SERVER_MAX_ROOT_DIR_LEN);
308  pathCombine(session->rootDir, rootDir, SFTP_SERVER_MAX_ROOT_DIR_LEN);
309 
310  //Clean the resulting path
311  pathCanonicalize(session->rootDir);
312  pathRemoveSlash(session->rootDir);
313 
314  //Set default user's home directory
315  pathCopy(session->homeDir, session->rootDir, SFTP_SERVER_MAX_HOME_DIR_LEN);
316 
317  //Successful processing
318  return NO_ERROR;
319 }
320 
321 
322 /**
323  * @brief Set user's home directory
324  * @param[in] session Handle referencing an SFTP session
325  * @param[in] homeDir NULL-terminated string specifying the home directory
326  * @return Error code
327  **/
328 
330 {
331  SftpServerContext *context;
332 
333  //Check parameters
334  if(session == NULL || homeDir == NULL)
336 
337  //Point to the SFTP server context
338  context = session->context;
339 
340  //Set user's home directory
341  pathCopy(session->homeDir, context->rootDir, SFTP_SERVER_MAX_HOME_DIR_LEN);
342  pathCombine(session->homeDir, homeDir, SFTP_SERVER_MAX_HOME_DIR_LEN);
343 
344  //Clean the resulting path
345  pathCanonicalize(session->homeDir);
346  pathRemoveSlash(session->homeDir);
347 
348  //Successful processing
349  return NO_ERROR;
350 }
351 
352 
353 /**
354  * @brief SFTP server task
355  * @param[in] param Pointer to the SFTP server context
356  **/
357 
358 void sftpServerTask(void *param)
359 {
360  error_t error;
361  uint_t i;
362  systime_t timeout;
363  SftpServerContext *context;
364  SftpServerSession *session;
365 
366  //Point to the SFTP server context
367  context = (SftpServerContext *) param;
368 
369 #if (NET_RTOS_SUPPORT == ENABLED)
370  //Task prologue
371  osEnterTask();
372 
373  //Process events
374  while(1)
375  {
376 #endif
377  //Set polling timeout
378  timeout = SFTP_SERVER_TICK_INTERVAL;
379 
380  //Clear event descriptor set
381  osMemset(context->eventDesc, 0, sizeof(context->eventDesc));
382 
383  //Loop through SFTP sessions
384  for(i = 0; i < context->numSessions; i++)
385  {
386  //Point to the structure describing the current session
387  session = &context->sessions[i];
388 
389  //Active session?
390  if(session->state != SFTP_SERVER_SESSION_STATE_CLOSED)
391  {
392  //Register session events
393  sftpServerRegisterSessionEvents(session, &context->eventDesc[i]);
394 
395  //Check whether the channel is ready for I/O operation
396  if(context->eventDesc[i].eventFlags != 0)
397  {
398  //No need to poll the underlying channel for incoming traffic
399  timeout = 0;
400  }
401  }
402  }
403 
404  //Wait for one of the set of channels to become ready to perform I/O
405  error = sshPollChannels(context->eventDesc, context->numSessions,
406  &context->event, timeout);
407 
408  //Check status code
409  if(error == NO_ERROR || error == ERROR_TIMEOUT)
410  {
411  //Stop request?
412  if(context->stop)
413  {
414  //Stop SFTP server operation
415  context->running = FALSE;
416  //Task epilogue
417  osExitTask();
418  //Kill ourselves
420  }
421 
422  //Loop through SFTP sessions
423  for(i = 0; i < context->numSessions; i++)
424  {
425  //Point to the structure describing the current session
426  session = &context->sessions[i];
427 
428  //Active session?
429  if(session->state != SFTP_SERVER_SESSION_STATE_CLOSED)
430  {
431  //Check whether the channel is ready to perform I/O
432  if(context->eventDesc[i].eventFlags != 0)
433  {
434  //Session event handler
436  }
437  }
438  }
439  }
440 
441  //Handle periodic operations
442  sftpServerTick(context);
443 
444 #if (NET_RTOS_SUPPORT == ENABLED)
445  }
446 #endif
447 }
448 
449 
450 /**
451  * @brief Release SFTP server context
452  * @param[in] context Pointer to the SFTP server context
453  **/
454 
456 {
457  //Make sure the SFTP server context is valid
458  if(context != NULL)
459  {
460  //Free previously allocated resources
461  osDeleteEvent(&context->event);
462 
463  //Clear SFTP server context
464  osMemset(context, 0, sizeof(SftpServerContext));
465  }
466 }
467 
468 #endif
unsigned int uint_t
Definition: compiler_port.h:50
char char_t
Definition: compiler_port.h:48
Debugging facilities.
#define TRACE_INFO(...)
Definition: debug.h:95
error_t
Error codes.
Definition: error.h:43
@ ERROR_ALREADY_RUNNING
Definition: error.h:292
@ ERROR_TIMEOUT
Definition: error.h:95
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
@ NO_ERROR
Success.
Definition: error.h:44
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
#define osMemset(p, value, length)
Definition: os_port.h:135
#define osStrlen(s)
Definition: os_port.h:165
#define TRUE
Definition: os_port.h:50
#define FALSE
Definition: os_port.h:46
#define osStrcpy(s1, s2)
Definition: os_port.h:207
void osDeleteEvent(OsEvent *event)
Delete an event object.
const OsTaskParameters OS_TASK_DEFAULT_PARAMS
void osDelayTask(systime_t delay)
Delay routine.
OsTaskId osCreateTask(const char_t *name, OsTaskCode taskCode, void *arg, const OsTaskParameters *params)
Create a task.
void osDeleteTask(OsTaskId taskId)
Delete a task.
bool_t osCreateEvent(OsEvent *event)
Create an event object.
void osSetEvent(OsEvent *event)
Set the specified event object to the signaled state.
void(* OsTaskCode)(void *arg)
Task routine.
#define osEnterTask()
#define OS_SELF_TASK_ID
#define OS_INVALID_TASK_ID
uint32_t systime_t
System time.
#define osExitTask()
void pathCombine(char_t *path, const char_t *more, size_t maxLen)
Concatenate two paths.
Definition: path.c:370
void pathCanonicalize(char_t *path)
Simplify a path.
Definition: path.c:150
void pathCopy(char_t *dest, const char_t *src, size_t maxLen)
Copy a path.
Definition: path.c:129
void pathRemoveSlash(char_t *path)
Remove the trailing slash from a given path.
Definition: path.c:340
Path manipulation helper functions.
error_t sftpServerInit(SftpServerContext *context, const SftpServerSettings *settings)
Initialize SFTP server context.
Definition: sftp_server.c:85
void sftpServerTask(void *param)
SFTP server task.
Definition: sftp_server.c:358
void sftpServerGetDefaultSettings(SftpServerSettings *settings)
Initialize settings with default values.
Definition: sftp_server.c:50
error_t sftpServerSetHomeDir(SftpServerSession *session, const char_t *homeDir)
Set user's home directory.
Definition: sftp_server.c:329
error_t sftpServerSetRootDir(SftpServerSession *session, const char_t *rootDir)
Set user's root directory.
Definition: sftp_server.c:295
error_t sftpServerStart(SftpServerContext *context)
Start SFTP server.
Definition: sftp_server.c:183
error_t sftpServerStop(SftpServerContext *context)
Stop SFTP server.
Definition: sftp_server.c:242
void sftpServerDeinit(SftpServerContext *context)
Release SFTP server context.
Definition: sftp_server.c:455
SFTP server.
#define SFTP_SERVER_MAX_ROOT_DIR_LEN
Definition: sftp_server.h:95
#define SftpServerSession
Definition: sftp_server.h:120
#define SFTP_SERVER_MAX_SESSIONS
Definition: sftp_server.h:60
#define SftpServerContext
Definition: sftp_server.h:116
@ SFTP_SERVER_SESSION_STATE_CLOSED
Definition: sftp_server.h:157
#define SFTP_SERVER_MAX_HOME_DIR_LEN
Definition: sftp_server.h:102
#define SFTP_SERVER_PRIORITY
Definition: sftp_server.h:55
#define SFTP_SERVER_STACK_SIZE
Definition: sftp_server.h:48
#define SFTP_SERVER_TICK_INTERVAL
Definition: sftp_server.h:67
void sftpServerCloseSession(SftpServerSession *session)
Close an SFTP session.
void sftpServerProcessSessionEvents(SftpServerSession *session)
Session event handler.
error_t sftpServerChannelRequestCallback(SshChannel *channel, const SshString *type, const uint8_t *data, size_t length, void *param)
SSH channel request callback.
void sftpServerTick(SftpServerContext *context)
Handle periodic operations.
void sftpServerRegisterSessionEvents(SftpServerSession *session, SshChannelEventDesc *eventDesc)
Register session events.
Helper functions for SFTP server.
error_t sshPollChannels(SshChannelEventDesc *eventDesc, uint_t size, OsEvent *extEvent, systime_t timeout)
Wait for one of a set of channels to become ready to perform I/O.
Definition: ssh.c:2376
Secure Shell (SSH)
error_t sshServerRegisterChannelRequestCallback(SshServerContext *context, SshChannelReqCallback callback, void *param)
Register channel request callback function.
Definition: ssh_server.c:360
error_t sshServerUnregisterChannelRequestCallback(SshServerContext *context, SshChannelReqCallback callback)
Unregister channel request callback function.
Definition: ssh_server.c:376
File or directory object.
Definition: sftp_server.h:186
SFTP server settings.
Definition: sftp_server.h:203
OsTaskParameters task
Task parameters.
Definition: sftp_server.h:204
const char_t * rootDir
Root directory.
Definition: sftp_server.h:210
uint_t numFileObjects
Maximum number of file objects.
Definition: sftp_server.h:208
SshServerContext * sshServerContext
SSH server context.
Definition: sftp_server.h:205
SftpServerSession * sessions
SFTP sessions.
Definition: sftp_server.h:207
SftpFileObject * fileObjects
File objects.
Definition: sftp_server.h:209
uint_t numSessions
Maximum number of SFTP sessions.
Definition: sftp_server.h:206
SftpServerGetFilePermCallback getFilePermCallback
Callback used to retrieve file permissions.
Definition: sftp_server.h:212
SftpServerCheckUserCallback checkUserCallback
User verification callback function.
Definition: sftp_server.h:211