Debian Codegraph @

src/shared/luo-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <linux/liveupdate.h>
5 #include <linux/magic.h>
6 #include <sys/ioctl.h>
7 #include <sys/vfs.h>
8
9 #include "sd-json.h"
10
11 #include "alloc-util.h"
12 #include "errno-util.h"
13 #include "fd-util.h"
14 #include "json-util.h"
15 #include "log.h"
16 #include "luo-util.h"
17 #include "memfd-util.h"
18 #include "parse-util.h"
19 #include "stat-util.h"
20 #include "string-util.h"
21
22 /* Kernel API defined at https://docs.kernel.org/userspace-api/liveupdate.html The /dev/liveupdate is a
23 * single-owner singleton, only a single process at any given time can open it. Callers can create named
24 * "sessions", and then add FDs to them. The session name can be used to retrieve the session after reboot.
25 * To identify an FD, a 64bit token (what we would call an 'index' in our codebase) is passed in, and the
26 * caller is responsible for coming up with the token and tracking them. */
27
28 int luo_open_device(void) {
29 return RET_NERRNO(open("/dev/liveupdate", O_RDWR|O_CLOEXEC));
30 }
31
32 int luo_create_session(int device_fd, const char *name) {
33 struct liveupdate_ioctl_create_session args = {
34 .size = sizeof(args),
35 .fd = -EBADF,
36 };
37
38 assert(device_fd >= 0);
39 assert(name);
40
41 if (strlen(name) >= sizeof(args.name))
42 return -ENAMETOOLONG;
43
44 strncpy_exact((char *) args.name, name, sizeof(args.name));
45
46 if (ioctl(device_fd, LIVEUPDATE_IOCTL_CREATE_SESSION, &args) < 0)
47 return -errno;
48
49 return args.fd;
50 }
51
52 int luo_retrieve_session(int device_fd, const char *name) {
53 struct liveupdate_ioctl_retrieve_session args = {
54 .size = sizeof(args),
55 .fd = -EBADF,
56 };
57
58 assert(device_fd >= 0);
59 assert(name);
60
61 if (strlen(name) >= sizeof(args.name))
62 return -ENAMETOOLONG;
63
64 strncpy_exact((char *) args.name, name, sizeof(args.name));
65
66 if (ioctl(device_fd, LIVEUPDATE_IOCTL_RETRIEVE_SESSION, &args) < 0)
67 return -errno;
68
69 return args.fd;
70 }
71
72 int luo_session_preserve_fd(int session_fd, int fd, uint64_t token) {
73 struct liveupdate_session_preserve_fd args = {
74 .size = sizeof(args),
75 .fd = fd,
76 .token = token,
77 };
78
79 assert(session_fd >= 0);
80 assert(fd >= 0);
81
82 return RET_NERRNO(ioctl(session_fd, LIVEUPDATE_SESSION_PRESERVE_FD, &args));
83 }
84
85 int luo_session_retrieve_fd(int session_fd, uint64_t token) {
86 struct liveupdate_session_retrieve_fd args = {
87 .size = sizeof(args),
88 .fd = -EBADF,
89 .token = token,
90 };
91 int r;
92
93 assert(session_fd >= 0);
94
95 if (ioctl(session_fd, LIVEUPDATE_SESSION_RETRIEVE_FD, &args) < 0)
96 return -errno;
97
98 r = fd_cloexec(args.fd, true);
99 if (r < 0) {
100 safe_close(args.fd);
101 return r;
102 }
103
104 return args.fd;
105 }
106
107 int luo_session_finish(int session_fd) {
108 struct liveupdate_session_finish args = {
109 .size = sizeof(args),
110 };
111
112 assert(session_fd >= 0);
113
114 return RET_NERRNO(ioctl(session_fd, LIVEUPDATE_SESSION_FINISH, &args));
115 }
116
117 int luo_parse_serialization(sd_json_variant **ret, int **ret_fds, size_t *ret_n_fds) {
118 _cleanup_(sd_json_variant_unrefp) sd_json_variant *root = NULL;
119 _cleanup_free_ int *fd_list = NULL;
120 size_t n_fds = 0;
121 int serialize_fd = -EBADF, r;
122
123 assert(ret);
124 assert(ret_fds);
125 assert(ret_n_fds);
126
127 const char *luo_fd_str = secure_getenv("SYSTEMD_LUO_SERIALIZE_FD");
128 if (!luo_fd_str) {
129 *ret = NULL;
130 *ret_fds = NULL;
131 *ret_n_fds = 0;
132 return 0;
133 }
134
135 serialize_fd = parse_fd(luo_fd_str);
136 if (serialize_fd < 0)
137 return log_warning_errno(serialize_fd,
138 "Failed to parse SYSTEMD_LUO_SERIALIZE_FD='%s': %m", luo_fd_str);
139
140 r = sd_json_parse_fd(
141 /* path= */ NULL,
142 serialize_fd,
143 SD_JSON_PARSE_MUST_BE_OBJECT|SD_JSON_PARSE_REOPEN_FD,
144 &root,
145 /* reterr_line= */ NULL,
146 /* reterr_column= */ NULL);
147 if (r < 0)
148 return log_warning_errno(r, "Failed to parse LUO serialization JSON: %m");
149
150 /* Collect all fd numbers referenced in the JSON (plus the serialization fd itself)
151 * so the caller can protect them from close_all_fds(). */
152 const char *unit_id _unused_;
153 sd_json_variant *unit_entries;
154
155 JSON_VARIANT_OBJECT_FOREACH(unit_id, unit_entries, root) {
156 sd_json_variant *entry;
157
158 JSON_VARIANT_ARRAY_FOREACH(entry, unit_entries) {
159 struct {
160 int fd;
161 } p = {
162 .fd = -EBADF,
163 };
164
165 static const sd_json_dispatch_field dispatch_table[] = {
166 { "fd", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_int, voffsetof(p, fd), 0 },
167 {}
168 };
169
170 r = sd_json_dispatch(entry, dispatch_table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG|SD_JSON_WARNING, &p);
171 if (r < 0)
172 continue;
173
174 if (p.fd < 0)
175 continue;
176
177 if (!GREEDY_REALLOC(fd_list, n_fds + 1))
178 return log_oom();
179
180 fd_list[n_fds++] = p.fd;
181 }
182 }
183
184 /* Also protect the serialization fd itself */
185 if (!GREEDY_REALLOC(fd_list, n_fds + 1))
186 return log_oom();
187 fd_list[n_fds++] = serialize_fd;
188
189 log_debug("Parsed LUO serialization with %zu fd(s) to preserve.", n_fds);
190
191 *ret = TAKE_PTR(root);
192 *ret_fds = TAKE_PTR(fd_list);
193 *ret_n_fds = n_fds;
194 return 0;
195 }
196
197 int luo_preserve_fd_stores(sd_json_variant *serialization, int *ret_session_fd) {
198 _cleanup_close_ int device_fd = -EBADF, session_fd = -EBADF;
199 _cleanup_(sd_json_variant_unrefp) sd_json_variant *mapping = NULL;
200 const char *unit_id;
201 sd_json_variant *entries;
202 uint64_t token = LUO_MAPPING_INDEX + 1;
203 int r;
204
205 assert(ret_session_fd);
206
207 if (!serialization) {
208 *ret_session_fd = -EBADF;
209 return 0; /* No LUO serialization, nothing to preserve */
210 }
211
212 device_fd = luo_open_device();
213 if (ERRNO_IS_NEG_DEVICE_ABSENT(device_fd)) {
214 *ret_session_fd = -EBADF;
215 return 0; /* LUO not supported, ignore */
216 }
217 if (device_fd < 0)
218 return log_error_errno(device_fd, "Failed to open /dev/liveupdate: %m");
219
220 session_fd = luo_create_session(device_fd, LUO_SESSION_NAME);
221 if (session_fd < 0)
222 return log_error_errno(session_fd, "Failed to create LUO session '%s': %m", LUO_SESSION_NAME);
223
224 /* Build the mapping JSON for the new kernel's PID 1 and preserve each fd.
225 * JSON format: { "unit_id": [ {"type": "fd", "name": "...", "token": N},
226 * {"type": "luo_session", "name": "...", "sessionName": "..."} ], ... }
227 *
228 * For regular fds: type=fd, preserved in the systemd session with the given LUO token.
229 * For LUO session fds: type=luo_session, the session survives kexec independently, as it cannot be
230 * nested. */
231 JSON_VARIANT_OBJECT_FOREACH(unit_id, entries, serialization) {
232 _cleanup_(sd_json_variant_unrefp) sd_json_variant *fd_list = NULL;
233 sd_json_variant *entry;
234
235 JSON_VARIANT_ARRAY_FOREACH(entry, entries) {
236 struct {
237 const char *type;
238 const char *name;
239 int fd;
240 const char *session_name;
241 } p = {
242 .fd = -EBADF,
243 };
244
245 static const sd_json_dispatch_field dispatch_table[] = {
246 { "type", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, type), SD_JSON_MANDATORY },
247 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, name), SD_JSON_MANDATORY },
248 { "fd", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_int, voffsetof(p, fd), 0 },
249 { "sessionName", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, session_name), 0 },
250 {}
251 };
252
253 r = sd_json_dispatch(entry, dispatch_table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG|SD_JSON_WARNING, &p);
254 if (r < 0)
255 continue;
256
257 if (streq(p.type, "fd")) {
258 if (p.fd < 0) {
259 log_warning("LUO mapping for unit '%s' fd '%s': missing or negative fd, skipping.", unit_id, p.name);
260 continue;
261 }
262
263 /* Regular fd, preserve in the systemd session */
264 r = luo_session_preserve_fd(session_fd, p.fd, token);
265 if (r < 0) {
266 log_warning_errno(r, "Failed to preserve LUO fd %i (name '%s') with token %" PRIu64 ", will be lost across kexec: %m", p.fd, p.name, token);
267 continue;
268 }
269
270 r = sd_json_variant_append_arraybo(
271 &fd_list,
272 SD_JSON_BUILD_PAIR_STRING("type", "fd"),
273 SD_JSON_BUILD_PAIR_STRING("name", p.name),
274 SD_JSON_BUILD_PAIR_UNSIGNED("token", token));
275 if (r < 0)
276 return log_error_errno(r, "Failed to build LUO mapping: %m");
277
278 ++token;
279 } else if (streq(p.type, "luo_session")) {
280 if (!p.session_name) {
281 log_warning("LUO mapping for unit '%s' fd '%s': missing sessionName, skipping.", unit_id, p.name);
282 continue;
283 }
284
285 /* Remember the FDStore name to session name mapping */
286 r = sd_json_variant_append_arraybo(
287 &fd_list,
288 SD_JSON_BUILD_PAIR_STRING("type", "luo_session"),
289 SD_JSON_BUILD_PAIR_STRING("name", p.name),
290 SD_JSON_BUILD_PAIR_STRING("sessionName", p.session_name));
291 if (r < 0)
292 return log_error_errno(r, "Failed to build LUO mapping for session fd: %m");
293
294 log_debug("LUO session fd '%s' (session '%s') recorded in mapping.",
295 p.name, p.session_name);
296 } else
297 log_warning("Unknown fd type '%s' for unit '%s' fd '%s', skipping.", p.type, unit_id, p.name);
298 }
299
300 if (fd_list) {
301 r = sd_json_variant_set_field(&mapping, unit_id, fd_list);
302 if (r < 0)
303 return log_error_errno(r, "Failed to add unit to LUO mapping: %m");
304 }
305 }
306
307 if (!mapping) {
308 log_debug("No fds were preserved in LUO session.");
309 *ret_session_fd = -EBADF;
310 return 0;
311 }
312
313 /* Store the mapping as a memfd at LUO token 0 */
314 _cleanup_free_ char *mapping_text = NULL;
315
316 r = sd_json_variant_format(mapping, /* flags= */ 0, &mapping_text);
317 if (r < 0)
318 return log_error_errno(r, "Failed to format LUO mapping JSON: %m");
319
320 _cleanup_close_ int mapping_fd = -EBADF;
321
322 mapping_fd = memfd_new_and_seal_string("luo-mapping", mapping_text);
323 if (mapping_fd < 0)
324 return log_error_errno(mapping_fd, "Failed to create LUO mapping memfd: %m");
325
326 r = luo_session_preserve_fd(session_fd, mapping_fd, LUO_MAPPING_INDEX);
327 if (r < 0)
328 return log_error_errno(r, "Failed to preserve LUO mapping memfd: %m");
329
330 log_info("Preserved fd stores in LUO session '%s' for kexec.", LUO_SESSION_NAME);
331
332 /* Return the session fd to the caller as it must stay open until the kexec syscall,
333 * otherwise the kernel discards the session. */
334 *ret_session_fd = TAKE_FD(session_fd);
335 return 1;
336 }
337
338 int fd_get_luo_session_name(int fd, char **ret) {
339 _cleanup_free_ char *path = NULL;
340 int r;
341
342 assert(fd >= 0);
343
344 // TODO: switch to LUO specific inode magic once available
345 r = fd_is_fs_type(fd, ANON_INODE_FS_MAGIC);
346 if (r < 0)
347 return r;
348 if (r == 0)
349 return -EMEDIUMTYPE;
350
351 r = fd_get_path(fd, &path);
352 if (r < 0)
353 return r;
354
355 /* Path is "anon_inode:[luo_session] <session_name>" */
356 const char *suffix = startswith(path, "anon_inode:[luo_session] ");
357 if (isempty(suffix))
358 return -EMEDIUMTYPE;
359
360 if (ret)
361 return strdup_to(ret, suffix);
362
363 return 0;
364 }
365
366 int fd_is_luo_session(int fd) {
367 int r;
368
369 r = fd_get_luo_session_name(fd, /* ret= */ NULL);
370 if (r == -EMEDIUMTYPE)
371 return false;
372 if (r < 0)
373 return r;
374
375 return true;
376 }