summaryrefslogtreecommitdiffstats
path: root/lib.c
diff options
context:
space:
mode:
authorMateusz Grzonka <mateusz.grzonka@intel.com>2021-09-02 11:48:12 +0200
committerJes Sorensen <jsorensen@fb.com>2021-10-08 13:09:11 +0200
commit60815698c0acda9bbf9b880bf78831cc8d9e159f (patch)
treef6646642bddbd74c370b196699846c2677cc92f3 /lib.c
parentFix error message when creating raid 4, 5 and 10 (diff)
downloadmdadm-60815698c0acda9bbf9b880bf78831cc8d9e159f.tar.xz
mdadm-60815698c0acda9bbf9b880bf78831cc8d9e159f.zip
Refactor parse_num and use it to parse optarg.
Use parse_num instead of atoi to parse optarg. Replace atoi by strtol. Move inst to int conversion into manage_new. Add better error handling. Signed-off-by: Mateusz Grzonka <mateusz.grzonka@intel.com> Signed-off-by: Jes Sorensen <jsorensen@fb.com>
Diffstat (limited to 'lib.c')
-rw-r--r--lib.c28
1 files changed, 28 insertions, 0 deletions
diff --git a/lib.c b/lib.c
index 60890b95..76d1fbb9 100644
--- a/lib.c
+++ b/lib.c
@@ -25,6 +25,7 @@
#include "mdadm.h"
#include "dlink.h"
#include <ctype.h>
+#include <limits.h>
/* This fill contains various 'library' style function. They
* have no dependency on anything outside this file.
@@ -534,3 +535,30 @@ void free_line(char *line)
}
dl_free(line);
}
+
+/**
+ * parse_num() - Parse int from string.
+ * @dest: Pointer to destination.
+ * @num: Pointer to string that is going to be parsed.
+ *
+ * If string contains anything after a number, error code is returned.
+ * The same happens when number is bigger than INT_MAX or smaller than 0.
+ * Writes to destination only if successfully read the number.
+ *
+ * Return: 0 on success, 1 otherwise.
+ */
+int parse_num(int *dest, char *num)
+{
+ char *c = NULL;
+ long temp;
+
+ if (!num)
+ return 1;
+
+ errno = 0;
+ temp = strtol(num, &c, 10);
+ if (temp < 0 || temp > INT_MAX || *c || errno != 0 || num == c)
+ return 1;
+ *dest = temp;
+ return 0;
+}