entropy_func() threading support

This commit is contained in:
Paul Bakker 2013-09-28 15:23:57 +02:00
parent 1ffefaca1e
commit f4e7dc50ea
2 changed files with 34 additions and 3 deletions

View file

@ -41,6 +41,10 @@
#endif #endif
#endif #endif
#if defined(POLARSSL_THREADING_C)
#include "threading.h"
#endif
#if defined(POLARSSL_HAVEGE_C) #if defined(POLARSSL_HAVEGE_C)
#include "havege.h" #include "havege.h"
#endif #endif
@ -106,6 +110,9 @@ typedef struct
#if defined(POLARSSL_HAVEGE_C) #if defined(POLARSSL_HAVEGE_C)
havege_state havege_data; havege_state havege_data;
#endif #endif
#if defined(POLARSSL_THREADING_C)
threading_mutex_t mutex; /*!< mutex */
#endif
} }
entropy_context; entropy_context;
@ -149,6 +156,7 @@ int entropy_gather( entropy_context *ctx );
/** /**
* \brief Retrieve entropy from the accumulator (Max ENTROPY_BLOCK_SIZE) * \brief Retrieve entropy from the accumulator (Max ENTROPY_BLOCK_SIZE)
* (Thread-safe if POLARSSL_THREADING_C is enabled)
* *
* \param data Entropy context * \param data Entropy context
* \param output Buffer to fill * \param output Buffer to fill

View file

@ -40,6 +40,10 @@ void entropy_init( entropy_context *ctx )
{ {
memset( ctx, 0, sizeof(entropy_context) ); memset( ctx, 0, sizeof(entropy_context) );
#if defined(POLARSSL_THREADING_C)
polarssl_mutex_init( &ctx->mutex );
#endif
#if defined(POLARSSL_ENTROPY_SHA512_ACCUMULATOR) #if defined(POLARSSL_ENTROPY_SHA512_ACCUMULATOR)
sha512_starts( &ctx->accumulator, 0 ); sha512_starts( &ctx->accumulator, 0 );
#else #else
@ -67,6 +71,9 @@ void entropy_init( entropy_context *ctx )
void entropy_free( entropy_context *ctx ) void entropy_free( entropy_context *ctx )
{ {
((void) ctx); ((void) ctx);
#if defined(POLARSSL_THREADING_C)
polarssl_mutex_free( &ctx->mutex );
#endif
} }
int entropy_add_source( entropy_context *ctx, int entropy_add_source( entropy_context *ctx,
@ -175,16 +182,24 @@ int entropy_func( void *data, unsigned char *output, size_t len )
if( len > ENTROPY_BLOCK_SIZE ) if( len > ENTROPY_BLOCK_SIZE )
return( POLARSSL_ERR_ENTROPY_SOURCE_FAILED ); return( POLARSSL_ERR_ENTROPY_SOURCE_FAILED );
#if defined(POLARSSL_THREADING_C)
if( ( ret = polarssl_mutex_lock( &ctx->mutex ) ) != 0 )
return( ret );
#endif
/* /*
* Always gather extra entropy before a call * Always gather extra entropy before a call
*/ */
do do
{ {
if( count++ > ENTROPY_MAX_LOOP ) if( count++ > ENTROPY_MAX_LOOP )
return( POLARSSL_ERR_ENTROPY_SOURCE_FAILED ); {
ret = POLARSSL_ERR_ENTROPY_SOURCE_FAILED;
goto exit;
}
if( ( ret = entropy_gather( ctx ) ) != 0 ) if( ( ret = entropy_gather( ctx ) ) != 0 )
return( ret ); goto exit;
reached = 0; reached = 0;
@ -231,7 +246,15 @@ int entropy_func( void *data, unsigned char *output, size_t len )
memcpy( output, buf, len ); memcpy( output, buf, len );
return( 0 ); ret = 0;
exit:
#if defined(POLARSSL_THREADING_C)
if( polarssl_mutex_unlock( &ctx->mutex ) != 0 )
return( POLARSSL_ERR_THREADING_MUTEX_ERROR );
#endif
return( ret );
} }
#endif #endif