Debian Codegraph @

src/bootctl/bootctl-unlink.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <fnmatch.h>
5
6 #include "sd-id128.h"
7 #include "sd-json.h"
8 #include "sd-varlink.h"
9
10 #include "alloc-util.h"
11 #include "boot-entry.h"
12 #include "bootctl.h"
13 #include "bootctl-unlink.h"
14 #include "bootspec.h"
15 #include "bootspec-util.h"
16 #include "chase.h"
17 #include "efi-loader.h"
18 #include "errno-util.h"
19 #include "fd-util.h"
20 #include "find-esp.h"
21 #include "hashmap.h"
22 #include "id128-util.h"
23 #include "json-util.h"
24 #include "log.h"
25 #include "path-util.h"
26 #include "stat-util.h"
27 #include "string-util.h"
28 #include "strv.h"
29
30 typedef struct UnlinkContext {
31 char *root;
32 int root_fd;
33
34 sd_id128_t machine_id;
35 BootEntryTokenType entry_token_type;
36 char *entry_token;
37
38 char *esp_path;
39 dev_t esp_devid;
40 int esp_fd;
41
42 char *xbootldr_path;
43 dev_t xbootldr_devid;
44 int xbootldr_fd;
45 } UnlinkContext;
46
47 #define UNLINK_CONTEXT_NULL \
48 (UnlinkContext) { \
49 .root_fd = -EBADF, \
50 .entry_token_type = _BOOT_ENTRY_TOKEN_TYPE_INVALID, \
51 .esp_fd = -EBADF, \
52 .xbootldr_fd = -EBADF, \
53 }
54
55 static void unlink_context_done(UnlinkContext *c) {
56 assert(c);
57
58 c->root = mfree(c->root);
59 c->root_fd = safe_close(c->root_fd);
60
61 c->entry_token = mfree(c->entry_token);
62
63 c->esp_path = mfree(c->esp_path);
64 c->esp_fd = safe_close(c->esp_fd);
65 c->xbootldr_path = mfree(c->xbootldr_path);
66 c->xbootldr_fd = safe_close(c->xbootldr_fd);
67 }
68
69 static int ref_file(Hashmap **known_files, const char *fn, int increment) {
70 int n, r;
71
72 assert(known_files);
73
74 /* just gracefully ignore this. This way the caller doesn't have to verify whether the bootloader
75 * entry is relevant. */
76 if (!fn)
77 return 0;
78
79 char *k = NULL;
80 n = PTR_TO_INT(hashmap_get2(*known_files, fn, (void**)&k));
81 if (!INC_SAFE(&n, increment))
82 return -EOVERFLOW;
83
84 assert(n >= 0);
85
86 if (n == 0) {
87 (void) hashmap_remove(*known_files, k);
88 free(k);
89 } else if (!k) {
90 _cleanup_free_ char *t = NULL;
91
92 t = strdup(fn);
93 if (!t)
94 return -ENOMEM;
95
96 r = hashmap_ensure_put(known_files, &path_hash_ops_free, t, INT_TO_PTR(n));
97 if (r < 0)
98 return r;
99
100 TAKE_PTR(t);
101 } else {
102 r = hashmap_update(*known_files, k, INT_TO_PTR(n));
103 if (r < 0)
104 return r;
105 }
106
107 return n;
108 }
109
110 static int boot_entry_ref_files(
111 const BootEntry *e,
112 Hashmap **known_files,
113 int increment) {
114
115 int r;
116
117 assert(e);
118 assert(known_files);
119 assert(increment != 0);
120
121 r = ref_file(known_files, e->kernel, increment);
122 if (r < 0)
123 return r;
124
125 r = ref_file(known_files, e->efi, increment);
126 if (r < 0)
127 return r;
128
129 r = ref_file(known_files, e->uki, increment);
130 if (r < 0)
131 return r;
132
133 STRV_FOREACH(s, e->initrd) {
134 r = ref_file(known_files, *s, increment);
135 if (r < 0)
136 return r;
137 }
138
139 r = ref_file(known_files, e->device_tree, increment);
140 if (r < 0)
141 return r;
142
143 STRV_FOREACH(s, e->device_tree_overlay) {
144 r = ref_file(known_files, *s, increment);
145 if (r < 0)
146 return r;
147 }
148
149 FOREACH_ARRAY(x, e->local_extras.items, e->local_extras.n_items) {
150 r = ref_file(known_files, x->location, increment);
151 if (r < 0)
152 return r;
153 }
154
155 return 0;
156 }
157
158 int boot_config_count_known_files(
159 const BootConfig *config,
160 BootEntrySource source,
161 Hashmap **ret_known_files) {
162
163 int r;
164
165 assert(config);
166 assert(ret_known_files);
167
168 _cleanup_hashmap_free_ Hashmap *known_files = NULL;
169 FOREACH_ARRAY(e, config->entries, config->n_entries) {
170
171 if (e->source != source)
172 continue;
173
174 r = boot_entry_ref_files(e, &known_files, +1);
175 if (r < 0)
176 return r;
177 }
178
179 *ret_known_files = TAKE_PTR(known_files);
180 return 0;
181 }
182
183 static int unref_unlink_file(
184 Hashmap **known_files,
185 const char *root,
186 int root_fd,
187 const char *path,
188 bool dry_run) {
189
190 int r;
191
192 assert(known_files);
193
194 /* just gracefully ignore this. This way the caller doesn't
195 have to verify whether the bootloader entry is relevant */
196 if (root_fd < 0 || !root || !path)
197 return 0;
198
199 r = ref_file(known_files, path, -1);
200 if (r < 0)
201 return log_error_errno(r, "Failed to unref '%s': %m", path);
202 if (r > 0)
203 return 0;
204
205 if (dry_run) {
206 _cleanup_free_ char *resolved = NULL;
207 r = chase_and_accessat(
208 /* root_fd= */ root_fd,
209 /* dir_fd= */ root_fd,
210 path,
211 CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS|CHASE_MUST_BE_REGULAR,
212 F_OK,
213 &resolved);
214 if (r < 0) {
215 log_warning_errno(r, "Unable to determine whether '%s' exists, ignoring: %m", path);
216 return 0;
217 }
218
219 log_info("Would remove '%s'", resolved);
220 return 1;
221 }
222
223 _cleanup_free_ char *resolved = NULL;
224 r = chase_and_unlinkat(
225 /* root_fd= */ root_fd,
226 /* dir_fd= */ root_fd,
227 path,
228 CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS,
229 /* unlink_flags= */ 0,
230 &resolved);
231 if (r == -ENOENT)
232 log_debug("Resource '%s' is already removed, skipping.", path);
233 else if (r < 0) {
234 log_warning_errno(r, "Failed to remove '%s', ignoring: %m", path);
235 return 0;
236 } else
237 log_info("Removed '%s'", resolved);
238
239 _cleanup_free_ char *parent = NULL;
240 r = path_extract_directory(path, &parent);
241 if (r < 0)
242 log_debug_errno(r, "Failed to extract parent directory of '%s', ignoring.", path);
243 else {
244 _cleanup_free_ char *resolved_parent = NULL;
245 r = chase_and_unlinkat(
246 /* root_fd= */ root_fd,
247 /* dir_fd= */ root_fd,
248 parent,
249 CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS,
250 AT_REMOVEDIR,
251 &resolved_parent);
252 if (IN_SET(r, -ENOTEMPTY, -ENOENT))
253 log_debug_errno(r, "Failed to remove directory '%s', ignoring: %m", parent);
254 else if (r < 0)
255 log_warning_errno(r, "Failed to remove directory '%s', ignoring: %m", parent);
256 else
257 log_info("Removed '%s'.", resolved_parent);
258 }
259
260 return 1;
261 }
262
263 static ssize_t boot_config_find_in(
264 const BootConfig *config,
265 BootEntrySource source,
266 const char *id) {
267
268 assert(config);
269 assert(source >= 0);
270 assert(source < _BOOT_ENTRY_SOURCE_MAX);
271
272 if (!id)
273 return -ENOENT;
274
275 for (size_t i = 0; i < config->n_entries; i++)
276 if (config->entries[i].source == source &&
277 fnmatch(id, config->entries[i].id, FNM_CASEFOLD) == 0)
278 return (ssize_t) i;
279
280 return -ENOENT;
281 }
282
283 int boot_entry_unlink(
284 const BootEntry *e,
285 const char *root,
286 int root_fd,
287 Hashmap *known_files,
288 bool dry_run) {
289
290 int r;
291
292 assert(e);
293 assert(root_fd >= 0);
294
295 (void) unref_unlink_file(&known_files, root, root_fd, e->kernel, dry_run);
296 (void) unref_unlink_file(&known_files, root, root_fd, e->efi, dry_run);
297 (void) unref_unlink_file(&known_files, root, root_fd, e->uki, dry_run);
298 STRV_FOREACH(s, e->initrd)
299 (void) unref_unlink_file(&known_files, root, root_fd, *s, dry_run);
300 (void) unref_unlink_file(&known_files, root, root_fd, e->device_tree, dry_run);
301 STRV_FOREACH(s, e->device_tree_overlay)
302 (void) unref_unlink_file(&known_files, root, root_fd, *s, dry_run);
303 FOREACH_ARRAY(x, e->local_extras.items, e->local_extras.n_items)
304 (void) unref_unlink_file(&known_files, root, root_fd, x->location, dry_run);
305
306 if (dry_run)
307 log_info("Would remove \"%s\"", e->path);
308 else {
309 const char *p = path_startswith(e->path, root);
310 if (!p)
311 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "File '%s' is not inside root '%s', refusing.", e->path, root);
312
313 _cleanup_free_ char *resolved = NULL;
314 r = chase_and_unlinkat(
315 /* root_fd= */ root_fd,
316 /* dir_fd= */ root_fd,
317 p,
318 CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS,
319 /* unlink_flags= */ 0,
320 &resolved);
321 if (r == -ENOENT)
322 return 0; /* Already removed? */
323 if (r < 0)
324 return log_error_errno(r, "Failed to remove \"%s\": %m", e->path);
325
326 log_info("Removed '%s'.", resolved);
327 }
328
329 return 0;
330 }
331
332 static int unlink_entry(
333 const BootConfig *config,
334 const char *root,
335 int root_fd,
336 BootEntrySource source,
337 char **ids,
338 bool dry_run) {
339
340 size_t n_removed = 0;
341 int r;
342
343 assert(config);
344
345 _cleanup_hashmap_free_ Hashmap *known_files = NULL;
346 r = boot_config_count_known_files(config, source, &known_files);
347 if (r < 0)
348 return log_error_errno(r, "Failed to count files in %s: %m", root);
349
350 int ret = 0;
351 STRV_FOREACH(id, ids) {
352 log_debug("Unlinking '%s'", *id);
353 ssize_t idx = boot_config_find_in(config, source, *id);
354 if (idx < 0)
355 continue; /* There is nothing to remove. */
356
357 log_debug("Index %zi", idx);
358
359 if (idx == config->default_entry)
360 log_warning("%s is the default boot entry", *id);
361 if (idx == config->selected_entry)
362 log_warning("%s is the selected boot entry", *id);
363
364 r = boot_entry_unlink(config->entries + idx, root, root_fd, known_files, dry_run);
365 if (r < 0)
366 RET_GATHER(ret, r);
367 else
368 n_removed++;
369 }
370
371 if (n_removed == 0)
372 log_info("No matching entries found or removed.");
373
374 return ret;
375 }
376
377 static int unlink_context_from_cmdline(UnlinkContext *ret) {
378 int r;
379
380 assert(ret);
381
382 _cleanup_(unlink_context_done) UnlinkContext b = UNLINK_CONTEXT_NULL;
383 b.entry_token_type = arg_entry_token_type;
384
385 if (strdup_to(&b.entry_token, arg_entry_token) < 0)
386 return log_oom();
387
388 if (arg_root) {
389 b.root_fd = open(arg_root, O_CLOEXEC|O_DIRECTORY|O_PATH);
390 if (b.root_fd < 0)
391 return log_error_errno(errno, "Failed to open root directory '%s': %m", arg_root);
392
393 if (strdup_to(&b.root, arg_root) < 0)
394 return log_oom();
395 } else
396 b.root_fd = XAT_FDROOT;
397
398 r = acquire_esp(/* unprivileged_mode= */ false,
399 /* graceful= */ false,
400 &b.esp_fd,
401 /* ret_part= */ NULL,
402 /* ret_pstart= */ NULL,
403 /* ret_psize= */ NULL,
404 /* ret_uuid= */ NULL,
405 &b.esp_devid);
406 if (r < 0 && r != -ENOKEY)
407 return r; /* About all other errors acquire_esp() logs on its own */
408 if (r > 0) {
409 if (arg_root) {
410 const char *e = path_startswith(arg_esp_path, arg_root);
411 if (!e)
412 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "ESP path '%s' not below specified root '%s', refusing.", arg_esp_path, arg_root);
413
414 r = strdup_to(&b.esp_path, e);
415 } else
416 r = strdup_to(&b.esp_path, arg_esp_path);
417 if (r < 0)
418 return log_oom();
419 }
420
421 r = acquire_xbootldr(
422 /* unprivileged_mode= */ false,
423 &b.xbootldr_fd,
424 /* ret_uuid= */ NULL,
425 &b.xbootldr_devid);
426 if (r < 0 && r != -ENOKEY)
427 return r;
428 if (r > 0) {
429 if (arg_root) {
430 const char *e = path_startswith(arg_xbootldr_path, arg_root);
431 if (!e)
432 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "XBOOTLDR path '%s' not below specified root '%s', refusing.", arg_xbootldr_path, arg_root);
433
434 r = strdup_to(&b.xbootldr_path, e);
435 } else
436 r = strdup_to(&b.xbootldr_path, arg_xbootldr_path);
437 if (r < 0)
438 return log_oom();
439 }
440
441 /* Only if we found neither ESP nor XBOOTLDR let's fail. */
442 if (!b.xbootldr_path && !b.esp_path)
443 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Neither ESP nor XBOOTLDR found, refusing.");
444
445 *ret = TAKE_GENERIC(b, UnlinkContext, UNLINK_CONTEXT_NULL);
446 return 0;
447 }
448
449 static int run_unlink(
450 UnlinkContext *c,
451 char **_ids,
452 bool dry_run) {
453
454 int r;
455 assert(c);
456
457 _cleanup_free_ char *x = NULL, *y = NULL;
458 if (c->root && c->esp_path) {
459 x = path_join(c->root, c->esp_path);
460 if (!x)
461 return log_oom();
462 }
463
464 if (c->root && c->xbootldr_path) {
465 y = path_join(c->root, c->xbootldr_path);
466 if (!y)
467 return log_oom();
468 }
469
470 _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL;
471 r = boot_config_load_and_select(
472 &config,
473 c->root,
474 x ?: c->esp_path,
475 c->esp_devid,
476 y ?: c->xbootldr_path,
477 c->xbootldr_devid);
478 if (r < 0)
479 return r;
480
481 _cleanup_(strv_freep) char **ids = NULL;
482 if (strv_isempty(_ids)) {
483 r = id128_get_machine_at(c->root_fd, &c->machine_id);
484 if (r < 0 && !ERRNO_IS_NEG_MACHINE_ID_UNSET(r))
485 return log_error_errno(r, "Failed to get machine-id: %m");
486
487 const char *e = secure_getenv("KERNEL_INSTALL_CONF_ROOT");
488 r = boot_entry_token_ensure_at(
489 e ? XAT_FDROOT : c->root_fd,
490 e,
491 c->machine_id,
492 /* machine_id_is_random= */ false,
493 &c->entry_token_type,
494 &c->entry_token);
495 if (r < 0)
496 return r;
497
498 r = boot_config_find_oldest_commit(
499 &config,
500 c->entry_token,
501 &ids);
502 if (r == -ENXIO)
503 return log_error_errno(r, "No suitable boot menu entry to delete found.");
504 if (r == -EBUSY)
505 return log_error_errno(r, "Refusing to remove currently booted boot menu entry.");
506 if (r < 0)
507 return log_error_errno(r, "Failed to find suitable oldest boot menu entry: %m");
508
509 STRV_FOREACH(id, ids)
510 log_info("Will unlink '%s'.", *id);
511 } else {
512 ids = strv_copy(_ids);
513 if (!ids)
514 return log_oom();
515 }
516
517 strv_sort_uniq(ids);
518
519 r = 0;
520 if (c->esp_path)
521 RET_GATHER(r, unlink_entry(&config, x ?: c->esp_path, c->esp_fd, BOOT_ENTRY_ESP, ids, dry_run));
522
523 if (c->xbootldr_path && c->xbootldr_devid != c->esp_devid)
524 RET_GATHER(r, unlink_entry(&config, y ?: c->xbootldr_path, c->xbootldr_fd, BOOT_ENTRY_XBOOTLDR, ids, dry_run));
525
526 return r;
527 }
528
529 int verb_unlink(int argc, char *argv[], uintptr_t _data, void *userdata) {
530 int r;
531
532 assert(argc < 3);
533
534 if (arg_oldest != isempty(argv[1]))
535 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Exactly one of an entry ID or --oldest= must be specified.");
536
537 const char *id = empty_to_null(argv[1]);
538
539 _cleanup_(unlink_context_done) UnlinkContext c = UNLINK_CONTEXT_NULL;
540 r = unlink_context_from_cmdline(&c);
541 if (r < 0)
542 return r;
543
544 return run_unlink(&c, STRV_MAKE(id), arg_dry_run);
545 }
546
547 static JSON_DISPATCH_ENUM_DEFINE(json_dispatch_boot_entry_token_type, BootEntryTokenType, boot_entry_token_type_from_string);
548
549 typedef struct UnlinkParameters {
550 UnlinkContext context;
551 unsigned root_fd_index;
552 const char *id;
553 bool oldest;
554 } UnlinkParameters;
555
556 static void unlink_parameters_done(UnlinkParameters *p) {
557 assert(p);
558
559 unlink_context_done(&p->context);
560 }
561
562 int vl_method_unlink(
563 sd_varlink *link,
564 sd_json_variant *parameters,
565 sd_varlink_method_flags_t flags,
566 void *userdata) {
567
568 int r;
569
570 assert(link);
571
572 _cleanup_(unlink_parameters_done) UnlinkParameters p = {
573 .context = UNLINK_CONTEXT_NULL,
574 .root_fd_index = UINT_MAX,
575 };
576
577 static const sd_json_dispatch_field dispatch_table[] = {
578 { "rootFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, voffsetof(p, root_fd_index), 0 },
579 { "rootDirectory", SD_JSON_VARIANT_STRING, json_dispatch_path, voffsetof(p, context.root), 0 },
580 { "bootEntryTokenType", SD_JSON_VARIANT_STRING, json_dispatch_boot_entry_token_type, voffsetof(p, context.entry_token_type), 0 },
581 { "id", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, id), 0 },
582 { "oldest", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, voffsetof(p, oldest), 0 },
583 {},
584 };
585
586 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
587 if (r != 0)
588 return r;
589
590 /* Only allow oldest *or* id to be set */
591 if (p.oldest == !!p.id)
592 return sd_varlink_error_invalid_parameter_name(link, "id");
593 if (p.id && !efi_loader_entry_name_valid(p.id))
594 return sd_varlink_error_invalid_parameter_name(link, "id");
595
596 if (p.root_fd_index != UINT_MAX) {
597 p.context.root_fd = sd_varlink_peek_dup_fd(link, p.root_fd_index);
598 if (p.context.root_fd < 0)
599 return log_debug_errno(p.context.root_fd, "Failed to acquire root fd from Varlink: %m");
600
601 r = fd_verify_safe_flags_full(p.context.root_fd, O_DIRECTORY);
602 if (r < 0)
603 return sd_varlink_error_invalid_parameter_name(link, "rootFileDescriptor");
604
605 r = fd_verify_directory(p.context.root_fd);
606 if (r < 0)
607 return log_debug_errno(r, "Specified file descriptor does not refer to a directory: %m");
608
609 if (!p.context.root) {
610 r = fd_get_path(p.context.root_fd, &p.context.root);
611 if (r < 0)
612 return log_debug_errno(r, "Failed to get path of file descriptor: %m");
613
614 if (empty_or_root(p.context.root))
615 p.context.root = mfree(p.context.root);
616 }
617 } else if (p.context.root) {
618 p.context.root_fd = open(p.context.root, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
619 if (p.context.root_fd < 0)
620 return log_debug_errno(errno, "Failed to open '%s': %m", p.context.root);
621 } else
622 p.context.root_fd = XAT_FDROOT;
623
624 if (p.context.entry_token_type < 0)
625 p.context.entry_token_type = BOOT_ENTRY_TOKEN_AUTO;
626
627 r = find_esp_and_warn_at_full(
628 p.context.root_fd,
629 /* path= */ NULL,
630 /* unprivileged_mode= */ false,
631 &p.context.esp_path,
632 &p.context.esp_fd,
633 /* ret_part= */ NULL,
634 /* ret_pstart= */ NULL,
635 /* ret_psize= */ NULL,
636 /* ret_uuid= */ NULL,
637 &p.context.esp_devid);
638 if (r < 0 && r != -ENOKEY)
639 return r;
640 r = find_xbootldr_and_warn_at_full(
641 p.context.root_fd,
642 /* path= */ NULL,
643 /* unprivileged_mode= */ false,
644 &p.context.xbootldr_path,
645 &p.context.xbootldr_fd,
646 /* ret_uuid= */ NULL,
647 &p.context.xbootldr_devid);
648 if (r < 0 && r != -ENOKEY)
649 return r;
650
651 /* Only if we found neither ESP nor XBOOTLDR let's fail. */
652 if (!p.context.xbootldr_path && !p.context.esp_path)
653 return sd_varlink_error(link, "io.systemd.BootControl.NoDollarBootFound", NULL);
654
655 r = run_unlink(&p.context, STRV_MAKE(p.id), /* dry_run= */ false);
656 if (r == -EUNATCH) /* no boot entry token is set */
657 return sd_varlink_error(link, "io.systemd.BootControl.BootEntryTokenUnavailable", NULL);
658 if (r < 0)
659 return r;
660
661 return sd_varlink_reply(link, NULL);
662 }