parse-util: make sure "3.+1s" or "3. 1s" are not considered valid time specification

Indeed, strtoll() is super-hard to use properly! :-(

Also added more tests for those cases and copied the tests to parse_nsec as well.
This commit is contained in:
Filipe Brandenburger 2018-07-19 21:50:35 -07:00
parent 5a9fb35843
commit 279f52a1d3
2 changed files with 22 additions and 2 deletions

View File

@ -1,5 +1,6 @@
/* SPDX-License-Identifier: LGPL-2.1+ */
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
@ -1023,7 +1024,8 @@ int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
if (*e == '.') {
char *b = e + 1;
if (*b == '-') /* Don't allow 0.-0 */
/* Don't allow "0.-0", "3.+1" or "3. 1" */
if (*b == '-' || *b == '+' || isspace(*b))
return -EINVAL;
errno = 0;
@ -1161,7 +1163,7 @@ int parse_nsec(const char *t, nsec_t *nsec) {
if (*e == '.') {
char *b = e + 1;
if (*b == '-')
if (*b == '-' || *b == '+' || isspace(*b))
return -EINVAL;
errno = 0;

View File

@ -36,6 +36,8 @@ static void test_parse_sec(void) {
assert_se(u == USEC_INFINITY);
assert_se(parse_sec(" infinity ", &u) >= 0);
assert_se(u == USEC_INFINITY);
assert_se(parse_sec("+3.1s", &u) >= 0);
assert_se(u == 3100 * USEC_PER_MSEC);
assert_se(parse_sec(" xyz ", &u) < 0);
assert_se(parse_sec("", &u) < 0);
@ -50,6 +52,9 @@ static void test_parse_sec(void) {
assert_se(parse_sec("3.-0s ", &u) < 0);
assert_se(parse_sec(" infinity .7", &u) < 0);
assert_se(parse_sec(".3 infinity", &u) < 0);
assert_se(parse_sec("3.+1s", &u) < 0);
assert_se(parse_sec("3. 1s", &u) < 0);
assert_se(parse_sec("3.s", &u) < 0);
}
static void test_parse_sec_fix_0(void) {
@ -118,6 +123,8 @@ static void test_parse_nsec(void) {
assert_se(u == NSEC_INFINITY);
assert_se(parse_nsec(" infinity ", &u) >= 0);
assert_se(u == NSEC_INFINITY);
assert_se(parse_nsec("+3.1s", &u) >= 0);
assert_se(u == 3100 * NSEC_PER_MSEC);
assert_se(parse_nsec(" xyz ", &u) < 0);
assert_se(parse_nsec("", &u) < 0);
@ -126,6 +133,17 @@ static void test_parse_nsec(void) {
assert_se(parse_nsec(".s ", &u) < 0);
assert_se(parse_nsec(" infinity .7", &u) < 0);
assert_se(parse_nsec(".3 infinity", &u) < 0);
assert_se(parse_nsec("-5s ", &u) < 0);
assert_se(parse_nsec("-0.3s ", &u) < 0);
assert_se(parse_nsec("-0.0s ", &u) < 0);
assert_se(parse_nsec("-0.-0s ", &u) < 0);
assert_se(parse_nsec("0.-0s ", &u) < 0);
assert_se(parse_nsec("3.-0s ", &u) < 0);
assert_se(parse_nsec(" infinity .7", &u) < 0);
assert_se(parse_nsec(".3 infinity", &u) < 0);
assert_se(parse_nsec("3.+1s", &u) < 0);
assert_se(parse_nsec("3. 1s", &u) < 0);
assert_se(parse_nsec("3.s", &u) < 0);
}
static void test_format_timespan_one(usec_t x, usec_t accuracy) {