pping: Fix edge cases of parse_bounded_double()

Fix two edge cases with the parse_bounded_double() function.

1. It accept an empty string without raising an error. This should not
   have been an issue in practice as getopt_long() should have detected
   it as an lack of argument. This is addressed by adding a check for
   if it has parsed anything at all.

2. It could overflow/underflow without raising an error. This is
   addressed by adding a check of errno (which is set in case of
   overflow/underflow, but not in case of conversion error).

Signed-off-by: Simon Sundberg <simon.sundberg@kau.se>
This commit is contained in:
Simon Sundberg
2023-05-25 16:30:56 +02:00
parent 83a85adb96
commit 1cb4e93b04

View File

@ -155,14 +155,22 @@ static int parse_bounded_double(double *res, const char *str, double low,
double high, const char *name)
{
char *endptr;
errno = 0;
*res = strtod(str, &endptr);
if (strlen(str) != endptr - str) {
if (endptr == str || strlen(str) != endptr - str) {
fprintf(stderr, "%s %s is not a valid number\n", name, str);
return -EINVAL;
}
if (errno == ERANGE) {
fprintf(stderr, "%s %s overflowed\n", name, str);
return -ERANGE;
}
if (*res < low || *res > high) {
fprintf(stderr, "%s must in range [%g, %g]\n", name, low, high);
return -EINVAL;
fprintf(stderr, "%s must be in range [%g, %g]\n", name, low, high);
return -ERANGE;
}
return 0;