in platform/posix/transport/src/mbedtls_pkcs11_posix.c [768:847]
MbedtlsPkcs11Status_t Mbedtls_Pkcs11_Connect( NetworkContext_t * pNetworkContext,
const char * pHostName,
uint16_t port,
const MbedtlsPkcs11Credentials_t * pMbedtlsPkcs11Credentials,
uint32_t recvTimeoutMs )
{
MbedtlsPkcs11Context_t * pMbedtlsPkcs11Context = NULL;
MbedtlsPkcs11Status_t returnStatus = MBEDTLS_PKCS11_SUCCESS;
int32_t mbedtlsError = 0;
char portStr[ 6 ] = { 0 };
if( ( pNetworkContext == NULL ) ||
( pNetworkContext->pParams == NULL ) ||
( pHostName == NULL ) ||
( pMbedtlsPkcs11Credentials == NULL ) ||
( pMbedtlsPkcs11Credentials->pRootCaPath == NULL ) ||
( pMbedtlsPkcs11Credentials->pClientCertLabel == NULL ) ||
( pMbedtlsPkcs11Credentials->pPrivateKeyLabel == NULL ) )
{
LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, "
"pHostName=%p, pMbedtlsPkcs11Credentials=%p.",
( void * ) pNetworkContext,
( const void * ) pHostName,
( const void * ) pMbedtlsPkcs11Credentials ) );
returnStatus = MBEDTLS_PKCS11_INVALID_PARAMETER;
}
else
{
snprintf( portStr, sizeof( portStr ), "%u", port );
pMbedtlsPkcs11Context = pNetworkContext->pParams;
/* Configure MbedTLS. */
returnStatus = configureMbedtls( pMbedtlsPkcs11Context, pHostName, pMbedtlsPkcs11Credentials, recvTimeoutMs );
}
/* Establish a TCP connection with the server. */
if( returnStatus == MBEDTLS_PKCS11_SUCCESS )
{
mbedtlsError = mbedtls_net_connect( &( pMbedtlsPkcs11Context->socketContext ),
pHostName,
portStr,
MBEDTLS_NET_PROTO_TCP );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to connect to %s with error %d.", pHostName, mbedtlsError ) );
returnStatus = MBEDTLS_PKCS11_CONNECT_FAILURE;
}
}
if( returnStatus == MBEDTLS_PKCS11_SUCCESS )
{
/* Perform the TLS handshake. */
do
{
mbedtlsError = mbedtls_ssl_handshake( &( pMbedtlsPkcs11Context->context ) );
} while( ( mbedtlsError == MBEDTLS_ERR_SSL_WANT_READ ) ||
( mbedtlsError == MBEDTLS_ERR_SSL_WANT_WRITE ) );
if( ( mbedtlsError != 0 ) || ( mbedtls_ssl_get_verify_result( &( pMbedtlsPkcs11Context->context ) ) != 0U ) )
{
LogError( ( "Failed to perform TLS handshake: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
returnStatus = MBEDTLS_PKCS11_HANDSHAKE_FAILED;
}
}
/* Clean up on failure. */
if( returnStatus != MBEDTLS_PKCS11_SUCCESS )
{
contextFree( pMbedtlsPkcs11Context );
}
else
{
LogInfo( ( "TLS Connection to %s established.", pHostName ) );
}
return returnStatus;
}