Cli: validate that width and height arguments are numbers
This commit is contained in:
1 parent
cc041168a1
commit
c05f2b1b59
1 file changed
+35
-2
+35
-2
@@ -2,6 +2,8 @@
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define FLAGS \
|
||||
FLAG(height, "h", true) \
|
||||
@@ -137,13 +139,41 @@ int Cli::run(int argc, char * argv[])
|
||||
return 0;
|
||||
}
|
||||
|
||||
static bool parse_size(const char * flag, const char * value, size_t * out)
|
||||
{
|
||||
bool valid = value[0] != '\0';
|
||||
for (const char * c = value; *c != '\0'; c++)
|
||||
{
|
||||
if (*c < '0' || *c > '9')
|
||||
{
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (valid)
|
||||
{
|
||||
errno = 0;
|
||||
unsigned long long v = strtoull(value, nullptr, 10);
|
||||
if (errno == 0 && v <= SIZE_MAX)
|
||||
{
|
||||
*out = (size_t)v;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
fprintf(stderr, "Error: invalid value for option %s: '%s'\n", flag, value);
|
||||
return false;
|
||||
}
|
||||
|
||||
int Cli::handle_option(size_t flag_idx, const char * arg_value)
|
||||
{
|
||||
switch (flag_idx)
|
||||
{
|
||||
case flag_height:
|
||||
case flag_height_l:
|
||||
this->options.height = atoi(arg_value);
|
||||
if (!parse_size(flag_defs[flag_idx].flag, arg_value, &this->options.height))
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
|
||||
case flag_help:
|
||||
@@ -165,7 +195,10 @@ int Cli::handle_option(size_t flag_idx, const char * arg_value)
|
||||
|
||||
case flag_width:
|
||||
case flag_width_l:
|
||||
this->options.width = atoi(arg_value);
|
||||
if (!parse_size(flag_defs[flag_idx].flag, arg_value, &this->options.width))
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
|
||||
case flag_version:
|
||||
|
||||
Reference in new issue
Block a user