From: Christian Brauner Date: Tue, 6 Sep 2016 15:32:47 +0000 (+0200) Subject: utils: add lxc_safe_uint() X-Git-Tag: lxc-2.1.0~257^2~28 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=6bc2eafe9094f53fccc1607cab751c1046f83a39;p=thirdparty%2Flxc.git utils: add lxc_safe_uint() This function safely parses an unsigned integer. On success it returns 0 and stores the unsigned integer in @converted. On error it returns a negative errno. Signed-off-by: Christian Brauner --- diff --git a/src/lxc/utils.c b/src/lxc/utils.c index 9198340f6..9bf31570d 100644 --- a/src/lxc/utils.c +++ b/src/lxc/utils.c @@ -1988,3 +1988,23 @@ int lxc_preserve_ns(const int pid, const char *ns) return open(path, O_RDONLY | O_CLOEXEC); } + +int lxc_safe_uint(const char *numstr, unsigned int *converted) +{ + char *err = NULL; + unsigned long int uli; + + errno = 0; + uli = strtoul(numstr, &err, 0); + if (errno > 0) + return -errno; + + if (!err || err == numstr || *err != '\0') + return -EINVAL; + + if (uli > UINT_MAX) + return -ERANGE; + + *converted = (unsigned)uli; + return 0; +} diff --git a/src/lxc/utils.h b/src/lxc/utils.h index 9b92daf3d..0706125e1 100644 --- a/src/lxc/utils.h +++ b/src/lxc/utils.h @@ -316,4 +316,8 @@ int lxc_preserve_ns(const int pid, const char *ns); /* Check whether a signal is blocked by a process. */ bool task_blocking_signal(pid_t pid, int signal); + +/* Helper functions to parse numbers. */ +int lxc_safe_uint(const char *numstr, unsigned int *converted); + #endif /* __LXC_UTILS_H */