]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/cap-list.c
2b7834ad98ca705c58b3e87b20b93c1a1d743509
[thirdparty/systemd.git] / src / basic / cap-list.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <string.h>
5
6 #include "alloc-util.h"
7 #include "capability-util.h"
8 #include "cap-list.h"
9 #include "extract-word.h"
10 #include "macro.h"
11 #include "parse-util.h"
12 #include "stdio-util.h"
13 #include "util.h"
14
15 static const struct capability_name* lookup_capability(register const char *str, register GPERF_LEN_TYPE len);
16
17 #include "cap-from-name.h"
18 #include "cap-to-name.h"
19
20 const char *capability_to_name(int id) {
21
22 if (id < 0)
23 return NULL;
24
25 if ((size_t) id >= ELEMENTSOF(capability_names))
26 return NULL;
27
28 return capability_names[id];
29 }
30
31 int capability_from_name(const char *name) {
32 const struct capability_name *sc;
33 int r, i;
34
35 assert(name);
36
37 /* Try to parse numeric capability */
38 r = safe_atoi(name, &i);
39 if (r >= 0) {
40 if (i >= 0 && i < 64)
41 return i;
42 else
43 return -EINVAL;
44 }
45
46 /* Try to parse string capability */
47 sc = lookup_capability(name, strlen(name));
48 if (!sc)
49 return -EINVAL;
50
51 return sc->id;
52 }
53
54 int capability_list_length(void) {
55 return (int) ELEMENTSOF(capability_names);
56 }
57
58 int capability_set_to_string_alloc(uint64_t set, char **s) {
59 _cleanup_free_ char *str = NULL;
60 size_t allocated = 0, n = 0;
61
62 assert(s);
63
64 for (unsigned i = 0; i <= cap_last_cap(); i++)
65 if (set & (UINT64_C(1) << i)) {
66 const char *p;
67 char buf[2 + 16 + 1];
68 size_t add;
69
70 p = capability_to_name(i);
71 if (!p) {
72 xsprintf(buf, "0x%x", i);
73 p = buf;
74 }
75
76 add = strlen(p);
77
78 if (!GREEDY_REALLOC(str, allocated, n + add + 2))
79 return -ENOMEM;
80
81 strcpy(mempcpy(str + n, p, add), " ");
82 n += add + 1;
83 }
84
85 if (!GREEDY_REALLOC(str, allocated, n + 1))
86 return -ENOMEM;
87
88 str[n > 0 ? n - 1 : 0] = '\0'; /* truncate the last space, if it's there */
89
90 *s = TAKE_PTR(str);
91
92 return 0;
93 }
94
95 int capability_set_from_string(const char *s, uint64_t *set) {
96 uint64_t val = 0;
97 const char *p;
98
99 assert(set);
100
101 for (p = s;;) {
102 _cleanup_free_ char *word = NULL;
103 int r;
104
105 r = extract_first_word(&p, &word, NULL, EXTRACT_UNQUOTE);
106 if (r == -ENOMEM)
107 return r;
108 if (r <= 0)
109 break;
110
111 r = capability_from_name(word);
112 if (r < 0)
113 continue;
114
115 val |= ((uint64_t) UINT64_C(1)) << (uint64_t) r;
116 }
117
118 *set = val;
119
120 return 0;
121 }