]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/atoi/strtou_noneg.[ch]: Add strtou[l]l_noneg()
authorAlejandro Colomar <alx@kernel.org>
Sun, 10 Dec 2023 23:51:05 +0000 (00:51 +0100)
committerSerge Hallyn <serge@hallyn.com>
Mon, 22 Jan 2024 23:17:15 +0000 (17:17 -0600)
These functions reject negative numbers, instead of silently converting
them into unsigned, which strtou[l]l(3) do.

Reviewed-by: Iker Pedrosa <ipedrosa@redhat.com>
Cc: "Serge E. Hallyn" <serge@hallyn.com>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/Makefile.am
lib/atoi/strtou_noneg.c [new file with mode: 0644]
lib/atoi/strtou_noneg.h [new file with mode: 0644]

index 308099fc26262263a389a078a414f75df22d6404..0254977bc2fc8f6f565530f4baad63d18b6057f3 100644 (file)
@@ -30,6 +30,8 @@ libshadow_la_SOURCES = \
        agetpass.h \
        alloc.c \
        alloc.h \
+       atoi/strtou_noneg.c \
+       atoi/strtou_noneg.h \
        attr.h \
        audit_help.c \
        basename.c \
diff --git a/lib/atoi/strtou_noneg.c b/lib/atoi/strtou_noneg.c
new file mode 100644 (file)
index 0000000..14602a9
--- /dev/null
@@ -0,0 +1,13 @@
+// SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: BSD-3-Clause
+
+
+#include <config.h>
+
+#include "atoi/strtou_noneg.h"
+
+
+extern inline unsigned long strtoul_noneg(const char *s,
+    char **restrict endp, int base);
+extern inline unsigned long long strtoull_noneg(const char *s,
+    char **restrict endp, int base);
diff --git a/lib/atoi/strtou_noneg.h b/lib/atoi/strtou_noneg.h
new file mode 100644 (file)
index 0000000..5670dc9
--- /dev/null
@@ -0,0 +1,47 @@
+// SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: BSD-3-Clause
+
+
+#ifndef SHADOW_INCLUDE_LIB_ATOI_STRTOU_NONEG_H_
+#define SHADOW_INCLUDE_LIB_ATOI_STRTOU_NONEG_H_
+
+
+#include <config.h>
+
+#include <errno.h>
+#include <stdlib.h>
+
+#include "attr.h"
+
+
+ATTR_STRING(1) ATTR_ACCESS(write_only, 2)
+inline unsigned long strtoul_noneg(const char *s,
+    char **restrict endp, int base);
+ATTR_STRING(1) ATTR_ACCESS(write_only, 2)
+inline unsigned long long strtoull_noneg(const char *s,
+    char **restrict endp, int base);
+
+
+inline unsigned long
+strtoul_noneg(const char *s, char **restrict endp, int base)
+{
+       if (strtol(s, endp, base) < 0) {
+               errno = ERANGE;
+               return 0;
+       }
+       return strtoul(s, endp, base);
+}
+
+
+inline unsigned long long
+strtoull_noneg(const char *s, char **restrict endp, int base)
+{
+       if (strtol(s, endp, base) < 0) {
+               errno = ERANGE;
+               return 0;
+       }
+       return strtoull(s, endp, base);
+}
+
+
+#endif  // include guard