scp_client_misc.c
Go to the documentation of this file.
1 /**
2  * @file scp_client_misc.c
3  * @brief Helper functions for SCP client
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2019-2026 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.6.0
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL SCP_TRACE_LEVEL
33 
34 //Dependencies
35 #include "ssh/ssh.h"
36 #include "ssh/ssh_connection.h"
37 #include "ssh/ssh_request.h"
38 #include "ssh/ssh_misc.h"
39 #include "scp/scp_client.h"
40 #include "scp/scp_client_misc.h"
41 #include "debug.h"
42 
43 //Check SSH stack configuration
44 #if (SCP_CLIENT_SUPPORT == ENABLED)
45 
46 
47 /**
48  * @brief Update SCP client state
49  * @param[in] context Pointer to the SCP client context
50  * @param[in] newState New state to switch to
51  **/
52 
54  ScpClientState newState)
55 {
56  //Switch to the new state
57  context->state = newState;
58 
59  //Save current time
60  context->timestamp = osGetSystemTime();
61 }
62 
63 
64 /**
65  * @brief Open SSH connection
66  * @param[in] context Pointer to the SCP client context
67  * @return Error code
68  **/
69 
71 {
72  error_t error;
73  Socket *socket;
74  SshConnection *connection;
75 
76  //Initialize SSH context
77  error = sshInit(&context->sshContext, &context->sshConnection, 1,
78  &context->sshChannel, 1);
79  //Any error to report?
80  if(error)
81  return error;
82 
83  //Select client operation mode
84  error = sshSetOperationMode(&context->sshContext, SSH_OPERATION_MODE_CLIENT);
85  //Any error to report?
86  if(error)
87  return error;
88 
89  //Invoke user-defined callback, if any
90  if(context->sshInitCallback != NULL)
91  {
92  //Perform SSH related initialization
93  error = context->sshInitCallback(context, &context->sshContext);
94  //Any error to report?
95  if(error)
96  return error;
97  }
98 
99  //Open a TCP socket
100  socket = socketOpenEx(context->netContext, SOCKET_TYPE_STREAM,
102 
103  //Valid socket handle
104  if(socket != NULL)
105  {
106  //Associate the socket with the relevant interface
107  socketBindToInterface(socket, context->interface);
108  //Set timeout
109  socketSetTimeout(socket, context->timeout);
110 
111  //Open a new SSH connection
112  connection = sshOpenConnection(&context->sshContext, socket);
113 
114  //Failed to open connection?
115  if(connection == NULL)
116  {
117  //Clean up side effects
119  //Report an error
120  error = ERROR_OPEN_FAILED;
121  }
122  }
123  else
124  {
125  //Failed to open socket
126  error = ERROR_OPEN_FAILED;
127  }
128 
129  //Return status code
130  return error;
131 }
132 
133 
134 /**
135  * @brief Establish SSH connection
136  * @param[in] context Pointer to the SCP client context
137  * @return Error code
138  **/
139 
141 {
142  error_t error;
143 
144  //Check the state of the SSH connection
145  if(context->sshConnection.state < SSH_CONN_STATE_OPEN)
146  {
147  //Perform SSH key exchange and user authentication
148  error = scpClientProcessEvents(context);
149  }
150  else if(context->sshConnection.state == SSH_CONN_STATE_OPEN)
151  {
152  //The SSH connection is established
154  //Successful processing
155  error = NO_ERROR;
156  }
157  else
158  {
159  //Invalid state
160  error = ERROR_WRONG_STATE;
161  }
162 
163  //Return status code
164  return error;
165 }
166 
167 
168 /**
169  * @brief Close SSH connection
170  * @param[in] context Pointer to the SCP client context
171  **/
172 
174 {
175  //Check the state of the SSH connection
176  if(context->sshConnection.state != SSH_CONN_STATE_CLOSED)
177  {
178  //Close SSH connection
179  sshCloseConnection(&context->sshConnection);
180  }
181 
182  //Release SSH context
183  sshDeinit(&context->sshContext);
184 }
185 
186 
187 /**
188  * @brief Send a SCP directive to the server
189  * @param[in] context Pointer to the SCP client context
190  * @param[in] directive SCP directive parameters
191  * @return Error code
192  **/
193 
195  const ScpDirective *directive)
196 {
197  error_t error;
198  size_t n;
199 
200  //Initialize status code
201  error = NO_ERROR;
202 
203  //Format and and send status message
204  while(!error)
205  {
206  //Manage message transmission
207  if(context->bufferLen == 0)
208  {
209  //Format directive line
210  n = scpFormatDirective(directive, context->buffer);
211 
212  //Save the length of the directive line
213  context->bufferLen = n;
214  context->bufferPos = 0;
215  }
216  else if(context->bufferPos < context->bufferLen)
217  {
218  //Send more data
219  error = sshWriteChannel(&context->sshChannel,
220  context->buffer + context->bufferPos,
221  context->bufferLen - context->bufferPos, &n, 0);
222 
223  //Check status code
224  if(error == NO_ERROR || error == ERROR_TIMEOUT)
225  {
226  //Advance data pointer
227  context->bufferPos += n;
228  }
229  }
230  else
231  {
232  //Flush transmit buffer
233  context->bufferLen = 0;
234  context->bufferPos = 0;
235 
236  //We are done
237  break;
238  }
239 
240  //Check status code
241  if(error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
242  {
243  //Process SSH connection events
244  error = scpClientProcessEvents(context);
245  }
246  }
247 
248  //Return status code
249  return error;
250 }
251 
252 
253 /**
254  * @brief Receive a SCP directive from the server
255  * @param[in] context Pointer to the SCP client context
256  * @param[in] directive SCP directive parameters
257  * @return Error code
258  **/
259 
261  ScpDirective *directive)
262 {
263  error_t error;
264  size_t n;
265  uint8_t opcode;
266 
267  //Initialize status code
268  error = NO_ERROR;
269 
270  //Receive and parse SCP directive
271  while(!error)
272  {
273  //Manage message reception
274  if(context->bufferLen == 0)
275  {
276  //Read the directive opcode
277  error = sshReadChannel(&context->sshChannel, context->buffer, 1,
278  &n, 0);
279 
280  //Check status code
281  if(!error)
282  {
283  //Adjust the length of the buffer
284  context->bufferLen += n;
285  }
286  }
287  else if(context->bufferLen < SCP_CLIENT_BUFFER_SIZE)
288  {
289  //Retrieve directive opcode
290  opcode = context->buffer[0];
291 
292  //Check directive opcode
293  if(opcode == SCP_OPCODE_OK ||
295  {
296  //Parse the received directive
297  error = scpParseDirective(context->buffer, directive);
298 
299  //Flush receive buffer
300  context->bufferLen = 0;
301  context->bufferPos = 0;
302 
303  //We are done
304  break;
305  }
306  else if(opcode == SCP_OPCODE_WARNING ||
308  opcode == SCP_OPCODE_FILE ||
309  opcode == SCP_OPCODE_DIR ||
311  {
312  //Limit the number of bytes to read at a time
313  n = SCP_CLIENT_BUFFER_SIZE - context->bufferLen;
314 
315  //Read more data
316  error = sshReadChannel(&context->sshChannel, context->buffer +
317  context->bufferLen, n, &n, SSH_FLAG_BREAK_CRLF);
318 
319  //Check status code
320  if(!error)
321  {
322  //Adjust the length of the buffer
323  context->bufferLen += n;
324 
325  //Check whether the string is properly terminated
326  if(context->bufferLen > 0 &&
327  context->buffer[context->bufferLen - 1] == '\n')
328  {
329  //Properly terminate the string with a NULL character
330  context->buffer[context->bufferLen - 1] = '\0';
331 
332  //Parse the received directive
333  error = scpParseDirective(context->buffer, directive);
334 
335  //Flush receive buffer
336  context->bufferLen = 0;
337  context->bufferPos = 0;
338 
339  //We are done
340  break;
341  }
342  else
343  {
344  //Wait for a new line character
345  error = ERROR_WOULD_BLOCK;
346  }
347  }
348  }
349  else
350  {
351  //Unknown directive
352  error = ERROR_INVALID_COMMAND;
353  }
354  }
355  else
356  {
357  //The implementation limits the size of messages it accepts
358  error = ERROR_BUFFER_OVERFLOW;
359  }
360 
361  //Check status code
362  if(error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
363  {
364  //Process SSH connection events
365  error = scpClientProcessEvents(context);
366  }
367  }
368 
369  //Return status code
370  return error;
371 }
372 
373 
374 /**
375  * @brief Process SCP client events
376  * @param[in] context Pointer to the SCP client context
377  * @return Error code
378  **/
379 
381 {
382  error_t error;
383  uint_t i;
384  SshContext *sshContext;
385  SshConnection *connection;
386 
387  //Point to the SSH context
388  sshContext = &context->sshContext;
389 
390  //Clear event descriptor set
391  osMemset(sshContext->eventDesc, 0, sizeof(sshContext->eventDesc));
392 
393  //Specify the events the application is interested in
394  for(i = 0; i < sshContext->numConnections; i++)
395  {
396  //Point to the structure describing the current connection
397  connection = &sshContext->connections[i];
398 
399  //Loop through active connections only
400  if(connection->state != SSH_CONN_STATE_CLOSED)
401  {
402  //Register the events related to the current SSH connection
403  sshRegisterConnectionEvents(sshContext, connection, &sshContext->eventDesc[i]);
404  }
405  }
406 
407  //Wait for one of the set of sockets to become ready to perform I/O
408  error = socketPoll(sshContext->eventDesc, sshContext->numConnections,
409  &sshContext->event, context->timeout);
410 
411  //Verify status code
412  if(error == NO_ERROR || error == ERROR_WAIT_CANCELED)
413  {
414  //Clear status code
415  error = NO_ERROR;
416 
417  //Event-driven processing
418  for(i = 0; i < sshContext->numConnections && !error; i++)
419  {
420  //Point to the structure describing the current connection
421  connection = &sshContext->connections[i];
422 
423  //Loop through active connections only
424  if(connection->state != SSH_CONN_STATE_CLOSED)
425  {
426  //Check whether the socket is ready to perform I/O
427  if(sshContext->eventDesc[i].eventFlags != 0)
428  {
429  //Connection event handler
430  error = sshProcessConnectionEvents(sshContext, connection);
431  }
432  }
433  }
434  }
435 
436  //Check status code
437  if(error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
438  {
439  //Check whether the timeout has elapsed
440  error = scpClientCheckTimeout(context);
441  }
442 
443  //Return status code
444  return error;
445 }
446 
447 
448 /**
449  * @brief Determine whether a timeout error has occurred
450  * @param[in] context Pointer to the SCP client context
451  * @return Error code
452  **/
453 
455 {
456  error_t error;
457  systime_t time;
458 
459  //Get current time
460  time = osGetSystemTime();
461 
462  //Check whether the timeout has elapsed
463  if(timeCompare(time, context->timestamp + context->timeout) >= 0)
464  {
465  //Report a timeout error
466  error = ERROR_TIMEOUT;
467  }
468  else
469  {
470 #if (NET_RTOS_SUPPORT == ENABLED)
471  //Successful operation
472  error = NO_ERROR;
473 #else
474  //The operation would block
475  error = ERROR_WOULD_BLOCK;
476 #endif
477  }
478 
479  //Return status code
480  return error;
481 }
482 
483 #endif
SCP client.
uint8_t opcode
Definition: dns_common.h:191
@ SSH_CONN_STATE_OPEN
Definition: ssh.h:1088
Helper functions for SCP client.
@ ERROR_WOULD_BLOCK
Definition: error.h:96
@ ERROR_BUFFER_OVERFLOW
Definition: error.h:143
SSH connection protocol.
SshConnection * sshOpenConnection(SshContext *context, Socket *socket)
Open a new SSH connection.
Definition: ssh_misc.c:68
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:2094
error_t scpClientProcessEvents(ScpClientContext *context)
Process SCP client events.
error_t scpClientSendDirective(ScpClientContext *context, const ScpDirective *directive)
Send a SCP directive to the server.
@ SCP_OPCODE_OK
Definition: scp_common.h:63
@ ERROR_INVALID_COMMAND
Definition: error.h:100
void scpClientChangeState(ScpClientContext *context, ScpClientState newState)
Update SCP client state.
@ SCP_OPCODE_END
Definition: scp_common.h:68
@ SOCKET_TYPE_STREAM
Definition: socket.h:92
#define timeCompare(t1, t2)
Definition: os_port.h:40
@ SCP_CLIENT_STATE_CONNECTED
Definition: scp_client.h:78
@ ERROR_WRONG_STATE
Definition: error.h:210
error_t sshInit(SshContext *context, SshConnection *connections, uint_t numConnections, SshChannel *channels, uint_t numChannels)
SSH context initialization.
Definition: ssh.c:58
error_t sshReadChannel(SshChannel *channel, void *data, size_t size, size_t *received, uint_t flags)
Receive data from the specified channel.
Definition: ssh.c:2205
@ ERROR_OPEN_FAILED
Definition: error.h:75
#define SshContext
Definition: ssh.h:892
error_t
Error codes.
Definition: error.h:43
void sshDeinit(SshContext *context)
Release SSH context.
Definition: ssh.c:2581
SCP directive parameters.
Definition: scp_common.h:78
error_t scpClientOpenConnection(ScpClientContext *context)
Open SSH connection.
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
#define ScpClientContext
Definition: scp_client.h:61
@ SCP_OPCODE_TIME
Definition: scp_common.h:69
@ SSH_OPERATION_MODE_CLIENT
Definition: ssh.h:914
error_t sshProcessConnectionEvents(SshContext *context, SshConnection *connection)
Connection event handler.
Definition: ssh_misc.c:375
void sshCloseConnection(SshConnection *connection)
Close SSH connection.
Definition: ssh_misc.c:174
error_t sshWriteChannel(SshChannel *channel, const void *data, size_t length, size_t *written, uint_t flags)
Write data to the specified channel.
Definition: ssh.c:2076
@ SCP_OPCODE_DIR
Definition: scp_common.h:67
@ SSH_CONN_STATE_CLOSED
Definition: ssh.h:1057
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:2182
#define socketBindToInterface
Definition: net_legacy.h:193
uint32_t systime_t
System time.
@ ERROR_TIMEOUT
Definition: error.h:95
size_t scpFormatDirective(const ScpDirective *directive, char_t *buffer)
Format SCP directive.
Definition: scp_common.c:48
uint32_t time
@ SCP_OPCODE_FILE
Definition: scp_common.h:66
void scpClientCloseConnection(ScpClientContext *context)
Close SSH connection.
uint8_t n
void sshRegisterConnectionEvents(SshContext *context, SshConnection *connection, SocketEventDesc *eventDesc)
Register connection events.
Definition: ssh_misc.c:282
#define SshConnection
Definition: ssh.h:896
Socket * socketOpenEx(NetContext *context, uint_t type, uint_t protocol)
Create a socket.
Definition: socket.c:146
#define Socket
Definition: socket.h:36
@ ERROR_WAIT_CANCELED
Definition: error.h:73
@ SSH_FLAG_BREAK_CRLF
Definition: ssh.h:940
#define SCP_CLIENT_BUFFER_SIZE
Definition: scp_client.h:54
SSH helper functions.
error_t scpParseDirective(const char_t *buffer, ScpDirective *directive)
Parse SCP directive.
Definition: scp_common.c:127
unsigned int uint_t
Definition: compiler_port.h:57
#define osMemset(p, value, length)
Definition: os_port.h:138
error_t sshSetOperationMode(SshContext *context, SshOperationMode mode)
Set operation mode (client or server)
Definition: ssh.c:167
@ SCP_OPCODE_ERROR
Definition: scp_common.h:65
Secure Shell (SSH)
@ SCP_OPCODE_WARNING
Definition: scp_common.h:64
ScpClientState
SCP client state.
Definition: scp_client.h:74
@ SOCKET_IP_PROTO_TCP
Definition: socket.h:107
error_t scpClientCheckTimeout(ScpClientContext *context)
Determine whether a timeout error has occurred.
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:169
Global request and channel request handling.
error_t scpClientReceiveDirective(ScpClientContext *context, ScpDirective *directive)
Receive a SCP directive from the server.
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
error_t scpClientEstablishConnection(ScpClientContext *context)
Establish SSH connection.
systime_t osGetSystemTime(void)
Retrieve system time.