]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
util: introduce parse_ip_protocol()
authorYu Watanabe <watanabe.yu+github@gmail.com>
Thu, 29 Nov 2018 15:09:30 +0000 (16:09 +0100)
committerYu Watanabe <watanabe.yu+github@gmail.com>
Sun, 2 Dec 2018 05:13:41 +0000 (06:13 +0100)
Not only protocol name in lower case, but it optionally accepts
IP protocol name in upper case and IP protocol number.

src/shared/ip-protocol-list.c
src/shared/ip-protocol-list.h

index 775cd3313d12abe9e8bb684f8a224fc420a91913..f0c4ddae2d528417cbad4151d93441cddc724f25 100644 (file)
@@ -2,9 +2,11 @@
 
 #include <errno.h>
 #include <netinet/in.h>
-#include <string.h>
 
+#include "alloc-util.h"
 #include "ip-protocol-list.h"
+#include "parse-util.h"
+#include "string-util.h"
 #include "macro.h"
 
 static const struct ip_protocol_name* lookup_ip_protocol(register const char *str, register GPERF_LEN_TYPE len);
@@ -34,3 +36,32 @@ int ip_protocol_from_name(const char *name) {
 
         return sc->id;
 }
+
+int parse_ip_protocol(const char *s) {
+        _cleanup_free_ char *str = NULL;
+        int i, r;
+
+        assert(s);
+
+        if (isempty(s))
+                return IPPROTO_IP;
+
+        /* Do not use strdupa() here, as the input string may come from *
+         * command line or config files. */
+        str = strdup(s);
+        if (!str)
+                return -ENOMEM;
+
+        i = ip_protocol_from_name(ascii_strlower(str));
+        if (i >= 0)
+                return i;
+
+        r = safe_atoi(str, &i);
+        if (r < 0)
+                return r;
+
+        if (!ip_protocol_to_name(i))
+                return -EINVAL;
+
+        return i;
+}
index dfe346744f70fe31f64ccd6ec4c04ed85fdc0e9c..5c94969695f7677bb495cd8a7da4336309716cfe 100644 (file)
@@ -3,3 +3,4 @@
 
 const char *ip_protocol_to_name(int id);
 int ip_protocol_from_name(const char *name);
+int parse_ip_protocol(const char *s);