Debian Codegraph @

src/shared/ip-protocol-list.c

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