diff options
author | Ivan Nardi <12729895+IvanNardi@users.noreply.github.com> | 2024-01-04 13:16:39 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-01-04 13:16:39 +0100 |
commit | f23e9dc7bb7ffc4fe0b5c1151ecefa29a0ce5b79 (patch) | |
tree | f935e033f08dad050b163ab41a827da8feb55125 /src/lib/ndpi_utils.c | |
parent | 7f9973bd0ce2366c09c614d2fdb2883f27ba1106 (diff) |
Add an implementation of the BSD function `strtonum` (#2238)
The main difference with the original function is that we allow to
specify the base.
Credit for the original idea and the first implementation to @0xA50C1A1
Diffstat (limited to 'src/lib/ndpi_utils.c')
-rw-r--r-- | src/lib/ndpi_utils.c | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/lib/ndpi_utils.c b/src/lib/ndpi_utils.c index da5727915..dd5067906 100644 --- a/src/lib/ndpi_utils.c +++ b/src/lib/ndpi_utils.c @@ -3065,3 +3065,40 @@ int tpkt_verify_hdr(const struct ndpi_packet_struct * const packet) (packet->payload[0] == 3) && (packet->payload[1] == 0) && (get_u_int16_t(packet->payload,2) == htons(packet->payload_packet_len))); } + +/* ******************************************* */ + +int64_t ndpi_strtonum(const char *numstr, int64_t minval, int64_t maxval, const char **errstrp, int base) +{ + int64_t val = 0; + char* endptr; + + if (minval > maxval) { + *errstrp = "minval > maxval"; + return 0; + } + + errno = 0; /* To distinguish success/failure after call */ + val = (int64_t)strtoll(numstr, &endptr, base); + + if((val == LLONG_MIN && errno == ERANGE) || (val < minval)) { + *errstrp = "value too small"; + return 0; + } + if((val == LLONG_MAX && errno == ERANGE) || (val > maxval )) { + *errstrp = "value too large"; + return 0; + } + if(errno != 0 && val == 0) { + *errstrp = "generic error"; + return 0; + } + if(endptr == numstr) { + *errstrp = "No digits were found"; + return 0; + } + /* Like the original strtonum, we allow further characters after the number */ + + *errstrp = NULL; + return val; +} |