From 88ebbbf0fe6d03fc5509ebf0c1f568763e04cce4 Mon Sep 17 00:00:00 2001 From: Piotr Nowicki Date: Fri, 13 Mar 2020 16:26:08 +0100 Subject: [PATCH] Add function for parsing arguments Signed-off-by: Piotr Nowicki --- programs/ssl/ssl_base64_dump.c | 126 +++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) diff --git a/programs/ssl/ssl_base64_dump.c b/programs/ssl/ssl_base64_dump.c index 3b664c990..ca435f2c3 100644 --- a/programs/ssl/ssl_base64_dump.c +++ b/programs/ssl/ssl_base64_dump.c @@ -19,8 +19,134 @@ * This file is part of mbed TLS (https://tls.mbed.org) */ +#include +#include +#include +#include + +/* + * This program version + */ +#define PROG_NAME "ssl_base64_dump" +#define VER_MAJOR 0 +#define VER_MINOR 1 + +/* + * Global values + */ +FILE *b64_file = NULL; /* file with base64 codes to deserialize */ +char debug = 0; /* flag for debug messages */ + +/* + * Basic printing functions + */ +void print_version( ) +{ + printf( "%s v%d.%d\n", PROG_NAME, VER_MAJOR, VER_MINOR ); +} + +void print_usage( ) +{ + print_version(); + printf( + "Usage:\n" + "\t-f path - Path to the file with base64 code\n" + "\t-v - Show version\n" + "\t-h - Show this usage\n" + "\t-d - Print more information\n" + "\n" + ); +} + +void printf_dbg( const char *str, ... ) +{ + if( debug ) + { + va_list args; + va_start( args, str ); + printf( "debug: " ); + vprintf( str, args ); + fflush( stdout ); + va_end( args ); + } +} + +void printf_err( const char *str, ... ) +{ + va_list args; + va_start( args, str ); + fprintf( stderr, "ERROR: " ); + vfprintf( stderr, str, args ); + fflush( stderr ); + va_end( args ); +} + +/* + * Exit from the program in case of error + */ +void error_exit() +{ + if( NULL != b64_file ) + { + fclose( b64_file ); + } + exit( -1 ); +} + +/* + * This function takes the input arguments of this program + */ +void parse_arguments( int argc, char *argv[] ) +{ + int i = 1; + + if( argc < 2 ) + { + print_usage(); + error_exit(); + } + + while( i < argc ) + { + if( strcmp( argv[i], "-d" ) == 0 ) + { + debug = 1; + } + else if( strcmp( argv[i], "-h" ) == 0 ) + { + print_usage(); + } + else if( strcmp( argv[i], "-v" ) == 0 ) + { + print_version(); + } + else if( strcmp( argv[i], "-f" ) == 0 ) + { + if( ++i >= argc ) + { + printf_err( "File path is empty\n" ); + error_exit(); + } + + if( ( b64_file = fopen( argv[i], "r" ) ) == NULL ) + { + printf_err( "Cannot find file \"%s\"\n", argv[i] ); + error_exit(); + } + } + else + { + print_usage(); + error_exit(); + } + + i++; + } +} + int main( int argc, char *argv[] ) { + parse_arguments( argc, argv ); return 0; }