Hi, While reviewing and testing patch [1] that replaces atoi() with option_parse_int() for CLI option parsing, I found that option_parse_int() doesn’t handle whitespace-only strings properly. It treats them as 0.
Basically, what option_parse_int() does is like:
1. Use strtoint() to parse an option value
2. Skip all trailing whitespace
3. Check if any characters remain. If yes, return an error. This step detects
invalid values like “1a”, “1 a”, and “1 a ”
4. Check for out-of-range error
So, for a whitespace-only value, strtoint() returns 0 in step 1, step 2 skips
all whitespace, step 3 won’t detect an error as no characters remain, and step
4 may pass because 0 is valid for many options.
To fix this bug, we need to check if strtoint() fails to convert the string.
strtoint() internally calls strtol(). According to the POSIX doc for strtol()
[2]:
```
Upon successful completion, these functions shall return the
converted value, if any. If no conversion could be performed, 0
shall be returned and errno may be set to [EINVAL].
```
When no conversion happens, strtol() MAY set errno to EINVAL, which implies
that we should not rely on errno == EINVAL, as some implementations may not set
errno.
So, we can just check endptr==optarg. When they are equal, it means that no
conversion was performed. This covers both empty strings and whitespace-only
cases.
Actually, when a user directly types a command line in a shell, it’s very
unlikely to make such a mistake of passing whitespace as an option value,
because the shell treats whitespace as a separator unless the user explicitly
quotes it, like:
```
$ pg_dump --extra-float-digits=‘ ‘ ...
```
However, when debugging in an IDE like VSCode, which I’m using, where we
configure command-line arguments in JSON format, it might be easier to
mistakenly specify whitespace as an option value, as in the following
configuration I’m using to debug this patch:
```
{
"name": "(lldb) Run pgbench",
"type": "cppdbg",
"request": "launch",
"program": "/usr/local/pgsql/bin/pgbench",
"args": ["-i", "-d", "evantest", "--partitions= "],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb"
},
```
[1]
https://postgr.es/m/caphduzcsnycpomwga5kfo9dr-shdoew1skg2dw_kxxx+zoc...@mail.gmail.com
[2] https://man7.org/linux/man-pages/man3/strtol.3p.html
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
v1-0001-Reject-empty-and-whitespace-only-integer-option-v.patch
Description: Binary data
