fix faulty string to int conversion utilities

Sun, 17 Dec 2023 15:33:50 +0100

author
Mike Becker <universe@uap-core.de>
date
Sun, 17 Dec 2023 15:33:50 +0100
changeset 800
30d484806c2b
parent 799
d479b5e25b6e
child 801
ce97ff16f00e

fix faulty string to int conversion utilities

Probably it was expected that errno is set to EINVAL when illegal characters are encountered. But this is not standard and does not happen on every system, allowing illegal strings to be parsed as valid integers.

libidav/utils.c file | annotate | diff | comparison | revisions
--- a/libidav/utils.c	Sun Dec 17 15:22:34 2023 +0100
+++ b/libidav/utils.c	Sun Dec 17 15:33:50 2023 +0100
@@ -213,10 +213,11 @@
 }
 
 int util_strtouint(const char *str, uint64_t *value) {
+    if (str == NULL || *str == '\0') return 0;
     char *end;
     errno = 0;
     uint64_t val = strtoull(str, &end, 0);
-    if(errno == 0) {
+    if(errno == 0 && *end == '\0') {
         *value = val;
         return 1;
     } else {
@@ -225,10 +226,11 @@
 }
 
 int util_strtoint(const char *str, int64_t *value) {
+    if (str == NULL || *str == '\0') return 0;
     char *end;
     errno = 0;
     int64_t val = strtoll(str, &end, 0);
-    if(errno == 0) {
+    if(errno == 0 && *end == '\0') {
         *value = val;
         return 1;
     } else {
@@ -237,11 +239,14 @@
 }
 
 int util_szstrtouint(const char *str, uint64_t *value) {
+    if (str == NULL || *str == '\0') return 0;
     char *end;
     errno = 0;
     size_t len = strlen(str);
     uint64_t val = strtoull(str, &end, 0);
-    if(end == str+len) {
+    if(errno != 0) {
+        return 0;
+    } if(end == str+len) {
         *value = val;
         return 1;
     } else if(end == str+len-1) {

mercurial