]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/boot/bootctl.c
tree-wide: use reallocarray() where appropriate
[thirdparty/systemd.git] / src / boot / bootctl.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <blkid.h>
4 #include <ctype.h>
5 #include <dirent.h>
6 #include <errno.h>
7 #include <ftw.h>
8 #include <getopt.h>
9 #include <limits.h>
10 #include <linux/magic.h>
11 #include <stdbool.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/mman.h>
16 #include <sys/stat.h>
17 #include <sys/statfs.h>
18 #include <unistd.h>
19
20 #include "sd-id128.h"
21
22 #include "alloc-util.h"
23 #include "blkid-util.h"
24 #include "bootspec.h"
25 #include "copy.h"
26 #include "dirent-util.h"
27 #include "efivars.h"
28 #include "fd-util.h"
29 #include "fileio.h"
30 #include "fs-util.h"
31 #include "locale-util.h"
32 #include "main-func.h"
33 #include "pager.h"
34 #include "parse-util.h"
35 #include "pretty-print.h"
36 #include "rm-rf.h"
37 #include "stat-util.h"
38 #include "stdio-util.h"
39 #include "string-util.h"
40 #include "strv.h"
41 #include "terminal-util.h"
42 #include "tmpfile-util.h"
43 #include "umask-util.h"
44 #include "utf8.h"
45 #include "util.h"
46 #include "verbs.h"
47 #include "virt.h"
48
49 static char *arg_esp_path = NULL;
50 static char *arg_xbootldr_path = NULL;
51 static bool arg_print_esp_path = false;
52 static bool arg_print_dollar_boot_path = false;
53 static bool arg_touch_variables = true;
54 static PagerFlags arg_pager_flags = 0;
55
56 STATIC_DESTRUCTOR_REGISTER(arg_esp_path, freep);
57 STATIC_DESTRUCTOR_REGISTER(arg_xbootldr_path, freep);
58
59 static const char *arg_dollar_boot_path(void) {
60 /* $BOOT shall be the XBOOTLDR partition if it exists, and otherwise the ESP */
61 return arg_xbootldr_path ?: arg_esp_path;
62 }
63
64 static int acquire_esp(
65 bool unprivileged_mode,
66 uint32_t *ret_part,
67 uint64_t *ret_pstart,
68 uint64_t *ret_psize,
69 sd_id128_t *ret_uuid) {
70
71 char *np;
72 int r;
73
74 /* Find the ESP, and log about errors. Note that find_esp_and_warn() will log in all error cases on
75 * its own, except for ENOKEY (which is good, we want to show our own message in that case,
76 * suggesting use of --esp-path=) and EACCESS (only when we request unprivileged mode; in this case
77 * we simply eat up the error here, so that --list and --status work too, without noise about
78 * this). */
79
80 r = find_esp_and_warn(arg_esp_path, unprivileged_mode, &np, ret_part, ret_pstart, ret_psize, ret_uuid);
81 if (r == -ENOKEY)
82 return log_error_errno(r,
83 "Couldn't find EFI system partition. It is recommended to mount it to /boot or /efi.\n"
84 "Alternatively, use --esp-path= to specify path to mount point.");
85 if (r < 0)
86 return r;
87
88 free_and_replace(arg_esp_path, np);
89 log_debug("Using EFI System Partition at %s.", arg_esp_path);
90
91 return 1;
92 }
93
94 static int acquire_xbootldr(bool unprivileged_mode, sd_id128_t *ret_uuid) {
95 char *np;
96 int r;
97
98 r = find_xbootldr_and_warn(arg_xbootldr_path, unprivileged_mode, &np, ret_uuid);
99 if (r == -ENOKEY) {
100 log_debug_errno(r, "Didn't find an XBOOTLDR partition, using the ESP as $BOOT.");
101 if (ret_uuid)
102 *ret_uuid = SD_ID128_NULL;
103 return 0;
104 }
105 if (r < 0)
106 return r;
107
108 free_and_replace(arg_xbootldr_path, np);
109 log_debug("Using XBOOTLDR partition at %s as $BOOT.", arg_xbootldr_path);
110
111 return 1;
112 }
113
114 /* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */
115 static int get_file_version(int fd, char **v) {
116 struct stat st;
117 char *buf;
118 const char *s, *e;
119 char *x = NULL;
120 int r = 0;
121
122 assert(fd >= 0);
123 assert(v);
124
125 if (fstat(fd, &st) < 0)
126 return log_error_errno(errno, "Failed to stat EFI binary: %m");
127
128 r = stat_verify_regular(&st);
129 if (r < 0)
130 return log_error_errno(errno, "EFI binary is not a regular file: %m");
131
132 if (st.st_size < 27) {
133 *v = NULL;
134 return 0;
135 }
136
137 buf = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
138 if (buf == MAP_FAILED)
139 return log_error_errno(errno, "Failed to memory map EFI binary: %m");
140
141 s = memmem(buf, st.st_size - 8, "#### LoaderInfo: ", 17);
142 if (!s)
143 goto finish;
144 s += 17;
145
146 e = memmem(s, st.st_size - (s - buf), " ####", 5);
147 if (!e || e - s < 3) {
148 r = log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Malformed version string.");
149 goto finish;
150 }
151
152 x = strndup(s, e - s);
153 if (!x) {
154 r = log_oom();
155 goto finish;
156 }
157 r = 1;
158
159 finish:
160 (void) munmap(buf, st.st_size);
161 *v = x;
162 return r;
163 }
164
165 static int enumerate_binaries(const char *esp_path, const char *path, const char *prefix) {
166 _cleanup_closedir_ DIR *d = NULL;
167 struct dirent *de;
168 int c = 0, r;
169 char *p;
170
171 assert(esp_path);
172 assert(path);
173
174 p = strjoina(esp_path, "/", path);
175 d = opendir(p);
176 if (!d) {
177 if (errno == ENOENT)
178 return 0;
179
180 return log_error_errno(errno, "Failed to read \"%s\": %m", p);
181 }
182
183 FOREACH_DIRENT(de, d, break) {
184 _cleanup_free_ char *v = NULL;
185 _cleanup_close_ int fd = -1;
186
187 if (!endswith_no_case(de->d_name, ".efi"))
188 continue;
189
190 if (prefix && !startswith_no_case(de->d_name, prefix))
191 continue;
192
193 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
194 if (fd < 0)
195 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
196
197 r = get_file_version(fd, &v);
198 if (r < 0)
199 return r;
200 if (r > 0)
201 printf(" File: %s/%s/%s (%s%s%s)\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path, de->d_name, ansi_highlight(), v, ansi_normal());
202 else
203 printf(" File: %s/%s/%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path, de->d_name);
204
205 c++;
206 }
207
208 return c;
209 }
210
211 static int status_binaries(const char *esp_path, sd_id128_t partition) {
212 int r;
213
214 printf("Available Boot Loaders on ESP:\n");
215
216 if (!esp_path) {
217 printf(" ESP: Cannot find or access mount point of ESP.\n\n");
218 return -ENOENT;
219 }
220
221 printf(" ESP: %s", esp_path);
222 if (!sd_id128_is_null(partition))
223 printf(" (/dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x)", SD_ID128_FORMAT_VAL(partition));
224 printf("\n");
225
226 r = enumerate_binaries(esp_path, "EFI/systemd", NULL);
227 if (r < 0)
228 goto finish;
229 if (r == 0)
230 log_info("systemd-boot not installed in ESP.");
231
232 r = enumerate_binaries(esp_path, "EFI/BOOT", "boot");
233 if (r < 0)
234 goto finish;
235 if (r == 0)
236 log_info("No default/fallback boot loader installed in ESP.");
237
238 r = 0;
239
240 finish:
241 printf("\n");
242 return r;
243 }
244
245 static int print_efi_option(uint16_t id, bool in_order) {
246 _cleanup_free_ char *title = NULL;
247 _cleanup_free_ char *path = NULL;
248 sd_id128_t partition;
249 bool active;
250 int r = 0;
251
252 r = efi_get_boot_option(id, &title, &partition, &path, &active);
253 if (r < 0)
254 return r;
255
256 /* print only configured entries with partition information */
257 if (!path || sd_id128_is_null(partition))
258 return 0;
259
260 efi_tilt_backslashes(path);
261
262 printf(" Title: %s%s%s\n", ansi_highlight(), strna(title), ansi_normal());
263 printf(" ID: 0x%04X\n", id);
264 printf(" Status: %sactive%s\n", active ? "" : "in", in_order ? ", boot-order" : "");
265 printf(" Partition: /dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", SD_ID128_FORMAT_VAL(partition));
266 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path);
267 printf("\n");
268
269 return 0;
270 }
271
272 static int status_variables(void) {
273 _cleanup_free_ uint16_t *options = NULL, *order = NULL;
274 int n_options, n_order, i;
275
276 n_options = efi_get_boot_options(&options);
277 if (n_options == -ENOENT)
278 return log_error_errno(n_options,
279 "Failed to access EFI variables, efivarfs"
280 " needs to be available at /sys/firmware/efi/efivars/.");
281 if (n_options < 0)
282 return log_error_errno(n_options, "Failed to read EFI boot entries: %m");
283
284 n_order = efi_get_boot_order(&order);
285 if (n_order == -ENOENT)
286 n_order = 0;
287 else if (n_order < 0)
288 return log_error_errno(n_order, "Failed to read EFI boot order: %m");
289
290 /* print entries in BootOrder first */
291 printf("Boot Loaders Listed in EFI Variables:\n");
292 for (i = 0; i < n_order; i++)
293 print_efi_option(order[i], true);
294
295 /* print remaining entries */
296 for (i = 0; i < n_options; i++) {
297 int j;
298
299 for (j = 0; j < n_order; j++)
300 if (options[i] == order[j])
301 goto next_option;
302
303 print_efi_option(options[i], false);
304
305 next_option:
306 continue;
307 }
308
309 return 0;
310 }
311
312 static int boot_entry_show(const BootEntry *e, bool show_as_default) {
313 assert(e);
314
315 printf(" title: %s%s%s%s%s%s\n"
316 " type: %s\n",
317 ansi_highlight(),
318 boot_entry_title(e),
319 ansi_normal(),
320 ansi_highlight_green(),
321 show_as_default ? " (default)" : "",
322 ansi_normal(),
323 boot_entry_type_to_string(e->type));
324
325 if (e->id)
326 printf(" id: %s\n", e->id);
327 if (e->version)
328 printf(" version: %s\n", e->version);
329 if (e->machine_id)
330 printf(" machine-id: %s\n", e->machine_id);
331 if (e->architecture)
332 printf(" architecture: %s\n", e->architecture);
333 if (e->kernel)
334 printf(" linux: %s\n", e->kernel);
335 if (!strv_isempty(e->initrd)) {
336 _cleanup_free_ char *t;
337
338 t = strv_join(e->initrd, " ");
339 if (!t)
340 return log_oom();
341
342 printf(" initrd: %s\n", t);
343 }
344 if (!strv_isempty(e->options)) {
345 _cleanup_free_ char *t;
346
347 t = strv_join(e->options, " ");
348 if (!t)
349 return log_oom();
350
351 printf(" options: %s\n", t);
352 }
353 if (e->device_tree)
354 printf(" devicetree: %s\n", e->device_tree);
355
356 return 0;
357 }
358
359 static int status_entries(
360 const char *esp_path,
361 sd_id128_t esp_partition_uuid,
362 const char *xbootldr_path,
363 sd_id128_t xbootldr_partition_uuid) {
364
365 _cleanup_(boot_config_free) BootConfig config = {};
366 sd_id128_t dollar_boot_partition_uuid;
367 const char *dollar_boot_path;
368 int r;
369
370 assert(esp_path || xbootldr_path);
371
372 if (xbootldr_path) {
373 dollar_boot_path = xbootldr_path;
374 dollar_boot_partition_uuid = xbootldr_partition_uuid;
375 } else {
376 dollar_boot_path = esp_path;
377 dollar_boot_partition_uuid = esp_partition_uuid;
378 }
379
380 printf("Boot Loader Entries:\n"
381 " $BOOT: %s", dollar_boot_path);
382 if (!sd_id128_is_null(dollar_boot_partition_uuid))
383 printf(" (/dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x)", SD_ID128_FORMAT_VAL(dollar_boot_partition_uuid));
384 printf("\n\n");
385
386 r = boot_entries_load_config(esp_path, xbootldr_path, &config);
387 if (r < 0)
388 return r;
389
390 if (config.default_entry < 0)
391 printf("%zu entries, no entry could be determined as default.\n", config.n_entries);
392 else {
393 printf("Default Boot Loader Entry:\n");
394
395 boot_entry_show(config.entries + config.default_entry, false);
396 }
397
398 return 0;
399 }
400
401 static int compare_product(const char *a, const char *b) {
402 size_t x, y;
403
404 assert(a);
405 assert(b);
406
407 x = strcspn(a, " ");
408 y = strcspn(b, " ");
409 if (x != y)
410 return x < y ? -1 : x > y ? 1 : 0;
411
412 return strncmp(a, b, x);
413 }
414
415 static int compare_version(const char *a, const char *b) {
416 assert(a);
417 assert(b);
418
419 a += strcspn(a, " ");
420 a += strspn(a, " ");
421 b += strcspn(b, " ");
422 b += strspn(b, " ");
423
424 return strverscmp(a, b);
425 }
426
427 static int version_check(int fd_from, const char *from, int fd_to, const char *to) {
428 _cleanup_free_ char *a = NULL, *b = NULL;
429 int r;
430
431 assert(fd_from >= 0);
432 assert(from);
433 assert(fd_to >= 0);
434 assert(to);
435
436 r = get_file_version(fd_from, &a);
437 if (r < 0)
438 return r;
439 if (r == 0)
440 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
441 "Source file \"%s\" does not carry version information!",
442 from);
443
444 r = get_file_version(fd_to, &b);
445 if (r < 0)
446 return r;
447 if (r == 0 || compare_product(a, b) != 0)
448 return log_notice_errno(SYNTHETIC_ERRNO(EEXIST),
449 "Skipping \"%s\", since it's owned by another boot loader.",
450 to);
451
452 if (compare_version(a, b) < 0)
453 return log_warning_errno(SYNTHETIC_ERRNO(ESTALE), "Skipping \"%s\", since a newer boot loader version exists already.", to);
454
455 return 0;
456 }
457
458 static int copy_file_with_version_check(const char *from, const char *to, bool force) {
459 _cleanup_close_ int fd_from = -1, fd_to = -1;
460 _cleanup_free_ char *t = NULL;
461 int r;
462
463 fd_from = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
464 if (fd_from < 0)
465 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", from);
466
467 if (!force) {
468 fd_to = open(to, O_RDONLY|O_CLOEXEC|O_NOCTTY);
469 if (fd_to < 0) {
470 if (errno != -ENOENT)
471 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", to);
472 } else {
473 r = version_check(fd_from, from, fd_to, to);
474 if (r < 0)
475 return r;
476
477 if (lseek(fd_from, 0, SEEK_SET) == (off_t) -1)
478 return log_error_errno(errno, "Failed to seek in \"%s\": %m", from);
479
480 fd_to = safe_close(fd_to);
481 }
482 }
483
484 r = tempfn_random(to, NULL, &t);
485 if (r < 0)
486 return log_oom();
487
488 RUN_WITH_UMASK(0000) {
489 fd_to = open(t, O_WRONLY|O_CREAT|O_CLOEXEC|O_EXCL|O_NOFOLLOW, 0644);
490 if (fd_to < 0)
491 return log_error_errno(errno, "Failed to open \"%s\" for writing: %m", t);
492 }
493
494 r = copy_bytes(fd_from, fd_to, (uint64_t) -1, COPY_REFLINK);
495 if (r < 0) {
496 (void) unlink(t);
497 return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
498 }
499
500 (void) copy_times(fd_from, fd_to, 0);
501
502 if (fsync(fd_to) < 0) {
503 (void) unlink_noerrno(t);
504 return log_error_errno(errno, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
505 }
506
507 (void) fsync_directory_of_file(fd_to);
508
509 if (renameat(AT_FDCWD, t, AT_FDCWD, to) < 0) {
510 (void) unlink_noerrno(t);
511 return log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", t, to);
512 }
513
514 log_info("Copied \"%s\" to \"%s\".", from, to);
515
516 return 0;
517 }
518
519 static int mkdir_one(const char *prefix, const char *suffix) {
520 _cleanup_free_ char *p = NULL;
521
522 p = path_join(prefix, suffix);
523 if (mkdir(p, 0700) < 0) {
524 if (errno != EEXIST)
525 return log_error_errno(errno, "Failed to create \"%s\": %m", p);
526 } else
527 log_info("Created \"%s\".", p);
528
529 return 0;
530 }
531
532 static const char *const esp_subdirs[] = {
533 "EFI",
534 "EFI/systemd",
535 "EFI/BOOT",
536 "loader",
537 /* Note that "/loader/entries" is not listed here, since it should be placed in $BOOT, which might
538 * not necessarily be the ESP */
539 NULL
540 };
541
542 static int create_esp_subdirs(const char *esp_path) {
543 const char *const *i;
544 int r;
545
546 STRV_FOREACH(i, esp_subdirs) {
547 r = mkdir_one(esp_path, *i);
548 if (r < 0)
549 return r;
550 }
551
552 return 0;
553 }
554
555 static int copy_one_file(const char *esp_path, const char *name, bool force) {
556 char *p, *q;
557 int r;
558
559 p = strjoina(BOOTLIBDIR "/", name);
560 q = strjoina(esp_path, "/EFI/systemd/", name);
561 r = copy_file_with_version_check(p, q, force);
562
563 if (startswith(name, "systemd-boot")) {
564 int k;
565 char *v;
566
567 /* Create the EFI default boot loader name (specified for removable devices) */
568 v = strjoina(esp_path, "/EFI/BOOT/BOOT",
569 name + STRLEN("systemd-boot"));
570 ascii_strupper(strrchr(v, '/') + 1);
571
572 k = copy_file_with_version_check(p, v, force);
573 if (k < 0 && r == 0)
574 r = k;
575 }
576
577 return r;
578 }
579
580 static int install_binaries(const char *esp_path, bool force) {
581 struct dirent *de;
582 _cleanup_closedir_ DIR *d = NULL;
583 int r = 0;
584
585 d = opendir(BOOTLIBDIR);
586 if (!d)
587 return log_error_errno(errno, "Failed to open \""BOOTLIBDIR"\": %m");
588
589 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read \""BOOTLIBDIR"\": %m")) {
590 int k;
591
592 if (!endswith_no_case(de->d_name, ".efi"))
593 continue;
594
595 k = copy_one_file(esp_path, de->d_name, force);
596 if (k < 0 && r == 0)
597 r = k;
598 }
599
600 return r;
601 }
602
603 static bool same_entry(uint16_t id, const sd_id128_t uuid, const char *path) {
604 _cleanup_free_ char *opath = NULL;
605 sd_id128_t ouuid;
606 int r;
607
608 r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
609 if (r < 0)
610 return false;
611 if (!sd_id128_equal(uuid, ouuid))
612 return false;
613 if (!streq_ptr(path, opath))
614 return false;
615
616 return true;
617 }
618
619 static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
620 _cleanup_free_ uint16_t *options = NULL;
621 int n, i;
622
623 n = efi_get_boot_options(&options);
624 if (n < 0)
625 return n;
626
627 /* find already existing systemd-boot entry */
628 for (i = 0; i < n; i++)
629 if (same_entry(options[i], uuid, path)) {
630 *id = options[i];
631 return 1;
632 }
633
634 /* find free slot in the sorted BootXXXX variable list */
635 for (i = 0; i < n; i++)
636 if (i != options[i]) {
637 *id = i;
638 return 1;
639 }
640
641 /* use the next one */
642 if (i == 0xffff)
643 return -ENOSPC;
644 *id = i;
645 return 0;
646 }
647
648 static int insert_into_order(uint16_t slot, bool first) {
649 _cleanup_free_ uint16_t *order = NULL;
650 uint16_t *t;
651 int n, i;
652
653 n = efi_get_boot_order(&order);
654 if (n <= 0)
655 /* no entry, add us */
656 return efi_set_boot_order(&slot, 1);
657
658 /* are we the first and only one? */
659 if (n == 1 && order[0] == slot)
660 return 0;
661
662 /* are we already in the boot order? */
663 for (i = 0; i < n; i++) {
664 if (order[i] != slot)
665 continue;
666
667 /* we do not require to be the first one, all is fine */
668 if (!first)
669 return 0;
670
671 /* move us to the first slot */
672 memmove(order + 1, order, i * sizeof(uint16_t));
673 order[0] = slot;
674 return efi_set_boot_order(order, n);
675 }
676
677 /* extend array */
678 t = reallocarray(order, n + 1, sizeof(uint16_t));
679 if (!t)
680 return -ENOMEM;
681 order = t;
682
683 /* add us to the top or end of the list */
684 if (first) {
685 memmove(order + 1, order, n * sizeof(uint16_t));
686 order[0] = slot;
687 } else
688 order[n] = slot;
689
690 return efi_set_boot_order(order, n + 1);
691 }
692
693 static int remove_from_order(uint16_t slot) {
694 _cleanup_free_ uint16_t *order = NULL;
695 int n, i;
696
697 n = efi_get_boot_order(&order);
698 if (n <= 0)
699 return n;
700
701 for (i = 0; i < n; i++) {
702 if (order[i] != slot)
703 continue;
704
705 if (i + 1 < n)
706 memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
707 return efi_set_boot_order(order, n - 1);
708 }
709
710 return 0;
711 }
712
713 static int install_variables(const char *esp_path,
714 uint32_t part, uint64_t pstart, uint64_t psize,
715 sd_id128_t uuid, const char *path,
716 bool first) {
717 char *p;
718 uint16_t slot;
719 int r;
720
721 if (!is_efi_boot()) {
722 log_warning("Not booted with EFI, skipping EFI variable setup.");
723 return 0;
724 }
725
726 p = strjoina(esp_path, path);
727 if (access(p, F_OK) < 0) {
728 if (errno == ENOENT)
729 return 0;
730
731 return log_error_errno(errno, "Cannot access \"%s\": %m", p);
732 }
733
734 r = find_slot(uuid, path, &slot);
735 if (r < 0)
736 return log_error_errno(r,
737 r == -ENOENT ?
738 "Failed to access EFI variables. Is the \"efivarfs\" filesystem mounted?" :
739 "Failed to determine current boot order: %m");
740
741 if (first || r == 0) {
742 r = efi_add_boot_option(slot, "Linux Boot Manager",
743 part, pstart, psize,
744 uuid, path);
745 if (r < 0)
746 return log_error_errno(r, "Failed to create EFI Boot variable entry: %m");
747
748 log_info("Created EFI boot entry \"Linux Boot Manager\".");
749 }
750
751 return insert_into_order(slot, first);
752 }
753
754 static int remove_boot_efi(const char *esp_path) {
755 char *p;
756 _cleanup_closedir_ DIR *d = NULL;
757 struct dirent *de;
758 int r, c = 0;
759
760 p = strjoina(esp_path, "/EFI/BOOT");
761 d = opendir(p);
762 if (!d) {
763 if (errno == ENOENT)
764 return 0;
765
766 return log_error_errno(errno, "Failed to open directory \"%s\": %m", p);
767 }
768
769 FOREACH_DIRENT(de, d, break) {
770 _cleanup_close_ int fd = -1;
771 _cleanup_free_ char *v = NULL;
772
773 if (!endswith_no_case(de->d_name, ".efi"))
774 continue;
775
776 if (!startswith_no_case(de->d_name, "boot"))
777 continue;
778
779 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
780 if (fd < 0)
781 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
782
783 r = get_file_version(fd, &v);
784 if (r < 0)
785 return r;
786 if (r > 0 && startswith(v, "systemd-boot ")) {
787 r = unlinkat(dirfd(d), de->d_name, 0);
788 if (r < 0)
789 return log_error_errno(errno, "Failed to remove \"%s/%s\": %m", p, de->d_name);
790
791 log_info("Removed \"%s/%s\".", p, de->d_name);
792 }
793
794 c++;
795 }
796
797 return c;
798 }
799
800 static int rmdir_one(const char *prefix, const char *suffix) {
801 char *p;
802
803 p = strjoina(prefix, "/", suffix);
804 if (rmdir(p) < 0) {
805 bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
806
807 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
808 "Failed to remove directory \"%s\": %m", p);
809 if (!ignore)
810 return -errno;
811 } else
812 log_info("Removed \"%s\".", p);
813
814 return 0;
815 }
816
817 static int remove_esp_subdirs(const char *esp_path) {
818 size_t i;
819 int r = 0;
820
821 for (i = ELEMENTSOF(esp_subdirs)-1; i > 0; i--) {
822 int q;
823
824 q = rmdir_one(esp_path, esp_subdirs[i-1]);
825 if (q < 0 && r >= 0)
826 r = q;
827 }
828
829 return r;
830 }
831
832 static int remove_binaries(const char *esp_path) {
833 char *p;
834 int r, q;
835
836 p = strjoina(esp_path, "/EFI/systemd");
837 r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
838
839 q = remove_boot_efi(esp_path);
840 if (q < 0 && r == 0)
841 r = q;
842
843 return r;
844 }
845
846 static int remove_loader_config(const char *esp_path) {
847 const char *p;
848
849 assert(esp_path);
850
851 p = strjoina(esp_path, "/loader/loader.conf");
852 if (unlink(p) < 0) {
853 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno, "Failed to unlink file \"%s\": %m", p);
854 if (errno != ENOENT)
855 return -errno;
856 } else
857 log_info("Removed \"%s\".", p);
858
859 return 0;
860 }
861
862 static int remove_entries_directory(const char *dollar_boot_path) {
863 assert(dollar_boot_path);
864
865 return rmdir_one(dollar_boot_path, "/loader/entries");
866 }
867
868 static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
869 uint16_t slot;
870 int r;
871
872 if (!is_efi_boot())
873 return 0;
874
875 r = find_slot(uuid, path, &slot);
876 if (r != 1)
877 return 0;
878
879 r = efi_remove_boot_option(slot);
880 if (r < 0)
881 return r;
882
883 if (in_order)
884 return remove_from_order(slot);
885
886 return 0;
887 }
888
889 static int install_loader_config(const char *esp_path, sd_id128_t machine_id) {
890 char machine_string[SD_ID128_STRING_MAX];
891 _cleanup_(unlink_and_freep) char *t = NULL;
892 _cleanup_fclose_ FILE *f = NULL;
893 const char *p;
894 int r, fd;
895
896 p = strjoina(esp_path, "/loader/loader.conf");
897 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
898 return 0;
899
900 fd = open_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t);
901 if (fd < 0)
902 return log_error_errno(fd, "Failed to open \"%s\" for writing: %m", p);
903
904 f = fdopen(fd, "w");
905 if (!f) {
906 safe_close(fd);
907 return log_oom();
908 }
909
910 fprintf(f, "#timeout 3\n"
911 "#console-mode keep\n"
912 "default %s-*\n", sd_id128_to_string(machine_id, machine_string));
913
914 r = fflush_sync_and_check(f);
915 if (r < 0)
916 return log_error_errno(r, "Failed to write \"%s\": %m", p);
917
918 r = link_tmpfile(fd, t, p);
919 if (r == -EEXIST)
920 return 0; /* Silently skip creation if the file exists now (recheck) */
921 if (r < 0)
922 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
923
924 t = mfree(t);
925 return 1;
926 }
927
928 static int install_entries_directories(const char *dollar_boot_path, sd_id128_t machine_id) {
929 int r;
930 char buf[SD_ID128_STRING_MAX];
931
932 assert(dollar_boot_path);
933
934 /* Both /loader/entries and the entry directories themselves should be located on the same
935 * partition. Also create the parent directory for entry directories, so that kernel-install
936 * knows where to put them. */
937
938 r = mkdir_one(dollar_boot_path, "loader/entries");
939 if (r < 0)
940 return r;
941
942 return mkdir_one(dollar_boot_path, sd_id128_to_string(machine_id, buf));
943 }
944
945 static int help(int argc, char *argv[], void *userdata) {
946 _cleanup_free_ char *link = NULL;
947 int r;
948
949 r = terminal_urlify_man("bootctl", "1", &link);
950 if (r < 0)
951 return log_oom();
952
953 printf("%s [COMMAND] [OPTIONS...]\n\n"
954 "Install, update or remove the systemd-boot EFI boot manager.\n\n"
955 " -h --help Show this help\n"
956 " --version Print version\n"
957 " --esp-path=PATH Path to the EFI System Partition (ESP)\n"
958 " --boot-path=PATH Path to the $BOOT partition\n"
959 " -p --print-esp-path Print path to the EFI System Partition\n"
960 " --print-boot-path Print path to the $BOOT partition\n"
961 " --no-variables Don't touch EFI variables\n"
962 " --no-pager Do not pipe output into a pager\n"
963 "\nBoot Loader Commands:\n"
964 " status Show status of installed systemd-boot and EFI variables\n"
965 " install Install systemd-boot to the ESP and EFI variables\n"
966 " update Update systemd-boot in the ESP and EFI variables\n"
967 " remove Remove systemd-boot from the ESP and EFI variables\n"
968 "\nBoot Loader Entries Commands:\n"
969 " list List boot loader entries\n"
970 " set-default ID Set default boot loader entry\n"
971 " set-oneshot ID Set default boot loader entry, for next boot only\n"
972 "\nSee the %s for details.\n"
973 , program_invocation_short_name
974 , link);
975
976 return 0;
977 }
978
979 static int parse_argv(int argc, char *argv[]) {
980 enum {
981 ARG_ESP_PATH = 0x100,
982 ARG_BOOT_PATH,
983 ARG_PRINT_BOOT_PATH,
984 ARG_VERSION,
985 ARG_NO_VARIABLES,
986 ARG_NO_PAGER,
987 };
988
989 static const struct option options[] = {
990 { "help", no_argument, NULL, 'h' },
991 { "version", no_argument, NULL, ARG_VERSION },
992 { "esp-path", required_argument, NULL, ARG_ESP_PATH },
993 { "path", required_argument, NULL, ARG_ESP_PATH }, /* Compatibility alias */
994 { "boot-path", required_argument, NULL, ARG_BOOT_PATH },
995 { "print-esp-path", no_argument, NULL, 'p' },
996 { "print-path", no_argument, NULL, 'p' }, /* Compatibility alias */
997 { "print-boot-path", no_argument, NULL, ARG_PRINT_BOOT_PATH },
998 { "no-variables", no_argument, NULL, ARG_NO_VARIABLES },
999 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1000 {}
1001 };
1002
1003 int c, r;
1004
1005 assert(argc >= 0);
1006 assert(argv);
1007
1008 while ((c = getopt_long(argc, argv, "hp", options, NULL)) >= 0)
1009 switch (c) {
1010
1011 case 'h':
1012 help(0, NULL, NULL);
1013 return 0;
1014
1015 case ARG_VERSION:
1016 return version();
1017
1018 case ARG_ESP_PATH:
1019 r = free_and_strdup(&arg_esp_path, optarg);
1020 if (r < 0)
1021 return log_oom();
1022 break;
1023
1024 case ARG_BOOT_PATH:
1025 r = free_and_strdup(&arg_xbootldr_path, optarg);
1026 if (r < 0)
1027 return log_oom();
1028 break;
1029
1030 case 'p':
1031 arg_print_esp_path = true;
1032 break;
1033
1034 case ARG_PRINT_BOOT_PATH:
1035 arg_print_dollar_boot_path = true;
1036 break;
1037
1038 case ARG_NO_VARIABLES:
1039 arg_touch_variables = false;
1040 break;
1041
1042 case ARG_NO_PAGER:
1043 arg_pager_flags |= PAGER_DISABLE;
1044 break;
1045
1046 case '?':
1047 return -EINVAL;
1048
1049 default:
1050 assert_not_reached("Unknown option");
1051 }
1052
1053 return 1;
1054 }
1055
1056 static void read_loader_efi_var(const char *name, char **var) {
1057 int r;
1058
1059 r = efi_get_variable_string(EFI_VENDOR_LOADER, name, var);
1060 if (r < 0 && r != -ENOENT)
1061 log_warning_errno(r, "Failed to read EFI variable %s: %m", name);
1062 }
1063
1064 static int verb_status(int argc, char *argv[], void *userdata) {
1065 sd_id128_t esp_uuid = SD_ID128_NULL, xbootldr_uuid = SD_ID128_NULL;
1066 int r, k;
1067
1068 r = acquire_esp(geteuid() != 0, NULL, NULL, NULL, &esp_uuid);
1069 if (arg_print_esp_path) {
1070 if (r == -EACCES) /* If we couldn't acquire the ESP path, log about access errors (which is the only
1071 * error the find_esp_and_warn() won't log on its own) */
1072 return log_error_errno(r, "Failed to determine ESP location: %m");
1073 if (r < 0)
1074 return r;
1075
1076 puts(arg_esp_path);
1077 }
1078
1079 r = acquire_xbootldr(geteuid() != 0, &xbootldr_uuid);
1080 if (arg_print_dollar_boot_path) {
1081 if (r == -EACCES)
1082 return log_error_errno(r, "Failed to determine XBOOTLDR location: %m");
1083 if (r < 0)
1084 return r;
1085
1086 puts(arg_dollar_boot_path());
1087 }
1088
1089 if (arg_print_esp_path || arg_print_dollar_boot_path)
1090 return 0;
1091
1092 r = 0; /* If we couldn't determine the path, then don't consider that a problem from here on, just show what we
1093 * can show */
1094
1095 (void) pager_open(arg_pager_flags);
1096
1097 if (is_efi_boot()) {
1098 static const struct {
1099 uint64_t flag;
1100 const char *name;
1101 } flags[] = {
1102 { EFI_LOADER_FEATURE_BOOT_COUNTING, "Boot counting" },
1103 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT, "Menu timeout control" },
1104 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT, "One-shot menu timeout control" },
1105 { EFI_LOADER_FEATURE_ENTRY_DEFAULT, "Default entry control" },
1106 { EFI_LOADER_FEATURE_ENTRY_ONESHOT, "One-shot entry control" },
1107 };
1108
1109 _cleanup_free_ char *fw_type = NULL, *fw_info = NULL, *loader = NULL, *loader_path = NULL, *stub = NULL;
1110 sd_id128_t loader_part_uuid = SD_ID128_NULL;
1111 uint64_t loader_features = 0;
1112 size_t i;
1113
1114 read_loader_efi_var("LoaderFirmwareType", &fw_type);
1115 read_loader_efi_var("LoaderFirmwareInfo", &fw_info);
1116 read_loader_efi_var("LoaderInfo", &loader);
1117 read_loader_efi_var("StubInfo", &stub);
1118 read_loader_efi_var("LoaderImageIdentifier", &loader_path);
1119 (void) efi_loader_get_features(&loader_features);
1120
1121 if (loader_path)
1122 efi_tilt_backslashes(loader_path);
1123
1124 k = efi_loader_get_device_part_uuid(&loader_part_uuid);
1125 if (k < 0 && k != -ENOENT)
1126 r = log_warning_errno(k, "Failed to read EFI variable LoaderDevicePartUUID: %m");
1127
1128 printf("System:\n");
1129 printf(" Firmware: %s%s (%s)%s\n", ansi_highlight(), strna(fw_type), strna(fw_info), ansi_normal());
1130 printf(" Secure Boot: %sd\n", enable_disable(is_efi_secure_boot()));
1131 printf(" Setup Mode: %s\n", is_efi_secure_boot_setup_mode() ? "setup" : "user");
1132 printf("\n");
1133
1134 printf("Current Boot Loader:\n");
1135 printf(" Product: %s%s%s\n", ansi_highlight(), strna(loader), ansi_normal());
1136
1137 for (i = 0; i < ELEMENTSOF(flags); i++) {
1138
1139 if (i == 0)
1140 printf(" Features: ");
1141 else
1142 printf(" ");
1143
1144 if (FLAGS_SET(loader_features, flags[i].flag))
1145 printf("%s%s%s %s\n", ansi_highlight_green(), special_glyph(SPECIAL_GLYPH_CHECK_MARK), ansi_normal(), flags[i].name);
1146 else
1147 printf("%s%s%s %s\n", ansi_highlight_red(), special_glyph(SPECIAL_GLYPH_CROSS_MARK), ansi_normal(), flags[i].name);
1148 }
1149
1150 if (stub)
1151 printf(" Stub: %s\n", stub);
1152 if (!sd_id128_is_null(loader_part_uuid))
1153 printf(" ESP: /dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
1154 SD_ID128_FORMAT_VAL(loader_part_uuid));
1155 else
1156 printf(" ESP: n/a\n");
1157 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), strna(loader_path));
1158 printf("\n");
1159 } else
1160 printf("System:\n Not booted with EFI\n\n");
1161
1162 if (arg_esp_path) {
1163 k = status_binaries(arg_esp_path, esp_uuid);
1164 if (k < 0)
1165 r = k;
1166 }
1167
1168 if (is_efi_boot()) {
1169 k = status_variables();
1170 if (k < 0)
1171 r = k;
1172 }
1173
1174 if (arg_esp_path || arg_xbootldr_path) {
1175 k = status_entries(arg_esp_path, esp_uuid, arg_xbootldr_path, xbootldr_uuid);
1176 if (k < 0)
1177 r = k;
1178 }
1179
1180 return r;
1181 }
1182
1183 static int verb_list(int argc, char *argv[], void *userdata) {
1184 _cleanup_(boot_config_free) BootConfig config = {};
1185 int r;
1186
1187 /* If we lack privileges we invoke find_esp_and_warn() in "unprivileged mode" here, which does two things: turn
1188 * off logging about access errors and turn off potentially privileged device probing. Here we're interested in
1189 * the latter but not the former, hence request the mode, and log about EACCES. */
1190
1191 r = acquire_esp(geteuid() != 0, NULL, NULL, NULL, NULL);
1192 if (r == -EACCES) /* We really need the ESP path for this call, hence also log about access errors */
1193 return log_error_errno(r, "Failed to determine ESP: %m");
1194 if (r < 0)
1195 return r;
1196
1197 r = acquire_xbootldr(geteuid() != 0, NULL);
1198 if (r == -EACCES)
1199 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1200 if (r < 0)
1201 return r;
1202
1203 r = boot_entries_load_config(arg_esp_path, arg_xbootldr_path, &config);
1204 if (r < 0)
1205 return r;
1206
1207 (void) boot_entries_augment_from_loader(&config, false);
1208
1209 if (config.n_entries == 0)
1210 log_info("No boot loader entries found.");
1211 else {
1212 size_t n;
1213
1214 (void) pager_open(arg_pager_flags);
1215
1216 printf("Boot Loader Entries:\n");
1217
1218 for (n = 0; n < config.n_entries; n++) {
1219 r = boot_entry_show(config.entries + n, n == (size_t) config.default_entry);
1220 if (r < 0)
1221 return r;
1222
1223 if (n+1 < config.n_entries)
1224 putchar('\n');
1225 }
1226 }
1227
1228 return 0;
1229 }
1230
1231 static int sync_everything(void) {
1232 int ret = 0, k;
1233
1234 if (arg_esp_path) {
1235 k = syncfs_path(AT_FDCWD, arg_esp_path);
1236 if (k < 0)
1237 ret = log_error_errno(k, "Failed to synchronize the ESP '%s': %m", arg_esp_path);
1238 }
1239
1240 if (arg_xbootldr_path) {
1241 k = syncfs_path(AT_FDCWD, arg_xbootldr_path);
1242 if (k < 0)
1243 ret = log_error_errno(k, "Failed to synchronize $BOOT '%s': %m", arg_xbootldr_path);
1244 }
1245
1246 return ret;
1247 }
1248
1249 static int verb_install(int argc, char *argv[], void *userdata) {
1250 sd_id128_t uuid = SD_ID128_NULL;
1251 uint64_t pstart = 0, psize = 0;
1252 uint32_t part = 0;
1253 sd_id128_t machine_id;
1254 bool install;
1255 int r;
1256
1257 r = acquire_esp(false, &part, &pstart, &psize, &uuid);
1258 if (r < 0)
1259 return r;
1260
1261 r = acquire_xbootldr(false, NULL);
1262 if (r < 0)
1263 return r;
1264
1265 r = sd_id128_get_machine(&machine_id);
1266 if (r < 0)
1267 return log_error_errno(r, "Failed to get machine id: %m");
1268
1269 install = streq(argv[0], "install");
1270
1271 RUN_WITH_UMASK(0002) {
1272 if (install) {
1273 /* Don't create any of these directories when we are just updating. When we update
1274 * we'll drop-in our files (unless there are newer ones already), but we won't create
1275 * the directories for them in the first place. */
1276 r = create_esp_subdirs(arg_esp_path);
1277 if (r < 0)
1278 return r;
1279 }
1280
1281 r = install_binaries(arg_esp_path, install);
1282 if (r < 0)
1283 return r;
1284
1285 if (install) {
1286 r = install_loader_config(arg_esp_path, machine_id);
1287 if (r < 0)
1288 return r;
1289
1290 r = install_entries_directories(arg_dollar_boot_path(), machine_id);
1291 if (r < 0)
1292 return r;
1293 }
1294 }
1295
1296 (void) sync_everything();
1297
1298 if (arg_touch_variables)
1299 r = install_variables(arg_esp_path,
1300 part, pstart, psize, uuid,
1301 "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi",
1302 install);
1303
1304 return r;
1305 }
1306
1307 static int verb_remove(int argc, char *argv[], void *userdata) {
1308 sd_id128_t uuid = SD_ID128_NULL;
1309 int r, q;
1310
1311 r = acquire_esp(false, NULL, NULL, NULL, &uuid);
1312 if (r < 0)
1313 return r;
1314
1315 r = acquire_xbootldr(false, NULL);
1316 if (r < 0)
1317 return r;
1318
1319 r = remove_binaries(arg_esp_path);
1320
1321 q = remove_loader_config(arg_esp_path);
1322 if (q < 0 && r >= 0)
1323 r = q;
1324
1325 q = remove_entries_directory(arg_dollar_boot_path());
1326 if (q < 0 && r >= 0)
1327 r = q;
1328
1329 q = remove_esp_subdirs(arg_esp_path);
1330 if (q < 0 && r >= 0)
1331 r = q;
1332
1333 (void) sync_everything();
1334
1335 if (arg_touch_variables) {
1336 q = remove_variables(uuid, "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi", true);
1337 if (q < 0 && r >= 0)
1338 r = q;
1339 }
1340
1341 return r;
1342 }
1343
1344 static int verb_set_default(int argc, char *argv[], void *userdata) {
1345 const char *name;
1346 int r;
1347
1348 if (!is_efi_boot())
1349 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1350 "Not booted with UEFI.");
1351
1352 if (access("/sys/firmware/efi/efivars/LoaderInfo-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f", F_OK) < 0) {
1353 if (errno == ENOENT) {
1354 log_error_errno(errno, "Not booted with a supported boot loader.");
1355 return -EOPNOTSUPP;
1356 }
1357
1358 return log_error_errno(errno, "Failed to detect whether boot loader supports '%s' operation: %m", argv[0]);
1359 }
1360
1361 if (detect_container() > 0)
1362 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1363 "'%s' operation not supported in a container.",
1364 argv[0]);
1365
1366 if (!arg_touch_variables)
1367 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1368 "'%s' operation cannot be combined with --touch-variables=no.",
1369 argv[0]);
1370
1371 name = streq(argv[0], "set-default") ? "LoaderEntryDefault" : "LoaderEntryOneShot";
1372
1373 if (isempty(argv[1])) {
1374 r = efi_set_variable(EFI_VENDOR_LOADER, name, NULL, 0);
1375 if (r < 0 && r != -ENOENT)
1376 return log_error_errno(r, "Failed to remove EFI variale: %m");
1377 } else {
1378 _cleanup_free_ char16_t *encoded = NULL;
1379
1380 encoded = utf8_to_utf16(argv[1], strlen(argv[1]));
1381 if (!encoded)
1382 return log_oom();
1383
1384 r = efi_set_variable(EFI_VENDOR_LOADER, name, encoded, char16_strlen(encoded) * 2 + 2);
1385 if (r < 0)
1386 return log_error_errno(r, "Failed to update EFI variable: %m");
1387 }
1388
1389 return 0;
1390 }
1391
1392 static int bootctl_main(int argc, char *argv[]) {
1393
1394 static const Verb verbs[] = {
1395 { "help", VERB_ANY, VERB_ANY, 0, help },
1396 { "status", VERB_ANY, 1, VERB_DEFAULT, verb_status },
1397 { "install", VERB_ANY, 1, VERB_MUST_BE_ROOT, verb_install },
1398 { "update", VERB_ANY, 1, VERB_MUST_BE_ROOT, verb_install },
1399 { "remove", VERB_ANY, 1, VERB_MUST_BE_ROOT, verb_remove },
1400 { "list", VERB_ANY, 1, 0, verb_list },
1401 { "set-default", 2, 2, VERB_MUST_BE_ROOT, verb_set_default },
1402 { "set-oneshot", 2, 2, VERB_MUST_BE_ROOT, verb_set_default },
1403 {}
1404 };
1405
1406 return dispatch_verb(argc, argv, verbs, NULL);
1407 }
1408
1409 static int run(int argc, char *argv[]) {
1410 int r;
1411
1412 log_parse_environment();
1413 log_open();
1414
1415 /* If we run in a container, automatically turn off EFI file system access */
1416 if (detect_container() > 0)
1417 arg_touch_variables = false;
1418
1419 r = parse_argv(argc, argv);
1420 if (r <= 0)
1421 return r;
1422
1423 return bootctl_main(argc, argv);
1424 }
1425
1426 DEFINE_MAIN_FUNCTION(run);