From: Willy Tarreau Date: Tue, 27 Apr 2021 16:30:28 +0000 (+0200) Subject: CLEANUP: cfgparse: de-uglify early file error handling in readcfgfile() X-Git-Tag: v2.4-dev18~28 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=da543e130cbaab91c96b1ecb96118141441bce4a;p=thirdparty%2Fhaproxy.git CLEANUP: cfgparse: de-uglify early file error handling in readcfgfile() In readcfgfile() when malloc() fails to allocate a buffer for the config line, it currently says "parsing[]: out of memory" while the error is unrelated to the config file and may make one think it has to do with the file's size. The second test (fopen() returning error) needs to release the previously allocated line. Both directly return -1 which is not even documented as a valid error code for the function. Let's simply make sure that the few variables freed at the end are properly preset, and jump there upon error, after having displayed a meaningful error message. Now at least we can get this: $ ./haproxy -f /dev/kmem [NOTICE] 116/191904 (23233) : haproxy version is 2.4-dev17-c3808c-13 [NOTICE] 116/191904 (23233) : path to executable is ./haproxy [ALERT] 116/191904 (23233) : Could not open configuration file /dev/kmem : Permission denied --- diff --git a/src/cfgparse.c b/src/cfgparse.c index 5fdee40f13..48e35a1f37 100644 --- a/src/cfgparse.c +++ b/src/cfgparse.c @@ -1500,7 +1500,8 @@ static void check_section_position(char *section_name, /* * This function reads and parses the configuration file given in the argument. - * Returns the error code, 0 if OK, or any combination of : + * Returns the error code, 0 if OK, -1 if the config file couldn't be opened, + * or any combination of : * - ERR_ABORT: must abort ASAP * - ERR_FATAL: we can continue parsing but not start the service * - ERR_WARN: a warning has been emitted @@ -1510,9 +1511,9 @@ static void check_section_position(char *section_name, */ int readcfgfile(const char *file) { - char *thisline; + char *thisline = NULL; int linesize = LINESIZE; - FILE *f; + FILE *f = NULL; int linenum = 0; int err_code = 0; struct cfg_section *cs = NULL, *pcs = NULL; @@ -1528,13 +1529,14 @@ int readcfgfile(const char *file) int non_global_section_parsed = 0; if ((thisline = malloc(sizeof(*thisline) * linesize)) == NULL) { - ha_alert("parsing [%s] : out of memory.\n", file); - return -1; + ha_alert("Out of memory trying to allocate a buffer for a configuration line.\n"); + err_code = -1; + goto err; } - if ((f=fopen(file,"r")) == NULL) { - free(thisline); - return -1; + if ((f = fopen(file,"r")) == NULL) { + err_code = -1; + goto err; } next_line: @@ -1922,7 +1924,9 @@ err: cursection = NULL; free(thisline); free(outline); - fclose(f); + if (f) + fclose(f); + return err_code; }