]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/ip-protocol-list.c
hwdb: Add mapping for Xiaomi Mipad 2 bottom bezel capacitive buttons
[thirdparty/systemd.git] / src / shared / ip-protocol-list.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <netinet/in.h>
5
6 #include "alloc-util.h"
7 #include "ip-protocol-list.h"
8 #include "macro.h"
9 #include "parse-util.h"
10 #include "string-util.h"
11
12 static const struct ip_protocol_name* lookup_ip_protocol(register const char *str, register GPERF_LEN_TYPE len);
13
14 #include "ip-protocol-from-name.h"
15 #include "ip-protocol-to-name.h"
16
17 const char *ip_protocol_to_name(int id) {
18
19 if (id < 0)
20 return NULL;
21
22 if ((size_t) id >= ELEMENTSOF(ip_protocol_names))
23 return NULL;
24
25 return ip_protocol_names[id];
26 }
27
28 int ip_protocol_from_name(const char *name) {
29 const struct ip_protocol_name *sc;
30
31 assert(name);
32
33 sc = lookup_ip_protocol(name, strlen(name));
34 if (!sc)
35 return -EINVAL;
36
37 return sc->id;
38 }
39
40 int parse_ip_protocol_full(const char *s, bool relaxed) {
41 int r, p;
42
43 assert(s);
44
45 if (isempty(s))
46 return IPPROTO_IP;
47
48 /* People commonly use lowercase protocol names, which we can look up very quickly, so let's try that
49 * first. */
50 r = ip_protocol_from_name(s);
51 if (r >= 0)
52 return r;
53
54 /* Do not use strdupa() here, as the input string may come from command line or config files. */
55 _cleanup_free_ char *t = strdup(s);
56 if (!t)
57 return -ENOMEM;
58
59 r = ip_protocol_from_name(ascii_strlower(t));
60 if (r >= 0)
61 return r;
62
63 r = safe_atoi(t, &p);
64 if (r < 0)
65 return r;
66 if (p < 0)
67 return -ERANGE;
68
69 /* If @relaxed, we don't check that we have a name for the protocol. */
70 if (!relaxed && !ip_protocol_to_name(p))
71 return -EPROTONOSUPPORT;
72
73 return p;
74 }
75
76 const char *ip_protocol_to_tcp_udp(int id) {
77 return IN_SET(id, IPPROTO_TCP, IPPROTO_UDP) ?
78 ip_protocol_to_name(id) : NULL;
79 }
80
81 int ip_protocol_from_tcp_udp(const char *ip_protocol) {
82 int id = ip_protocol_from_name(ip_protocol);
83 return IN_SET(id, IPPROTO_TCP, IPPROTO_UDP) ? id : -EINVAL;
84 }