]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/cap-list.c
path-util: make use of TAKE_PTR() where we can
[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 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 && 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 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 size_t allocated = 0, n = 0;
60
61 assert(s);
62
63 for (unsigned i = 0; i <= cap_last_cap(); i++)
64 if (set & (UINT64_C(1) << i)) {
65 const char *p;
66 char buf[2 + 16 + 1];
67 size_t add;
68
69 p = capability_to_name(i);
70 if (!p) {
71 xsprintf(buf, "0x%x", i);
72 p = buf;
73 }
74
75 add = strlen(p);
76
77 if (!GREEDY_REALLOC(str, allocated, n + add + 2))
78 return -ENOMEM;
79
80 strcpy(mempcpy(str + n, p, add), " ");
81 n += add + 1;
82 }
83
84 if (!GREEDY_REALLOC(str, allocated, n + 1))
85 return -ENOMEM;
86
87 str[n > 0 ? n - 1 : 0] = '\0'; /* truncate the last space, if it's there */
88
89 *s = TAKE_PTR(str);
90
91 return 0;
92 }
93
94 int capability_set_from_string(const char *s, uint64_t *set) {
95 uint64_t val = 0;
96
97 assert(set);
98
99 for (const char *p = s;;) {
100 _cleanup_free_ char *word = NULL;
101 int r;
102
103 r = extract_first_word(&p, &word, NULL, EXTRACT_UNQUOTE);
104 if (r == -ENOMEM)
105 return r;
106 if (r <= 0)
107 break;
108
109 r = capability_from_name(word);
110 if (r < 0)
111 continue;
112
113 val |= ((uint64_t) UINT64_C(1)) << (uint64_t) r;
114 }
115
116 *set = val;
117
118 return 0;
119 }