From 2b245ebd9f8092b687621fcdfdbb8f2336069b53 Mon Sep 17 00:00:00 2001 From: Paul Bakker Date: Sun, 19 Apr 2009 18:44:26 +0000 Subject: [PATCH] - Moved file loading to load_file --- ChangeLog | 2 ++ library/x509parse.c | 71 +++++++++++++++++++++------------------------ 2 files changed, 35 insertions(+), 38 deletions(-) diff --git a/ChangeLog b/ChangeLog index b27c0ed3f..d20689edc 100644 --- a/ChangeLog +++ b/ChangeLog @@ -12,6 +12,8 @@ PolarSSL ChangeLog * Fixed minor memory leak in x509parse_crt() and added better handling of 'full' certificate chains (found by Mathias Olsson). + * Centralized file opening and reading for x509 files into + load_file() = Version 0.10.0 released on 2009-01-12 * Migrated XySSL to PolarSSL diff --git a/library/x509parse.c b/library/x509parse.c index 7d88a0cc3..feb4d5074 100644 --- a/library/x509parse.c +++ b/library/x509parse.c @@ -1003,40 +1003,53 @@ int x509parse_crt( x509_cert *chain, unsigned char *buf, int buflen ) return( 0 ); } +/* + * Load all data from a file into a given buffer. + */ +int load_file( char *path, unsigned char **buf, size_t *n ) +{ + FILE *f; + + if( ( f = fopen( path, "rb" ) ) == NULL ) + return( 1 ); + + fseek( f, 0, SEEK_END ); + *n = (size_t) ftell( f ); + fseek( f, 0, SEEK_SET ); + + if( ( *buf = (unsigned char *) malloc( *n + 1 ) ) == NULL ) + return( 1 ); + + if( fread( *buf, 1, *n, f ) != *n ) + { + fclose( f ); + free( *buf ); + return( 1 ); + } + + fclose( f ); + + (*buf)[*n] = '\0'; + + return( 0 ); +} + /* * Load one or more certificates and add them to the chained list */ int x509parse_crtfile( x509_cert *chain, char *path ) { int ret; - FILE *f; size_t n; unsigned char *buf; - if( ( f = fopen( path, "rb" ) ) == NULL ) + if ( load_file( path, &buf, &n ) ) return( 1 ); - fseek( f, 0, SEEK_END ); - n = (size_t) ftell( f ); - fseek( f, 0, SEEK_SET ); - - if( ( buf = (unsigned char *) malloc( n + 1 ) ) == NULL ) - return( 1 ); - - if( fread( buf, 1, n, f ) != n ) - { - fclose( f ); - free( buf ); - return( 1 ); - } - - buf[n] = '\0'; - ret = x509parse_crt( chain, buf, (int) n ); memset( buf, 0, n + 1 ); free( buf ); - fclose( f ); return( ret ); } @@ -1299,29 +1312,12 @@ int x509parse_key( rsa_context *rsa, unsigned char *buf, int buflen, int x509parse_keyfile( rsa_context *rsa, char *path, char *pwd ) { int ret; - FILE *f; size_t n; unsigned char *buf; - if( ( f = fopen( path, "rb" ) ) == NULL ) + if ( load_file( path, &buf, &n ) ) return( 1 ); - fseek( f, 0, SEEK_END ); - n = (size_t) ftell( f ); - fseek( f, 0, SEEK_SET ); - - if( ( buf = (unsigned char *) malloc( n + 1 ) ) == NULL ) - return( 1 ); - - if( fread( buf, 1, n, f ) != n ) - { - fclose( f ); - free( buf ); - return( 1 ); - } - - buf[n] = '\0'; - if( pwd == NULL ) ret = x509parse_key( rsa, buf, (int) n, NULL, 0 ); else @@ -1330,7 +1326,6 @@ int x509parse_keyfile( rsa_context *rsa, char *path, char *pwd ) memset( buf, 0, n + 1 ); free( buf ); - fclose( f ); return( ret ); }