1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
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
capability_to_name(int id)20 const char *capability_to_name(int id) {
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
capability_from_name(const char * name)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 && i < 64)
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 /* This is the number of capability names we are *compiled* with.
54 * For the max capability number of the currently-running kernel,
55 * use cap_last_cap(). */
capability_list_length(void)56 int capability_list_length(void) {
57 return (int) ELEMENTSOF(capability_names);
58 }
59
capability_set_to_string_alloc(uint64_t set,char ** s)60 int capability_set_to_string_alloc(uint64_t set, char **s) {
61 _cleanup_free_ char *str = NULL;
62 size_t n = 0;
63
64 assert(s);
65
66 for (unsigned i = 0; i <= cap_last_cap(); i++)
67 if (set & (UINT64_C(1) << i)) {
68 const char *p;
69 char buf[2 + 16 + 1];
70 size_t add;
71
72 p = capability_to_name(i);
73 if (!p) {
74 xsprintf(buf, "0x%x", i);
75 p = buf;
76 }
77
78 add = strlen(p);
79
80 if (!GREEDY_REALLOC(str, n + add + 2))
81 return -ENOMEM;
82
83 strcpy(mempcpy(str + n, p, add), " ");
84 n += add + 1;
85 }
86
87 if (!GREEDY_REALLOC(str, n + 1))
88 return -ENOMEM;
89
90 str[n > 0 ? n - 1 : 0] = '\0'; /* truncate the last space, if it's there */
91
92 *s = TAKE_PTR(str);
93
94 return 0;
95 }
96
capability_set_from_string(const char * s,uint64_t * set)97 int capability_set_from_string(const char *s, uint64_t *set) {
98 uint64_t val = 0;
99
100 assert(set);
101
102 for (const char *p = s;;) {
103 _cleanup_free_ char *word = NULL;
104 int r;
105
106 r = extract_first_word(&p, &word, NULL, EXTRACT_UNQUOTE);
107 if (r == -ENOMEM)
108 return r;
109 if (r <= 0)
110 break;
111
112 r = capability_from_name(word);
113 if (r < 0)
114 continue;
115
116 val |= ((uint64_t) UINT64_C(1)) << (uint64_t) r;
117 }
118
119 *set = val;
120
121 return 0;
122 }
123