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