[修改] 增加freeRTOS
1. 版本FreeRTOSv202212.01,命名为kernel;
This commit is contained in:
@ -0,0 +1,134 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file mbedtls_bio_tcp_sockets_wrapper.c
|
||||
* @brief Implements mbed TLS platform send/receive functions for the TCP sockets wrapper.
|
||||
*/
|
||||
|
||||
/* MbedTLS includes. */
|
||||
#if !defined( MBEDTLS_CONFIG_FILE )
|
||||
#include "mbedtls/mbedtls_config.h"
|
||||
#else
|
||||
#include MBEDTLS_CONFIG_FILE
|
||||
#endif
|
||||
#include "threading_alt.h"
|
||||
#include "mbedtls/entropy.h"
|
||||
#include "mbedtls/ssl.h"
|
||||
|
||||
/* TCP Sockets Wrapper include.*/
|
||||
#include "tcp_sockets_wrapper.h"
|
||||
|
||||
/* MbedTLS Bio TCP sockets wrapper include. */
|
||||
#include "mbedtls_bio_tcp_sockets_wrapper.h"
|
||||
|
||||
/**
|
||||
* @brief Sends data over TCP socket.
|
||||
*
|
||||
* @param[in] ctx The network context containing the socket handle.
|
||||
* @param[in] buf Buffer containing the bytes to send.
|
||||
* @param[in] len Number of bytes to send from the buffer.
|
||||
*
|
||||
* @return Number of bytes sent on success; else a negative value.
|
||||
*/
|
||||
int xMbedTLSBioTCPSocketsWrapperSend( void * ctx,
|
||||
const unsigned char * buf,
|
||||
size_t len )
|
||||
{
|
||||
int32_t xReturnStatus;
|
||||
|
||||
configASSERT( ctx != NULL );
|
||||
configASSERT( buf != NULL );
|
||||
|
||||
xReturnStatus = TCP_Sockets_Send( ( Socket_t ) ctx, buf, len );
|
||||
|
||||
switch( xReturnStatus )
|
||||
{
|
||||
/* Socket was closed or just got closed. */
|
||||
case TCP_SOCKETS_ERRNO_ENOTCONN:
|
||||
/* Not enough memory for the socket to create either an Rx or Tx stream. */
|
||||
case TCP_SOCKETS_ERRNO_ENOMEM:
|
||||
/* Socket is not valid, is not a TCP socket, or is not bound. */
|
||||
case TCP_SOCKETS_ERRNO_EINVAL:
|
||||
/* Socket received a signal, causing the read operation to be aborted. */
|
||||
case TCP_SOCKETS_ERRNO_EINTR:
|
||||
xReturnStatus = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
|
||||
break;
|
||||
|
||||
/* A timeout occurred before any data could be sent. */
|
||||
case TCP_SOCKETS_ERRNO_ENOSPC:
|
||||
xReturnStatus = MBEDTLS_ERR_SSL_TIMEOUT;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return ( int ) xReturnStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Receives data from TCP socket.
|
||||
*
|
||||
* @param[in] ctx The network context containing the socket handle.
|
||||
* @param[out] buf Buffer to receive bytes into.
|
||||
* @param[in] len Number of bytes to receive from the network.
|
||||
*
|
||||
* @return Number of bytes received if successful; Negative value on error.
|
||||
*/
|
||||
int xMbedTLSBioTCPSocketsWrapperRecv( void * ctx,
|
||||
unsigned char * buf,
|
||||
size_t len )
|
||||
{
|
||||
int32_t xReturnStatus;
|
||||
|
||||
configASSERT( ctx != NULL );
|
||||
configASSERT( buf != NULL );
|
||||
|
||||
xReturnStatus = TCP_Sockets_Recv( ( Socket_t ) ctx, buf, len );
|
||||
|
||||
switch( xReturnStatus )
|
||||
{
|
||||
/* No data could be sent because the socket was or just got closed. */
|
||||
case TCP_SOCKETS_ERRNO_ENOTCONN:
|
||||
/* No data could be sent because there was insufficient memory. */
|
||||
case TCP_SOCKETS_ERRNO_ENOMEM:
|
||||
/* No data could be sent because xSocket was not a valid TCP socket. */
|
||||
case TCP_SOCKETS_ERRNO_EINVAL:
|
||||
xReturnStatus = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
|
||||
break;
|
||||
|
||||
/* A timeout occurred before any data could be received. */
|
||||
case 0:
|
||||
xReturnStatus = MBEDTLS_ERR_SSL_WANT_READ;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return ( int ) xReturnStatus;
|
||||
}
|
||||
@ -0,0 +1,62 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file mbedtls_bio_tcp_sockets_wrapper.h
|
||||
* @brief TLS transport interface header.
|
||||
*/
|
||||
|
||||
#ifndef MBEDTLS_BIO_TCP_SOCKETS_WRAPPER
|
||||
#define MBEDTLS_BIO_TCP_SOCKETS_WRAPPER
|
||||
|
||||
/**
|
||||
* @brief Sends data over TCP socket.
|
||||
*
|
||||
* @param[in] ctx The network context containing the socket handle.
|
||||
* @param[in] buf Buffer containing the bytes to send.
|
||||
* @param[in] len Number of bytes to send from the buffer.
|
||||
*
|
||||
* @return Number of bytes sent on success; else a negative value.
|
||||
*/
|
||||
int xMbedTLSBioTCPSocketsWrapperSend( void * ctx,
|
||||
const unsigned char * buf,
|
||||
size_t len );
|
||||
|
||||
/**
|
||||
* @brief Receives data from TCP socket.
|
||||
*
|
||||
* @param[in] ctx The network context containing the socket handle.
|
||||
* @param[out] buf Buffer to receive bytes into.
|
||||
* @param[in] len Number of bytes to receive from the network.
|
||||
*
|
||||
* @return Number of bytes received if successful; Negative value on error.
|
||||
*/
|
||||
int xMbedTLSBioTCPSocketsWrapperRecv( void * ctx,
|
||||
unsigned char * buf,
|
||||
size_t len );
|
||||
|
||||
|
||||
#endif /* MBEDTLS_BIO_TCP_SOCKETS_WRAPPER */
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,62 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef MBEDTLS_PKCS11_H
|
||||
#define MBEDTLS_PKCS11_H
|
||||
|
||||
#include <string.h>
|
||||
#include "mbedtls/pk.h"
|
||||
#include "core_pkcs11_config.h"
|
||||
#include "core_pkcs11.h"
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Initialize an mbedtls_pk_context for the given PKCS11 object handle.
|
||||
*
|
||||
* @param pxMbedtlsPkCtx Pointer to an MbedTLS PK context to initialize.
|
||||
* @param xSessionHandle Handle of an initialize PKCS#11 session.
|
||||
* @param xPkHandle Handle of a PKCS11 Private Key object.
|
||||
* @return CK_RV CKR_OK on success.
|
||||
*/
|
||||
CK_RV xPKCS11_initMbedtlsPkContext( mbedtls_pk_context * pxMbedtlsPkCtx,
|
||||
CK_SESSION_HANDLE xSessionHandle,
|
||||
CK_OBJECT_HANDLE xPkHandle );
|
||||
|
||||
/**
|
||||
* @brief Callback to generate random data with the PKCS11 API.
|
||||
*
|
||||
* @param[in] pvCtx void pointer to a PKCS11 Session handle.
|
||||
* @param[in] pucRandom Byte array to fill with random data.
|
||||
* @param[in] xRandomLength Length of byte array.
|
||||
*
|
||||
* @return 0 on success.
|
||||
*/
|
||||
int lMbedCryptoRngCallbackPKCS11( void * pvCtx,
|
||||
unsigned char * pucOutput,
|
||||
size_t uxLen );
|
||||
|
||||
#endif /* MBEDTLS_PKCS11_H */
|
||||
@ -0,0 +1,80 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
#include "logging_levels.h"
|
||||
|
||||
#define LIBRARY_LOG_NAME "MbedTLSRNGP11"
|
||||
#define LIBRARY_LOG_LEVEL LOG_ERROR
|
||||
|
||||
#include "logging_stack.h"
|
||||
|
||||
/**
|
||||
* @file mbedtls_rng_pkcs11.c
|
||||
* @brief Implements an mbedtls RNG callback using the PKCS#11 API
|
||||
*/
|
||||
|
||||
#include "core_pkcs11_config.h"
|
||||
#include "core_pkcs11.h"
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
int lMbedCryptoRngCallbackPKCS11( void * pvCtx,
|
||||
unsigned char * pucOutput,
|
||||
size_t uxLen )
|
||||
{
|
||||
int lRslt;
|
||||
CK_FUNCTION_LIST_PTR pxFunctionList = NULL;
|
||||
CK_SESSION_HANDLE * pxSessionHandle = ( CK_SESSION_HANDLE * ) pvCtx;
|
||||
|
||||
if( pucOutput == NULL )
|
||||
{
|
||||
lRslt = -1;
|
||||
}
|
||||
else if( pvCtx == NULL )
|
||||
{
|
||||
lRslt = -1;
|
||||
LogError( ( "pvCtx must not be NULL." ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
lRslt = ( int ) C_GetFunctionList( &pxFunctionList );
|
||||
}
|
||||
|
||||
if( ( lRslt != CKR_OK ) ||
|
||||
( pxFunctionList == NULL ) ||
|
||||
( pxFunctionList->C_GenerateRandom == NULL ) )
|
||||
{
|
||||
lRslt = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
lRslt = ( int ) pxFunctionList->C_GenerateRandom( *pxSessionHandle, pucOutput, uxLen );
|
||||
}
|
||||
|
||||
return lRslt;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
@ -0,0 +1,6 @@
|
||||
Building a network transport implementation:
|
||||
|
||||
1. Go into the sub directory for the TCP/IP stack you are using (e.g. freertos_plus_tcp).
|
||||
2. Build the wrapper file located in the directory (i.e. sockets_wrapper.c).
|
||||
3. Select an additional folder based on the TLS stack you are using (e.g. using_mbedtls), or the using_plaintext folder if not using TLS.
|
||||
4. Build and include all files from the selected folder.
|
||||
@ -0,0 +1,125 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file tcp_sockets_wrapper.h
|
||||
* @brief TCP transport functions wrapper.
|
||||
*/
|
||||
|
||||
#ifndef TCP_SOCKETS_WRAPPER_H
|
||||
#define TCP_SOCKETS_WRAPPER_H
|
||||
|
||||
|
||||
/* Standard includes. */
|
||||
#include <stdint.h>
|
||||
|
||||
/* FreeRTOS Kernel includes. */
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
/* Error codes. */
|
||||
#define TCP_SOCKETS_ERRNO_NONE ( 0 ) /*!< No error. */
|
||||
#define TCP_SOCKETS_ERRNO_ERROR ( -1 ) /*!< Catch-all sockets error code. */
|
||||
#define TCP_SOCKETS_ERRNO_EWOULDBLOCK ( -2 ) /*!< A resource is temporarily unavailable. */
|
||||
#define TCP_SOCKETS_ERRNO_ENOMEM ( -3 ) /*!< Memory allocation failed. */
|
||||
#define TCP_SOCKETS_ERRNO_EINVAL ( -4 ) /*!< Invalid argument. */
|
||||
#define TCP_SOCKETS_ERRNO_ENOPROTOOPT ( -5 ) /*!< A bad option was specified . */
|
||||
#define TCP_SOCKETS_ERRNO_ENOTCONN ( -6 ) /*!< The supplied socket is not connected. */
|
||||
#define TCP_SOCKETS_ERRNO_EISCONN ( -7 ) /*!< The supplied socket is already connected. */
|
||||
#define TCP_SOCKETS_ERRNO_ECLOSED ( -8 ) /*!< The supplied socket has already been closed. */
|
||||
#define TCP_SOCKETS_ERRNO_PERIPHERAL_RESET ( -9 ) /*!< Communications peripheral has been reset. */
|
||||
#define TCP_SOCKETS_ERRNO_ENOSPC ( -10 ) /*!< No space left on device */
|
||||
#define TCP_SOCKETS_ERRNO_EINTR ( -11 ) /*!< Interrupted system call */
|
||||
|
||||
#ifndef SOCKET_T_TYPEDEFED
|
||||
struct xSOCKET;
|
||||
typedef struct xSOCKET * Socket_t; /**< @brief Socket handle data type. */
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Establish a connection to server.
|
||||
*
|
||||
* @param[out] pTcpSocket The output parameter to return the created socket descriptor.
|
||||
* @param[in] pHostName Server hostname to connect to.
|
||||
* @param[in] pServerInfo Server port to connect to.
|
||||
* @param[in] receiveTimeoutMs Timeout (in milliseconds) for transport receive.
|
||||
* @param[in] sendTimeoutMs Timeout (in milliseconds) for transport send.
|
||||
*
|
||||
* @note A timeout of 0 means infinite timeout.
|
||||
*
|
||||
* @return Non-zero value on error, 0 on success.
|
||||
*/
|
||||
BaseType_t TCP_Sockets_Connect( Socket_t * pTcpSocket,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs );
|
||||
|
||||
/**
|
||||
* @brief End connection to server.
|
||||
*
|
||||
* @param[in] tcpSocket The socket descriptor.
|
||||
*/
|
||||
void TCP_Sockets_Disconnect( Socket_t tcpSocket );
|
||||
|
||||
/**
|
||||
* @brief Transmit data to the remote socket.
|
||||
*
|
||||
* The socket must have already been created using a call to TCP_Sockets_Connect().
|
||||
*
|
||||
* @param[in] xSocket The handle of the sending socket.
|
||||
* @param[in] pvBuffer The buffer containing the data to be sent.
|
||||
* @param[in] xDataLength The length of the data to be sent.
|
||||
*
|
||||
* @return
|
||||
* * On success, the number of bytes actually sent is returned.
|
||||
* * If an error occurred, a negative value is returned. @ref SocketsErrors
|
||||
*/
|
||||
int32_t TCP_Sockets_Send( Socket_t xSocket,
|
||||
const void * pvBuffer,
|
||||
size_t xDataLength );
|
||||
|
||||
/**
|
||||
* @brief Receive data from a TCP socket.
|
||||
*
|
||||
* The socket must have already been created using a call to TCP_Sockets_Connect().
|
||||
*
|
||||
* @param[in] xSocket The handle of the socket from which data is being received.
|
||||
* @param[out] pvBuffer The buffer into which the received data will be placed.
|
||||
* @param[in] xBufferLength The maximum number of bytes which can be received.
|
||||
* pvBuffer must be at least xBufferLength bytes long.
|
||||
*
|
||||
* @return
|
||||
* * If the receive was successful then the number of bytes received (placed in the
|
||||
* buffer pointed to by pvBuffer) is returned.
|
||||
* * If a timeout occurred before data could be received then 0 is returned (timeout
|
||||
* is set using @ref SOCKETS_SO_RCVTIMEO).
|
||||
* * If an error occurred, a negative value is returned. @ref SocketsErrors
|
||||
*/
|
||||
int32_t TCP_Sockets_Recv( Socket_t xSocket,
|
||||
void * pvBuffer,
|
||||
size_t xBufferLength );
|
||||
|
||||
#endif /* ifndef TCP_SOCKETS_WRAPPER_H */
|
||||
@ -0,0 +1,921 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/* Include header that defines log levels. */
|
||||
#include "logging_levels.h"
|
||||
|
||||
/* Logging configuration for the Sockets. */
|
||||
#ifndef LIBRARY_LOG_NAME
|
||||
#define LIBRARY_LOG_NAME "TCP Sockets"
|
||||
#endif
|
||||
#ifndef LIBRARY_LOG_LEVEL
|
||||
#define LIBRARY_LOG_LEVEL LOG_ERROR
|
||||
#endif
|
||||
|
||||
/* Prototype for the function used to print to console on Windows simulator
|
||||
* of FreeRTOS.
|
||||
* The function prints to the console before the network is connected;
|
||||
* then a UDP port after the network has connected. */
|
||||
extern void vLoggingPrintf( const char * pcFormatString,
|
||||
... );
|
||||
|
||||
/* Map the SdkLog macro to the logging function to enable logging
|
||||
* on Windows simulator. */
|
||||
#ifndef SdkLog
|
||||
#define SdkLog( message ) vLoggingPrintf message
|
||||
#endif
|
||||
|
||||
#include "logging_stack.h"
|
||||
|
||||
/* Standard includes. */
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
/* FreeRTOS includes. */
|
||||
#include "FreeRTOS.h"
|
||||
#include "event_groups.h"
|
||||
|
||||
/* TCP sockets wrapper includes. */
|
||||
#include "tcp_sockets_wrapper.h"
|
||||
|
||||
/* FreeRTOS Cellular Library api includes. */
|
||||
#include "cellular_config.h"
|
||||
#include "cellular_config_defaults.h"
|
||||
#include "cellular_api.h"
|
||||
|
||||
/* Configure logs for the functions in this file. */
|
||||
#include "logging_levels.h"
|
||||
#ifndef LIBRARY_LOG_NAME
|
||||
#define LIBRARY_LOG_NAME "CellularSocket"
|
||||
#endif
|
||||
#ifndef LIBRARY_LOG_LEVEL
|
||||
#define LIBRARY_LOG_LEVEL LOG_INFO
|
||||
#endif
|
||||
#include "logging_stack.h"
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/* Cellular socket wrapper needs application provide the cellular handle and pdn context id. */
|
||||
/* User of cellular socket wrapper should provide this variable. */
|
||||
/* coverity[misra_c_2012_rule_8_6_violation] */
|
||||
extern CellularHandle_t CellularHandle;
|
||||
|
||||
/* User of cellular socket wrapper should provide this variable. */
|
||||
/* coverity[misra_c_2012_rule_8_6_violation] */
|
||||
extern uint8_t CellularSocketPdnContextId;
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/* Windows simulator implementation. */
|
||||
#if defined( _WIN32 ) || defined( _WIN64 )
|
||||
#define strtok_r strtok_s
|
||||
#endif
|
||||
|
||||
#define CELLULAR_SOCKET_OPEN_FLAG ( 1UL << 0 )
|
||||
#define CELLULAR_SOCKET_CONNECT_FLAG ( 1UL << 1 )
|
||||
|
||||
#define SOCKET_DATA_RECEIVED_CALLBACK_BIT ( 0x00000001U )
|
||||
#define SOCKET_OPEN_CALLBACK_BIT ( 0x00000002U )
|
||||
#define SOCKET_OPEN_FAILED_CALLBACK_BIT ( 0x00000004U )
|
||||
#define SOCKET_CLOSE_CALLBACK_BIT ( 0x00000008U )
|
||||
|
||||
/* Ticks MS conversion macros. */
|
||||
#define TICKS_TO_MS( xTicks ) ( ( ( xTicks ) * 1000U ) / ( ( uint32_t ) configTICK_RATE_HZ ) )
|
||||
#define UINT32_MAX_DELAY_MS ( 0xFFFFFFFFUL )
|
||||
#define UINT32_MAX_MS_TICKS ( UINT32_MAX_DELAY_MS / ( TICKS_TO_MS( 1U ) ) )
|
||||
|
||||
/* Cellular socket access mode. */
|
||||
#define CELLULAR_SOCKET_ACCESS_MODE CELLULAR_ACCESSMODE_BUFFER
|
||||
|
||||
/* Cellular socket open timeout. */
|
||||
#define CELLULAR_SOCKET_OPEN_TIMEOUT_TICKS ( portMAX_DELAY )
|
||||
#define CELLULAR_SOCKET_CLOSE_TIMEOUT_TICKS ( pdMS_TO_TICKS( 10000U ) )
|
||||
|
||||
/* Time conversion constants. */
|
||||
#define _MILLISECONDS_PER_SECOND ( 1000 ) /**< @brief Milliseconds per second. */
|
||||
#define _MILLISECONDS_PER_TICK ( _MILLISECONDS_PER_SECOND / configTICK_RATE_HZ ) /**< Milliseconds per FreeRTOS tick. */
|
||||
|
||||
/* Invalid socket. */
|
||||
#define CELLULAR_INVALID_SOCKET ( ( Socket_t ) ~0U )
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
typedef struct xSOCKET
|
||||
{
|
||||
CellularSocketHandle_t cellularSocketHandle;
|
||||
uint32_t ulFlags;
|
||||
|
||||
TickType_t receiveTimeout;
|
||||
TickType_t sendTimeout;
|
||||
|
||||
EventGroupHandle_t socketEventGroupHandle;
|
||||
} cellularSocketWrapper_t;
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Get the count of milliseconds since vTaskStartScheduler was called.
|
||||
*
|
||||
* @return The count of milliseconds since vTaskStartScheduler was called.
|
||||
*/
|
||||
static uint64_t getTimeMs( void );
|
||||
|
||||
/**
|
||||
* @brief Receive data from cellular socket.
|
||||
*
|
||||
* @param[in] pCellularSocketContext Cellular socket wrapper context for socket operations.
|
||||
* @param[out] buf The data buffer for receiving data.
|
||||
* @param[in] len The length of the data buffer
|
||||
*
|
||||
* @note This function receives data. It returns when non-zero bytes of data is received,
|
||||
* when an error occurs, or when timeout occurs. Receive timeout unit is TickType_t.
|
||||
* Any timeout value bigger than portMAX_DELAY will be regarded as portMAX_DELAY.
|
||||
* In this case, this function waits portMAX_DELAY until non-zero bytes of data is received
|
||||
* or until an error occurs.
|
||||
*
|
||||
* @return Positive value indicate the number of bytes received. Otherwise, error code defined
|
||||
* in sockets_wrapper.h is returned.
|
||||
*/
|
||||
static BaseType_t prvNetworkRecvCellular( const cellularSocketWrapper_t * pCellularSocketContext,
|
||||
uint8_t * buf,
|
||||
size_t len );
|
||||
|
||||
/**
|
||||
* @brief Callback used to inform about the status of socket open.
|
||||
*
|
||||
* @param[in] urcEvent URC Event that happened.
|
||||
* @param[in] socketHandle Socket handle for which data is ready.
|
||||
* @param[in] pCallbackContext pCallbackContext parameter in
|
||||
* Cellular_SocketRegisterSocketOpenCallback function.
|
||||
*/
|
||||
static void prvCellularSocketOpenCallback( CellularUrcEvent_t urcEvent,
|
||||
CellularSocketHandle_t socketHandle,
|
||||
void * pCallbackContext );
|
||||
|
||||
/**
|
||||
* @brief Callback used to inform that data is ready for reading on a socket.
|
||||
*
|
||||
* @param[in] socketHandle Socket handle for which data is ready.
|
||||
* @param[in] pCallbackContext pCallbackContext parameter in
|
||||
* Cellular_SocketRegisterDataReadyCallback function.
|
||||
*/
|
||||
static void prvCellularSocketDataReadyCallback( CellularSocketHandle_t socketHandle,
|
||||
void * pCallbackContext );
|
||||
|
||||
|
||||
/**
|
||||
* @brief Callback used to inform that remote end closed the connection for a
|
||||
* connected socket.
|
||||
*
|
||||
* @param[in] socketHandle Socket handle for which remote end closed the
|
||||
* connection.
|
||||
* @param[in] pCallbackContext pCallbackContext parameter in
|
||||
* Cellular_SocketRegisterClosedCallback function.
|
||||
*/
|
||||
static void prvCellularSocketClosedCallback( CellularSocketHandle_t socketHandle,
|
||||
void * pCallbackContext );
|
||||
|
||||
/**
|
||||
* @brief Setup socket receive timeout.
|
||||
*
|
||||
* @param[in] pCellularSocketContext Cellular socket wrapper context for socket operations.
|
||||
* @param[out] receiveTimeout Socket receive timeout in TickType_t.
|
||||
*
|
||||
* @return On success, TCP_SOCKETS_ERRNO_NONE is returned. If an error occurred, error code defined
|
||||
* in sockets_wrapper.h is returned.
|
||||
*/
|
||||
static BaseType_t prvSetupSocketRecvTimeout( cellularSocketWrapper_t * pCellularSocketContext,
|
||||
TickType_t receiveTimeout );
|
||||
|
||||
/**
|
||||
* @brief Setup socket send timeout.
|
||||
*
|
||||
* @param[in] pCellularSocketContext Cellular socket wrapper context for socket operations.
|
||||
* @param[out] sendTimeout Socket send timeout in TickType_t.
|
||||
*
|
||||
* @note Send timeout unit is TickType_t. The underlying cellular API uses miliseconds for timeout.
|
||||
* Any send timeout greater than UINT32_MAX_MS_TICKS( UINT32_MAX_DELAY_MS/MS_PER_TICKS ) or
|
||||
* portMAX_DELAY is regarded as UINT32_MAX_DELAY_MS for cellular API.
|
||||
*
|
||||
* @return On success, TCP_SOCKETS_ERRNO_NONE is returned. If an error occurred, error code defined
|
||||
* in sockets_wrapper.h is returned.
|
||||
*/
|
||||
static BaseType_t prvSetupSocketSendTimeout( cellularSocketWrapper_t * pCellularSocketContext,
|
||||
TickType_t sendTimeout );
|
||||
|
||||
/**
|
||||
* @brief Setup cellular socket callback function.
|
||||
*
|
||||
* @param[in] CellularSocketHandle_t Cellular socket handle for cellular socket operations.
|
||||
* @param[in] pCellularSocketContext Cellular socket wrapper context for socket operations.
|
||||
*
|
||||
* @return On success, TCP_SOCKETS_ERRNO_NONE is returned. If an error occurred, error code defined
|
||||
* in sockets_wrapper.h is returned.
|
||||
*/
|
||||
static BaseType_t prvCellularSocketRegisterCallback( CellularSocketHandle_t cellularSocketHandle,
|
||||
cellularSocketWrapper_t * pCellularSocketContext );
|
||||
|
||||
/**
|
||||
* @brief Calculate elapsed time from current time and input parameters.
|
||||
*
|
||||
* @param[in] entryTimeMs The entry time to be compared with current time.
|
||||
* @param[in] timeoutValueMs Timeout value for the comparison between entry time and current time.
|
||||
* @param[out] pElapsedTimeMs The elapsed time if timeout condition is true.
|
||||
*
|
||||
* @return True if the difference between entry time and current time is bigger or
|
||||
* equal to timeoutValueMs. Otherwise, return false.
|
||||
*/
|
||||
static bool _calculateElapsedTime( uint64_t entryTimeMs,
|
||||
uint32_t timeoutValueMs,
|
||||
uint64_t * pElapsedTimeMs );
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static uint64_t getTimeMs( void )
|
||||
{
|
||||
TimeOut_t xCurrentTime = { 0 };
|
||||
|
||||
/* This must be unsigned because the behavior of signed integer overflow is undefined. */
|
||||
uint64_t ullTickCount = 0ULL;
|
||||
|
||||
/* Get the current tick count and overflow count. vTaskSetTimeOutState()
|
||||
* is used to get these values because they are both static in tasks.c. */
|
||||
vTaskSetTimeOutState( &xCurrentTime );
|
||||
|
||||
/* Adjust the tick count for the number of times a TickType_t has overflowed. */
|
||||
ullTickCount = ( uint64_t ) ( xCurrentTime.xOverflowCount ) << ( sizeof( TickType_t ) * 8 );
|
||||
|
||||
/* Add the current tick count. */
|
||||
ullTickCount += xCurrentTime.xTimeOnEntering;
|
||||
|
||||
/* Return the ticks converted to milliseconds. */
|
||||
return ullTickCount * _MILLISECONDS_PER_TICK;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static BaseType_t prvNetworkRecvCellular( const cellularSocketWrapper_t * pCellularSocketContext,
|
||||
uint8_t * buf,
|
||||
size_t len )
|
||||
{
|
||||
CellularSocketHandle_t cellularSocketHandle = NULL;
|
||||
BaseType_t retRecvLength = 0;
|
||||
uint32_t recvLength = 0;
|
||||
TickType_t recvTimeout = 0;
|
||||
TickType_t recvStartTime = 0;
|
||||
CellularError_t socketStatus = CELLULAR_SUCCESS;
|
||||
EventBits_t waitEventBits = 0;
|
||||
|
||||
cellularSocketHandle = pCellularSocketContext->cellularSocketHandle;
|
||||
|
||||
if( pCellularSocketContext->receiveTimeout >= portMAX_DELAY )
|
||||
{
|
||||
recvTimeout = portMAX_DELAY;
|
||||
}
|
||||
else
|
||||
{
|
||||
recvTimeout = pCellularSocketContext->receiveTimeout;
|
||||
}
|
||||
|
||||
recvStartTime = xTaskGetTickCount();
|
||||
|
||||
( void ) xEventGroupClearBits( pCellularSocketContext->socketEventGroupHandle,
|
||||
SOCKET_DATA_RECEIVED_CALLBACK_BIT );
|
||||
socketStatus = Cellular_SocketRecv( CellularHandle, cellularSocketHandle, buf, len, &recvLength );
|
||||
|
||||
/* Calculate remain recvTimeout. */
|
||||
if( recvTimeout != portMAX_DELAY )
|
||||
{
|
||||
if( ( recvStartTime + recvTimeout ) > xTaskGetTickCount() )
|
||||
{
|
||||
recvTimeout = recvTimeout - ( xTaskGetTickCount() - recvStartTime );
|
||||
}
|
||||
else
|
||||
{
|
||||
recvTimeout = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if( ( socketStatus == CELLULAR_SUCCESS ) && ( recvLength == 0U ) &&
|
||||
( recvTimeout != 0U ) )
|
||||
{
|
||||
waitEventBits = xEventGroupWaitBits( pCellularSocketContext->socketEventGroupHandle,
|
||||
SOCKET_DATA_RECEIVED_CALLBACK_BIT | SOCKET_CLOSE_CALLBACK_BIT,
|
||||
pdTRUE,
|
||||
pdFALSE,
|
||||
recvTimeout );
|
||||
|
||||
if( ( waitEventBits & SOCKET_CLOSE_CALLBACK_BIT ) != 0U )
|
||||
{
|
||||
socketStatus = CELLULAR_SOCKET_CLOSED;
|
||||
}
|
||||
else if( ( waitEventBits & SOCKET_DATA_RECEIVED_CALLBACK_BIT ) != 0U )
|
||||
{
|
||||
socketStatus = Cellular_SocketRecv( CellularHandle, cellularSocketHandle, buf, len, &recvLength );
|
||||
}
|
||||
else
|
||||
{
|
||||
LogInfo( ( "prvNetworkRecv timeout" ) );
|
||||
socketStatus = CELLULAR_SUCCESS;
|
||||
recvLength = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if( socketStatus == CELLULAR_SUCCESS )
|
||||
{
|
||||
retRecvLength = ( BaseType_t ) recvLength;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "prvNetworkRecv failed %d", socketStatus ) );
|
||||
retRecvLength = TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
|
||||
LogDebug( ( "prvNetworkRecv expect %d read %d", len, recvLength ) );
|
||||
return retRecvLength;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static void prvCellularSocketOpenCallback( CellularUrcEvent_t urcEvent,
|
||||
CellularSocketHandle_t socketHandle,
|
||||
void * pCallbackContext )
|
||||
{
|
||||
cellularSocketWrapper_t * pCellularSocketContext = ( cellularSocketWrapper_t * ) pCallbackContext;
|
||||
|
||||
( void ) socketHandle;
|
||||
|
||||
if( pCellularSocketContext != NULL )
|
||||
{
|
||||
LogDebug( ( "Socket open callback on Socket %p %d %d.",
|
||||
pCellularSocketContext, socketHandle, urcEvent ) );
|
||||
|
||||
if( urcEvent == CELLULAR_URC_SOCKET_OPENED )
|
||||
{
|
||||
pCellularSocketContext->ulFlags = pCellularSocketContext->ulFlags | CELLULAR_SOCKET_CONNECT_FLAG;
|
||||
( void ) xEventGroupSetBits( pCellularSocketContext->socketEventGroupHandle,
|
||||
SOCKET_OPEN_CALLBACK_BIT );
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Socket open failed. */
|
||||
( void ) xEventGroupSetBits( pCellularSocketContext->socketEventGroupHandle,
|
||||
SOCKET_OPEN_FAILED_CALLBACK_BIT );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "Spurious socket open callback." ) );
|
||||
}
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static void prvCellularSocketDataReadyCallback( CellularSocketHandle_t socketHandle,
|
||||
void * pCallbackContext )
|
||||
{
|
||||
cellularSocketWrapper_t * pCellularSocketContext = ( cellularSocketWrapper_t * ) pCallbackContext;
|
||||
|
||||
( void ) socketHandle;
|
||||
|
||||
if( pCellularSocketContext != NULL )
|
||||
{
|
||||
LogDebug( ( "Data ready on Socket %p", pCellularSocketContext ) );
|
||||
( void ) xEventGroupSetBits( pCellularSocketContext->socketEventGroupHandle,
|
||||
SOCKET_DATA_RECEIVED_CALLBACK_BIT );
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "spurious data callback" ) );
|
||||
}
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static void prvCellularSocketClosedCallback( CellularSocketHandle_t socketHandle,
|
||||
void * pCallbackContext )
|
||||
{
|
||||
cellularSocketWrapper_t * pCellularSocketContext = ( cellularSocketWrapper_t * ) pCallbackContext;
|
||||
|
||||
( void ) socketHandle;
|
||||
|
||||
if( pCellularSocketContext != NULL )
|
||||
{
|
||||
LogInfo( ( "Socket Close on Socket %p", pCellularSocketContext ) );
|
||||
pCellularSocketContext->ulFlags = pCellularSocketContext->ulFlags & ( ~CELLULAR_SOCKET_CONNECT_FLAG );
|
||||
( void ) xEventGroupSetBits( pCellularSocketContext->socketEventGroupHandle,
|
||||
SOCKET_CLOSE_CALLBACK_BIT );
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "spurious socket close callback" ) );
|
||||
}
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static BaseType_t prvSetupSocketRecvTimeout( cellularSocketWrapper_t * pCellularSocketContext,
|
||||
TickType_t receiveTimeout )
|
||||
{
|
||||
BaseType_t retSetSockOpt = TCP_SOCKETS_ERRNO_NONE;
|
||||
|
||||
if( pCellularSocketContext == NULL )
|
||||
{
|
||||
retSetSockOpt = TCP_SOCKETS_ERRNO_EINVAL;
|
||||
}
|
||||
else
|
||||
{
|
||||
if( receiveTimeout >= portMAX_DELAY )
|
||||
{
|
||||
pCellularSocketContext->receiveTimeout = portMAX_DELAY;
|
||||
}
|
||||
else
|
||||
{
|
||||
pCellularSocketContext->receiveTimeout = receiveTimeout;
|
||||
}
|
||||
}
|
||||
|
||||
return retSetSockOpt;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static BaseType_t prvSetupSocketSendTimeout( cellularSocketWrapper_t * pCellularSocketContext,
|
||||
TickType_t sendTimeout )
|
||||
{
|
||||
BaseType_t retSetSockOpt = TCP_SOCKETS_ERRNO_NONE;
|
||||
uint32_t sendTimeoutMs = 0;
|
||||
CellularSocketHandle_t cellularSocketHandle = NULL;
|
||||
|
||||
if( pCellularSocketContext == NULL )
|
||||
{
|
||||
retSetSockOpt = TCP_SOCKETS_ERRNO_EINVAL;
|
||||
}
|
||||
else
|
||||
{
|
||||
cellularSocketHandle = pCellularSocketContext->cellularSocketHandle;
|
||||
|
||||
if( sendTimeout >= UINT32_MAX_MS_TICKS )
|
||||
{
|
||||
/* Check if the ticks cause overflow. */
|
||||
pCellularSocketContext->sendTimeout = portMAX_DELAY;
|
||||
sendTimeoutMs = UINT32_MAX_DELAY_MS;
|
||||
}
|
||||
else if( sendTimeout >= portMAX_DELAY )
|
||||
{
|
||||
LogWarn( ( "Sendtimeout %d longer than portMAX_DELAY, %d ms is used instead",
|
||||
sendTimeout, UINT32_MAX_DELAY_MS ) );
|
||||
pCellularSocketContext->sendTimeout = portMAX_DELAY;
|
||||
sendTimeoutMs = UINT32_MAX_DELAY_MS;
|
||||
}
|
||||
else
|
||||
{
|
||||
pCellularSocketContext->sendTimeout = sendTimeout;
|
||||
sendTimeoutMs = TICKS_TO_MS( sendTimeout );
|
||||
}
|
||||
}
|
||||
|
||||
return retSetSockOpt;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static BaseType_t prvCellularSocketRegisterCallback( CellularSocketHandle_t cellularSocketHandle,
|
||||
cellularSocketWrapper_t * pCellularSocketContext )
|
||||
{
|
||||
BaseType_t retRegCallback = TCP_SOCKETS_ERRNO_NONE;
|
||||
CellularError_t socketStatus = CELLULAR_SUCCESS;
|
||||
|
||||
if( cellularSocketHandle == NULL )
|
||||
{
|
||||
retRegCallback = TCP_SOCKETS_ERRNO_EINVAL;
|
||||
}
|
||||
|
||||
if( retRegCallback == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
socketStatus = Cellular_SocketRegisterDataReadyCallback( CellularHandle, cellularSocketHandle,
|
||||
prvCellularSocketDataReadyCallback, ( void * ) pCellularSocketContext );
|
||||
|
||||
if( socketStatus != CELLULAR_SUCCESS )
|
||||
{
|
||||
LogError( ( "Failed to SocketRegisterDataReadyCallback. Socket status %d.", socketStatus ) );
|
||||
retRegCallback = TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
if( retRegCallback == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
socketStatus = Cellular_SocketRegisterSocketOpenCallback( CellularHandle, cellularSocketHandle,
|
||||
prvCellularSocketOpenCallback, ( void * ) pCellularSocketContext );
|
||||
|
||||
if( socketStatus != CELLULAR_SUCCESS )
|
||||
{
|
||||
LogError( ( "Failed to SocketRegisterSocketOpenCallbac. Socket status %d.", socketStatus ) );
|
||||
retRegCallback = TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
if( retRegCallback == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
socketStatus = Cellular_SocketRegisterClosedCallback( CellularHandle, cellularSocketHandle,
|
||||
prvCellularSocketClosedCallback, ( void * ) pCellularSocketContext );
|
||||
|
||||
if( socketStatus != CELLULAR_SUCCESS )
|
||||
{
|
||||
LogError( ( "Failed to SocketRegisterClosedCallback. Socket status %d.", socketStatus ) );
|
||||
retRegCallback = TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
return retRegCallback;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static bool _calculateElapsedTime( uint64_t entryTimeMs,
|
||||
uint32_t timeoutValueMs,
|
||||
uint64_t * pElapsedTimeMs )
|
||||
{
|
||||
uint64_t currentTimeMs = getTimeMs();
|
||||
bool isExpired = false;
|
||||
|
||||
/* timeoutValueMs with UINT32_MAX_DELAY_MS means wait for ever, same behavior as freertos_plus_tcp. */
|
||||
if( timeoutValueMs == UINT32_MAX_DELAY_MS )
|
||||
{
|
||||
isExpired = false;
|
||||
}
|
||||
|
||||
/* timeoutValueMs = 0 means none blocking mode. */
|
||||
else if( timeoutValueMs == 0U )
|
||||
{
|
||||
isExpired = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
*pElapsedTimeMs = currentTimeMs - entryTimeMs;
|
||||
|
||||
if( ( currentTimeMs - entryTimeMs ) >= timeoutValueMs )
|
||||
{
|
||||
isExpired = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
isExpired = false;
|
||||
}
|
||||
}
|
||||
|
||||
return isExpired;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
BaseType_t TCP_Sockets_Connect( Socket_t * pTcpSocket,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs )
|
||||
{
|
||||
CellularSocketHandle_t cellularSocketHandle = NULL;
|
||||
cellularSocketWrapper_t * pCellularSocketContext = NULL;
|
||||
CellularError_t cellularSocketStatus = CELLULAR_INVALID_HANDLE;
|
||||
|
||||
CellularSocketAddress_t serverAddress = { 0 };
|
||||
EventBits_t waitEventBits = 0;
|
||||
BaseType_t retConnect = TCP_SOCKETS_ERRNO_NONE;
|
||||
|
||||
/* Create a new TCP socket. */
|
||||
cellularSocketStatus = Cellular_CreateSocket( CellularHandle,
|
||||
CellularSocketPdnContextId,
|
||||
CELLULAR_SOCKET_DOMAIN_AF_INET,
|
||||
CELLULAR_SOCKET_TYPE_STREAM,
|
||||
CELLULAR_SOCKET_PROTOCOL_TCP,
|
||||
&cellularSocketHandle );
|
||||
|
||||
if( cellularSocketStatus != CELLULAR_SUCCESS )
|
||||
{
|
||||
LogError( ( "Failed to create cellular sockets. %d", cellularSocketStatus ) );
|
||||
retConnect = TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
|
||||
/* Allocate socket context. */
|
||||
if( retConnect == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
pCellularSocketContext = pvPortMalloc( sizeof( cellularSocketWrapper_t ) );
|
||||
|
||||
if( pCellularSocketContext == NULL )
|
||||
{
|
||||
LogError( ( "Failed to allocate new socket context." ) );
|
||||
( void ) Cellular_SocketClose( CellularHandle, cellularSocketHandle );
|
||||
retConnect = TCP_SOCKETS_ERRNO_ENOMEM;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Initialize all the members to sane values. */
|
||||
LogDebug( ( "Created CELLULAR Socket %p.", pCellularSocketContext ) );
|
||||
( void ) memset( pCellularSocketContext, 0, sizeof( cellularSocketWrapper_t ) );
|
||||
pCellularSocketContext->cellularSocketHandle = cellularSocketHandle;
|
||||
pCellularSocketContext->ulFlags |= CELLULAR_SOCKET_OPEN_FLAG;
|
||||
pCellularSocketContext->socketEventGroupHandle = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
/* Allocate event group for callback function. */
|
||||
if( retConnect == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
pCellularSocketContext->socketEventGroupHandle = xEventGroupCreate();
|
||||
|
||||
if( pCellularSocketContext->socketEventGroupHandle == NULL )
|
||||
{
|
||||
LogError( ( "Failed create cellular socket eventGroupHandle %p.", pCellularSocketContext ) );
|
||||
retConnect = TCP_SOCKETS_ERRNO_ENOMEM;
|
||||
}
|
||||
}
|
||||
|
||||
/* Register cellular socket callback function. */
|
||||
if( retConnect == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
serverAddress.ipAddress.ipAddressType = CELLULAR_IP_ADDRESS_V4;
|
||||
strncpy( serverAddress.ipAddress.ipAddress, pHostName, CELLULAR_IP_ADDRESS_MAX_SIZE );
|
||||
serverAddress.port = port;
|
||||
|
||||
LogDebug( ( "Ip address %s port %d\r\n", serverAddress.ipAddress.ipAddress, serverAddress.port ) );
|
||||
retConnect = prvCellularSocketRegisterCallback( cellularSocketHandle, pCellularSocketContext );
|
||||
}
|
||||
|
||||
/* Setup cellular socket send/recv timeout. */
|
||||
if( retConnect == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
retConnect = prvSetupSocketSendTimeout( pCellularSocketContext, pdMS_TO_TICKS( sendTimeoutMs ) );
|
||||
}
|
||||
|
||||
if( retConnect == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
retConnect = prvSetupSocketRecvTimeout( pCellularSocketContext, pdMS_TO_TICKS( receiveTimeoutMs ) );
|
||||
}
|
||||
|
||||
/* Cellular socket connect. */
|
||||
if( retConnect == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
( void ) xEventGroupClearBits( pCellularSocketContext->socketEventGroupHandle,
|
||||
SOCKET_DATA_RECEIVED_CALLBACK_BIT | SOCKET_OPEN_FAILED_CALLBACK_BIT );
|
||||
cellularSocketStatus = Cellular_SocketConnect( CellularHandle, cellularSocketHandle, CELLULAR_SOCKET_ACCESS_MODE, &serverAddress );
|
||||
|
||||
if( cellularSocketStatus != CELLULAR_SUCCESS )
|
||||
{
|
||||
LogError( ( "Failed to establish new connection. Socket status %d.", cellularSocketStatus ) );
|
||||
retConnect = TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
/* Wait the socket connection. */
|
||||
if( retConnect == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
waitEventBits = xEventGroupWaitBits( pCellularSocketContext->socketEventGroupHandle,
|
||||
SOCKET_OPEN_CALLBACK_BIT | SOCKET_OPEN_FAILED_CALLBACK_BIT,
|
||||
pdTRUE,
|
||||
pdFALSE,
|
||||
CELLULAR_SOCKET_OPEN_TIMEOUT_TICKS );
|
||||
|
||||
if( waitEventBits != SOCKET_OPEN_CALLBACK_BIT )
|
||||
{
|
||||
LogError( ( "Socket connect timeout." ) );
|
||||
retConnect = TCP_SOCKETS_ERRNO_ENOTCONN;
|
||||
}
|
||||
}
|
||||
|
||||
/* Cleanup the socket if any error. */
|
||||
if( retConnect != TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
if( cellularSocketHandle != NULL )
|
||||
{
|
||||
( void ) Cellular_SocketClose( CellularHandle, cellularSocketHandle );
|
||||
( void ) Cellular_SocketRegisterDataReadyCallback( CellularHandle, cellularSocketHandle, NULL, NULL );
|
||||
( void ) Cellular_SocketRegisterSocketOpenCallback( CellularHandle, cellularSocketHandle, NULL, NULL );
|
||||
( void ) Cellular_SocketRegisterClosedCallback( CellularHandle, cellularSocketHandle, NULL, NULL );
|
||||
|
||||
if( pCellularSocketContext != NULL )
|
||||
{
|
||||
pCellularSocketContext->cellularSocketHandle = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
if( ( pCellularSocketContext != NULL ) && ( pCellularSocketContext->socketEventGroupHandle != NULL ) )
|
||||
{
|
||||
vEventGroupDelete( pCellularSocketContext->socketEventGroupHandle );
|
||||
pCellularSocketContext->socketEventGroupHandle = NULL;
|
||||
}
|
||||
|
||||
if( pCellularSocketContext != NULL )
|
||||
{
|
||||
vPortFree( pCellularSocketContext );
|
||||
pCellularSocketContext = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
*pTcpSocket = pCellularSocketContext;
|
||||
|
||||
return retConnect;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
void TCP_Sockets_Disconnect( Socket_t xSocket )
|
||||
{
|
||||
int32_t retClose = TCP_SOCKETS_ERRNO_NONE;
|
||||
cellularSocketWrapper_t * pCellularSocketContext = ( cellularSocketWrapper_t * ) xSocket;
|
||||
CellularSocketHandle_t cellularSocketHandle = NULL;
|
||||
uint32_t recvLength = 0;
|
||||
uint8_t buf[ 128 ] = { 0 };
|
||||
CellularError_t cellularSocketStatus = CELLULAR_SUCCESS;
|
||||
|
||||
/* xSocket need to be check against SOCKET_INVALID_SOCKET. */
|
||||
/* coverity[misra_c_2012_rule_11_4_violation] */
|
||||
if( ( pCellularSocketContext == NULL ) || ( xSocket == CELLULAR_INVALID_SOCKET ) )
|
||||
{
|
||||
LogError( ( "Invalid xSocket %p", pCellularSocketContext ) );
|
||||
retClose = TCP_SOCKETS_ERRNO_EINVAL;
|
||||
}
|
||||
else
|
||||
{
|
||||
cellularSocketHandle = pCellularSocketContext->cellularSocketHandle;
|
||||
}
|
||||
|
||||
if( retClose == TCP_SOCKETS_ERRNO_NONE )
|
||||
{
|
||||
if( cellularSocketHandle != NULL )
|
||||
{
|
||||
/* Receive all the data before socket close. */
|
||||
do
|
||||
{
|
||||
recvLength = 0;
|
||||
cellularSocketStatus = Cellular_SocketRecv( CellularHandle, cellularSocketHandle, buf, 128, &recvLength );
|
||||
LogDebug( ( "%u bytes received in close", recvLength ) );
|
||||
} while( ( recvLength != 0 ) && ( cellularSocketStatus == CELLULAR_SUCCESS ) );
|
||||
|
||||
/* Close sockets. */
|
||||
if( Cellular_SocketClose( CellularHandle, cellularSocketHandle ) != CELLULAR_SUCCESS )
|
||||
{
|
||||
LogWarn( ( "Failed to destroy connection." ) );
|
||||
retClose = TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
|
||||
( void ) Cellular_SocketRegisterDataReadyCallback( CellularHandle, cellularSocketHandle, NULL, NULL );
|
||||
( void ) Cellular_SocketRegisterSocketOpenCallback( CellularHandle, cellularSocketHandle, NULL, NULL );
|
||||
( void ) Cellular_SocketRegisterClosedCallback( CellularHandle, cellularSocketHandle, NULL, NULL );
|
||||
pCellularSocketContext->cellularSocketHandle = NULL;
|
||||
}
|
||||
|
||||
if( pCellularSocketContext->socketEventGroupHandle != NULL )
|
||||
{
|
||||
vEventGroupDelete( pCellularSocketContext->socketEventGroupHandle );
|
||||
pCellularSocketContext->socketEventGroupHandle = NULL;
|
||||
}
|
||||
|
||||
vPortFree( pCellularSocketContext );
|
||||
}
|
||||
|
||||
LogDebug( ( "Sockets close exit with code %d", retClose ) );
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
int32_t TCP_Sockets_Recv( Socket_t xSocket,
|
||||
void * pvBuffer,
|
||||
size_t xBufferLength )
|
||||
{
|
||||
cellularSocketWrapper_t * pCellularSocketContext = ( cellularSocketWrapper_t * ) xSocket;
|
||||
uint8_t * buf = ( uint8_t * ) pvBuffer;
|
||||
BaseType_t retRecvLength = 0;
|
||||
|
||||
if( pCellularSocketContext == NULL )
|
||||
{
|
||||
LogError( ( "Cellular prvNetworkRecv Invalid xSocket %p", pCellularSocketContext ) );
|
||||
retRecvLength = ( BaseType_t ) TCP_SOCKETS_ERRNO_EINVAL;
|
||||
}
|
||||
else if( ( ( pCellularSocketContext->ulFlags & CELLULAR_SOCKET_OPEN_FLAG ) == 0U ) ||
|
||||
( ( pCellularSocketContext->ulFlags & CELLULAR_SOCKET_CONNECT_FLAG ) == 0U ) )
|
||||
{
|
||||
LogError( ( "Cellular prvNetworkRecv Invalid xSocket flag %p %u",
|
||||
pCellularSocketContext, pCellularSocketContext->ulFlags ) );
|
||||
retRecvLength = ( BaseType_t ) TCP_SOCKETS_ERRNO_ENOTCONN;
|
||||
}
|
||||
else
|
||||
{
|
||||
retRecvLength = ( BaseType_t ) prvNetworkRecvCellular( pCellularSocketContext, buf, xBufferLength );
|
||||
}
|
||||
|
||||
return retRecvLength;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/* This function sends the data until timeout or data is completely sent to server.
|
||||
* Send timeout unit is TickType_t. Any timeout value greater than UINT32_MAX_MS_TICKS
|
||||
* or portMAX_DELAY will be regarded as MAX delay. In this case, this function
|
||||
* will not return until all bytes of data are sent successfully or until an error occurs. */
|
||||
int32_t TCP_Sockets_Send( Socket_t xSocket,
|
||||
const void * pvBuffer,
|
||||
size_t xDataLength )
|
||||
{
|
||||
uint8_t * buf = ( uint8_t * ) pvBuffer;
|
||||
CellularSocketHandle_t cellularSocketHandle = NULL;
|
||||
BaseType_t retSendLength = 0;
|
||||
uint32_t sentLength = 0;
|
||||
CellularError_t socketStatus = CELLULAR_SUCCESS;
|
||||
cellularSocketWrapper_t * pCellularSocketContext = ( cellularSocketWrapper_t * ) xSocket;
|
||||
uint32_t bytesToSend = xDataLength;
|
||||
uint64_t entryTimeMs = getTimeMs();
|
||||
uint64_t elapsedTimeMs = 0;
|
||||
uint32_t sendTimeoutMs = 0;
|
||||
|
||||
if( pCellularSocketContext == NULL )
|
||||
{
|
||||
LogError( ( "Cellular TCP_Sockets_Send Invalid xSocket %p", pCellularSocketContext ) );
|
||||
retSendLength = ( BaseType_t ) TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
else if( ( ( pCellularSocketContext->ulFlags & CELLULAR_SOCKET_OPEN_FLAG ) == 0U ) ||
|
||||
( ( pCellularSocketContext->ulFlags & CELLULAR_SOCKET_CONNECT_FLAG ) == 0U ) )
|
||||
{
|
||||
LogError( ( "Cellular TCP_Sockets_Send Invalid xSocket flag %p 0x%08x",
|
||||
pCellularSocketContext, pCellularSocketContext->ulFlags ) );
|
||||
retSendLength = ( BaseType_t ) TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
else
|
||||
{
|
||||
cellularSocketHandle = pCellularSocketContext->cellularSocketHandle;
|
||||
|
||||
/* Convert ticks to ms delay. */
|
||||
if( ( pCellularSocketContext->sendTimeout >= UINT32_MAX_MS_TICKS ) || ( pCellularSocketContext->sendTimeout >= portMAX_DELAY ) )
|
||||
{
|
||||
/* Check if the ticks cause overflow. */
|
||||
sendTimeoutMs = UINT32_MAX_DELAY_MS;
|
||||
}
|
||||
else
|
||||
{
|
||||
sendTimeoutMs = TICKS_TO_MS( pCellularSocketContext->sendTimeout );
|
||||
}
|
||||
|
||||
/* Loop sending data until data is sent completely or timeout. */
|
||||
while( bytesToSend > 0U )
|
||||
{
|
||||
socketStatus = Cellular_SocketSend( CellularHandle,
|
||||
cellularSocketHandle,
|
||||
&buf[ retSendLength ],
|
||||
bytesToSend,
|
||||
&sentLength );
|
||||
|
||||
if( socketStatus == CELLULAR_SUCCESS )
|
||||
{
|
||||
retSendLength = retSendLength + ( BaseType_t ) sentLength;
|
||||
bytesToSend = bytesToSend - sentLength;
|
||||
}
|
||||
|
||||
/* Check socket status or timeout break. */
|
||||
if( ( socketStatus != CELLULAR_SUCCESS ) ||
|
||||
( _calculateElapsedTime( entryTimeMs, sendTimeoutMs, &elapsedTimeMs ) ) )
|
||||
{
|
||||
if( socketStatus == CELLULAR_SOCKET_CLOSED )
|
||||
{
|
||||
/* Socket already closed. No data is sent. */
|
||||
retSendLength = 0;
|
||||
}
|
||||
else if( socketStatus != CELLULAR_SUCCESS )
|
||||
{
|
||||
retSendLength = ( BaseType_t ) TCP_SOCKETS_ERRNO_ERROR;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
LogDebug( ( "TCP_Sockets_Send expect %d write %d", xDataLength, sentLength ) );
|
||||
}
|
||||
|
||||
return retSendLength;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
@ -0,0 +1,189 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file sockets_wrapper.c
|
||||
* @brief FreeRTOS Sockets connect and disconnect wrapper implementation.
|
||||
*/
|
||||
|
||||
/* Include header that defines log levels. */
|
||||
#include "logging_levels.h"
|
||||
|
||||
/* Logging configuration for the Sockets. */
|
||||
#ifndef LIBRARY_LOG_NAME
|
||||
#define LIBRARY_LOG_NAME "SocketsWrapper"
|
||||
#endif
|
||||
#ifndef LIBRARY_LOG_LEVEL
|
||||
#define LIBRARY_LOG_LEVEL LOG_INFO
|
||||
#endif
|
||||
|
||||
extern void vLoggingPrintf( const char * pcFormatString,
|
||||
... );
|
||||
|
||||
#include "logging_stack.h"
|
||||
|
||||
/* Standard includes. */
|
||||
#include <string.h>
|
||||
|
||||
/* FreeRTOS includes. */
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
#include "sockets_wrapper.h"
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/* Maximum number of times to call FreeRTOS_recv when initiating a graceful shutdown. */
|
||||
#ifndef FREERTOS_SOCKETS_WRAPPER_SHUTDOWN_LOOPS
|
||||
#define FREERTOS_SOCKETS_WRAPPER_SHUTDOWN_LOOPS ( 3 )
|
||||
#endif
|
||||
|
||||
/* A negative error code indicating a network failure. */
|
||||
#define FREERTOS_SOCKETS_WRAPPER_NETWORK_ERROR ( -1 )
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
BaseType_t Sockets_Connect( Socket_t * pTcpSocket,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs )
|
||||
{
|
||||
Socket_t tcpSocket = FREERTOS_INVALID_SOCKET;
|
||||
BaseType_t socketStatus = 0;
|
||||
struct freertos_sockaddr serverAddress = { 0 };
|
||||
TickType_t transportTimeout = 0;
|
||||
|
||||
/* Create a new TCP socket. */
|
||||
tcpSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP );
|
||||
|
||||
if( tcpSocket == FREERTOS_INVALID_SOCKET )
|
||||
{
|
||||
LogError( ( "Failed to create new socket." ) );
|
||||
socketStatus = FREERTOS_SOCKETS_WRAPPER_NETWORK_ERROR;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogDebug( ( "Created new TCP socket." ) );
|
||||
|
||||
/* Connection parameters. */
|
||||
serverAddress.sin_family = FREERTOS_AF_INET;
|
||||
serverAddress.sin_port = FreeRTOS_htons( port );
|
||||
serverAddress.sin_addr = ( uint32_t ) FreeRTOS_gethostbyname( pHostName );
|
||||
serverAddress.sin_len = ( uint8_t ) sizeof( serverAddress );
|
||||
|
||||
/* Check for errors from DNS lookup. */
|
||||
if( serverAddress.sin_addr == 0U )
|
||||
{
|
||||
LogError( ( "Failed to connect to server: DNS resolution failed: Hostname=%s.",
|
||||
pHostName ) );
|
||||
socketStatus = FREERTOS_SOCKETS_WRAPPER_NETWORK_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
if( socketStatus == 0 )
|
||||
{
|
||||
/* Establish connection. */
|
||||
LogDebug( ( "Creating TCP Connection to %s.", pHostName ) );
|
||||
socketStatus = FreeRTOS_connect( tcpSocket, &serverAddress, sizeof( serverAddress ) );
|
||||
|
||||
if( socketStatus != 0 )
|
||||
{
|
||||
LogError( ( "Failed to connect to server: FreeRTOS_Connect failed: ReturnCode=%d,"
|
||||
" Hostname=%s, Port=%u.",
|
||||
socketStatus,
|
||||
pHostName,
|
||||
port ) );
|
||||
}
|
||||
}
|
||||
|
||||
if( socketStatus == 0 )
|
||||
{
|
||||
/* Set socket receive timeout. */
|
||||
transportTimeout = pdMS_TO_TICKS( receiveTimeoutMs );
|
||||
/* Setting the receive block time cannot fail. */
|
||||
( void ) FreeRTOS_setsockopt( tcpSocket,
|
||||
0,
|
||||
FREERTOS_SO_RCVTIMEO,
|
||||
&transportTimeout,
|
||||
sizeof( TickType_t ) );
|
||||
|
||||
/* Set socket send timeout. */
|
||||
transportTimeout = pdMS_TO_TICKS( sendTimeoutMs );
|
||||
/* Setting the send block time cannot fail. */
|
||||
( void ) FreeRTOS_setsockopt( tcpSocket,
|
||||
0,
|
||||
FREERTOS_SO_SNDTIMEO,
|
||||
&transportTimeout,
|
||||
sizeof( TickType_t ) );
|
||||
}
|
||||
|
||||
/* Clean up on failure. */
|
||||
if( socketStatus != 0 )
|
||||
{
|
||||
if( tcpSocket != FREERTOS_INVALID_SOCKET )
|
||||
{
|
||||
( void ) FreeRTOS_closesocket( tcpSocket );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Set the socket. */
|
||||
*pTcpSocket = tcpSocket;
|
||||
LogInfo( ( "Established TCP connection with %s.", pHostName ) );
|
||||
}
|
||||
|
||||
return socketStatus;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
void Sockets_Disconnect( Socket_t tcpSocket )
|
||||
{
|
||||
BaseType_t waitForShutdownLoopCount = 0;
|
||||
uint8_t pDummyBuffer[ 2 ];
|
||||
|
||||
if( tcpSocket != FREERTOS_INVALID_SOCKET )
|
||||
{
|
||||
/* Initiate graceful shutdown. */
|
||||
( void ) FreeRTOS_shutdown( tcpSocket, FREERTOS_SHUT_RDWR );
|
||||
|
||||
/* Wait for the socket to disconnect gracefully (indicated by FreeRTOS_recv()
|
||||
* returning a FREERTOS_EINVAL error) before closing the socket. */
|
||||
while( FreeRTOS_recv( tcpSocket, pDummyBuffer, sizeof( pDummyBuffer ), 0 ) >= 0 )
|
||||
{
|
||||
/* We don't need to delay since FreeRTOS_recv should already have a timeout. */
|
||||
|
||||
if( ++waitForShutdownLoopCount >= FREERTOS_SOCKETS_WRAPPER_SHUTDOWN_LOOPS )
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
( void ) FreeRTOS_closesocket( tcpSocket );
|
||||
}
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
@ -0,0 +1,68 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file sockets_wrapper.h
|
||||
* @brief FreeRTOS Sockets connect and disconnect function wrapper.
|
||||
*/
|
||||
|
||||
#ifndef SOCKETS_WRAPPER_H
|
||||
#define SOCKETS_WRAPPER_H
|
||||
|
||||
/* FreeRTOS+TCP includes. */
|
||||
#include "FreeRTOS_IP.h"
|
||||
#include "FreeRTOS_Sockets.h"
|
||||
#include "FreeRTOS_DNS.h"
|
||||
|
||||
#define SOCKETS_INVALID_SOCKET ( ( Socket_t ) ~0U )
|
||||
|
||||
/**
|
||||
* @brief Establish a connection to server.
|
||||
*
|
||||
* @param[out] pTcpSocket The output parameter to return the created socket descriptor.
|
||||
* @param[in] pHostName Server hostname to connect to.
|
||||
* @param[in] pServerInfo Server port to connect to.
|
||||
* @param[in] receiveTimeoutMs Timeout (in milliseconds) for transport receive.
|
||||
* @param[in] sendTimeoutMs Timeout (in milliseconds) for transport send.
|
||||
*
|
||||
* @note A timeout of 0 means infinite timeout.
|
||||
*
|
||||
* @return Non-zero value on error, 0 on success.
|
||||
*/
|
||||
BaseType_t Sockets_Connect( Socket_t * pTcpSocket,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs );
|
||||
|
||||
/**
|
||||
* @brief End connection to server.
|
||||
*
|
||||
* @param[in] tcpSocket The socket descriptor.
|
||||
*/
|
||||
void Sockets_Disconnect( Socket_t tcpSocket );
|
||||
|
||||
#endif /* ifndef SOCKETS_WRAPPER_H */
|
||||
@ -0,0 +1,334 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file sockets_wrapper.c
|
||||
* @brief FreeRTOS Sockets connect and disconnect wrapper implementation.
|
||||
*/
|
||||
|
||||
/* Include header that defines log levels. */
|
||||
#include "logging_levels.h"
|
||||
|
||||
/* Logging configuration for the Sockets. */
|
||||
#ifndef LIBRARY_LOG_NAME
|
||||
#define LIBRARY_LOG_NAME "SocketsWrapper"
|
||||
#endif
|
||||
#ifndef LIBRARY_LOG_LEVEL
|
||||
#define LIBRARY_LOG_LEVEL LOG_INFO
|
||||
#endif
|
||||
|
||||
extern void vLoggingPrintf( const char * pcFormatString,
|
||||
... );
|
||||
|
||||
#include "logging_stack.h"
|
||||
|
||||
/* Standard includes. */
|
||||
#include <string.h>
|
||||
|
||||
/* FreeRTOS includes. */
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
/* FreeRTOS+TCP includes. */
|
||||
#include "FreeRTOS_IP.h"
|
||||
#include "FreeRTOS_Sockets.h"
|
||||
#include "FreeRTOS_DNS.h"
|
||||
|
||||
/* TCP Sockets Wrapper include.*/
|
||||
/* Let sockets wrapper know that Socket_t is defined already. */
|
||||
#define SOCKET_T_TYPEDEFED
|
||||
#include "tcp_sockets_wrapper.h"
|
||||
|
||||
/**
|
||||
* @brief Maximum number of times to call FreeRTOS_recv when initiating a graceful shutdown.
|
||||
*/
|
||||
#ifndef FREERTOS_SOCKETS_WRAPPER_SHUTDOWN_LOOPS
|
||||
#define FREERTOS_SOCKETS_WRAPPER_SHUTDOWN_LOOPS ( 3 )
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief negative error code indicating a network failure.
|
||||
*/
|
||||
#define FREERTOS_SOCKETS_WRAPPER_NETWORK_ERROR ( -1 )
|
||||
|
||||
/**
|
||||
* @brief Establish a connection to server.
|
||||
*
|
||||
* @param[out] pTcpSocket The output parameter to return the created socket descriptor.
|
||||
* @param[in] pHostName Server hostname to connect to.
|
||||
* @param[in] pServerInfo Server port to connect to.
|
||||
* @param[in] receiveTimeoutMs Timeout (in milliseconds) for transport receive.
|
||||
* @param[in] sendTimeoutMs Timeout (in milliseconds) for transport send.
|
||||
*
|
||||
* @note A timeout of 0 means infinite timeout.
|
||||
*
|
||||
* @return Non-zero value on error, 0 on success.
|
||||
*/
|
||||
BaseType_t TCP_Sockets_Connect( Socket_t * pTcpSocket,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs )
|
||||
{
|
||||
Socket_t tcpSocket = FREERTOS_INVALID_SOCKET;
|
||||
BaseType_t socketStatus = 0;
|
||||
struct freertos_sockaddr serverAddress = { 0 };
|
||||
TickType_t transportTimeout = 0;
|
||||
|
||||
configASSERT( pTcpSocket != NULL );
|
||||
configASSERT( pHostName != NULL );
|
||||
|
||||
/* Create a new TCP socket. */
|
||||
tcpSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP );
|
||||
|
||||
if( tcpSocket == FREERTOS_INVALID_SOCKET )
|
||||
{
|
||||
LogError( ( "Failed to create new socket." ) );
|
||||
socketStatus = FREERTOS_SOCKETS_WRAPPER_NETWORK_ERROR;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogDebug( ( "Created new TCP socket." ) );
|
||||
|
||||
/* Connection parameters. */
|
||||
serverAddress.sin_family = FREERTOS_AF_INET;
|
||||
serverAddress.sin_port = FreeRTOS_htons( port );
|
||||
serverAddress.sin_addr = ( uint32_t ) FreeRTOS_gethostbyname( pHostName );
|
||||
serverAddress.sin_len = ( uint8_t ) sizeof( serverAddress );
|
||||
|
||||
/* Check for errors from DNS lookup. */
|
||||
if( serverAddress.sin_addr == 0U )
|
||||
{
|
||||
LogError( ( "Failed to connect to server: DNS resolution failed: Hostname=%s.",
|
||||
pHostName ) );
|
||||
socketStatus = FREERTOS_SOCKETS_WRAPPER_NETWORK_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
if( socketStatus == 0 )
|
||||
{
|
||||
/* Establish connection. */
|
||||
LogDebug( ( "Creating TCP Connection to %s.", pHostName ) );
|
||||
socketStatus = FreeRTOS_connect( tcpSocket, &serverAddress, sizeof( serverAddress ) );
|
||||
|
||||
if( socketStatus != 0 )
|
||||
{
|
||||
LogError( ( "Failed to connect to server: FreeRTOS_Connect failed: ReturnCode=%d,"
|
||||
" Hostname=%s, Port=%u.",
|
||||
socketStatus,
|
||||
pHostName,
|
||||
port ) );
|
||||
}
|
||||
}
|
||||
|
||||
if( socketStatus == 0 )
|
||||
{
|
||||
/* Set socket receive timeout. */
|
||||
transportTimeout = pdMS_TO_TICKS( receiveTimeoutMs );
|
||||
/* Setting the receive block time cannot fail. */
|
||||
( void ) FreeRTOS_setsockopt( tcpSocket,
|
||||
0,
|
||||
FREERTOS_SO_RCVTIMEO,
|
||||
&transportTimeout,
|
||||
sizeof( TickType_t ) );
|
||||
|
||||
/* Set socket send timeout. */
|
||||
transportTimeout = pdMS_TO_TICKS( sendTimeoutMs );
|
||||
/* Setting the send block time cannot fail. */
|
||||
( void ) FreeRTOS_setsockopt( tcpSocket,
|
||||
0,
|
||||
FREERTOS_SO_SNDTIMEO,
|
||||
&transportTimeout,
|
||||
sizeof( TickType_t ) );
|
||||
}
|
||||
|
||||
/* Clean up on failure. */
|
||||
if( socketStatus != 0 )
|
||||
{
|
||||
if( tcpSocket != FREERTOS_INVALID_SOCKET )
|
||||
{
|
||||
( void ) FreeRTOS_closesocket( tcpSocket );
|
||||
tcpSocket = FREERTOS_INVALID_SOCKET;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Set the socket. */
|
||||
*pTcpSocket = tcpSocket;
|
||||
LogInfo( ( "Established TCP connection with %s.", pHostName ) );
|
||||
}
|
||||
|
||||
return socketStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief End connection to server.
|
||||
*
|
||||
* @param[in] tcpSocket The socket descriptor.
|
||||
*/
|
||||
void TCP_Sockets_Disconnect( Socket_t tcpSocket )
|
||||
{
|
||||
BaseType_t waitForShutdownLoopCount = 0;
|
||||
uint8_t pDummyBuffer[ 2 ];
|
||||
|
||||
if( ( tcpSocket != NULL ) && ( tcpSocket != FREERTOS_INVALID_SOCKET ) )
|
||||
{
|
||||
/* Initiate graceful shutdown. */
|
||||
( void ) FreeRTOS_shutdown( tcpSocket, FREERTOS_SHUT_RDWR );
|
||||
|
||||
/* Wait for the socket to disconnect gracefully (indicated by FreeRTOS_recv()
|
||||
* returning a FREERTOS_EINVAL error) before closing the socket. */
|
||||
while( FreeRTOS_recv( tcpSocket, pDummyBuffer, sizeof( pDummyBuffer ), 0 ) >= 0 )
|
||||
{
|
||||
/* We don't need to delay since FreeRTOS_recv should already have a timeout. */
|
||||
|
||||
if( ++waitForShutdownLoopCount >= FREERTOS_SOCKETS_WRAPPER_SHUTDOWN_LOOPS )
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
( void ) FreeRTOS_closesocket( tcpSocket );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Transmit data to the remote socket.
|
||||
*
|
||||
* The socket must have already been created using a call to TCP_Sockets_Connect().
|
||||
*
|
||||
* @param[in] xSocket The handle of the sending socket.
|
||||
* @param[in] pvBuffer The buffer containing the data to be sent.
|
||||
* @param[in] xDataLength The length of the data to be sent.
|
||||
*
|
||||
* @return
|
||||
* * On success, the number of bytes actually sent is returned.
|
||||
* * If an error occurred, a negative value is returned. @ref SocketsErrors
|
||||
*/
|
||||
int32_t TCP_Sockets_Send( Socket_t xSocket,
|
||||
const void * pvBuffer,
|
||||
size_t xBufferLength )
|
||||
{
|
||||
BaseType_t xSendStatus;
|
||||
int xReturnStatus = TCP_SOCKETS_ERRNO_ERROR;
|
||||
|
||||
configASSERT( xSocket != NULL );
|
||||
configASSERT( pvBuffer != NULL );
|
||||
|
||||
xSendStatus = FreeRTOS_send( xSocket, pvBuffer, xBufferLength, 0 );
|
||||
|
||||
switch( xSendStatus )
|
||||
{
|
||||
/* Socket was closed or just got closed. */
|
||||
case -pdFREERTOS_ERRNO_ENOTCONN:
|
||||
xReturnStatus = TCP_SOCKETS_ERRNO_ENOTCONN;
|
||||
break;
|
||||
|
||||
/* Not enough memory for the socket to create either an Rx or Tx stream. */
|
||||
case -pdFREERTOS_ERRNO_ENOMEM:
|
||||
xReturnStatus = TCP_SOCKETS_ERRNO_ENOMEM;
|
||||
break;
|
||||
|
||||
/* Socket is not valid, is not a TCP socket, or is not bound. */
|
||||
case -pdFREERTOS_ERRNO_EINVAL:
|
||||
xReturnStatus = TCP_SOCKETS_ERRNO_EINVAL;
|
||||
break;
|
||||
|
||||
/* Socket received a signal, causing the read operation to be aborted. */
|
||||
case -pdFREERTOS_ERRNO_EINTR:
|
||||
xReturnStatus = TCP_SOCKETS_ERRNO_EINTR;
|
||||
break;
|
||||
|
||||
/* A timeout occurred before any data could be sent as the TCP buffer was full. */
|
||||
case -pdFREERTOS_ERRNO_ENOSPC:
|
||||
xReturnStatus = TCP_SOCKETS_ERRNO_ENOSPC;
|
||||
break;
|
||||
|
||||
default:
|
||||
xReturnStatus = ( int ) xSendStatus;
|
||||
break;
|
||||
}
|
||||
|
||||
return xReturnStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Receive data from a TCP socket.
|
||||
*
|
||||
* The socket must have already been created using a call to TCP_Sockets_Connect().
|
||||
*
|
||||
* @param[in] xSocket The handle of the socket from which data is being received.
|
||||
* @param[out] pvBuffer The buffer into which the received data will be placed.
|
||||
* @param[in] xBufferLength The maximum number of bytes which can be received.
|
||||
* pvBuffer must be at least xBufferLength bytes long.
|
||||
*
|
||||
* @return
|
||||
* * If the receive was successful then the number of bytes received (placed in the
|
||||
* buffer pointed to by pvBuffer) is returned.
|
||||
* * If a timeout occurred before data could be received then 0 is returned (timeout
|
||||
* is set using @ref SOCKETS_SO_RCVTIMEO).
|
||||
* * If an error occurred, a negative value is returned. @ref SocketsErrors
|
||||
*/
|
||||
int32_t TCP_Sockets_Recv( Socket_t xSocket,
|
||||
void * pvBuffer,
|
||||
size_t xBufferLength )
|
||||
{
|
||||
BaseType_t xRecvStatus;
|
||||
int xReturnStatus = TCP_SOCKETS_ERRNO_ERROR;
|
||||
|
||||
configASSERT( xSocket != NULL );
|
||||
configASSERT( pvBuffer != NULL );
|
||||
|
||||
xRecvStatus = FreeRTOS_recv( xSocket, pvBuffer, xBufferLength, 0 );
|
||||
|
||||
switch( xRecvStatus )
|
||||
{
|
||||
/* Socket was closed or just got closed. */
|
||||
case -pdFREERTOS_ERRNO_ENOTCONN:
|
||||
xReturnStatus = TCP_SOCKETS_ERRNO_ENOTCONN;
|
||||
break;
|
||||
|
||||
/* Not enough memory for the socket to create either an Rx or Tx stream. */
|
||||
case -pdFREERTOS_ERRNO_ENOMEM:
|
||||
xReturnStatus = TCP_SOCKETS_ERRNO_ENOMEM;
|
||||
break;
|
||||
|
||||
/* Socket is not valid, is not a TCP socket, or is not bound. */
|
||||
case -pdFREERTOS_ERRNO_EINVAL:
|
||||
xReturnStatus = TCP_SOCKETS_ERRNO_EINVAL;
|
||||
break;
|
||||
|
||||
/* Socket received a signal, causing the read operation to be aborted. */
|
||||
case -pdFREERTOS_ERRNO_EINTR:
|
||||
xReturnStatus = TCP_SOCKETS_ERRNO_EINTR;
|
||||
break;
|
||||
|
||||
default:
|
||||
xReturnStatus = ( int ) xRecvStatus;
|
||||
break;
|
||||
}
|
||||
|
||||
return xReturnStatus;
|
||||
}
|
||||
@ -0,0 +1,895 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file tls_freertos.c
|
||||
* @brief TLS transport interface implementations. This implementation uses
|
||||
* mbedTLS.
|
||||
*/
|
||||
|
||||
#include "logging_levels.h"
|
||||
|
||||
#define LIBRARY_LOG_NAME "MbedtlsTransport"
|
||||
#define LIBRARY_LOG_LEVEL LOG_INFO
|
||||
|
||||
#include "logging_stack.h"
|
||||
|
||||
/* Standard includes. */
|
||||
#include <string.h>
|
||||
|
||||
/* FreeRTOS includes. */
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
/* MbedTLS Bio TCP sockets wrapper include. */
|
||||
#include "mbedtls_bio_tcp_sockets_wrapper.h"
|
||||
|
||||
/* TLS transport header. */
|
||||
#include "transport_mbedtls.h"
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Each compilation unit that consumes the NetworkContext must define it.
|
||||
* It should contain a single pointer as seen below whenever the header file
|
||||
* of this transport implementation is included to your project.
|
||||
*
|
||||
* @note When using multiple transports in the same compilation unit,
|
||||
* define this pointer as void *.
|
||||
*/
|
||||
struct NetworkContext
|
||||
{
|
||||
TlsTransportParams_t * pParams;
|
||||
};
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Represents string to be logged when mbedTLS returned error
|
||||
* does not contain a high-level code.
|
||||
*/
|
||||
static const char * pNoHighLevelMbedTlsCodeStr = "<No-High-Level-Code>";
|
||||
|
||||
/**
|
||||
* @brief Represents string to be logged when mbedTLS returned error
|
||||
* does not contain a low-level code.
|
||||
*/
|
||||
static const char * pNoLowLevelMbedTlsCodeStr = "<No-Low-Level-Code>";
|
||||
|
||||
/**
|
||||
* @brief Utility for converting the high-level code in an mbedTLS error to string,
|
||||
* if the code-contains a high-level code; otherwise, using a default string.
|
||||
*/
|
||||
#define mbedtlsHighLevelCodeOrDefault( mbedTlsCode ) \
|
||||
( mbedtls_high_level_strerr( mbedTlsCode ) != NULL ) ? \
|
||||
mbedtls_high_level_strerr( mbedTlsCode ) : pNoHighLevelMbedTlsCodeStr
|
||||
|
||||
/**
|
||||
* @brief Utility for converting the level-level code in an mbedTLS error to string,
|
||||
* if the code-contains a level-level code; otherwise, using a default string.
|
||||
*/
|
||||
#define mbedtlsLowLevelCodeOrDefault( mbedTlsCode ) \
|
||||
( mbedtls_low_level_strerr( mbedTlsCode ) != NULL ) ? \
|
||||
mbedtls_low_level_strerr( mbedTlsCode ) : pNoLowLevelMbedTlsCodeStr
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Initialize the mbed TLS structures in a network connection.
|
||||
*
|
||||
* @param[in] pSslContext The SSL context to initialize.
|
||||
*/
|
||||
static void sslContextInit( SSLContext_t * pSslContext );
|
||||
|
||||
/**
|
||||
* @brief Free the mbed TLS structures in a network connection.
|
||||
*
|
||||
* @param[in] pSslContext The SSL context to free.
|
||||
*/
|
||||
static void sslContextFree( SSLContext_t * pSslContext );
|
||||
|
||||
/**
|
||||
* @brief Add X509 certificate to the trusted list of root certificates.
|
||||
*
|
||||
* OpenSSL does not provide a single function for reading and loading certificates
|
||||
* from files into stores, so the file API must be called. Start with the
|
||||
* root certificate.
|
||||
*
|
||||
* @param[out] pSslContext SSL context to which the trusted server root CA is to be added.
|
||||
* @param[in] pRootCa PEM-encoded string of the trusted server root CA.
|
||||
* @param[in] rootCaSize Size of the trusted server root CA.
|
||||
*
|
||||
* @return 0 on success; otherwise, failure;
|
||||
*/
|
||||
static int32_t setRootCa( SSLContext_t * pSslContext,
|
||||
const uint8_t * pRootCa,
|
||||
size_t rootCaSize );
|
||||
|
||||
/**
|
||||
* @brief Set X509 certificate as client certificate for the server to authenticate.
|
||||
*
|
||||
* @param[out] pSslContext SSL context to which the client certificate is to be set.
|
||||
* @param[in] pClientCert PEM-encoded string of the client certificate.
|
||||
* @param[in] clientCertSize Size of the client certificate.
|
||||
*
|
||||
* @return 0 on success; otherwise, failure;
|
||||
*/
|
||||
static int32_t setClientCertificate( SSLContext_t * pSslContext,
|
||||
const uint8_t * pClientCert,
|
||||
size_t clientCertSize );
|
||||
|
||||
/**
|
||||
* @brief Set private key for the client's certificate.
|
||||
*
|
||||
* @param[out] pSslContext SSL context to which the private key is to be set.
|
||||
* @param[in] pPrivateKey PEM-encoded string of the client private key.
|
||||
* @param[in] privateKeySize Size of the client private key.
|
||||
*
|
||||
* @return 0 on success; otherwise, failure;
|
||||
*/
|
||||
static int32_t setPrivateKey( SSLContext_t * pSslContext,
|
||||
const uint8_t * pPrivateKey,
|
||||
size_t privateKeySize );
|
||||
|
||||
/**
|
||||
* @brief Passes TLS credentials to the OpenSSL library.
|
||||
*
|
||||
* Provides the root CA certificate, client certificate, and private key to the
|
||||
* OpenSSL library. If the client certificate or private key is not NULL, mutual
|
||||
* authentication is used when performing the TLS handshake.
|
||||
*
|
||||
* @param[out] pSslContext SSL context to which the credentials are to be imported.
|
||||
* @param[in] pNetworkCredentials TLS credentials to be imported.
|
||||
*
|
||||
* @return 0 on success; otherwise, failure;
|
||||
*/
|
||||
static int32_t setCredentials( SSLContext_t * pSslContext,
|
||||
const NetworkCredentials_t * pNetworkCredentials );
|
||||
|
||||
/**
|
||||
* @brief Set optional configurations for the TLS connection.
|
||||
*
|
||||
* This function is used to set SNI and ALPN protocols.
|
||||
*
|
||||
* @param[in] pSslContext SSL context to which the optional configurations are to be set.
|
||||
* @param[in] pHostName Remote host name, used for server name indication.
|
||||
* @param[in] pNetworkCredentials TLS setup parameters.
|
||||
*/
|
||||
static void setOptionalConfigurations( SSLContext_t * pSslContext,
|
||||
const char * pHostName,
|
||||
const NetworkCredentials_t * pNetworkCredentials );
|
||||
|
||||
/**
|
||||
* @brief Setup TLS by initializing contexts and setting configurations.
|
||||
*
|
||||
* @param[in] pNetworkContext Network context.
|
||||
* @param[in] pHostName Remote host name, used for server name indication.
|
||||
* @param[in] pNetworkCredentials TLS setup parameters.
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS,
|
||||
* or #TLS_TRANSPORT_INTERNAL_ERROR.
|
||||
*/
|
||||
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
const NetworkCredentials_t * pNetworkCredentials );
|
||||
|
||||
/**
|
||||
* @brief Perform the TLS handshake on a TCP connection.
|
||||
*
|
||||
* @param[in] pNetworkContext Network context.
|
||||
* @param[in] pNetworkCredentials TLS setup parameters.
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_HANDSHAKE_FAILED, or #TLS_TRANSPORT_INTERNAL_ERROR.
|
||||
*/
|
||||
static TlsTransportStatus_t tlsHandshake( NetworkContext_t * pNetworkContext,
|
||||
const NetworkCredentials_t * pNetworkCredentials );
|
||||
|
||||
/**
|
||||
* @brief Initialize mbedTLS.
|
||||
*
|
||||
* @param[out] entropyContext mbed TLS entropy context for generation of random numbers.
|
||||
* @param[out] ctrDrgbContext mbed TLS CTR DRBG context for generation of random numbers.
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, or #TLS_TRANSPORT_INTERNAL_ERROR.
|
||||
*/
|
||||
static TlsTransportStatus_t initMbedtls( mbedtls_entropy_context * pEntropyContext,
|
||||
mbedtls_ctr_drbg_context * pCtrDrgbContext );
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static void sslContextInit( SSLContext_t * pSslContext )
|
||||
{
|
||||
configASSERT( pSslContext != NULL );
|
||||
|
||||
mbedtls_ssl_config_init( &( pSslContext->config ) );
|
||||
mbedtls_x509_crt_init( &( pSslContext->rootCa ) );
|
||||
mbedtls_pk_init( &( pSslContext->privKey ) );
|
||||
mbedtls_x509_crt_init( &( pSslContext->clientCert ) );
|
||||
mbedtls_ssl_init( &( pSslContext->context ) );
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static void sslContextFree( SSLContext_t * pSslContext )
|
||||
{
|
||||
configASSERT( pSslContext != NULL );
|
||||
|
||||
mbedtls_ssl_free( &( pSslContext->context ) );
|
||||
mbedtls_x509_crt_free( &( pSslContext->rootCa ) );
|
||||
mbedtls_x509_crt_free( &( pSslContext->clientCert ) );
|
||||
mbedtls_pk_free( &( pSslContext->privKey ) );
|
||||
mbedtls_entropy_free( &( pSslContext->entropyContext ) );
|
||||
mbedtls_ctr_drbg_free( &( pSslContext->ctrDrgbContext ) );
|
||||
mbedtls_ssl_config_free( &( pSslContext->config ) );
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static int32_t setRootCa( SSLContext_t * pSslContext,
|
||||
const uint8_t * pRootCa,
|
||||
size_t rootCaSize )
|
||||
{
|
||||
int32_t mbedtlsError = -1;
|
||||
|
||||
configASSERT( pSslContext != NULL );
|
||||
configASSERT( pRootCa != NULL );
|
||||
|
||||
/* Parse the server root CA certificate into the SSL context. */
|
||||
mbedtlsError = mbedtls_x509_crt_parse( &( pSslContext->rootCa ),
|
||||
pRootCa,
|
||||
rootCaSize );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to parse server root CA certificate: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
mbedtls_ssl_conf_ca_chain( &( pSslContext->config ),
|
||||
&( pSslContext->rootCa ),
|
||||
NULL );
|
||||
}
|
||||
|
||||
return mbedtlsError;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static int32_t setClientCertificate( SSLContext_t * pSslContext,
|
||||
const uint8_t * pClientCert,
|
||||
size_t clientCertSize )
|
||||
{
|
||||
int32_t mbedtlsError = -1;
|
||||
|
||||
configASSERT( pSslContext != NULL );
|
||||
configASSERT( pClientCert != NULL );
|
||||
|
||||
/* Setup the client certificate. */
|
||||
mbedtlsError = mbedtls_x509_crt_parse( &( pSslContext->clientCert ),
|
||||
pClientCert,
|
||||
clientCertSize );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to parse the client certificate: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
}
|
||||
|
||||
return mbedtlsError;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static int32_t setPrivateKey( SSLContext_t * pSslContext,
|
||||
const uint8_t * pPrivateKey,
|
||||
size_t privateKeySize )
|
||||
{
|
||||
int32_t mbedtlsError = -1;
|
||||
|
||||
configASSERT( pSslContext != NULL );
|
||||
configASSERT( pPrivateKey != NULL );
|
||||
|
||||
#if MBEDTLS_VERSION_NUMBER < 0x03000000
|
||||
mbedtlsError = mbedtls_pk_parse_key( &( pSslContext->privKey ),
|
||||
pPrivateKey,
|
||||
privateKeySize,
|
||||
NULL, 0 );
|
||||
#else
|
||||
mbedtlsError = mbedtls_pk_parse_key( &( pSslContext->privKey ),
|
||||
pPrivateKey,
|
||||
privateKeySize,
|
||||
NULL, 0,
|
||||
mbedtls_ctr_drbg_random,
|
||||
&( pSslContext->ctrDrgbContext ) );
|
||||
#endif /* if MBEDTLS_VERSION_NUMBER < 0x03000000 */
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to parse the client key: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
}
|
||||
|
||||
return mbedtlsError;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static int32_t setCredentials( SSLContext_t * pSslContext,
|
||||
const NetworkCredentials_t * pNetworkCredentials )
|
||||
{
|
||||
int32_t mbedtlsError = -1;
|
||||
|
||||
configASSERT( pSslContext != NULL );
|
||||
configASSERT( pNetworkCredentials != NULL );
|
||||
|
||||
/* Set up the certificate security profile, starting from the default value. */
|
||||
pSslContext->certProfile = mbedtls_x509_crt_profile_default;
|
||||
|
||||
/* Set SSL authmode and the RNG context. */
|
||||
mbedtls_ssl_conf_authmode( &( pSslContext->config ),
|
||||
MBEDTLS_SSL_VERIFY_REQUIRED );
|
||||
mbedtls_ssl_conf_rng( &( pSslContext->config ),
|
||||
mbedtls_ctr_drbg_random,
|
||||
&( pSslContext->ctrDrgbContext ) );
|
||||
mbedtls_ssl_conf_cert_profile( &( pSslContext->config ),
|
||||
&( pSslContext->certProfile ) );
|
||||
|
||||
mbedtlsError = setRootCa( pSslContext,
|
||||
pNetworkCredentials->pRootCa,
|
||||
pNetworkCredentials->rootCaSize );
|
||||
|
||||
if( ( pNetworkCredentials->pClientCert != NULL ) &&
|
||||
( pNetworkCredentials->pPrivateKey != NULL ) )
|
||||
{
|
||||
if( mbedtlsError == 0 )
|
||||
{
|
||||
mbedtlsError = setClientCertificate( pSslContext,
|
||||
pNetworkCredentials->pClientCert,
|
||||
pNetworkCredentials->clientCertSize );
|
||||
}
|
||||
|
||||
if( mbedtlsError == 0 )
|
||||
{
|
||||
mbedtlsError = setPrivateKey( pSslContext,
|
||||
pNetworkCredentials->pPrivateKey,
|
||||
pNetworkCredentials->privateKeySize );
|
||||
}
|
||||
|
||||
if( mbedtlsError == 0 )
|
||||
{
|
||||
mbedtlsError = mbedtls_ssl_conf_own_cert( &( pSslContext->config ),
|
||||
&( pSslContext->clientCert ),
|
||||
&( pSslContext->privKey ) );
|
||||
}
|
||||
}
|
||||
|
||||
return mbedtlsError;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static void setOptionalConfigurations( SSLContext_t * pSslContext,
|
||||
const char * pHostName,
|
||||
const NetworkCredentials_t * pNetworkCredentials )
|
||||
{
|
||||
int32_t mbedtlsError = -1;
|
||||
|
||||
configASSERT( pSslContext != NULL );
|
||||
configASSERT( pHostName != NULL );
|
||||
configASSERT( pNetworkCredentials != NULL );
|
||||
|
||||
if( pNetworkCredentials->pAlpnProtos != NULL )
|
||||
{
|
||||
/* Include an application protocol list in the TLS ClientHello
|
||||
* message. */
|
||||
mbedtlsError = mbedtls_ssl_conf_alpn_protocols( &( pSslContext->config ),
|
||||
pNetworkCredentials->pAlpnProtos );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to configure ALPN protocol in mbed TLS: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
/* Enable SNI if requested. */
|
||||
if( pNetworkCredentials->disableSni == pdFALSE )
|
||||
{
|
||||
mbedtlsError = mbedtls_ssl_set_hostname( &( pSslContext->context ),
|
||||
pHostName );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to set server name: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
/* Set Maximum Fragment Length if enabled. */
|
||||
#ifdef MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
|
||||
/* Enable the max fragment extension. 4096 bytes is currently the largest fragment size permitted.
|
||||
* See RFC 8449 https://tools.ietf.org/html/rfc8449 for more information.
|
||||
*
|
||||
* Smaller values can be found in "mbedtls/include/ssl.h".
|
||||
*/
|
||||
mbedtlsError = mbedtls_ssl_conf_max_frag_len( &( pSslContext->config ), MBEDTLS_SSL_MAX_FRAG_LEN_4096 );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to maximum fragment length extension: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
}
|
||||
#endif /* ifdef MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
const NetworkCredentials_t * pNetworkCredentials )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
int32_t mbedtlsError = 0;
|
||||
|
||||
configASSERT( pNetworkContext != NULL );
|
||||
configASSERT( pNetworkContext->pParams != NULL );
|
||||
configASSERT( pHostName != NULL );
|
||||
configASSERT( pNetworkCredentials != NULL );
|
||||
configASSERT( pNetworkCredentials->pRootCa != NULL );
|
||||
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
/* Initialize the mbed TLS context structures. */
|
||||
sslContextInit( &( pTlsTransportParams->sslContext ) );
|
||||
|
||||
mbedtlsError = mbedtls_ssl_config_defaults( &( pTlsTransportParams->sslContext.config ),
|
||||
MBEDTLS_SSL_IS_CLIENT,
|
||||
MBEDTLS_SSL_TRANSPORT_STREAM,
|
||||
MBEDTLS_SSL_PRESET_DEFAULT );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to set default SSL configuration: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
|
||||
/* Per mbed TLS docs, mbedtls_ssl_config_defaults only fails on memory allocation. */
|
||||
returnStatus = TLS_TRANSPORT_INSUFFICIENT_MEMORY;
|
||||
}
|
||||
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
mbedtlsError = setCredentials( &( pTlsTransportParams->sslContext ),
|
||||
pNetworkCredentials );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Optionally set SNI and ALPN protocols. */
|
||||
setOptionalConfigurations( &( pTlsTransportParams->sslContext ),
|
||||
pHostName,
|
||||
pNetworkCredentials );
|
||||
}
|
||||
}
|
||||
|
||||
return returnStatus;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static TlsTransportStatus_t tlsHandshake( NetworkContext_t * pNetworkContext,
|
||||
const NetworkCredentials_t * pNetworkCredentials )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
int32_t mbedtlsError = 0;
|
||||
|
||||
configASSERT( pNetworkContext != NULL );
|
||||
configASSERT( pNetworkContext->pParams != NULL );
|
||||
configASSERT( pNetworkCredentials != NULL );
|
||||
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
/* Initialize the mbed TLS secured connection context. */
|
||||
mbedtlsError = mbedtls_ssl_setup( &( pTlsTransportParams->sslContext.context ),
|
||||
&( pTlsTransportParams->sslContext.config ) );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to set up mbed TLS SSL context: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
|
||||
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Set the underlying IO for the TLS connection. */
|
||||
|
||||
/* MISRA Rule 11.2 flags the following line for casting the second
|
||||
* parameter to void *. This rule is suppressed because
|
||||
* #mbedtls_ssl_set_bio requires the second parameter as void *.
|
||||
*/
|
||||
/* coverity[misra_c_2012_rule_11_2_violation] */
|
||||
|
||||
/* These two macros MBEDTLS_SSL_SEND and MBEDTLS_SSL_RECV need to be
|
||||
* defined in mbedtls_config.h according to which implementation you use.
|
||||
*/
|
||||
mbedtls_ssl_set_bio( &( pTlsTransportParams->sslContext.context ),
|
||||
( void * ) pTlsTransportParams->tcpSocket,
|
||||
xMbedTLSBioTCPSocketsWrapperSend,
|
||||
xMbedTLSBioTCPSocketsWrapperRecv,
|
||||
NULL );
|
||||
}
|
||||
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* Perform the TLS handshake. */
|
||||
do
|
||||
{
|
||||
mbedtlsError = mbedtls_ssl_handshake( &( pTlsTransportParams->sslContext.context ) );
|
||||
} while( ( mbedtlsError == MBEDTLS_ERR_SSL_WANT_READ ) ||
|
||||
( mbedtlsError == MBEDTLS_ERR_SSL_WANT_WRITE ) );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to perform TLS handshake: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
|
||||
returnStatus = TLS_TRANSPORT_HANDSHAKE_FAILED;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogInfo( ( "(Network connection %p) TLS handshake successful.",
|
||||
pNetworkContext ) );
|
||||
}
|
||||
}
|
||||
|
||||
return returnStatus;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static TlsTransportStatus_t initMbedtls( mbedtls_entropy_context * pEntropyContext,
|
||||
mbedtls_ctr_drbg_context * pCtrDrgbContext )
|
||||
{
|
||||
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
int32_t mbedtlsError = 0;
|
||||
|
||||
#if defined( MBEDTLS_THREADING_ALT )
|
||||
/* Set the mutex functions for mbed TLS thread safety. */
|
||||
mbedtls_platform_threading_init();
|
||||
#endif
|
||||
|
||||
/* Initialize contexts for random number generation. */
|
||||
mbedtls_entropy_init( pEntropyContext );
|
||||
mbedtls_ctr_drbg_init( pCtrDrgbContext );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to add entropy source: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
|
||||
}
|
||||
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* Seed the random number generator. */
|
||||
mbedtlsError = mbedtls_ctr_drbg_seed( pCtrDrgbContext,
|
||||
mbedtls_entropy_func,
|
||||
pEntropyContext,
|
||||
NULL,
|
||||
0 );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to seed PRNG: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
LogDebug( ( "Successfully initialized mbedTLS." ) );
|
||||
}
|
||||
|
||||
return returnStatus;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
const NetworkCredentials_t * pNetworkCredentials,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
BaseType_t socketStatus = 0;
|
||||
BaseType_t isSocketConnected = pdFALSE, isTlsSetup = pdFALSE;
|
||||
|
||||
if( ( pNetworkContext == NULL ) ||
|
||||
( pNetworkContext->pParams == NULL ) ||
|
||||
( pHostName == NULL ) ||
|
||||
( pNetworkCredentials == NULL ) )
|
||||
{
|
||||
LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, "
|
||||
"pHostName=%p, pNetworkCredentials=%p.",
|
||||
pNetworkContext,
|
||||
pHostName,
|
||||
pNetworkCredentials ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_PARAMETER;
|
||||
}
|
||||
else if( ( pNetworkCredentials->pRootCa == NULL ) )
|
||||
{
|
||||
LogError( ( "pRootCa cannot be NULL." ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_PARAMETER;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Empty else for MISRA 15.7 compliance. */
|
||||
}
|
||||
|
||||
/* Establish a TCP connection with the server. */
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
|
||||
/* Initialize tcpSocket. */
|
||||
pTlsTransportParams->tcpSocket = NULL;
|
||||
|
||||
socketStatus = TCP_Sockets_Connect( &( pTlsTransportParams->tcpSocket ),
|
||||
pHostName,
|
||||
port,
|
||||
receiveTimeoutMs,
|
||||
sendTimeoutMs );
|
||||
|
||||
if( socketStatus != 0 )
|
||||
{
|
||||
LogError( ( "Failed to connect to %s with error %d.",
|
||||
pHostName,
|
||||
socketStatus ) );
|
||||
returnStatus = TLS_TRANSPORT_CONNECT_FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/* Initialize mbedtls. */
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
isSocketConnected = pdTRUE;
|
||||
|
||||
returnStatus = initMbedtls( &( pTlsTransportParams->sslContext.entropyContext ),
|
||||
&( pTlsTransportParams->sslContext.ctrDrgbContext ) );
|
||||
}
|
||||
|
||||
/* Initialize TLS contexts and set credentials. */
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
returnStatus = tlsSetup( pNetworkContext, pHostName, pNetworkCredentials );
|
||||
}
|
||||
|
||||
/* Perform TLS handshake. */
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
isTlsSetup = pdTRUE;
|
||||
|
||||
returnStatus = tlsHandshake( pNetworkContext, pNetworkCredentials );
|
||||
}
|
||||
|
||||
/* Clean up on failure. */
|
||||
if( returnStatus != TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* Free SSL context if it's setup. */
|
||||
if( isTlsSetup == pdTRUE )
|
||||
{
|
||||
sslContextFree( &( pTlsTransportParams->sslContext ) );
|
||||
}
|
||||
|
||||
/* Call Sockets_Disconnect if socket was connected. */
|
||||
if( isSocketConnected == pdTRUE )
|
||||
{
|
||||
TCP_Sockets_Disconnect( pTlsTransportParams->tcpSocket );
|
||||
pTlsTransportParams->tcpSocket = NULL;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogInfo( ( "(Network connection %p) Connection to %s established.",
|
||||
pNetworkContext,
|
||||
pHostName ) );
|
||||
}
|
||||
|
||||
return returnStatus;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
BaseType_t tlsStatus = 0;
|
||||
|
||||
if( ( pNetworkContext != NULL ) && ( pNetworkContext->pParams != NULL ) )
|
||||
{
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
/* Attempting to terminate TLS connection. */
|
||||
tlsStatus = ( BaseType_t ) mbedtls_ssl_close_notify( &( pTlsTransportParams->sslContext.context ) );
|
||||
|
||||
/* Ignore the WANT_READ and WANT_WRITE return values. */
|
||||
if( ( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_READ ) &&
|
||||
( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_WRITE ) )
|
||||
{
|
||||
if( tlsStatus == 0 )
|
||||
{
|
||||
LogInfo( ( "(Network connection %p) TLS close-notify sent.",
|
||||
pNetworkContext ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "(Network connection %p) Failed to send TLS close-notify: mbedTLSError= %s : %s.",
|
||||
pNetworkContext,
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
/* WANT_READ and WANT_WRITE can be ignored. Logging for debugging purposes. */
|
||||
LogInfo( ( "(Network connection %p) TLS close-notify sent; "
|
||||
"received %s as the TLS status can be ignored for close-notify.",
|
||||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ? "WANT_READ" : "WANT_WRITE",
|
||||
pNetworkContext ) );
|
||||
}
|
||||
|
||||
/* Call socket shutdown function to close connection. */
|
||||
TCP_Sockets_Disconnect( pTlsTransportParams->tcpSocket );
|
||||
|
||||
/* Free mbed TLS contexts. */
|
||||
sslContextFree( &( pTlsTransportParams->sslContext ) );
|
||||
}
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
|
||||
void * pBuffer,
|
||||
size_t bytesToRecv )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
int32_t tlsStatus = 0;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) )
|
||||
{
|
||||
LogError( ( "invalid input, pNetworkContext=%p", pNetworkContext ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( pBuffer == NULL )
|
||||
{
|
||||
LogError( ( "invalid input, pBuffer == NULL" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( bytesToRecv == 0 )
|
||||
{
|
||||
LogError( ( "invalid input, bytesToRecv == 0" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
|
||||
tlsStatus = ( int32_t ) mbedtls_ssl_read( &( pTlsTransportParams->sslContext.context ),
|
||||
pBuffer,
|
||||
bytesToRecv );
|
||||
|
||||
if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) ||
|
||||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ||
|
||||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) )
|
||||
{
|
||||
LogDebug( ( "Failed to read data. However, a read can be retried on this error. "
|
||||
"mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
|
||||
/* Mark these set of errors as a timeout. The libraries may retry read
|
||||
* on these errors. */
|
||||
tlsStatus = 0;
|
||||
}
|
||||
else if( tlsStatus < 0 )
|
||||
{
|
||||
LogError( ( "Failed to read data: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Empty else marker. */
|
||||
}
|
||||
}
|
||||
|
||||
return tlsStatus;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext,
|
||||
const void * pBuffer,
|
||||
size_t bytesToSend )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
int32_t tlsStatus = 0;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) )
|
||||
{
|
||||
LogError( ( "invalid input, pNetworkContext=%p", pNetworkContext ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( pBuffer == NULL )
|
||||
{
|
||||
LogError( ( "invalid input, pBuffer == NULL" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( bytesToSend == 0 )
|
||||
{
|
||||
LogError( ( "invalid input, bytesToSend == 0" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
|
||||
tlsStatus = ( int32_t ) mbedtls_ssl_write( &( pTlsTransportParams->sslContext.context ),
|
||||
pBuffer,
|
||||
bytesToSend );
|
||||
|
||||
if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) ||
|
||||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ||
|
||||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) )
|
||||
{
|
||||
LogDebug( ( "Failed to send data. However, send can be retried on this error. "
|
||||
"mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
|
||||
/* Mark these set of errors as a timeout. The libraries may retry send
|
||||
* on these errors. */
|
||||
tlsStatus = 0;
|
||||
}
|
||||
else if( tlsStatus < 0 )
|
||||
{
|
||||
LogError( ( "Failed to send data: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Empty else marker. */
|
||||
}
|
||||
}
|
||||
|
||||
return tlsStatus;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
@ -0,0 +1,219 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file tls_freertos.h
|
||||
* @brief TLS transport interface header.
|
||||
*/
|
||||
|
||||
#ifndef USING_MBEDTLS
|
||||
#define USING_MBEDTLS
|
||||
|
||||
/**************************************************/
|
||||
/******* DO NOT CHANGE the following order ********/
|
||||
/**************************************************/
|
||||
|
||||
/* Logging related header files are required to be included in the following order:
|
||||
* 1. Include the header file "logging_levels.h".
|
||||
* 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL.
|
||||
* 3. Include the header file "logging_stack.h".
|
||||
*/
|
||||
|
||||
/* Include header that defines log levels. */
|
||||
#include "logging_levels.h"
|
||||
|
||||
/* Logging configuration for the Sockets. */
|
||||
#ifndef LIBRARY_LOG_NAME
|
||||
#define LIBRARY_LOG_NAME "TlsTransport"
|
||||
#endif
|
||||
#ifndef LIBRARY_LOG_LEVEL
|
||||
#define LIBRARY_LOG_LEVEL LOG_ERROR
|
||||
#endif
|
||||
|
||||
/* Prototype for the function used to print to console on Windows simulator
|
||||
* of FreeRTOS.
|
||||
* The function prints to the console before the network is connected;
|
||||
* then a UDP port after the network has connected. */
|
||||
extern void vLoggingPrintf( const char * pcFormatString,
|
||||
... );
|
||||
|
||||
/* Map the SdkLog macro to the logging function to enable logging
|
||||
* on Windows simulator. */
|
||||
#ifndef SdkLog
|
||||
#define SdkLog( message ) vLoggingPrintf message
|
||||
#endif
|
||||
|
||||
#include "logging_stack.h"
|
||||
|
||||
/************ End of logging configuration ****************/
|
||||
|
||||
/* TCP Sockets Wrapper include.*/
|
||||
#include "tcp_sockets_wrapper.h"
|
||||
|
||||
/* Transport interface include. */
|
||||
#include "transport_interface.h"
|
||||
|
||||
/* mbed TLS includes. */
|
||||
#include "mbedtls/ctr_drbg.h"
|
||||
#include "mbedtls/entropy.h"
|
||||
#include "mbedtls/ssl.h"
|
||||
#include "mbedtls/threading.h"
|
||||
#include "mbedtls/x509.h"
|
||||
#include "mbedtls/error.h"
|
||||
#include "mbedtls/build_info.h"
|
||||
|
||||
/**
|
||||
* @brief Secured connection context.
|
||||
*/
|
||||
typedef struct SSLContext
|
||||
{
|
||||
mbedtls_ssl_config config; /**< @brief SSL connection configuration. */
|
||||
mbedtls_ssl_context context; /**< @brief SSL connection context */
|
||||
mbedtls_x509_crt_profile certProfile; /**< @brief Certificate security profile for this connection. */
|
||||
mbedtls_x509_crt rootCa; /**< @brief Root CA certificate context. */
|
||||
mbedtls_x509_crt clientCert; /**< @brief Client certificate context. */
|
||||
mbedtls_pk_context privKey; /**< @brief Client private key context. */
|
||||
mbedtls_entropy_context entropyContext; /**< @brief Entropy context for random number generation. */
|
||||
mbedtls_ctr_drbg_context ctrDrgbContext; /**< @brief CTR DRBG context for random number generation. */
|
||||
} SSLContext_t;
|
||||
|
||||
/**
|
||||
* @brief Parameters for the network context of the transport interface
|
||||
* implementation that uses mbedTLS and FreeRTOS+TCP sockets.
|
||||
*/
|
||||
typedef struct TlsTransportParams
|
||||
{
|
||||
Socket_t tcpSocket;
|
||||
SSLContext_t sslContext;
|
||||
} TlsTransportParams_t;
|
||||
|
||||
/**
|
||||
* @brief Contains the credentials necessary for tls connection setup.
|
||||
*/
|
||||
typedef struct NetworkCredentials
|
||||
{
|
||||
/**
|
||||
* @brief To use ALPN, set this to a NULL-terminated list of supported
|
||||
* protocols in decreasing order of preference.
|
||||
*
|
||||
* See [this link]
|
||||
* (https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/)
|
||||
* for more information.
|
||||
*/
|
||||
const char ** pAlpnProtos;
|
||||
|
||||
/**
|
||||
* @brief Disable server name indication (SNI) for a TLS session.
|
||||
*/
|
||||
BaseType_t disableSni;
|
||||
|
||||
const uint8_t * pRootCa; /**< @brief String representing a trusted server root certificate. */
|
||||
size_t rootCaSize; /**< @brief Size associated with #NetworkCredentials.pRootCa. */
|
||||
const uint8_t * pClientCert; /**< @brief String representing the client certificate. */
|
||||
size_t clientCertSize; /**< @brief Size associated with #NetworkCredentials.pClientCert. */
|
||||
const uint8_t * pPrivateKey; /**< @brief String representing the client certificate's private key. */
|
||||
size_t privateKeySize; /**< @brief Size associated with #NetworkCredentials.pPrivateKey. */
|
||||
} NetworkCredentials_t;
|
||||
|
||||
/**
|
||||
* @brief TLS Connect / Disconnect return status.
|
||||
*/
|
||||
typedef enum TlsTransportStatus
|
||||
{
|
||||
TLS_TRANSPORT_SUCCESS = 0, /**< Function successfully completed. */
|
||||
TLS_TRANSPORT_INVALID_PARAMETER, /**< At least one parameter was invalid. */
|
||||
TLS_TRANSPORT_INSUFFICIENT_MEMORY, /**< Insufficient memory required to establish connection. */
|
||||
TLS_TRANSPORT_INVALID_CREDENTIALS, /**< Provided credentials were invalid. */
|
||||
TLS_TRANSPORT_HANDSHAKE_FAILED, /**< Performing TLS handshake with server failed. */
|
||||
TLS_TRANSPORT_INTERNAL_ERROR, /**< A call to a system API resulted in an internal error. */
|
||||
TLS_TRANSPORT_CONNECT_FAILURE /**< Initial connection to the server failed. */
|
||||
} TlsTransportStatus_t;
|
||||
|
||||
/**
|
||||
* @brief Create a TLS connection with FreeRTOS sockets.
|
||||
*
|
||||
* @param[out] pNetworkContext Pointer to a network context to contain the
|
||||
* initialized socket handle.
|
||||
* @param[in] pHostName The hostname of the remote endpoint.
|
||||
* @param[in] port The destination port.
|
||||
* @param[in] pNetworkCredentials Credentials for the TLS connection.
|
||||
* @param[in] receiveTimeoutMs Receive socket timeout.
|
||||
* @param[in] sendTimeoutMs Send socket timeout.
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS,
|
||||
* #TLS_TRANSPORT_HANDSHAKE_FAILED, #TLS_TRANSPORT_INTERNAL_ERROR, or #TLS_TRANSPORT_CONNECT_FAILURE.
|
||||
*/
|
||||
TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
const NetworkCredentials_t * pNetworkCredentials,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs );
|
||||
|
||||
/**
|
||||
* @brief Gracefully disconnect an established TLS connection.
|
||||
*
|
||||
* @param[in] pNetworkContext Network context.
|
||||
*/
|
||||
void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext );
|
||||
|
||||
/**
|
||||
* @brief Receives data from an established TLS connection.
|
||||
*
|
||||
* This is the TLS version of the transport interface's
|
||||
* #TransportRecv_t function.
|
||||
*
|
||||
* @param[in] pNetworkContext The Network context.
|
||||
* @param[out] pBuffer Buffer to receive bytes into.
|
||||
* @param[in] bytesToRecv Number of bytes to receive from the network.
|
||||
*
|
||||
* @return Number of bytes (> 0) received if successful;
|
||||
* 0 if the socket times out without reading any bytes;
|
||||
* negative value on error.
|
||||
*/
|
||||
int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
|
||||
void * pBuffer,
|
||||
size_t bytesToRecv );
|
||||
|
||||
/**
|
||||
* @brief Sends data over an established TLS connection.
|
||||
*
|
||||
* This is the TLS version of the transport interface's
|
||||
* #TransportSend_t function.
|
||||
*
|
||||
* @param[in] pNetworkContext The network context.
|
||||
* @param[in] pBuffer Buffer containing the bytes to send.
|
||||
* @param[in] bytesToSend Number of bytes to send from the buffer.
|
||||
*
|
||||
* @return Number of bytes (> 0) sent on success;
|
||||
* 0 if the socket times out without sending any bytes;
|
||||
* else a negative value to represent error.
|
||||
*/
|
||||
int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext,
|
||||
const void * pBuffer,
|
||||
size_t bytesToSend );
|
||||
|
||||
#endif /* ifndef USING_MBEDTLS */
|
||||
@ -0,0 +1,895 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file transport_mbedtls_pkcs11.c
|
||||
* @brief TLS transport interface implementations. This implementation uses
|
||||
* mbedTLS.
|
||||
*/
|
||||
|
||||
#include "logging_levels.h"
|
||||
|
||||
#define LIBRARY_LOG_NAME "PkcsTlsTransport"
|
||||
#define LIBRARY_LOG_LEVEL LOG_INFO
|
||||
|
||||
#include "logging_stack.h"
|
||||
|
||||
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
|
||||
|
||||
#include "mbedtls/private_access.h"
|
||||
|
||||
/* Standard includes. */
|
||||
#include <string.h>
|
||||
|
||||
/* FreeRTOS includes. */
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
/* MbedTLS Bio TCP sockets wrapper include. */
|
||||
#include "mbedtls_bio_tcp_sockets_wrapper.h"
|
||||
|
||||
/* TLS transport header. */
|
||||
#include "transport_mbedtls_pkcs11.h"
|
||||
#include "mbedtls_pkcs11.h"
|
||||
|
||||
/* PKCS #11 includes. */
|
||||
#include "core_pkcs11_config.h"
|
||||
#include "core_pkcs11.h"
|
||||
#include "pkcs11.h"
|
||||
#include "core_pki_utils.h"
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Each compilation unit that consumes the NetworkContext must define it.
|
||||
* It should contain a single pointer as seen below whenever the header file
|
||||
* of this transport implementation is included to your project.
|
||||
*
|
||||
* @note When using multiple transports in the same compilation unit,
|
||||
* define this pointer as void *.
|
||||
*/
|
||||
struct NetworkContext
|
||||
{
|
||||
TlsTransportParams_t * pParams;
|
||||
};
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Represents string to be logged when mbedTLS returned error
|
||||
* does not contain a high-level code.
|
||||
*/
|
||||
static const char * pNoHighLevelMbedTlsCodeStr = "<No-High-Level-Code>";
|
||||
|
||||
/**
|
||||
* @brief Represents string to be logged when mbedTLS returned error
|
||||
* does not contain a low-level code.
|
||||
*/
|
||||
static const char * pNoLowLevelMbedTlsCodeStr = "<No-Low-Level-Code>";
|
||||
|
||||
/**
|
||||
* @brief Utility for converting the high-level code in an mbedTLS error to string,
|
||||
* if the code-contains a high-level code; otherwise, using a default string.
|
||||
*/
|
||||
#define mbedtlsHighLevelCodeOrDefault( mbedTlsCode ) \
|
||||
( mbedtls_high_level_strerr( mbedTlsCode ) != NULL ) ? \
|
||||
mbedtls_high_level_strerr( mbedTlsCode ) : pNoHighLevelMbedTlsCodeStr
|
||||
|
||||
/**
|
||||
* @brief Utility for converting the level-level code in an mbedTLS error to string,
|
||||
* if the code-contains a level-level code; otherwise, using a default string.
|
||||
*/
|
||||
#define mbedtlsLowLevelCodeOrDefault( mbedTlsCode ) \
|
||||
( mbedtls_low_level_strerr( mbedTlsCode ) != NULL ) ? \
|
||||
mbedtls_low_level_strerr( mbedTlsCode ) : pNoLowLevelMbedTlsCodeStr
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Initialize the mbed TLS structures in a network connection.
|
||||
*
|
||||
* @param[in] pSslContext The SSL context to initialize.
|
||||
*/
|
||||
static void sslContextInit( SSLContext_t * pSslContext );
|
||||
|
||||
/**
|
||||
* @brief Free the mbed TLS structures in a network connection.
|
||||
*
|
||||
* @param[in] pSslContext The SSL context to free.
|
||||
*/
|
||||
static void sslContextFree( SSLContext_t * pSslContext );
|
||||
|
||||
/**
|
||||
* @brief Set up TLS on a TCP connection.
|
||||
*
|
||||
* @param[in] pNetworkContext Network context.
|
||||
* @param[in] pHostName Remote host name, used for server name indication.
|
||||
* @param[in] pNetworkCredentials TLS setup parameters.
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS,
|
||||
* #TLS_TRANSPORT_HANDSHAKE_FAILED, or #TLS_TRANSPORT_INTERNAL_ERROR.
|
||||
*/
|
||||
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
const NetworkCredentials_t * pNetworkCredentials );
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Callback that wraps PKCS#11 for pseudo-random number generation.
|
||||
*
|
||||
* @param[in] pvCtx Caller context.
|
||||
* @param[in] pucRandom Byte array to fill with random data.
|
||||
* @param[in] xRandomLength Length of byte array.
|
||||
*
|
||||
* @return Zero on success.
|
||||
*/
|
||||
static int32_t generateRandomBytes( void * pvCtx,
|
||||
unsigned char * pucRandom,
|
||||
size_t xRandomLength );
|
||||
|
||||
/**
|
||||
* @brief Helper for reading the specified certificate object, if present,
|
||||
* out of storage, into RAM, and then into an mbedTLS certificate context
|
||||
* object.
|
||||
*
|
||||
* @param[in] pSslContext Caller TLS context.
|
||||
* @param[in] pcLabelName PKCS #11 certificate object label.
|
||||
* @param[in] xClass PKCS #11 certificate object class.
|
||||
* @param[out] pxCertificateContext Certificate context.
|
||||
*
|
||||
* @return Zero on success.
|
||||
*/
|
||||
static CK_RV readCertificateIntoContext( SSLContext_t * pSslContext,
|
||||
const char * pcLabelName,
|
||||
CK_OBJECT_CLASS xClass,
|
||||
mbedtls_x509_crt * pxCertificateContext );
|
||||
|
||||
/**
|
||||
* @brief Helper for setting up potentially hardware-based cryptographic context
|
||||
* for the client TLS certificate and private key.
|
||||
*
|
||||
* @param[in] Caller context.
|
||||
* @param[in] PKCS11 label which contains the desired private key.
|
||||
*
|
||||
* @return Zero on success.
|
||||
*/
|
||||
static CK_RV initializeClientKeys( SSLContext_t * pxCtx,
|
||||
const char * pcLabelName );
|
||||
|
||||
/**
|
||||
* @brief Sign a cryptographic hash with the private key.
|
||||
*
|
||||
* @param[in] pvContext Crypto context.
|
||||
* @param[in] xMdAlg Unused.
|
||||
* @param[in] pucHash Length in bytes of hash to be signed.
|
||||
* @param[in] uiHashLen Byte array of hash to be signed.
|
||||
* @param[out] pucSig RSA signature bytes.
|
||||
* @param[in] pxSigLen Length in bytes of signature buffer.
|
||||
* @param[in] piRng Unused.
|
||||
* @param[in] pvRng Unused.
|
||||
*
|
||||
* @return Zero on success.
|
||||
*/
|
||||
static int32_t privateKeySigningCallback( void * pvContext,
|
||||
mbedtls_md_type_t xMdAlg,
|
||||
const unsigned char * pucHash,
|
||||
size_t xHashLen,
|
||||
unsigned char * pucSig,
|
||||
size_t * pxSigLen,
|
||||
int32_t ( * piRng )( void *,
|
||||
unsigned char *,
|
||||
size_t ),
|
||||
void * pvRng );
|
||||
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static void sslContextInit( SSLContext_t * pSslContext )
|
||||
{
|
||||
configASSERT( pSslContext != NULL );
|
||||
|
||||
mbedtls_ssl_config_init( &( pSslContext->config ) );
|
||||
mbedtls_x509_crt_init( &( pSslContext->rootCa ) );
|
||||
mbedtls_x509_crt_init( &( pSslContext->clientCert ) );
|
||||
mbedtls_ssl_init( &( pSslContext->context ) );
|
||||
|
||||
xInitializePkcs11Session( &( pSslContext->xP11Session ) );
|
||||
C_GetFunctionList( &( pSslContext->pxP11FunctionList ) );
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static void sslContextFree( SSLContext_t * pSslContext )
|
||||
{
|
||||
configASSERT( pSslContext != NULL );
|
||||
|
||||
mbedtls_ssl_free( &( pSslContext->context ) );
|
||||
mbedtls_x509_crt_free( &( pSslContext->rootCa ) );
|
||||
mbedtls_x509_crt_free( &( pSslContext->clientCert ) );
|
||||
mbedtls_ssl_config_free( &( pSslContext->config ) );
|
||||
|
||||
mbedtls_pk_free( &( pSslContext->privKey ) );
|
||||
|
||||
pSslContext->pxP11FunctionList->C_CloseSession( pSslContext->xP11Session );
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
const NetworkCredentials_t * pNetworkCredentials )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
int32_t mbedtlsError = 0;
|
||||
CK_RV xResult = CKR_OK;
|
||||
|
||||
configASSERT( pNetworkContext != NULL );
|
||||
configASSERT( pNetworkContext->pParams != NULL );
|
||||
configASSERT( pHostName != NULL );
|
||||
configASSERT( pNetworkCredentials != NULL );
|
||||
configASSERT( pNetworkCredentials->pRootCa != NULL );
|
||||
configASSERT( pNetworkCredentials->pClientCertLabel != NULL );
|
||||
configASSERT( pNetworkCredentials->pPrivateKeyLabel != NULL );
|
||||
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
|
||||
/* Initialize the mbed TLS context structures. */
|
||||
sslContextInit( &( pTlsTransportParams->sslContext ) );
|
||||
|
||||
mbedtlsError = mbedtls_ssl_config_defaults( &( pTlsTransportParams->sslContext.config ),
|
||||
MBEDTLS_SSL_IS_CLIENT,
|
||||
MBEDTLS_SSL_TRANSPORT_STREAM,
|
||||
MBEDTLS_SSL_PRESET_DEFAULT );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to set default SSL configuration: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
|
||||
/* Per mbed TLS docs, mbedtls_ssl_config_defaults only fails on memory allocation. */
|
||||
returnStatus = TLS_TRANSPORT_INSUFFICIENT_MEMORY;
|
||||
}
|
||||
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* Set up the certificate security profile, starting from the default value. */
|
||||
pTlsTransportParams->sslContext.certProfile = mbedtls_x509_crt_profile_default;
|
||||
|
||||
/* test.mosquitto.org only provides a 1024-bit RSA certificate, which is
|
||||
* not acceptable by the default mbed TLS certificate security profile.
|
||||
* For the purposes of this demo, allow the use of 1024-bit RSA certificates.
|
||||
* This block should be removed otherwise. */
|
||||
if( strncmp( pHostName, "test.mosquitto.org", strlen( pHostName ) ) == 0 )
|
||||
{
|
||||
pTlsTransportParams->sslContext.certProfile.rsa_min_bitlen = 1024;
|
||||
}
|
||||
|
||||
/* Set SSL authmode and the RNG context. */
|
||||
mbedtls_ssl_conf_authmode( &( pTlsTransportParams->sslContext.config ),
|
||||
MBEDTLS_SSL_VERIFY_REQUIRED );
|
||||
mbedtls_ssl_conf_rng( &( pTlsTransportParams->sslContext.config ),
|
||||
generateRandomBytes,
|
||||
&pTlsTransportParams->sslContext );
|
||||
mbedtls_ssl_conf_cert_profile( &( pTlsTransportParams->sslContext.config ),
|
||||
&( pTlsTransportParams->sslContext.certProfile ) );
|
||||
|
||||
/* Parse the server root CA certificate into the SSL context. */
|
||||
mbedtlsError = mbedtls_x509_crt_parse( &( pTlsTransportParams->sslContext.rootCa ),
|
||||
pNetworkCredentials->pRootCa,
|
||||
pNetworkCredentials->rootCaSize );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to parse server root CA certificate: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
else
|
||||
{
|
||||
mbedtls_ssl_conf_ca_chain( &( pTlsTransportParams->sslContext.config ),
|
||||
&( pTlsTransportParams->sslContext.rootCa ),
|
||||
NULL );
|
||||
}
|
||||
}
|
||||
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* Setup the client private key. */
|
||||
xResult = initializeClientKeys( &( pTlsTransportParams->sslContext ),
|
||||
pNetworkCredentials->pPrivateKeyLabel );
|
||||
|
||||
if( xResult != CKR_OK )
|
||||
{
|
||||
LogError( ( "Failed to setup key handling by PKCS #11." ) );
|
||||
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Setup the client certificate. */
|
||||
xResult = readCertificateIntoContext( &( pTlsTransportParams->sslContext ),
|
||||
pNetworkCredentials->pClientCertLabel,
|
||||
CKO_CERTIFICATE,
|
||||
&( pTlsTransportParams->sslContext.clientCert ) );
|
||||
|
||||
if( xResult != CKR_OK )
|
||||
{
|
||||
LogError( ( "Failed to get certificate from PKCS #11 module." ) );
|
||||
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
else
|
||||
{
|
||||
( void ) mbedtls_ssl_conf_own_cert( &( pTlsTransportParams->sslContext.config ),
|
||||
&( pTlsTransportParams->sslContext.clientCert ),
|
||||
&( pTlsTransportParams->sslContext.privKey ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if( ( returnStatus == TLS_TRANSPORT_SUCCESS ) && ( pNetworkCredentials->pAlpnProtos != NULL ) )
|
||||
{
|
||||
/* Include an application protocol list in the TLS ClientHello
|
||||
* message. */
|
||||
mbedtlsError = mbedtls_ssl_conf_alpn_protocols( &( pTlsTransportParams->sslContext.config ),
|
||||
pNetworkCredentials->pAlpnProtos );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to configure ALPN protocol in mbed TLS: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
|
||||
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* Initialize the mbed TLS secured connection context. */
|
||||
mbedtlsError = mbedtls_ssl_setup( &( pTlsTransportParams->sslContext.context ),
|
||||
&( pTlsTransportParams->sslContext.config ) );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to set up mbed TLS SSL context: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
|
||||
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Set the underlying IO for the TLS connection. */
|
||||
|
||||
/* MISRA Rule 11.2 flags the following line for casting the second
|
||||
* parameter to void *. This rule is suppressed because
|
||||
* #mbedtls_ssl_set_bio requires the second parameter as void *.
|
||||
*/
|
||||
/* coverity[misra_c_2012_rule_11_2_violation] */
|
||||
mbedtls_ssl_set_bio( &( pTlsTransportParams->sslContext.context ),
|
||||
( void * ) pTlsTransportParams->tcpSocket,
|
||||
xMbedTLSBioTCPSocketsWrapperSend,
|
||||
xMbedTLSBioTCPSocketsWrapperRecv,
|
||||
NULL );
|
||||
}
|
||||
}
|
||||
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* Enable SNI if requested. */
|
||||
if( pNetworkCredentials->disableSni == pdFALSE )
|
||||
{
|
||||
mbedtlsError = mbedtls_ssl_set_hostname( &( pTlsTransportParams->sslContext.context ),
|
||||
pHostName );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to set server name: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
|
||||
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Set Maximum Fragment Length if enabled. */
|
||||
#ifdef MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* Enable the max fragment extension. 4096 bytes is currently the largest fragment size permitted.
|
||||
* See RFC 8449 https://tools.ietf.org/html/rfc8449 for more information.
|
||||
*
|
||||
* Smaller values can be found in "mbedtls/include/ssl.h".
|
||||
*/
|
||||
mbedtlsError = mbedtls_ssl_conf_max_frag_len( &( pTlsTransportParams->sslContext.config ), MBEDTLS_SSL_MAX_FRAG_LEN_4096 );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to maximum fragment length extension: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
|
||||
}
|
||||
}
|
||||
#endif /* ifdef MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
|
||||
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* Perform the TLS handshake. */
|
||||
do
|
||||
{
|
||||
mbedtlsError = mbedtls_ssl_handshake( &( pTlsTransportParams->sslContext.context ) );
|
||||
} while( ( mbedtlsError == MBEDTLS_ERR_SSL_WANT_READ ) ||
|
||||
( mbedtlsError == MBEDTLS_ERR_SSL_WANT_WRITE ) );
|
||||
|
||||
if( mbedtlsError != 0 )
|
||||
{
|
||||
LogError( ( "Failed to perform TLS handshake: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
|
||||
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
|
||||
|
||||
returnStatus = TLS_TRANSPORT_HANDSHAKE_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
if( returnStatus != TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
sslContextFree( &( pTlsTransportParams->sslContext ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
LogInfo( ( "(Network connection %p) TLS handshake successful.",
|
||||
pNetworkContext ) );
|
||||
}
|
||||
|
||||
return returnStatus;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static int32_t generateRandomBytes( void * pvCtx,
|
||||
unsigned char * pucRandom,
|
||||
size_t xRandomLength )
|
||||
{
|
||||
/* Must cast from void pointer to conform to mbed TLS API. */
|
||||
SSLContext_t * pxCtx = ( SSLContext_t * ) pvCtx;
|
||||
CK_RV xResult;
|
||||
|
||||
xResult = pxCtx->pxP11FunctionList->C_GenerateRandom( pxCtx->xP11Session, pucRandom, xRandomLength );
|
||||
|
||||
if( xResult != CKR_OK )
|
||||
{
|
||||
LogError( ( "Failed to generate random bytes from the PKCS #11 module." ) );
|
||||
}
|
||||
|
||||
return xResult;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static CK_RV readCertificateIntoContext( SSLContext_t * pSslContext,
|
||||
const char * pcLabelName,
|
||||
CK_OBJECT_CLASS xClass,
|
||||
mbedtls_x509_crt * pxCertificateContext )
|
||||
{
|
||||
CK_RV xResult = CKR_OK;
|
||||
CK_ATTRIBUTE xTemplate = { 0 };
|
||||
CK_OBJECT_HANDLE xCertObj = 0;
|
||||
|
||||
/* Get the handle of the certificate. */
|
||||
xResult = xFindObjectWithLabelAndClass( pSslContext->xP11Session,
|
||||
pcLabelName,
|
||||
strnlen( pcLabelName,
|
||||
pkcs11configMAX_LABEL_LENGTH ),
|
||||
xClass,
|
||||
&xCertObj );
|
||||
|
||||
if( ( CKR_OK == xResult ) && ( xCertObj == CK_INVALID_HANDLE ) )
|
||||
{
|
||||
xResult = CKR_OBJECT_HANDLE_INVALID;
|
||||
}
|
||||
|
||||
/* Query the certificate size. */
|
||||
if( CKR_OK == xResult )
|
||||
{
|
||||
xTemplate.type = CKA_VALUE;
|
||||
xTemplate.ulValueLen = 0;
|
||||
xTemplate.pValue = NULL;
|
||||
xResult = pSslContext->pxP11FunctionList->C_GetAttributeValue( pSslContext->xP11Session,
|
||||
xCertObj,
|
||||
&xTemplate,
|
||||
1 );
|
||||
}
|
||||
|
||||
/* Create a buffer for the certificate. */
|
||||
if( CKR_OK == xResult )
|
||||
{
|
||||
xTemplate.pValue = pvPortMalloc( xTemplate.ulValueLen );
|
||||
|
||||
if( NULL == xTemplate.pValue )
|
||||
{
|
||||
xResult = CKR_HOST_MEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
/* Export the certificate. */
|
||||
if( CKR_OK == xResult )
|
||||
{
|
||||
xResult = pSslContext->pxP11FunctionList->C_GetAttributeValue( pSslContext->xP11Session,
|
||||
xCertObj,
|
||||
&xTemplate,
|
||||
1 );
|
||||
}
|
||||
|
||||
/* Decode the certificate. */
|
||||
if( CKR_OK == xResult )
|
||||
{
|
||||
xResult = mbedtls_x509_crt_parse( pxCertificateContext,
|
||||
( const unsigned char * ) xTemplate.pValue,
|
||||
xTemplate.ulValueLen );
|
||||
}
|
||||
|
||||
/* Free memory. */
|
||||
vPortFree( xTemplate.pValue );
|
||||
|
||||
return xResult;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Helper for setting up potentially hardware-based cryptographic context
|
||||
* for the client TLS certificate and private key.
|
||||
*
|
||||
* @param[in] Caller context.
|
||||
* @param[in] PKCS11 label which contains the desired private key.
|
||||
*
|
||||
* @return Zero on success.
|
||||
*/
|
||||
static CK_RV initializeClientKeys( SSLContext_t * pxCtx,
|
||||
const char * pcLabelName )
|
||||
{
|
||||
CK_RV xResult = CKR_OK;
|
||||
CK_SLOT_ID * pxSlotIds = NULL;
|
||||
CK_ULONG xCount = 0;
|
||||
CK_ATTRIBUTE xTemplate[ 2 ];
|
||||
mbedtls_pk_type_t xKeyAlgo = ( mbedtls_pk_type_t ) ~0;
|
||||
|
||||
/* Get the PKCS #11 module/token slot count. */
|
||||
if( CKR_OK == xResult )
|
||||
{
|
||||
xResult = ( BaseType_t ) pxCtx->pxP11FunctionList->C_GetSlotList( CK_TRUE,
|
||||
NULL,
|
||||
&xCount );
|
||||
}
|
||||
|
||||
/* Allocate memory to store the token slots. */
|
||||
if( CKR_OK == xResult )
|
||||
{
|
||||
pxSlotIds = ( CK_SLOT_ID * ) pvPortMalloc( sizeof( CK_SLOT_ID ) * xCount );
|
||||
|
||||
if( NULL == pxSlotIds )
|
||||
{
|
||||
xResult = CKR_HOST_MEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
/* Get all of the available private key slot identities. */
|
||||
if( CKR_OK == xResult )
|
||||
{
|
||||
xResult = ( BaseType_t ) pxCtx->pxP11FunctionList->C_GetSlotList( CK_TRUE,
|
||||
pxSlotIds,
|
||||
&xCount );
|
||||
}
|
||||
|
||||
/* Put the module in authenticated mode. */
|
||||
if( CKR_OK == xResult )
|
||||
{
|
||||
xResult = ( BaseType_t ) pxCtx->pxP11FunctionList->C_Login( pxCtx->xP11Session,
|
||||
CKU_USER,
|
||||
( CK_UTF8CHAR_PTR ) configPKCS11_DEFAULT_USER_PIN,
|
||||
sizeof( configPKCS11_DEFAULT_USER_PIN ) - 1 );
|
||||
}
|
||||
|
||||
if( CKR_OK == xResult )
|
||||
{
|
||||
/* Get the handle of the device private key. */
|
||||
xResult = xFindObjectWithLabelAndClass( pxCtx->xP11Session,
|
||||
pcLabelName,
|
||||
strnlen( pcLabelName,
|
||||
pkcs11configMAX_LABEL_LENGTH ),
|
||||
CKO_PRIVATE_KEY,
|
||||
&pxCtx->xP11PrivateKey );
|
||||
}
|
||||
|
||||
if( ( CKR_OK == xResult ) && ( pxCtx->xP11PrivateKey == CK_INVALID_HANDLE ) )
|
||||
{
|
||||
xResult = CK_INVALID_HANDLE;
|
||||
LogError( ( "Could not find private key." ) );
|
||||
}
|
||||
|
||||
if( xResult == CKR_OK )
|
||||
{
|
||||
xResult = xPKCS11_initMbedtlsPkContext( &( pxCtx->privKey ),
|
||||
pxCtx->xP11Session,
|
||||
pxCtx->xP11PrivateKey );
|
||||
}
|
||||
|
||||
/* Free memory. */
|
||||
vPortFree( pxSlotIds );
|
||||
|
||||
return xResult;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
const NetworkCredentials_t * pNetworkCredentials,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
BaseType_t socketStatus = 0;
|
||||
BaseType_t isSocketConnected = pdFALSE;
|
||||
|
||||
if( ( pNetworkContext == NULL ) ||
|
||||
( pNetworkContext->pParams == NULL ) ||
|
||||
( pHostName == NULL ) ||
|
||||
( pNetworkCredentials == NULL ) )
|
||||
{
|
||||
LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, "
|
||||
"pHostName=%p, pNetworkCredentials=%p.",
|
||||
pNetworkContext,
|
||||
pHostName,
|
||||
pNetworkCredentials ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_PARAMETER;
|
||||
}
|
||||
else if( ( pNetworkCredentials->pRootCa == NULL ) )
|
||||
{
|
||||
LogError( ( "pRootCa cannot be NULL." ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_PARAMETER;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Empty else for MISRA 15.7 compliance. */
|
||||
}
|
||||
|
||||
/* Establish a TCP connection with the server. */
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
|
||||
/* Initialize tcpSocket. */
|
||||
pTlsTransportParams->tcpSocket = NULL;
|
||||
|
||||
socketStatus = TCP_Sockets_Connect( &( pTlsTransportParams->tcpSocket ),
|
||||
pHostName,
|
||||
port,
|
||||
receiveTimeoutMs,
|
||||
sendTimeoutMs );
|
||||
|
||||
if( socketStatus != 0 )
|
||||
{
|
||||
LogError( ( "Failed to connect to %s with error %d.",
|
||||
pHostName,
|
||||
socketStatus ) );
|
||||
returnStatus = TLS_TRANSPORT_CONNECT_FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/* Perform TLS handshake. */
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
isSocketConnected = pdTRUE;
|
||||
|
||||
returnStatus = tlsSetup( pNetworkContext, pHostName, pNetworkCredentials );
|
||||
}
|
||||
|
||||
/* Clean up on failure. */
|
||||
if( returnStatus != TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
if( isSocketConnected == pdTRUE )
|
||||
{
|
||||
TCP_Sockets_Disconnect( pTlsTransportParams->tcpSocket );
|
||||
pTlsTransportParams->tcpSocket = NULL;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogInfo( ( "(Network connection %p) Connection to %s established.",
|
||||
pNetworkContext,
|
||||
pHostName ) );
|
||||
}
|
||||
|
||||
return returnStatus;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
BaseType_t tlsStatus = 0;
|
||||
|
||||
if( ( pNetworkContext != NULL ) && ( pNetworkContext->pParams != NULL ) )
|
||||
{
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
/* Attempting to terminate TLS connection. */
|
||||
tlsStatus = ( BaseType_t ) mbedtls_ssl_close_notify( &( pTlsTransportParams->sslContext.context ) );
|
||||
|
||||
/* Ignore the WANT_READ and WANT_WRITE return values. */
|
||||
if( ( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_READ ) &&
|
||||
( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_WRITE ) )
|
||||
{
|
||||
if( tlsStatus == 0 )
|
||||
{
|
||||
LogInfo( ( "(Network connection %p) TLS close-notify sent.",
|
||||
pNetworkContext ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "(Network connection %p) Failed to send TLS close-notify: mbedTLSError= %s : %s.",
|
||||
pNetworkContext,
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
/* Call socket shutdown function to close connection. */
|
||||
TCP_Sockets_Disconnect( pTlsTransportParams->tcpSocket );
|
||||
|
||||
/* Free mbed TLS contexts. */
|
||||
sslContextFree( &( pTlsTransportParams->sslContext ) );
|
||||
}
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
|
||||
void * pBuffer,
|
||||
size_t bytesToRecv )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
int32_t tlsStatus = 0;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) )
|
||||
{
|
||||
LogError( ( "invalid input, pNetworkContext=%p", pNetworkContext ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( pBuffer == NULL )
|
||||
{
|
||||
LogError( ( "invalid input, pBuffer == NULL" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( bytesToRecv == 0 )
|
||||
{
|
||||
LogError( ( "invalid input, bytesToRecv == 0" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
|
||||
tlsStatus = ( int32_t ) mbedtls_ssl_read( &( pTlsTransportParams->sslContext.context ),
|
||||
pBuffer,
|
||||
bytesToRecv );
|
||||
|
||||
if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) ||
|
||||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ||
|
||||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) )
|
||||
{
|
||||
LogDebug( ( "Failed to read data. However, a read can be retried on this error. "
|
||||
"mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
|
||||
/* Mark these set of errors as a timeout. The libraries may retry read
|
||||
* on these errors. */
|
||||
tlsStatus = 0;
|
||||
}
|
||||
else if( tlsStatus < 0 )
|
||||
{
|
||||
LogError( ( "Failed to read data: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Empty else marker. */
|
||||
}
|
||||
}
|
||||
|
||||
return tlsStatus;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext,
|
||||
const void * pBuffer,
|
||||
size_t bytesToSend )
|
||||
{
|
||||
TlsTransportParams_t * pTlsTransportParams = NULL;
|
||||
int32_t tlsStatus = 0;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) )
|
||||
{
|
||||
LogError( ( "invalid input, pNetworkContext=%p", pNetworkContext ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( pBuffer == NULL )
|
||||
{
|
||||
LogError( ( "invalid input, pBuffer == NULL" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( bytesToSend == 0 )
|
||||
{
|
||||
LogError( ( "invalid input, bytesToSend == 0" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
pTlsTransportParams = pNetworkContext->pParams;
|
||||
tlsStatus = ( int32_t ) mbedtls_ssl_write( &( pTlsTransportParams->sslContext.context ),
|
||||
pBuffer,
|
||||
bytesToSend );
|
||||
|
||||
if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) ||
|
||||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ||
|
||||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) )
|
||||
{
|
||||
LogDebug( ( "Failed to send data. However, send can be retried on this error. "
|
||||
"mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
|
||||
/* Mark these set of errors as a timeout. The libraries may retry send
|
||||
* on these errors. */
|
||||
tlsStatus = 0;
|
||||
}
|
||||
else if( tlsStatus < 0 )
|
||||
{
|
||||
LogError( ( "Failed to send data: mbedTLSError= %s : %s.",
|
||||
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
|
||||
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Empty else marker. */
|
||||
}
|
||||
}
|
||||
|
||||
return tlsStatus;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
@ -0,0 +1,199 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file transport_mbedtls_pkcs11.h
|
||||
* @brief TLS transport interface header.
|
||||
* @note This file is derived from the tls_freertos.h header file found in the mqtt
|
||||
* section of IoT Libraries source code. The file has been modified to support using
|
||||
* PKCS #11 when using TLS.
|
||||
*/
|
||||
|
||||
#ifndef TRANSPORT_MBEDTLS_PKCS11
|
||||
#define TRANSPORT_MBEDTLS_PKCS11
|
||||
|
||||
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
|
||||
|
||||
#include "mbedtls/private_access.h"
|
||||
|
||||
/* TCP Sockets Wrapper include.*/
|
||||
#include "tcp_sockets_wrapper.h"
|
||||
|
||||
/* Transport interface include. */
|
||||
#include "transport_interface.h"
|
||||
|
||||
/* mbed TLS includes. */
|
||||
#include "mbedtls/ctr_drbg.h"
|
||||
#include "mbedtls/entropy.h"
|
||||
#include "mbedtls/ssl.h"
|
||||
#include "mbedtls/threading.h"
|
||||
#include "mbedtls/x509.h"
|
||||
#include "mbedtls/pk.h"
|
||||
#include "mbedtls/error.h"
|
||||
|
||||
#include "pk_wrap.h"
|
||||
|
||||
/* PKCS #11 includes. */
|
||||
#include "core_pkcs11.h"
|
||||
|
||||
/**
|
||||
* @brief Secured connection context.
|
||||
*/
|
||||
typedef struct SSLContext
|
||||
{
|
||||
mbedtls_ssl_config config; /**< @brief SSL connection configuration. */
|
||||
mbedtls_ssl_context context; /**< @brief SSL connection context */
|
||||
mbedtls_x509_crt_profile certProfile; /**< @brief Certificate security profile for this connection. */
|
||||
mbedtls_x509_crt rootCa; /**< @brief Root CA certificate context. */
|
||||
mbedtls_x509_crt clientCert; /**< @brief Client certificate context. */
|
||||
mbedtls_pk_context privKey; /**< @brief Client private key context. */
|
||||
mbedtls_pk_info_t privKeyInfo; /**< @brief Client private key info. */
|
||||
|
||||
/* PKCS#11. */
|
||||
CK_FUNCTION_LIST_PTR pxP11FunctionList;
|
||||
CK_SESSION_HANDLE xP11Session;
|
||||
CK_OBJECT_HANDLE xP11PrivateKey;
|
||||
} SSLContext_t;
|
||||
|
||||
/**
|
||||
* @brief Definition of the network context for the transport interface
|
||||
* implementation that uses mbedTLS and FreeRTOS+TLS sockets.
|
||||
*/
|
||||
typedef struct TlsTransportParams
|
||||
{
|
||||
Socket_t tcpSocket;
|
||||
SSLContext_t sslContext;
|
||||
} TlsTransportParams_t;
|
||||
|
||||
/**
|
||||
* @brief Contains the credentials necessary for tls connection setup.
|
||||
*/
|
||||
typedef struct NetworkCredentials
|
||||
{
|
||||
/**
|
||||
* @brief To use ALPN, set this to a NULL-terminated list of supported
|
||||
* protocols in decreasing order of preference.
|
||||
*
|
||||
* See [this link]
|
||||
* (https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/)
|
||||
* for more information.
|
||||
*/
|
||||
const char ** pAlpnProtos;
|
||||
|
||||
/**
|
||||
* @brief Disable server name indication (SNI) for a TLS session.
|
||||
*/
|
||||
BaseType_t disableSni;
|
||||
|
||||
const unsigned char * pRootCa; /**< @brief String representing a trusted server root certificate. */
|
||||
size_t rootCaSize; /**< @brief Size associated with #NetworkCredentials.pRootCa. */
|
||||
const unsigned char * pUserName; /**< @brief username for MQTT. */
|
||||
size_t userNameSize; /**< @brief Size associated with #NetworkCredentials.pUserName. */
|
||||
const unsigned char * pPassword; /**< @brief String representing the password for MQTT. */
|
||||
size_t passwordSize; /**< @brief Size associated with #NetworkCredentials.pPassword. */
|
||||
const char * pClientCertLabel; /**< @brief PKCS #11 label string of the client certificate. */
|
||||
const char * pPrivateKeyLabel; /**< @brief PKCS #11 label for the private key. */
|
||||
} NetworkCredentials_t;
|
||||
|
||||
/**
|
||||
* @brief TLS Connect / Disconnect return status.
|
||||
*/
|
||||
typedef enum TlsTransportStatus
|
||||
{
|
||||
TLS_TRANSPORT_SUCCESS = 0, /**< Function successfully completed. */
|
||||
TLS_TRANSPORT_INVALID_PARAMETER, /**< At least one parameter was invalid. */
|
||||
TLS_TRANSPORT_INSUFFICIENT_MEMORY, /**< Insufficient memory required to establish connection. */
|
||||
TLS_TRANSPORT_INVALID_CREDENTIALS, /**< Provided credentials were invalid. */
|
||||
TLS_TRANSPORT_HANDSHAKE_FAILED, /**< Performing TLS handshake with server failed. */
|
||||
TLS_TRANSPORT_INTERNAL_ERROR, /**< A call to a system API resulted in an internal error. */
|
||||
TLS_TRANSPORT_CONNECT_FAILURE /**< Initial connection to the server failed. */
|
||||
} TlsTransportStatus_t;
|
||||
|
||||
/**
|
||||
* @brief Create a TLS connection with FreeRTOS sockets.
|
||||
*
|
||||
* @param[out] pNetworkContext Pointer to a network context to contain the
|
||||
* initialized socket handle.
|
||||
* @param[in] pHostName The hostname of the remote endpoint.
|
||||
* @param[in] port The destination port.
|
||||
* @param[in] pNetworkCredentials Credentials for the TLS connection.
|
||||
* @param[in] receiveTimeoutMs Receive socket timeout.
|
||||
* @param[in] sendTimeoutMs Send socket timeout.
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS,
|
||||
* #TLS_TRANSPORT_HANDSHAKE_FAILED, #TLS_TRANSPORT_INTERNAL_ERROR, or #TLS_TRANSPORT_CONNECT_FAILURE.
|
||||
*/
|
||||
TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
const NetworkCredentials_t * pNetworkCredentials,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs );
|
||||
|
||||
/**
|
||||
* @brief Gracefully disconnect an established TLS connection.
|
||||
*
|
||||
* @param[in] pNetworkContext Network context.
|
||||
*/
|
||||
void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext );
|
||||
|
||||
/**
|
||||
* @brief Receives data from an established TLS connection.
|
||||
*
|
||||
* This is the TLS version of the transport interface's
|
||||
* #TransportRecv_t function.
|
||||
*
|
||||
* @param[in] pNetworkContext The Network context.
|
||||
* @param[out] pBuffer Buffer to receive bytes into.
|
||||
* @param[in] bytesToRecv Number of bytes to receive from the network.
|
||||
*
|
||||
* @return Number of bytes (> 0) received if successful;
|
||||
* 0 if the socket times out without reading any bytes;
|
||||
* negative value on error.
|
||||
*/
|
||||
int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
|
||||
void * pBuffer,
|
||||
size_t bytesToRecv );
|
||||
|
||||
/**
|
||||
* @brief Sends data over an established TLS connection.
|
||||
*
|
||||
* This is the TLS version of the transport interface's
|
||||
* #TransportSend_t function.
|
||||
*
|
||||
* @param[in] pNetworkContext The network context.
|
||||
* @param[in] pBuffer Buffer containing the bytes to send.
|
||||
* @param[in] bytesToSend Number of bytes to send from the buffer.
|
||||
*
|
||||
* @return Number of bytes (> 0) sent on success;
|
||||
* 0 if the socket times out without sending any bytes;
|
||||
* else a negative value to represent error.
|
||||
*/
|
||||
int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext,
|
||||
const void * pBuffer,
|
||||
size_t bytesToSend );
|
||||
|
||||
#endif /* ifndef TRANSPORT_MBEDTLS_PKCS11 */
|
||||
@ -0,0 +1,183 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/* Standard includes. */
|
||||
#include <string.h>
|
||||
|
||||
/* FreeRTOS includes. */
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
/* Transport interface include. */
|
||||
#include "transport_plaintext.h"
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @brief Each compilation unit that consumes the NetworkContext must define it.
|
||||
* It should contain a single pointer as seen below whenever the header file
|
||||
* of this transport implementation is included to your project.
|
||||
*
|
||||
* @note When using multiple transports in the same compilation unit,
|
||||
* define this pointer as void *.
|
||||
*/
|
||||
struct NetworkContext
|
||||
{
|
||||
PlaintextTransportParams_t * pParams;
|
||||
};
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
PlaintextTransportStatus_t Plaintext_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs )
|
||||
{
|
||||
PlaintextTransportParams_t * pPlaintextTransportParams = NULL;
|
||||
PlaintextTransportStatus_t plaintextStatus = PLAINTEXT_TRANSPORT_SUCCESS;
|
||||
BaseType_t socketStatus = 0;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) || ( pHostName == NULL ) )
|
||||
{
|
||||
LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, "
|
||||
"pHostName=%p.",
|
||||
pNetworkContext,
|
||||
pHostName ) );
|
||||
plaintextStatus = PLAINTEXT_TRANSPORT_INVALID_PARAMETER;
|
||||
}
|
||||
else
|
||||
{
|
||||
pPlaintextTransportParams = pNetworkContext->pParams;
|
||||
|
||||
/* Initialize tcpSocket. */
|
||||
pPlaintextTransportParams->tcpSocket = NULL;
|
||||
|
||||
/* Establish a TCP connection with the server. */
|
||||
socketStatus = TCP_Sockets_Connect( &( pPlaintextTransportParams->tcpSocket ),
|
||||
pHostName,
|
||||
port,
|
||||
receiveTimeoutMs,
|
||||
sendTimeoutMs );
|
||||
|
||||
/* A non zero status is an error. */
|
||||
if( socketStatus != 0 )
|
||||
{
|
||||
LogError( ( "Failed to connect to %s with error %d.",
|
||||
pHostName,
|
||||
socketStatus ) );
|
||||
plaintextStatus = PLAINTEXT_TRANSPORT_CONNECT_FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
return plaintextStatus;
|
||||
}
|
||||
|
||||
PlaintextTransportStatus_t Plaintext_FreeRTOS_Disconnect( const NetworkContext_t * pNetworkContext )
|
||||
{
|
||||
PlaintextTransportParams_t * pPlaintextTransportParams = NULL;
|
||||
PlaintextTransportStatus_t plaintextStatus = PLAINTEXT_TRANSPORT_SUCCESS;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) )
|
||||
{
|
||||
LogError( ( "pNetworkContext cannot be NULL." ) );
|
||||
plaintextStatus = PLAINTEXT_TRANSPORT_INVALID_PARAMETER;
|
||||
}
|
||||
else
|
||||
{
|
||||
pPlaintextTransportParams = pNetworkContext->pParams;
|
||||
/* Call socket disconnect function to close connection. */
|
||||
TCP_Sockets_Disconnect( pPlaintextTransportParams->tcpSocket );
|
||||
}
|
||||
|
||||
return plaintextStatus;
|
||||
}
|
||||
|
||||
int32_t Plaintext_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
|
||||
void * pBuffer,
|
||||
size_t bytesToRecv )
|
||||
{
|
||||
PlaintextTransportParams_t * pPlaintextTransportParams = NULL;
|
||||
int32_t socketStatus = 1;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) )
|
||||
{
|
||||
LogError( ( "invalid input, pNetworkContext=%p", pNetworkContext ) );
|
||||
socketStatus = -1;
|
||||
}
|
||||
else if( pBuffer == NULL )
|
||||
{
|
||||
LogError( ( "invalid input, pBuffer == NULL" ) );
|
||||
socketStatus = -1;
|
||||
}
|
||||
else if( bytesToRecv == 0 )
|
||||
{
|
||||
LogError( ( "invalid input, bytesToRecv == 0" ) );
|
||||
socketStatus = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
pPlaintextTransportParams = pNetworkContext->pParams;
|
||||
|
||||
socketStatus = TCP_Sockets_Recv( pPlaintextTransportParams->tcpSocket,
|
||||
pBuffer,
|
||||
bytesToRecv );
|
||||
}
|
||||
|
||||
return socketStatus;
|
||||
}
|
||||
|
||||
int32_t Plaintext_FreeRTOS_send( NetworkContext_t * pNetworkContext,
|
||||
const void * pBuffer,
|
||||
size_t bytesToSend )
|
||||
{
|
||||
PlaintextTransportParams_t * pPlaintextTransportParams = NULL;
|
||||
int32_t socketStatus = 0;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) )
|
||||
{
|
||||
LogError( ( "invalid input, pNetworkContext=%p", pNetworkContext ) );
|
||||
socketStatus = -1;
|
||||
}
|
||||
else if( pBuffer == NULL )
|
||||
{
|
||||
LogError( ( "invalid input, pBuffer == NULL" ) );
|
||||
socketStatus = -1;
|
||||
}
|
||||
else if( bytesToSend == 0 )
|
||||
{
|
||||
LogError( ( "invalid input, bytesToSend == 0" ) );
|
||||
socketStatus = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
pPlaintextTransportParams = pNetworkContext->pParams;
|
||||
socketStatus = TCP_Sockets_Send( pPlaintextTransportParams->tcpSocket,
|
||||
pBuffer,
|
||||
bytesToSend );
|
||||
}
|
||||
|
||||
return socketStatus;
|
||||
}
|
||||
@ -0,0 +1,152 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef USING_PLAINTEXT_H
|
||||
#define USING_PLAINTEXT_H
|
||||
|
||||
/**************************************************/
|
||||
/******* DO NOT CHANGE the following order ********/
|
||||
/**************************************************/
|
||||
|
||||
/* Logging related header files are required to be included in the following order:
|
||||
* 1. Include the header file "logging_levels.h".
|
||||
* 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL.
|
||||
* 3. Include the header file "logging_stack.h".
|
||||
*/
|
||||
|
||||
/* Include header that defines log levels. */
|
||||
#include "logging_levels.h"
|
||||
|
||||
/* Logging configuration for the Sockets. */
|
||||
#ifndef LIBRARY_LOG_NAME
|
||||
#define LIBRARY_LOG_NAME "PlaintextTransport"
|
||||
#endif
|
||||
#ifndef LIBRARY_LOG_LEVEL
|
||||
#define LIBRARY_LOG_LEVEL LOG_ERROR
|
||||
#endif
|
||||
|
||||
/* Prototype for the function used to print to console on Windows simulator
|
||||
* of FreeRTOS.
|
||||
* The function prints to the console before the network is connected;
|
||||
* then a UDP port after the network has connected. */
|
||||
extern void vLoggingPrintf( const char * pcFormatString,
|
||||
... );
|
||||
|
||||
/* Map the SdkLog macro to the logging function to enable logging
|
||||
* on Windows simulator. */
|
||||
#ifndef SdkLog
|
||||
#define SdkLog( message ) vLoggingPrintf message
|
||||
#endif
|
||||
|
||||
#include "logging_stack.h"
|
||||
|
||||
/************ End of logging configuration ****************/
|
||||
|
||||
/* TCP Sockets Wrapper include.*/
|
||||
#include "tcp_sockets_wrapper.h"
|
||||
|
||||
/* Transport interface include. */
|
||||
#include "transport_interface.h"
|
||||
|
||||
/**
|
||||
* @brief Parameters for the network context that uses FreeRTOS+TCP sockets.
|
||||
*/
|
||||
typedef struct PlaintextTransportParams
|
||||
{
|
||||
Socket_t tcpSocket;
|
||||
} PlaintextTransportParams_t;
|
||||
|
||||
/**
|
||||
* @brief Plain text transport Connect / Disconnect return status.
|
||||
*/
|
||||
typedef enum PlaintextTransportStatus
|
||||
{
|
||||
PLAINTEXT_TRANSPORT_SUCCESS = 1, /**< Function successfully completed. */
|
||||
PLAINTEXT_TRANSPORT_INVALID_PARAMETER = 2, /**< At least one parameter was invalid. */
|
||||
PLAINTEXT_TRANSPORT_CONNECT_FAILURE = 3 /**< Initial connection to the server failed. */
|
||||
} PlaintextTransportStatus_t;
|
||||
|
||||
/**
|
||||
* @brief Create a TCP connection with FreeRTOS sockets.
|
||||
*
|
||||
* @param[out] pNetworkContext Pointer to a network context to contain the
|
||||
* initialized socket handle.
|
||||
* @param[in] pHostName The hostname of the remote endpoint.
|
||||
* @param[in] port The destination port.
|
||||
* @param[in] receiveTimeoutMs Receive socket timeout.
|
||||
*
|
||||
* @return #PLAINTEXT_TRANSPORT_SUCCESS, #PLAINTEXT_TRANSPORT_INVALID_PARAMETER,
|
||||
* or #PLAINTEXT_TRANSPORT_CONNECT_FAILURE.
|
||||
*/
|
||||
PlaintextTransportStatus_t Plaintext_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs );
|
||||
|
||||
/**
|
||||
* @brief Gracefully disconnect an established TCP connection.
|
||||
*
|
||||
* @param[in] pNetworkContext Network context containing the TCP socket handle.
|
||||
*
|
||||
* @return #PLAINTEXT_TRANSPORT_SUCCESS, or #PLAINTEXT_TRANSPORT_INVALID_PARAMETER.
|
||||
*/
|
||||
PlaintextTransportStatus_t Plaintext_FreeRTOS_Disconnect( const NetworkContext_t * pNetworkContext );
|
||||
|
||||
/**
|
||||
* @brief Receives data from an established TCP connection.
|
||||
*
|
||||
* @note When the number of bytes requested is 1, the TCP socket's Rx stream
|
||||
* is checked for available bytes to read. If there are none, this function
|
||||
* immediately returns 0 without blocking.
|
||||
*
|
||||
* @param[in] pNetworkContext The network context containing the TCP socket
|
||||
* handle.
|
||||
* @param[out] pBuffer Buffer to receive bytes into.
|
||||
* @param[in] bytesToRecv Number of bytes to receive from the network.
|
||||
*
|
||||
* @return Number of bytes received if successful; 0 if the socket times out;
|
||||
* Negative value on error.
|
||||
*/
|
||||
int32_t Plaintext_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
|
||||
void * pBuffer,
|
||||
size_t bytesToRecv );
|
||||
|
||||
/**
|
||||
* @brief Sends data over an established TCP connection.
|
||||
*
|
||||
* @param[in] pNetworkContext The network context containing the TCP socket
|
||||
* handle.
|
||||
* @param[in] pBuffer Buffer containing the bytes to send.
|
||||
* @param[in] bytesToSend Number of bytes to send from the buffer.
|
||||
*
|
||||
* @return Number of bytes sent on success; else a negative value.
|
||||
*/
|
||||
int32_t Plaintext_FreeRTOS_send( NetworkContext_t * pNetworkContext,
|
||||
const void * pBuffer,
|
||||
size_t bytesToSend );
|
||||
|
||||
#endif /* ifndef USING_PLAINTEXT_H */
|
||||
@ -0,0 +1,580 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file using_wolfSSL.c
|
||||
* @brief TLS transport interface implementations. This implementation uses
|
||||
* wolfSSL.
|
||||
*/
|
||||
|
||||
/* Standard includes. */
|
||||
#include <string.h>
|
||||
|
||||
/* FreeRTOS includes. */
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
/* FreeRTOS+TCP includes. */
|
||||
#include "FreeRTOS_IP.h"
|
||||
#include "FreeRTOS_Sockets.h"
|
||||
|
||||
/* TLS transport header. */
|
||||
#include "transport_wolfSSL.h"
|
||||
|
||||
/* FreeRTOS Socket wrapper include. */
|
||||
#include "tcp_sockets_wrapper.h"
|
||||
|
||||
/* wolfSSL user settings header */
|
||||
#include "user_settings.h"
|
||||
|
||||
/* Demo Specific configs. */
|
||||
#include "demo_config.h"
|
||||
|
||||
/**
|
||||
* @brief Initialize the TLS structures in a network connection.
|
||||
*
|
||||
* @param[in] pSslContext The SSL context to initialize.
|
||||
*/
|
||||
static void sslContextInit( SSLContext_t * pSslContext );
|
||||
|
||||
/**
|
||||
* @brief Free the TLS structures in a network connection.
|
||||
*
|
||||
* @param[in] pSslContext The SSL context to free.
|
||||
*/
|
||||
static void sslContextFree( SSLContext_t * pSslContext );
|
||||
|
||||
/**
|
||||
* @brief Set up TLS on a TCP connection.
|
||||
*
|
||||
* @param[in] pNetworkContext Network context.
|
||||
* @param[in] pHostName Remote host name, used for server name indication.
|
||||
* @param[in] pNetworkCredentials TLS setup parameters.
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS,
|
||||
* #TLS_TRANSPORT_HANDSHAKE_FAILED, or #TLS_TRANSPORT_INTERNAL_ERROR.
|
||||
*/
|
||||
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
const NetworkCredentials_t * pNetworkCredentials );
|
||||
|
||||
/**
|
||||
* @brief Initialize TLS component.
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, or #TLS_TRANSPORT_INTERNAL_ERROR.
|
||||
*/
|
||||
static TlsTransportStatus_t initTLS( void );
|
||||
|
||||
/*
|
||||
* @brief Receive date from the socket passed as the context
|
||||
*
|
||||
* @param[in] ssl WOLFSSL object.
|
||||
* @param[in] buf Buffer for received data
|
||||
* @param[in] sz Size to receive
|
||||
* @param[in] context Socket to be received from
|
||||
*
|
||||
* @return received size( > 0 ), #WOLFSSL_CBIO_ERR_CONN_CLOSE, #WOLFSSL_CBIO_ERR_WANT_READ.
|
||||
*/
|
||||
static int wolfSSL_IORecvGlue( WOLFSSL * ssl,
|
||||
char * buf,
|
||||
int sz,
|
||||
void * context );
|
||||
|
||||
/*
|
||||
* @brief Send date to the socket passed as the context
|
||||
*
|
||||
* @param[in] ssl WOLFSSL object.
|
||||
* @param[in] buf Buffer for data to be sent
|
||||
* @param[in] sz Size to send
|
||||
* @param[in] context Socket to be sent to
|
||||
*
|
||||
* @return received size( > 0 ), #WOLFSSL_CBIO_ERR_CONN_CLOSE, #WOLFSSL_CBIO_ERR_WANT_WRITE.
|
||||
*/
|
||||
static int wolfSSL_IOSendGlue( WOLFSSL * ssl,
|
||||
char * buf,
|
||||
int sz,
|
||||
void * context );
|
||||
|
||||
/*
|
||||
* @brief Load credentials from file/buffer
|
||||
*
|
||||
* @param[in] pNetCtx NetworkContext_t
|
||||
* @param[in] pNetCred NetworkCredentials_t
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INVALID_CREDENTIALS.
|
||||
*/
|
||||
static TlsTransportStatus_t loadCredentials( NetworkContext_t * pNetCtx,
|
||||
const NetworkCredentials_t * pNetCred );
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
static int wolfSSL_IORecvGlue( WOLFSSL * ssl,
|
||||
char * buf,
|
||||
int sz,
|
||||
void * context )
|
||||
{
|
||||
( void ) ssl; /* to prevent unused warning*/
|
||||
BaseType_t read = 0;
|
||||
|
||||
Socket_t xSocket = ( Socket_t ) context;
|
||||
|
||||
|
||||
read = TCP_Sockets_Recv( xSocket, ( void * ) buf, ( size_t ) sz );
|
||||
|
||||
if( ( read == 0 ) ||
|
||||
( read == -TCP_SOCKETS_ERRNO_EWOULDBLOCK ) )
|
||||
{
|
||||
read = WOLFSSL_CBIO_ERR_WANT_READ;
|
||||
}
|
||||
else if( read == -TCP_SOCKETS_ERRNO_ENOTCONN )
|
||||
{
|
||||
read = WOLFSSL_CBIO_ERR_CONN_CLOSE;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* do nothing */
|
||||
}
|
||||
|
||||
return ( int ) read;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static int wolfSSL_IOSendGlue( WOLFSSL * ssl,
|
||||
char * buf,
|
||||
int sz,
|
||||
void * context )
|
||||
{
|
||||
( void ) ssl; /* to prevent unused warning*/
|
||||
Socket_t xSocket = ( Socket_t ) context;
|
||||
BaseType_t sent = TCP_Sockets_Send( xSocket, ( void * ) buf, ( size_t ) sz );
|
||||
|
||||
if( sent == -TCP_SOCKETS_ERRNO_EWOULDBLOCK )
|
||||
{
|
||||
sent = WOLFSSL_CBIO_ERR_WANT_WRITE;
|
||||
}
|
||||
else if( sent == -TCP_SOCKETS_ERRNO_ENOTCONN )
|
||||
{
|
||||
sent = WOLFSSL_CBIO_ERR_CONN_CLOSE;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* do nothing */
|
||||
}
|
||||
|
||||
return ( int ) sent;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
static TlsTransportStatus_t initTLS( void )
|
||||
{
|
||||
/* initialize wolfSSL */
|
||||
wolfSSL_Init();
|
||||
|
||||
#ifdef DEBUG_WOLFSSL
|
||||
wolfSSL_Debugging_ON();
|
||||
#endif
|
||||
|
||||
return TLS_TRANSPORT_SUCCESS;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
static TlsTransportStatus_t loadCredentials( NetworkContext_t * pNetCtx,
|
||||
const NetworkCredentials_t * pNetCred )
|
||||
{
|
||||
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
|
||||
configASSERT( pNetCtx != NULL );
|
||||
configASSERT( pNetCred != NULL );
|
||||
|
||||
#if defined( democonfigCREDENTIALS_IN_BUFFER )
|
||||
if( wolfSSL_CTX_load_verify_buffer( pNetCtx->sslContext.ctx,
|
||||
( const byte * ) ( pNetCred->pRootCa ), ( long ) ( pNetCred->rootCaSize ),
|
||||
SSL_FILETYPE_PEM ) == SSL_SUCCESS )
|
||||
{
|
||||
if( wolfSSL_CTX_use_certificate_buffer( pNetCtx->sslContext.ctx,
|
||||
( const byte * ) ( pNetCred->pClientCert ), ( long ) ( pNetCred->clientCertSize ),
|
||||
SSL_FILETYPE_PEM ) == SSL_SUCCESS )
|
||||
{
|
||||
if( wolfSSL_CTX_use_PrivateKey_buffer( pNetCtx->sslContext.ctx,
|
||||
( const byte * ) ( pNetCred->pPrivateKey ), ( long ) ( pNetCred->privateKeySize ),
|
||||
SSL_FILETYPE_PEM ) == SSL_SUCCESS )
|
||||
{
|
||||
returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "Failed to load client-private-key from buffer" ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "Failed to load client-certificate from buffer" ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "Failed to load ca-certificate from buffer" ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
|
||||
return returnStatus;
|
||||
#else /* if defined( democonfigCREDENTIALS_IN_BUFFER ) */
|
||||
if( wolfSSL_CTX_load_verify_locations( pNetCtx->sslContext.ctx,
|
||||
( const char * ) ( pNetCred->pRootCa ), NULL ) == SSL_SUCCESS )
|
||||
{
|
||||
if( wolfSSL_CTX_use_certificate_file( pNetCtx->sslContext.ctx,
|
||||
( const char * ) ( pNetCred->pClientCert ), SSL_FILETYPE_PEM )
|
||||
== SSL_SUCCESS )
|
||||
{
|
||||
if( wolfSSL_CTX_use_PrivateKey_file( pNetCtx->sslContext.ctx,
|
||||
( const char * ) ( pNetCred->pPrivateKey ), SSL_FILETYPE_PEM )
|
||||
== SSL_SUCCESS )
|
||||
{
|
||||
returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "Failed to load client-private-key file" ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "Failed to load client-certificate file" ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "Failed to load ca-certificate file" ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
return returnStatus;
|
||||
#endif /* if defined( democonfigCREDENTIALS_IN_BUFFER ) */
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetCtx,
|
||||
const char * pHostName,
|
||||
const NetworkCredentials_t * pNetCred )
|
||||
{
|
||||
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
Socket_t xSocket = { 0 };
|
||||
|
||||
configASSERT( pNetCtx != NULL );
|
||||
configASSERT( pHostName != NULL );
|
||||
configASSERT( pNetCred != NULL );
|
||||
configASSERT( pNetCred->pRootCa != NULL );
|
||||
configASSERT( pNetCtx->tcpSocket != NULL );
|
||||
|
||||
if( pNetCtx->sslContext.ctx == NULL )
|
||||
{
|
||||
/* Attempt to create a context that uses the TLS 1.3 or 1.2 */
|
||||
pNetCtx->sslContext.ctx =
|
||||
wolfSSL_CTX_new( wolfSSLv23_client_method_ex( NULL ) );
|
||||
}
|
||||
|
||||
if( pNetCtx->sslContext.ctx != NULL )
|
||||
{
|
||||
/* load credentials from file */
|
||||
if( loadCredentials( pNetCtx, pNetCred ) == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
/* create a ssl object */
|
||||
pNetCtx->sslContext.ssl =
|
||||
wolfSSL_new( pNetCtx->sslContext.ctx );
|
||||
|
||||
if( pNetCtx->sslContext.ssl != NULL )
|
||||
{
|
||||
xSocket = pNetCtx->tcpSocket;
|
||||
|
||||
/* set Recv/Send glue functions to the WOLFSSL object */
|
||||
wolfSSL_SSLSetIORecv( pNetCtx->sslContext.ssl,
|
||||
wolfSSL_IORecvGlue );
|
||||
wolfSSL_SSLSetIOSend( pNetCtx->sslContext.ssl,
|
||||
wolfSSL_IOSendGlue );
|
||||
|
||||
/* set socket as a context of read/send glue funcs */
|
||||
wolfSSL_SetIOReadCtx( pNetCtx->sslContext.ssl, xSocket );
|
||||
wolfSSL_SetIOWriteCtx( pNetCtx->sslContext.ssl, xSocket );
|
||||
|
||||
/* let wolfSSL perform tls handshake */
|
||||
if( wolfSSL_connect( pNetCtx->sslContext.ssl )
|
||||
== SSL_SUCCESS )
|
||||
{
|
||||
returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
}
|
||||
else
|
||||
{
|
||||
wolfSSL_shutdown( pNetCtx->sslContext.ssl );
|
||||
wolfSSL_free( pNetCtx->sslContext.ssl );
|
||||
pNetCtx->sslContext.ssl = NULL;
|
||||
wolfSSL_CTX_free( pNetCtx->sslContext.ctx );
|
||||
pNetCtx->sslContext.ctx = NULL;
|
||||
|
||||
LogError( ( "Failed to establish a TLS connection" ) );
|
||||
returnStatus = TLS_TRANSPORT_HANDSHAKE_FAILED;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
wolfSSL_CTX_free( pNetCtx->sslContext.ctx );
|
||||
pNetCtx->sslContext.ctx = NULL;
|
||||
|
||||
LogError( ( "Failed to create wolfSSL object" ) );
|
||||
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
wolfSSL_CTX_free( pNetCtx->sslContext.ctx );
|
||||
pNetCtx->sslContext.ctx = NULL;
|
||||
|
||||
LogError( ( "Failed to load credentials" ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogError( ( "Failed to create a wolfSSL_CTX" ) );
|
||||
returnStatus = TLS_TRANSPORT_CONNECT_FAILURE;
|
||||
}
|
||||
|
||||
return returnStatus;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
const NetworkCredentials_t * pNetworkCredentials,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs )
|
||||
{
|
||||
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
|
||||
BaseType_t socketStatus = 0;
|
||||
BaseType_t isSocketConnected = pdFALSE;
|
||||
|
||||
if( ( pNetworkContext == NULL ) ||
|
||||
( pHostName == NULL ) ||
|
||||
( pNetworkCredentials == NULL ) )
|
||||
{
|
||||
LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, "
|
||||
"pHostName=%p, pNetworkCredentials=%p.",
|
||||
pNetworkContext,
|
||||
pHostName,
|
||||
pNetworkCredentials ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_PARAMETER;
|
||||
}
|
||||
else if( ( pNetworkCredentials->pRootCa == NULL ) )
|
||||
{
|
||||
LogError( ( "pRootCa cannot be NULL." ) );
|
||||
returnStatus = TLS_TRANSPORT_INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
/* Establish a TCP connection with the server. */
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
pNetworkContext->tcpSocket = NULL;
|
||||
|
||||
socketStatus = TCP_Sockets_Connect( &( pNetworkContext->tcpSocket ),
|
||||
pHostName,
|
||||
port,
|
||||
receiveTimeoutMs,
|
||||
sendTimeoutMs );
|
||||
|
||||
if( socketStatus != 0 )
|
||||
{
|
||||
LogError( ( "Failed to connect to %s with error %d.",
|
||||
pHostName,
|
||||
socketStatus ) );
|
||||
returnStatus = TLS_TRANSPORT_CONNECT_FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/* Initialize tls. */
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
isSocketConnected = pdTRUE;
|
||||
|
||||
returnStatus = initTLS();
|
||||
}
|
||||
|
||||
/* Perform TLS handshake. */
|
||||
if( returnStatus == TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
returnStatus = tlsSetup( pNetworkContext, pHostName, pNetworkCredentials );
|
||||
}
|
||||
|
||||
/* Clean up on failure. */
|
||||
if( returnStatus != TLS_TRANSPORT_SUCCESS )
|
||||
{
|
||||
if( isSocketConnected == pdTRUE )
|
||||
{
|
||||
TCP_Sockets_Disconnect( pNetworkContext->tcpSocket );
|
||||
pNetworkContext->tcpSocket = NULL;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogInfo( ( "(Network connection %p) Connection to %s established.",
|
||||
pNetworkContext,
|
||||
pHostName ) );
|
||||
}
|
||||
|
||||
return returnStatus;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext )
|
||||
{
|
||||
WOLFSSL * pSsl = pNetworkContext->sslContext.ssl;
|
||||
WOLFSSL_CTX * pCtx = NULL;
|
||||
|
||||
/* shutdown an active TLS connection */
|
||||
wolfSSL_shutdown( pSsl );
|
||||
|
||||
/* cleanup WOLFSSL object */
|
||||
wolfSSL_free( pSsl );
|
||||
pNetworkContext->sslContext.ssl = NULL;
|
||||
|
||||
/* Call socket shutdown function to close connection. */
|
||||
TCP_Sockets_Disconnect( pNetworkContext->tcpSocket );
|
||||
|
||||
/* free WOLFSSL_CTX object*/
|
||||
pCtx = pNetworkContext->sslContext.ctx;
|
||||
|
||||
wolfSSL_CTX_free( pCtx );
|
||||
pNetworkContext->sslContext.ctx = NULL;
|
||||
|
||||
wolfSSL_Cleanup();
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
|
||||
void * pBuffer,
|
||||
size_t bytesToRecv )
|
||||
{
|
||||
int32_t tlsStatus = 0;
|
||||
int iResult = 0;
|
||||
WOLFSSL * pSsl = NULL;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->sslContext.ssl == NULL ) )
|
||||
{
|
||||
LogError( ( "invalid input, pNetworkContext=%p", pNetworkContext ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( pBuffer == NULL )
|
||||
{
|
||||
LogError( ( "invalid input, pBuffer == NULL" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( bytesToRecv == 0 )
|
||||
{
|
||||
LogError( ( "invalid input, bytesToRecv == 0" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
pSsl = pNetworkContext->sslContext.ssl;
|
||||
|
||||
iResult = wolfSSL_read( pSsl, pBuffer, bytesToRecv );
|
||||
|
||||
if( iResult > 0 )
|
||||
{
|
||||
tlsStatus = iResult;
|
||||
}
|
||||
else if( wolfSSL_want_read( pSsl ) == 1 )
|
||||
{
|
||||
tlsStatus = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
tlsStatus = wolfSSL_state( pSsl );
|
||||
LogError( ( "Error from wolfSSL_read %d : %s ",
|
||||
iResult, wolfSSL_ERR_reason_error_string( tlsStatus ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
return tlsStatus;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------*/
|
||||
|
||||
int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext,
|
||||
const void * pBuffer,
|
||||
size_t bytesToSend )
|
||||
{
|
||||
int32_t tlsStatus = 0;
|
||||
int iResult = 0;
|
||||
WOLFSSL * pSsl = NULL;
|
||||
|
||||
if( ( pNetworkContext == NULL ) || ( pNetworkContext->sslContext.ssl == NULL ) )
|
||||
{
|
||||
LogError( ( "invalid input, pNetworkContext=%p", pNetworkContext ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( pBuffer == NULL )
|
||||
{
|
||||
LogError( ( "invalid input, pBuffer == NULL" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else if( bytesToSend == 0 )
|
||||
{
|
||||
LogError( ( "invalid input, bytesToSend == 0" ) );
|
||||
tlsStatus = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
pSsl = pNetworkContext->sslContext.ssl;
|
||||
|
||||
iResult = wolfSSL_write( pSsl, pBuffer, bytesToSend );
|
||||
|
||||
if( iResult > 0 )
|
||||
{
|
||||
tlsStatus = iResult;
|
||||
}
|
||||
else if( wolfSSL_want_write( pSsl ) == 1 )
|
||||
{
|
||||
tlsStatus = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
tlsStatus = wolfSSL_state( pSsl );
|
||||
LogError( ( "Error from wolfSL_write %d : %s ",
|
||||
iResult, wolfSSL_ERR_reason_error_string( tlsStatus ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
return tlsStatus;
|
||||
}
|
||||
/*-----------------------------------------------------------*/
|
||||
@ -0,0 +1,199 @@
|
||||
/*
|
||||
* FreeRTOS V202212.01
|
||||
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* https://www.FreeRTOS.org
|
||||
* https://github.com/FreeRTOS
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file using_wolfSSL.h
|
||||
* @brief TLS transport interface header.
|
||||
*/
|
||||
|
||||
#ifndef USING_WOLFSSL_H
|
||||
#define USING_WOLFSSL_H
|
||||
|
||||
/**************************************************/
|
||||
/******* DO NOT CHANGE the following order ********/
|
||||
/**************************************************/
|
||||
|
||||
/* Logging related header files are required to be included in the following order:
|
||||
* 1. Include the header file "logging_levels.h".
|
||||
* 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL.
|
||||
* 3. Include the header file "logging_stack.h".
|
||||
*/
|
||||
|
||||
/* Include header that defines log levels. */
|
||||
#include "logging_levels.h"
|
||||
|
||||
/* Logging configuration for the Sockets. */
|
||||
#ifndef LIBRARY_LOG_NAME
|
||||
#define LIBRARY_LOG_NAME "TlsTransport"
|
||||
#endif
|
||||
#ifndef LIBRARY_LOG_LEVEL
|
||||
#define LIBRARY_LOG_LEVEL LOG_INFO
|
||||
#endif
|
||||
|
||||
#include "logging_stack.h"
|
||||
|
||||
/************ End of logging configuration ****************/
|
||||
|
||||
/* FreeRTOS+TCP include. */
|
||||
#include "FreeRTOS_Sockets.h"
|
||||
|
||||
/* Transport interface include. */
|
||||
#include "transport_interface.h"
|
||||
|
||||
/* wolfSSL interface include. */
|
||||
#include "wolfssl/ssl.h"
|
||||
|
||||
/**
|
||||
* @brief Secured connection context.
|
||||
*/
|
||||
typedef struct SSLContext
|
||||
{
|
||||
WOLFSSL_CTX* ctx; /**< @brief wolfSSL context */
|
||||
WOLFSSL* ssl; /**< @brief wolfSSL ssl session context */
|
||||
} SSLContext_t;
|
||||
|
||||
/**
|
||||
* @brief Definition of the network context for the transport interface
|
||||
* implementation that uses mbedTLS and FreeRTOS+TLS sockets.
|
||||
*/
|
||||
struct NetworkContext
|
||||
{
|
||||
Socket_t tcpSocket;
|
||||
SSLContext_t sslContext;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Contains the credentials necessary for tls connection setup.
|
||||
*/
|
||||
typedef struct NetworkCredentials
|
||||
{
|
||||
/**
|
||||
* @brief Set this to a non-NULL value to use ALPN.
|
||||
*
|
||||
* This string must be NULL-terminated.
|
||||
*
|
||||
* See [this link]
|
||||
* (https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/)
|
||||
* for more information.
|
||||
*/
|
||||
const char * pAlpnProtos;
|
||||
|
||||
/**
|
||||
* @brief Disable server name indication (SNI) for a TLS session.
|
||||
*/
|
||||
BaseType_t disableSni;
|
||||
|
||||
const unsigned char * pRootCa; /**< @brief String representing a trusted server root certificate. */
|
||||
size_t rootCaSize; /**< @brief Size associated with #IotNetworkCredentials.pRootCa. */
|
||||
const unsigned char * pClientCert; /**< @brief String representing the client certificate. */
|
||||
size_t clientCertSize; /**< @brief Size associated with #IotNetworkCredentials.pClientCert. */
|
||||
const unsigned char * pPrivateKey; /**< @brief String representing the client certificate's private key. */
|
||||
size_t privateKeySize; /**< @brief Size associated with #IotNetworkCredentials.pPrivateKey. */
|
||||
const unsigned char * pUserName; /**< @brief String representing the username for MQTT. */
|
||||
size_t userNameSize; /**< @brief Size associated with #IotNetworkCredentials.pUserName. */
|
||||
const unsigned char * pPassword; /**< @brief String representing the password for MQTT. */
|
||||
size_t passwordSize; /**< @brief Size associated with #IotNetworkCredentials.pPassword. */
|
||||
} NetworkCredentials_t;
|
||||
|
||||
/**
|
||||
* @brief TLS Connect / Disconnect return status.
|
||||
*/
|
||||
typedef enum TlsTransportStatus
|
||||
{
|
||||
TLS_TRANSPORT_SUCCESS = 0, /**< Function successfully completed. */
|
||||
TLS_TRANSPORT_INVALID_PARAMETER, /**< At least one parameter was invalid. */
|
||||
TLS_TRANSPORT_INSUFFICIENT_MEMORY, /**< Insufficient memory required to establish connection. */
|
||||
TLS_TRANSPORT_INVALID_CREDENTIALS, /**< Provided credentials were invalid. */
|
||||
TLS_TRANSPORT_HANDSHAKE_FAILED, /**< Performing TLS handshake with server failed. */
|
||||
TLS_TRANSPORT_INTERNAL_ERROR, /**< A call to a system API resulted in an internal error. */
|
||||
TLS_TRANSPORT_CONNECT_FAILURE /**< Initial connection to the server failed. */
|
||||
} TlsTransportStatus_t;
|
||||
|
||||
/**
|
||||
* @brief Create a TLS connection with FreeRTOS sockets.
|
||||
*
|
||||
* @param[out] pNetworkContext Pointer to a network context to contain the
|
||||
* initialized socket handle.
|
||||
* @param[in] pHostName The hostname of the remote endpoint.
|
||||
* @param[in] port The destination port.
|
||||
* @param[in] pNetworkCredentials Credentials for the TLS connection.
|
||||
* @param[in] receiveTimeoutMs Receive socket timeout.
|
||||
* @param[in] sendTimeoutMs Send socket timeout.
|
||||
*
|
||||
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS,
|
||||
* #TLS_TRANSPORT_HANDSHAKE_FAILED, #TLS_TRANSPORT_INTERNAL_ERROR, or #TLS_TRANSPORT_CONNECT_FAILURE.
|
||||
*/
|
||||
TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
|
||||
const char * pHostName,
|
||||
uint16_t port,
|
||||
const NetworkCredentials_t * pNetworkCredentials,
|
||||
uint32_t receiveTimeoutMs,
|
||||
uint32_t sendTimeoutMs );
|
||||
|
||||
/**
|
||||
* @brief Gracefully disconnect an established TLS connection.
|
||||
*
|
||||
* @param[in] pNetworkContext Network context.
|
||||
*/
|
||||
void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext );
|
||||
|
||||
/**
|
||||
* @brief Receives data from an established TLS connection.
|
||||
*
|
||||
* This is the TLS version of the transport interface's
|
||||
* #TransportRecv_t function.
|
||||
*
|
||||
* @param[in] pNetworkContext The Network context.
|
||||
* @param[out] pBuffer Buffer to receive bytes into.
|
||||
* @param[in] bytesToRecv Number of bytes to receive from the network.
|
||||
*
|
||||
* @return Number of bytes (> 0) received if successful;
|
||||
* 0 if the socket times out without reading any bytes;
|
||||
* negative value on error.
|
||||
*/
|
||||
int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
|
||||
void * pBuffer,
|
||||
size_t bytesToRecv );
|
||||
|
||||
/**
|
||||
* @brief Sends data over an established TLS connection.
|
||||
*
|
||||
* This is the TLS version of the transport interface's
|
||||
* #TransportSend_t function.
|
||||
*
|
||||
* @param[in] pNetworkContext The network context.
|
||||
* @param[in] pBuffer Buffer containing the bytes to send.
|
||||
* @param[in] bytesToSend Number of bytes to send from the buffer.
|
||||
*
|
||||
* @return Number of bytes (> 0) sent on success;
|
||||
* 0 if the socket times out without sending any bytes;
|
||||
* else a negative value to represent error.
|
||||
*/
|
||||
int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext,
|
||||
const void * pBuffer,
|
||||
size_t bytesToSend );
|
||||
|
||||
#endif /* ifndef USING_WOLFSSL_H */
|
||||
Reference in New Issue
Block a user