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