]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/boot/bootctl.c
license: LGPL-2.1+ -> LGPL-2.1-or-later
[thirdparty/systemd.git] / src / boot / bootctl.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <ctype.h>
4 #include <errno.h>
5 #include <ftw.h>
6 #include <getopt.h>
7 #include <limits.h>
8 #include <linux/magic.h>
9 #include <stdbool.h>
10 #include <stdlib.h>
11 #include <sys/mman.h>
12 #include <unistd.h>
13
14 #include "sd-id128.h"
15
16 #include "alloc-util.h"
17 #include "blkid-util.h"
18 #include "bootspec.h"
19 #include "copy.h"
20 #include "dirent-util.h"
21 #include "efi-loader.h"
22 #include "efivars.h"
23 #include "env-util.h"
24 #include "escape.h"
25 #include "fd-util.h"
26 #include "fileio.h"
27 #include "fs-util.h"
28 #include "locale-util.h"
29 #include "main-func.h"
30 #include "mkdir.h"
31 #include "pager.h"
32 #include "parse-util.h"
33 #include "pretty-print.h"
34 #include "random-util.h"
35 #include "rm-rf.h"
36 #include "stat-util.h"
37 #include "stdio-util.h"
38 #include "string-util.h"
39 #include "strv.h"
40 #include "terminal-util.h"
41 #include "tmpfile-util.h"
42 #include "umask-util.h"
43 #include "utf8.h"
44 #include "util.h"
45 #include "verbs.h"
46 #include "virt.h"
47
48 static char *arg_esp_path = NULL;
49 static char *arg_xbootldr_path = NULL;
50 static bool arg_print_esp_path = false;
51 static bool arg_print_dollar_boot_path = false;
52 static bool arg_touch_variables = true;
53 static PagerFlags arg_pager_flags = 0;
54 static bool arg_graceful = false;
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 arg_xbootldr_path = mfree(arg_xbootldr_path);
104 return 0;
105 }
106 if (r < 0)
107 return r;
108
109 free_and_replace(arg_xbootldr_path, np);
110 log_debug("Using XBOOTLDR partition at %s as $BOOT.", arg_xbootldr_path);
111
112 return 1;
113 }
114
115 /* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */
116 static int get_file_version(int fd, char **v) {
117 struct stat st;
118 char *buf;
119 const char *s, *e;
120 char *x = NULL;
121 int r;
122
123 assert(fd >= 0);
124 assert(v);
125
126 if (fstat(fd, &st) < 0)
127 return log_error_errno(errno, "Failed to stat EFI binary: %m");
128
129 r = stat_verify_regular(&st);
130 if (r < 0)
131 return log_error_errno(r, "EFI binary is not a regular file: %m");
132
133 if (st.st_size < 27) {
134 *v = NULL;
135 return 0;
136 }
137
138 buf = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
139 if (buf == MAP_FAILED)
140 return log_error_errno(errno, "Failed to memory map EFI binary: %m");
141
142 s = memmem(buf, st.st_size - 8, "#### LoaderInfo: ", 17);
143 if (!s)
144 goto finish;
145 s += 17;
146
147 e = memmem(s, st.st_size - (s - buf), " ####", 5);
148 if (!e || e - s < 3) {
149 r = log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Malformed version string.");
150 goto finish;
151 }
152
153 x = strndup(s, e - s);
154 if (!x) {
155 r = log_oom();
156 goto finish;
157 }
158 r = 1;
159
160 finish:
161 (void) munmap(buf, st.st_size);
162 *v = x;
163 return r;
164 }
165
166 static int enumerate_binaries(const char *esp_path, const char *path, const char *prefix) {
167 _cleanup_closedir_ DIR *d = NULL;
168 struct dirent *de;
169 const char *p;
170 int c = 0, r;
171
172 assert(esp_path);
173 assert(path);
174
175 p = prefix_roota(esp_path, path);
176 d = opendir(p);
177 if (!d) {
178 if (errno == ENOENT)
179 return 0;
180
181 return log_error_errno(errno, "Failed to read \"%s\": %m", p);
182 }
183
184 FOREACH_DIRENT(de, d, break) {
185 _cleanup_free_ char *v = NULL;
186 _cleanup_close_ int fd = -1;
187
188 if (!endswith_no_case(de->d_name, ".efi"))
189 continue;
190
191 if (prefix && !startswith_no_case(de->d_name, prefix))
192 continue;
193
194 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
195 if (fd < 0)
196 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
197
198 r = get_file_version(fd, &v);
199 if (r < 0)
200 return r;
201 if (r > 0)
202 printf(" File: %s/%s/%s (%s%s%s)\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path, de->d_name, ansi_highlight(), v, ansi_normal());
203 else
204 printf(" File: %s/%s/%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path, de->d_name);
205
206 c++;
207 }
208
209 return c;
210 }
211
212 static int status_binaries(const char *esp_path, sd_id128_t partition) {
213 int r;
214
215 printf("Available Boot Loaders on ESP:\n");
216
217 if (!esp_path) {
218 printf(" ESP: Cannot find or access mount point of ESP.\n\n");
219 return -ENOENT;
220 }
221
222 printf(" ESP: %s", esp_path);
223 if (!sd_id128_is_null(partition))
224 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR ")", SD_ID128_FORMAT_VAL(partition));
225 printf("\n");
226
227 r = enumerate_binaries(esp_path, "EFI/systemd", NULL);
228 if (r < 0)
229 goto finish;
230 if (r == 0)
231 log_info("systemd-boot not installed in ESP.");
232
233 r = enumerate_binaries(esp_path, "EFI/BOOT", "boot");
234 if (r < 0)
235 goto finish;
236 if (r == 0)
237 log_info("No default/fallback boot loader installed in ESP.");
238
239 r = 0;
240
241 finish:
242 printf("\n");
243 return r;
244 }
245
246 static int print_efi_option(uint16_t id, bool in_order) {
247 _cleanup_free_ char *title = NULL;
248 _cleanup_free_ char *path = NULL;
249 sd_id128_t partition;
250 bool active;
251 int r;
252
253 r = efi_get_boot_option(id, &title, &partition, &path, &active);
254 if (r < 0)
255 return r;
256
257 /* print only configured entries with partition information */
258 if (!path || sd_id128_is_null(partition))
259 return 0;
260
261 efi_tilt_backslashes(path);
262
263 printf(" Title: %s%s%s\n", ansi_highlight(), strna(title), ansi_normal());
264 printf(" ID: 0x%04X\n", id);
265 printf(" Status: %sactive%s\n", active ? "" : "in", in_order ? ", boot-order" : "");
266 printf(" Partition: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR "\n",
267 SD_ID128_FORMAT_VAL(partition));
268 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path);
269 printf("\n");
270
271 return 0;
272 }
273
274 static int status_variables(void) {
275 _cleanup_free_ uint16_t *options = NULL, *order = NULL;
276 int n_options, n_order, i;
277
278 n_options = efi_get_boot_options(&options);
279 if (n_options == -ENOENT)
280 return log_error_errno(n_options,
281 "Failed to access EFI variables, efivarfs"
282 " needs to be available at /sys/firmware/efi/efivars/.");
283 if (n_options < 0)
284 return log_error_errno(n_options, "Failed to read EFI boot entries: %m");
285
286 n_order = efi_get_boot_order(&order);
287 if (n_order == -ENOENT)
288 n_order = 0;
289 else if (n_order < 0)
290 return log_error_errno(n_order, "Failed to read EFI boot order: %m");
291
292 /* print entries in BootOrder first */
293 printf("Boot Loaders Listed in EFI Variables:\n");
294 for (i = 0; i < n_order; i++)
295 print_efi_option(order[i], true);
296
297 /* print remaining entries */
298 for (i = 0; i < n_options; i++) {
299 int j;
300
301 for (j = 0; j < n_order; j++)
302 if (options[i] == order[j])
303 goto next_option;
304
305 print_efi_option(options[i], false);
306
307 next_option:
308 continue;
309 }
310
311 return 0;
312 }
313
314 static int boot_entry_file_check(const char *root, const char *p) {
315 _cleanup_free_ char *path;
316
317 path = path_join(root, p);
318 if (!path)
319 return log_oom();
320
321 if (access(path, F_OK) < 0)
322 return -errno;
323
324 return 0;
325 }
326
327 static void boot_entry_file_list(const char *field, const char *root, const char *p, int *ret_status) {
328 int status = boot_entry_file_check(root, p);
329
330 printf("%13s%s ", strempty(field), field ? ":" : " ");
331 if (status < 0) {
332 errno = -status;
333 printf("%s%s%s (%m)\n", ansi_highlight_red(), p, ansi_normal());
334 } else
335 printf("%s\n", p);
336
337 if (*ret_status == 0 && status < 0)
338 *ret_status = status;
339 }
340
341 static int boot_entry_show(const BootEntry *e, bool show_as_default) {
342 int status = 0;
343
344 /* Returns 0 on success, negative on processing error, and positive if something is wrong with the
345 boot entry itself. */
346
347 assert(e);
348
349 printf(" title: %s%s%s" "%s%s%s\n",
350 ansi_highlight(), boot_entry_title(e), ansi_normal(),
351 ansi_highlight_green(), show_as_default ? " (default)" : "", ansi_normal());
352
353 if (e->id)
354 printf(" id: %s\n", e->id);
355 if (e->path) {
356 _cleanup_free_ char *link = NULL;
357
358 /* Let's urlify the link to make it easy to view in an editor, but only if it is a text
359 * file. Unified images are binary ELFs, and EFI variables are not pure text either. */
360 if (e->type == BOOT_ENTRY_CONF)
361 (void) terminal_urlify_path(e->path, NULL, &link);
362
363 printf(" source: %s\n", link ?: e->path);
364 }
365 if (e->version)
366 printf(" version: %s\n", e->version);
367 if (e->machine_id)
368 printf(" machine-id: %s\n", e->machine_id);
369 if (e->architecture)
370 printf(" architecture: %s\n", e->architecture);
371 if (e->kernel)
372 boot_entry_file_list("linux", e->root, e->kernel, &status);
373
374 char **s;
375 STRV_FOREACH(s, e->initrd)
376 boot_entry_file_list(s == e->initrd ? "initrd" : NULL,
377 e->root,
378 *s,
379 &status);
380 if (!strv_isempty(e->options)) {
381 _cleanup_free_ char *t = NULL, *t2 = NULL;
382 _cleanup_strv_free_ char **ts = NULL;
383
384 t = strv_join(e->options, " ");
385 if (!t)
386 return log_oom();
387
388 ts = strv_split_newlines(t);
389 if (!ts)
390 return log_oom();
391
392 t2 = strv_join(ts, "\n ");
393 if (!t2)
394 return log_oom();
395
396 printf(" options: %s\n", t2);
397 }
398 if (e->device_tree)
399 boot_entry_file_list("devicetree", e->root, e->device_tree, &status);
400
401 return -status;
402 }
403
404 static int status_entries(
405 const char *esp_path,
406 sd_id128_t esp_partition_uuid,
407 const char *xbootldr_path,
408 sd_id128_t xbootldr_partition_uuid) {
409
410 _cleanup_(boot_config_free) BootConfig config = {};
411 sd_id128_t dollar_boot_partition_uuid;
412 const char *dollar_boot_path;
413 int r;
414
415 assert(esp_path || xbootldr_path);
416
417 if (xbootldr_path) {
418 dollar_boot_path = xbootldr_path;
419 dollar_boot_partition_uuid = xbootldr_partition_uuid;
420 } else {
421 dollar_boot_path = esp_path;
422 dollar_boot_partition_uuid = esp_partition_uuid;
423 }
424
425 printf("Boot Loader Entries:\n"
426 " $BOOT: %s", dollar_boot_path);
427 if (!sd_id128_is_null(dollar_boot_partition_uuid))
428 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR ")",
429 SD_ID128_FORMAT_VAL(dollar_boot_partition_uuid));
430 printf("\n\n");
431
432 r = boot_entries_load_config(esp_path, xbootldr_path, &config);
433 if (r < 0)
434 return r;
435
436 if (config.default_entry < 0)
437 printf("%zu entries, no entry could be determined as default.\n", config.n_entries);
438 else {
439 printf("Default Boot Loader Entry:\n");
440
441 r = boot_entry_show(config.entries + config.default_entry, false);
442 if (r > 0)
443 /* < 0 is already logged by the function itself, let's just emit an extra warning if
444 the default entry is broken */
445 printf("\nWARNING: default boot entry is broken\n");
446 }
447
448 return 0;
449 }
450
451 static int compare_product(const char *a, const char *b) {
452 size_t x, y;
453
454 assert(a);
455 assert(b);
456
457 x = strcspn(a, " ");
458 y = strcspn(b, " ");
459 if (x != y)
460 return x < y ? -1 : x > y ? 1 : 0;
461
462 return strncmp(a, b, x);
463 }
464
465 static int compare_version(const char *a, const char *b) {
466 assert(a);
467 assert(b);
468
469 a += strcspn(a, " ");
470 a += strspn(a, " ");
471 b += strcspn(b, " ");
472 b += strspn(b, " ");
473
474 return strverscmp(a, b);
475 }
476
477 static int version_check(int fd_from, const char *from, int fd_to, const char *to) {
478 _cleanup_free_ char *a = NULL, *b = NULL;
479 int r;
480
481 assert(fd_from >= 0);
482 assert(from);
483 assert(fd_to >= 0);
484 assert(to);
485
486 r = get_file_version(fd_from, &a);
487 if (r < 0)
488 return r;
489 if (r == 0)
490 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
491 "Source file \"%s\" does not carry version information!",
492 from);
493
494 r = get_file_version(fd_to, &b);
495 if (r < 0)
496 return r;
497 if (r == 0 || compare_product(a, b) != 0)
498 return log_notice_errno(SYNTHETIC_ERRNO(EEXIST),
499 "Skipping \"%s\", since it's owned by another boot loader.",
500 to);
501
502 if (compare_version(a, b) < 0)
503 return log_warning_errno(SYNTHETIC_ERRNO(ESTALE), "Skipping \"%s\", since a newer boot loader version exists already.", to);
504
505 return 0;
506 }
507
508 static int copy_file_with_version_check(const char *from, const char *to, bool force) {
509 _cleanup_close_ int fd_from = -1, fd_to = -1;
510 _cleanup_free_ char *t = NULL;
511 int r;
512
513 fd_from = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
514 if (fd_from < 0)
515 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", from);
516
517 if (!force) {
518 fd_to = open(to, O_RDONLY|O_CLOEXEC|O_NOCTTY);
519 if (fd_to < 0) {
520 if (errno != ENOENT)
521 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", to);
522 } else {
523 r = version_check(fd_from, from, fd_to, to);
524 if (r < 0)
525 return r;
526
527 if (lseek(fd_from, 0, SEEK_SET) == (off_t) -1)
528 return log_error_errno(errno, "Failed to seek in \"%s\": %m", from);
529
530 fd_to = safe_close(fd_to);
531 }
532 }
533
534 r = tempfn_random(to, NULL, &t);
535 if (r < 0)
536 return log_oom();
537
538 RUN_WITH_UMASK(0000) {
539 fd_to = open(t, O_WRONLY|O_CREAT|O_CLOEXEC|O_EXCL|O_NOFOLLOW, 0644);
540 if (fd_to < 0)
541 return log_error_errno(errno, "Failed to open \"%s\" for writing: %m", t);
542 }
543
544 r = copy_bytes(fd_from, fd_to, (uint64_t) -1, COPY_REFLINK);
545 if (r < 0) {
546 (void) unlink(t);
547 return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
548 }
549
550 (void) copy_times(fd_from, fd_to, 0);
551
552 if (fsync(fd_to) < 0) {
553 (void) unlink_noerrno(t);
554 return log_error_errno(errno, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
555 }
556
557 (void) fsync_directory_of_file(fd_to);
558
559 if (renameat(AT_FDCWD, t, AT_FDCWD, to) < 0) {
560 (void) unlink_noerrno(t);
561 return log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", t, to);
562 }
563
564 log_info("Copied \"%s\" to \"%s\".", from, to);
565
566 return 0;
567 }
568
569 static int mkdir_one(const char *prefix, const char *suffix) {
570 _cleanup_free_ char *p = NULL;
571
572 p = path_join(prefix, suffix);
573 if (mkdir(p, 0700) < 0) {
574 if (errno != EEXIST)
575 return log_error_errno(errno, "Failed to create \"%s\": %m", p);
576 } else
577 log_info("Created \"%s\".", p);
578
579 return 0;
580 }
581
582 static const char *const esp_subdirs[] = {
583 /* The directories to place in the ESP */
584 "EFI",
585 "EFI/systemd",
586 "EFI/BOOT",
587 "loader",
588 NULL
589 };
590
591 static const char *const dollar_boot_subdirs[] = {
592 /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
593 "loader",
594 "loader/entries", /* Type #1 entries */
595 "EFI",
596 "EFI/Linux", /* Type #2 entries */
597 NULL
598 };
599
600 static int create_subdirs(const char *root, const char * const *subdirs) {
601 const char *const *i;
602 int r;
603
604 STRV_FOREACH(i, subdirs) {
605 r = mkdir_one(root, *i);
606 if (r < 0)
607 return r;
608 }
609
610 return 0;
611 }
612
613 static int copy_one_file(const char *esp_path, const char *name, bool force) {
614 const char *e;
615 char *p, *q;
616 int r;
617
618 p = strjoina(BOOTLIBDIR "/", name);
619 q = strjoina(esp_path, "/EFI/systemd/", name);
620 r = copy_file_with_version_check(p, q, force);
621
622 e = startswith(name, "systemd-boot");
623 if (e) {
624 int k;
625 char *v;
626
627 /* Create the EFI default boot loader name (specified for removable devices) */
628 v = strjoina(esp_path, "/EFI/BOOT/BOOT", e);
629 ascii_strupper(strrchr(v, '/') + 1);
630
631 k = copy_file_with_version_check(p, v, force);
632 if (k < 0 && r == 0)
633 r = k;
634 }
635
636 return r;
637 }
638
639 static int install_binaries(const char *esp_path, bool force) {
640 struct dirent *de;
641 _cleanup_closedir_ DIR *d = NULL;
642 int r = 0;
643
644 d = opendir(BOOTLIBDIR);
645 if (!d)
646 return log_error_errno(errno, "Failed to open \""BOOTLIBDIR"\": %m");
647
648 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read \""BOOTLIBDIR"\": %m")) {
649 int k;
650
651 if (!endswith_no_case(de->d_name, ".efi"))
652 continue;
653
654 k = copy_one_file(esp_path, de->d_name, force);
655 if (k < 0 && r == 0)
656 r = k;
657 }
658
659 return r;
660 }
661
662 static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
663 _cleanup_free_ char *opath = NULL;
664 sd_id128_t ouuid;
665 int r;
666
667 r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
668 if (r < 0)
669 return false;
670 if (!sd_id128_equal(uuid, ouuid))
671 return false;
672 if (!streq_ptr(path, opath))
673 return false;
674
675 return true;
676 }
677
678 static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
679 _cleanup_free_ uint16_t *options = NULL;
680 int n, i;
681
682 n = efi_get_boot_options(&options);
683 if (n < 0)
684 return n;
685
686 /* find already existing systemd-boot entry */
687 for (i = 0; i < n; i++)
688 if (same_entry(options[i], uuid, path)) {
689 *id = options[i];
690 return 1;
691 }
692
693 /* find free slot in the sorted BootXXXX variable list */
694 for (i = 0; i < n; i++)
695 if (i != options[i]) {
696 *id = i;
697 return 1;
698 }
699
700 /* use the next one */
701 if (i == 0xffff)
702 return -ENOSPC;
703 *id = i;
704 return 0;
705 }
706
707 static int insert_into_order(uint16_t slot, bool first) {
708 _cleanup_free_ uint16_t *order = NULL;
709 uint16_t *t;
710 int n, i;
711
712 n = efi_get_boot_order(&order);
713 if (n <= 0)
714 /* no entry, add us */
715 return efi_set_boot_order(&slot, 1);
716
717 /* are we the first and only one? */
718 if (n == 1 && order[0] == slot)
719 return 0;
720
721 /* are we already in the boot order? */
722 for (i = 0; i < n; i++) {
723 if (order[i] != slot)
724 continue;
725
726 /* we do not require to be the first one, all is fine */
727 if (!first)
728 return 0;
729
730 /* move us to the first slot */
731 memmove(order + 1, order, i * sizeof(uint16_t));
732 order[0] = slot;
733 return efi_set_boot_order(order, n);
734 }
735
736 /* extend array */
737 t = reallocarray(order, n + 1, sizeof(uint16_t));
738 if (!t)
739 return -ENOMEM;
740 order = t;
741
742 /* add us to the top or end of the list */
743 if (first) {
744 memmove(order + 1, order, n * sizeof(uint16_t));
745 order[0] = slot;
746 } else
747 order[n] = slot;
748
749 return efi_set_boot_order(order, n + 1);
750 }
751
752 static int remove_from_order(uint16_t slot) {
753 _cleanup_free_ uint16_t *order = NULL;
754 int n, i;
755
756 n = efi_get_boot_order(&order);
757 if (n <= 0)
758 return n;
759
760 for (i = 0; i < n; i++) {
761 if (order[i] != slot)
762 continue;
763
764 if (i + 1 < n)
765 memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
766 return efi_set_boot_order(order, n - 1);
767 }
768
769 return 0;
770 }
771
772 static int install_variables(const char *esp_path,
773 uint32_t part, uint64_t pstart, uint64_t psize,
774 sd_id128_t uuid, const char *path,
775 bool first) {
776 const char *p;
777 uint16_t slot;
778 int r;
779
780 if (!is_efi_boot()) {
781 log_warning("Not booted with EFI, skipping EFI variable setup.");
782 return 0;
783 }
784
785 p = prefix_roota(esp_path, path);
786 if (access(p, F_OK) < 0) {
787 if (errno == ENOENT)
788 return 0;
789
790 return log_error_errno(errno, "Cannot access \"%s\": %m", p);
791 }
792
793 r = find_slot(uuid, path, &slot);
794 if (r < 0)
795 return log_error_errno(r,
796 r == -ENOENT ?
797 "Failed to access EFI variables. Is the \"efivarfs\" filesystem mounted?" :
798 "Failed to determine current boot order: %m");
799
800 if (first || r == 0) {
801 r = efi_add_boot_option(slot, "Linux Boot Manager",
802 part, pstart, psize,
803 uuid, path);
804 if (r < 0)
805 return log_error_errno(r, "Failed to create EFI Boot variable entry: %m");
806
807 log_info("Created EFI boot entry \"Linux Boot Manager\".");
808 }
809
810 return insert_into_order(slot, first);
811 }
812
813 static int remove_boot_efi(const char *esp_path) {
814 _cleanup_closedir_ DIR *d = NULL;
815 struct dirent *de;
816 const char *p;
817 int r, c = 0;
818
819 p = prefix_roota(esp_path, "/EFI/BOOT");
820 d = opendir(p);
821 if (!d) {
822 if (errno == ENOENT)
823 return 0;
824
825 return log_error_errno(errno, "Failed to open directory \"%s\": %m", p);
826 }
827
828 FOREACH_DIRENT(de, d, break) {
829 _cleanup_close_ int fd = -1;
830 _cleanup_free_ char *v = NULL;
831
832 if (!endswith_no_case(de->d_name, ".efi"))
833 continue;
834
835 if (!startswith_no_case(de->d_name, "boot"))
836 continue;
837
838 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
839 if (fd < 0)
840 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
841
842 r = get_file_version(fd, &v);
843 if (r < 0)
844 return r;
845 if (r > 0 && startswith(v, "systemd-boot ")) {
846 r = unlinkat(dirfd(d), de->d_name, 0);
847 if (r < 0)
848 return log_error_errno(errno, "Failed to remove \"%s/%s\": %m", p, de->d_name);
849
850 log_info("Removed \"%s/%s\".", p, de->d_name);
851 }
852
853 c++;
854 }
855
856 return c;
857 }
858
859 static int rmdir_one(const char *prefix, const char *suffix) {
860 const char *p;
861
862 p = prefix_roota(prefix, suffix);
863 if (rmdir(p) < 0) {
864 bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
865
866 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
867 "Failed to remove directory \"%s\": %m", p);
868 if (!ignore)
869 return -errno;
870 } else
871 log_info("Removed \"%s\".", p);
872
873 return 0;
874 }
875
876 static int remove_subdirs(const char *root, const char *const *subdirs) {
877 int r, q;
878
879 /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
880 * short the array is. */
881
882 if (!subdirs[0]) /* A the end of the list */
883 return 0;
884
885 r = remove_subdirs(root, subdirs + 1);
886 q = rmdir_one(root, subdirs[0]);
887
888 return r < 0 ? r : q;
889 }
890
891 static int remove_binaries(const char *esp_path) {
892 const char *p;
893 int r, q;
894
895 p = prefix_roota(esp_path, "/EFI/systemd");
896 r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
897
898 q = remove_boot_efi(esp_path);
899 if (q < 0 && r == 0)
900 r = q;
901
902 return r;
903 }
904
905 static int remove_file(const char *root, const char *file) {
906 const char *p;
907
908 assert(root);
909 assert(file);
910
911 p = prefix_roota(root, file);
912 if (unlink(p) < 0) {
913 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
914 "Failed to unlink file \"%s\": %m", p);
915
916 return errno == ENOENT ? 0 : -errno;
917 }
918
919 log_info("Removed \"%s\".", p);
920 return 1;
921 }
922
923 static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
924 uint16_t slot;
925 int r;
926
927 if (!is_efi_boot())
928 return 0;
929
930 r = find_slot(uuid, path, &slot);
931 if (r != 1)
932 return 0;
933
934 r = efi_remove_boot_option(slot);
935 if (r < 0)
936 return r;
937
938 if (in_order)
939 return remove_from_order(slot);
940
941 return 0;
942 }
943
944 static int remove_loader_variables(void) {
945 const char *p;
946 int r = 0;
947
948 /* Remove all persistent loader variables we define */
949
950 FOREACH_STRING(p,
951 "LoaderConfigTimeout",
952 "LoaderConfigTimeoutOneShot",
953 "LoaderEntryDefault",
954 "LoaderEntryOneShot",
955 "LoaderSystemToken") {
956
957 int q;
958
959 q = efi_set_variable(EFI_VENDOR_LOADER, p, NULL, 0);
960 if (q == -ENOENT)
961 continue;
962 if (q < 0) {
963 log_warning_errno(q, "Failed to remove %s variable: %m", p);
964 if (r >= 0)
965 r = q;
966 } else
967 log_info("Removed EFI variable %s.", p);
968 }
969
970 return r;
971 }
972
973 static int install_loader_config(const char *esp_path) {
974 _cleanup_(unlink_and_freep) char *t = NULL;
975 _cleanup_fclose_ FILE *f = NULL;
976 _cleanup_close_ int fd = -1;
977 const char *p;
978 int r;
979
980 p = prefix_roota(esp_path, "/loader/loader.conf");
981 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
982 return 0;
983
984 fd = open_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t);
985 if (fd < 0)
986 return log_error_errno(fd, "Failed to open \"%s\" for writing: %m", p);
987
988 f = take_fdopen(&fd, "w");
989 if (!f)
990 return log_oom();
991
992 fprintf(f, "#timeout 3\n"
993 "#console-mode keep\n");
994
995 r = fflush_sync_and_check(f);
996 if (r < 0)
997 return log_error_errno(r, "Failed to write \"%s\": %m", p);
998
999 r = link_tmpfile(fileno(f), t, p);
1000 if (r == -EEXIST)
1001 return 0; /* Silently skip creation if the file exists now (recheck) */
1002 if (r < 0)
1003 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1004
1005 t = mfree(t);
1006 return 1;
1007 }
1008
1009 static int help(int argc, char *argv[], void *userdata) {
1010 _cleanup_free_ char *link = NULL;
1011 int r;
1012
1013 r = terminal_urlify_man("bootctl", "1", &link);
1014 if (r < 0)
1015 return log_oom();
1016
1017 printf("%1$s [OPTIONS...] COMMAND ...\n"
1018 "\n%5$sControl EFI firmware boot settings and manage boot loader.%6$s\n"
1019 "\n%3$sGeneric EFI Firmware/Boot Loader Commands:%4$s\n"
1020 " status Show status of installed boot loader and EFI variables\n"
1021 " reboot-to-firmware [BOOL]\n"
1022 " Query or set reboot-to-firmware EFI flag\n"
1023 " systemd-efi-options [STRING]\n"
1024 " Query or set system options string in EFI variable\n"
1025 "\n%3$sBoot Loader Specification Commands:%4$s\n"
1026 " list List boot loader entries\n"
1027 " set-default ID Set default boot loader entry\n"
1028 " set-oneshot ID Set default boot loader entry, for next boot only\n"
1029 "\n%3$ssystemd-boot Commands:%4$s\n"
1030 " install Install systemd-boot to the ESP and EFI variables\n"
1031 " update Update systemd-boot in the ESP and EFI variables\n"
1032 " remove Remove systemd-boot from the ESP and EFI variables\n"
1033 " is-installed Test whether systemd-boot is installed in the ESP\n"
1034 " random-seed Initialize random seed in ESP and EFI variables\n"
1035 "\n%3$sOptions:%4$s\n"
1036 " -h --help Show this help\n"
1037 " --version Print version\n"
1038 " --esp-path=PATH Path to the EFI System Partition (ESP)\n"
1039 " --boot-path=PATH Path to the $BOOT partition\n"
1040 " -p --print-esp-path Print path to the EFI System Partition\n"
1041 " -x --print-boot-path Print path to the $BOOT partition\n"
1042 " --no-variables Don't touch EFI variables\n"
1043 " --no-pager Do not pipe output into a pager\n"
1044 " --graceful Don't fail when the ESP cannot be found or EFI\n"
1045 " variables cannot be written\n"
1046 "\nSee the %2$s for details.\n"
1047 , program_invocation_short_name
1048 , link
1049 , ansi_underline(), ansi_normal()
1050 , ansi_highlight(), ansi_normal()
1051 );
1052
1053 return 0;
1054 }
1055
1056 static int parse_argv(int argc, char *argv[]) {
1057 enum {
1058 ARG_ESP_PATH = 0x100,
1059 ARG_BOOT_PATH,
1060 ARG_VERSION,
1061 ARG_NO_VARIABLES,
1062 ARG_NO_PAGER,
1063 ARG_GRACEFUL,
1064 };
1065
1066 static const struct option options[] = {
1067 { "help", no_argument, NULL, 'h' },
1068 { "version", no_argument, NULL, ARG_VERSION },
1069 { "esp-path", required_argument, NULL, ARG_ESP_PATH },
1070 { "path", required_argument, NULL, ARG_ESP_PATH }, /* Compatibility alias */
1071 { "boot-path", required_argument, NULL, ARG_BOOT_PATH },
1072 { "print-esp-path", no_argument, NULL, 'p' },
1073 { "print-path", no_argument, NULL, 'p' }, /* Compatibility alias */
1074 { "print-boot-path", no_argument, NULL, 'x' },
1075 { "no-variables", no_argument, NULL, ARG_NO_VARIABLES },
1076 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1077 { "graceful", no_argument, NULL, ARG_GRACEFUL },
1078 {}
1079 };
1080
1081 int c, r;
1082
1083 assert(argc >= 0);
1084 assert(argv);
1085
1086 while ((c = getopt_long(argc, argv, "hpx", options, NULL)) >= 0)
1087 switch (c) {
1088
1089 case 'h':
1090 help(0, NULL, NULL);
1091 return 0;
1092
1093 case ARG_VERSION:
1094 return version();
1095
1096 case ARG_ESP_PATH:
1097 r = free_and_strdup(&arg_esp_path, optarg);
1098 if (r < 0)
1099 return log_oom();
1100 break;
1101
1102 case ARG_BOOT_PATH:
1103 r = free_and_strdup(&arg_xbootldr_path, optarg);
1104 if (r < 0)
1105 return log_oom();
1106 break;
1107
1108 case 'p':
1109 if (arg_print_dollar_boot_path)
1110 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1111 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1112 arg_print_esp_path = true;
1113 break;
1114
1115 case 'x':
1116 if (arg_print_esp_path)
1117 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1118 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1119 arg_print_dollar_boot_path = true;
1120 break;
1121
1122 case ARG_NO_VARIABLES:
1123 arg_touch_variables = false;
1124 break;
1125
1126 case ARG_NO_PAGER:
1127 arg_pager_flags |= PAGER_DISABLE;
1128 break;
1129
1130 case ARG_GRACEFUL:
1131 arg_graceful = true;
1132 break;
1133
1134 case '?':
1135 return -EINVAL;
1136
1137 default:
1138 assert_not_reached("Unknown option");
1139 }
1140
1141 return 1;
1142 }
1143
1144 static void read_loader_efi_var(const char *name, char **var) {
1145 int r;
1146
1147 r = efi_get_variable_string(EFI_VENDOR_LOADER, name, var);
1148 if (r < 0 && r != -ENOENT)
1149 log_warning_errno(r, "Failed to read EFI variable %s: %m", name);
1150 }
1151
1152 static void print_yes_no_line(bool first, bool good, const char *name) {
1153 printf("%s%s%s%s %s\n",
1154 first ? " Features: " : " ",
1155 good ? ansi_highlight_green() : ansi_highlight_red(),
1156 good ? special_glyph(SPECIAL_GLYPH_CHECK_MARK) : special_glyph(SPECIAL_GLYPH_CROSS_MARK),
1157 ansi_normal(),
1158 name);
1159 }
1160
1161 static int verb_status(int argc, char *argv[], void *userdata) {
1162 sd_id128_t esp_uuid = SD_ID128_NULL, xbootldr_uuid = SD_ID128_NULL;
1163 int r, k;
1164
1165 r = acquire_esp(geteuid() != 0, NULL, NULL, NULL, &esp_uuid);
1166 if (arg_print_esp_path) {
1167 if (r == -EACCES) /* If we couldn't acquire the ESP path, log about access errors (which is the only
1168 * error the find_esp_and_warn() won't log on its own) */
1169 return log_error_errno(r, "Failed to determine ESP location: %m");
1170 if (r < 0)
1171 return r;
1172
1173 puts(arg_esp_path);
1174 }
1175
1176 r = acquire_xbootldr(geteuid() != 0, &xbootldr_uuid);
1177 if (arg_print_dollar_boot_path) {
1178 if (r == -EACCES)
1179 return log_error_errno(r, "Failed to determine XBOOTLDR location: %m");
1180 if (r < 0)
1181 return r;
1182
1183 const char *path = arg_dollar_boot_path();
1184 if (!path)
1185 return log_error_errno(SYNTHETIC_ERRNO(EACCES), "Failed to determine XBOOTLDR location: %m");
1186
1187 puts(path);
1188 }
1189
1190 if (arg_print_esp_path || arg_print_dollar_boot_path)
1191 return 0;
1192
1193 r = 0; /* If we couldn't determine the path, then don't consider that a problem from here on, just show what we
1194 * can show */
1195
1196 (void) pager_open(arg_pager_flags);
1197
1198 if (is_efi_boot()) {
1199 static const struct {
1200 uint64_t flag;
1201 const char *name;
1202 } flags[] = {
1203 { EFI_LOADER_FEATURE_BOOT_COUNTING, "Boot counting" },
1204 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT, "Menu timeout control" },
1205 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT, "One-shot menu timeout control" },
1206 { EFI_LOADER_FEATURE_ENTRY_DEFAULT, "Default entry control" },
1207 { EFI_LOADER_FEATURE_ENTRY_ONESHOT, "One-shot entry control" },
1208 { EFI_LOADER_FEATURE_XBOOTLDR, "Support for XBOOTLDR partition" },
1209 { EFI_LOADER_FEATURE_RANDOM_SEED, "Support for passing random seed to OS" },
1210 };
1211
1212 _cleanup_free_ char *fw_type = NULL, *fw_info = NULL, *loader = NULL, *loader_path = NULL, *stub = NULL;
1213 sd_id128_t loader_part_uuid = SD_ID128_NULL;
1214 uint64_t loader_features = 0;
1215 size_t i;
1216
1217 read_loader_efi_var("LoaderFirmwareType", &fw_type);
1218 read_loader_efi_var("LoaderFirmwareInfo", &fw_info);
1219 read_loader_efi_var("LoaderInfo", &loader);
1220 read_loader_efi_var("StubInfo", &stub);
1221 read_loader_efi_var("LoaderImageIdentifier", &loader_path);
1222 (void) efi_loader_get_features(&loader_features);
1223
1224 if (loader_path)
1225 efi_tilt_backslashes(loader_path);
1226
1227 k = efi_loader_get_device_part_uuid(&loader_part_uuid);
1228 if (k < 0 && k != -ENOENT)
1229 r = log_warning_errno(k, "Failed to read EFI variable LoaderDevicePartUUID: %m");
1230
1231 printf("System:\n");
1232 printf(" Firmware: %s%s (%s)%s\n", ansi_highlight(), strna(fw_type), strna(fw_info), ansi_normal());
1233 printf(" Secure Boot: %sd\n", enable_disable(is_efi_secure_boot()));
1234 printf(" Setup Mode: %s\n", is_efi_secure_boot_setup_mode() ? "setup" : "user");
1235
1236 k = efi_get_reboot_to_firmware();
1237 if (k > 0)
1238 printf(" Boot into FW: %sactive%s\n", ansi_highlight_yellow(), ansi_normal());
1239 else if (k == 0)
1240 printf(" Boot into FW: supported\n");
1241 else if (k == -EOPNOTSUPP)
1242 printf(" Boot into FW: not supported\n");
1243 else {
1244 errno = -k;
1245 printf(" Boot into FW: %sfailed%s (%m)\n", ansi_highlight_red(), ansi_normal());
1246 }
1247 printf("\n");
1248
1249 printf("Current Boot Loader:\n");
1250 printf(" Product: %s%s%s\n", ansi_highlight(), strna(loader), ansi_normal());
1251
1252 for (i = 0; i < ELEMENTSOF(flags); i++)
1253 print_yes_no_line(i == 0, FLAGS_SET(loader_features, flags[i].flag), flags[i].name);
1254
1255 sd_id128_t bootloader_esp_uuid;
1256 bool have_bootloader_esp_uuid = efi_loader_get_device_part_uuid(&bootloader_esp_uuid) >= 0;
1257
1258 print_yes_no_line(false, have_bootloader_esp_uuid, "Boot loader sets ESP partition information");
1259 if (have_bootloader_esp_uuid && !sd_id128_equal(esp_uuid, bootloader_esp_uuid))
1260 printf("WARNING: The boot loader reports different ESP UUID then detected!\n");
1261
1262 if (stub)
1263 printf(" Stub: %s\n", stub);
1264 if (!sd_id128_is_null(loader_part_uuid))
1265 printf(" ESP: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR "\n",
1266 SD_ID128_FORMAT_VAL(loader_part_uuid));
1267 else
1268 printf(" ESP: n/a\n");
1269 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), strna(loader_path));
1270 printf("\n");
1271
1272 printf("Random Seed:\n");
1273 printf(" Passed to OS: %s\n", yes_no(access("/sys/firmware/efi/efivars/LoaderRandomSeed-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f", F_OK) >= 0));
1274 printf(" System Token: %s\n", access("/sys/firmware/efi/efivars/LoaderSystemToken-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f", F_OK) >= 0 ? "set" : "not set");
1275
1276 if (arg_esp_path) {
1277 _cleanup_free_ char *p = NULL;
1278
1279 p = path_join(arg_esp_path, "/loader/random-seed");
1280 if (!p)
1281 return log_oom();
1282
1283 printf(" Exists: %s\n", yes_no(access(p, F_OK) >= 0));
1284 }
1285
1286 printf("\n");
1287 } else
1288 printf("System:\n Not booted with EFI\n\n");
1289
1290 if (arg_esp_path) {
1291 k = status_binaries(arg_esp_path, esp_uuid);
1292 if (k < 0)
1293 r = k;
1294 }
1295
1296 if (is_efi_boot()) {
1297 k = status_variables();
1298 if (k < 0)
1299 r = k;
1300 }
1301
1302 if (arg_esp_path || arg_xbootldr_path) {
1303 k = status_entries(arg_esp_path, esp_uuid, arg_xbootldr_path, xbootldr_uuid);
1304 if (k < 0)
1305 r = k;
1306 }
1307
1308 return r;
1309 }
1310
1311 static int verb_list(int argc, char *argv[], void *userdata) {
1312 _cleanup_(boot_config_free) BootConfig config = {};
1313 _cleanup_strv_free_ char **efi_entries = NULL;
1314 int r;
1315
1316 /* If we lack privileges we invoke find_esp_and_warn() in "unprivileged mode" here, which does two things: turn
1317 * off logging about access errors and turn off potentially privileged device probing. Here we're interested in
1318 * the latter but not the former, hence request the mode, and log about EACCES. */
1319
1320 r = acquire_esp(geteuid() != 0, NULL, NULL, NULL, NULL);
1321 if (r == -EACCES) /* We really need the ESP path for this call, hence also log about access errors */
1322 return log_error_errno(r, "Failed to determine ESP: %m");
1323 if (r < 0)
1324 return r;
1325
1326 r = acquire_xbootldr(geteuid() != 0, NULL);
1327 if (r == -EACCES)
1328 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1329 if (r < 0)
1330 return r;
1331
1332 r = boot_entries_load_config(arg_esp_path, arg_xbootldr_path, &config);
1333 if (r < 0)
1334 return r;
1335
1336 r = efi_loader_get_entries(&efi_entries);
1337 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
1338 log_debug_errno(r, "Boot loader reported no entries.");
1339 else if (r < 0)
1340 log_warning_errno(r, "Failed to determine entries reported by boot loader, ignoring: %m");
1341 else
1342 (void) boot_entries_augment_from_loader(&config, efi_entries, false);
1343
1344 if (config.n_entries == 0)
1345 log_info("No boot loader entries found.");
1346 else {
1347 size_t n;
1348
1349 (void) pager_open(arg_pager_flags);
1350
1351 printf("Boot Loader Entries:\n");
1352
1353 for (n = 0; n < config.n_entries; n++) {
1354 r = boot_entry_show(config.entries + n, n == (size_t) config.default_entry);
1355 if (r < 0)
1356 return r;
1357
1358 if (n+1 < config.n_entries)
1359 putchar('\n');
1360 }
1361 }
1362
1363 return 0;
1364 }
1365
1366 static int install_random_seed(const char *esp) {
1367 _cleanup_(unlink_and_freep) char *tmp = NULL;
1368 _cleanup_free_ void *buffer = NULL;
1369 _cleanup_free_ char *path = NULL;
1370 _cleanup_close_ int fd = -1;
1371 size_t sz, token_size;
1372 ssize_t n;
1373 int r;
1374
1375 assert(esp);
1376
1377 path = path_join(esp, "/loader/random-seed");
1378 if (!path)
1379 return log_oom();
1380
1381 sz = random_pool_size();
1382
1383 buffer = malloc(sz);
1384 if (!buffer)
1385 return log_oom();
1386
1387 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1388 if (r < 0)
1389 return log_error_errno(r, "Failed to acquire random seed: %m");
1390
1391 /* Normally create_subdirs() should already have created everything we need, but in case "bootctl
1392 * random-seed" is called we want to just create the minimum we need for it, and not the full
1393 * list. */
1394 r = mkdir_parents(path, 0755);
1395 if (r < 0)
1396 return log_error_errno(r, "Failed to create parent directory for %s: %m", path);
1397
1398 r = tempfn_random(path, "bootctl", &tmp);
1399 if (r < 0)
1400 return log_oom();
1401
1402 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|O_WRONLY|O_CLOEXEC, 0600);
1403 if (fd < 0) {
1404 tmp = mfree(tmp);
1405 return log_error_errno(fd, "Failed to open random seed file for writing: %m");
1406 }
1407
1408 n = write(fd, buffer, sz);
1409 if (n < 0)
1410 return log_error_errno(errno, "Failed to write random seed file: %m");
1411 if ((size_t) n != sz)
1412 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while writing random seed file.");
1413
1414 if (rename(tmp, path) < 0)
1415 return log_error_errno(r, "Failed to move random seed file into place: %m");
1416
1417 tmp = mfree(tmp);
1418
1419 log_info("Random seed file %s successfully written (%zu bytes).", path, sz);
1420
1421 if (!arg_touch_variables)
1422 return 0;
1423
1424 if (!is_efi_boot()) {
1425 log_notice("Not booted with EFI, skipping EFI variable setup.");
1426 return 0;
1427 }
1428
1429 r = getenv_bool("SYSTEMD_WRITE_SYSTEM_TOKEN");
1430 if (r < 0) {
1431 if (r != -ENXIO)
1432 log_warning_errno(r, "Failed to parse $SYSTEMD_WRITE_SYSTEM_TOKEN, ignoring.");
1433
1434 if (detect_vm() > 0) {
1435 /* Let's not write a system token if we detect we are running in a VM
1436 * environment. Why? Our default security model for the random seed uses the system
1437 * token as a mechanism to ensure we are not vulnerable to golden master sloppiness
1438 * issues, i.e. that people initialize the random seed file, then copy the image to
1439 * many systems and end up with the same random seed in each that is assumed to be
1440 * valid but in reality is the same for all machines. By storing a system token in
1441 * the EFI variable space we can make sure that even though the random seeds on disk
1442 * are all the same they will be different on each system under the assumption that
1443 * the EFI variable space is maintained separate from the random seed storage. That
1444 * is generally the case on physical systems, as the ESP is stored on persistent
1445 * storage, and the EFI variables in NVRAM. However in virtualized environments this
1446 * is generally not true: the EFI variable set is typically stored along with the
1447 * disk image itself. For example, using the OVMF EFI firmware the EFI variables are
1448 * stored in a file in the ESP itself. */
1449
1450 log_notice("Not installing system token, since we are running in a virtualized environment.");
1451 return 0;
1452 }
1453 } else if (r == 0) {
1454 log_notice("Not writing system token, because $SYSTEMD_WRITE_SYSTEM_TOKEN is set to false.");
1455 return 0;
1456 }
1457
1458 r = efi_get_variable(EFI_VENDOR_LOADER, "LoaderSystemToken", NULL, NULL, &token_size);
1459 if (r == -ENODATA)
1460 log_debug_errno(r, "LoaderSystemToken EFI variable is invalid (too short?), replacing.");
1461 else if (r < 0) {
1462 if (r != -ENOENT)
1463 return log_error_errno(r, "Failed to test system token validity: %m");
1464 } else {
1465 if (token_size >= sz) {
1466 /* Let's avoid writes if we can, and initialize this only once. */
1467 log_debug("System token already written, not updating.");
1468 return 0;
1469 }
1470
1471 log_debug("Existing system token size (%zu) does not match our expectations (%zu), replacing.", token_size, sz);
1472 }
1473
1474 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1475 if (r < 0)
1476 return log_error_errno(r, "Failed to acquire random seed: %m");
1477
1478 /* Let's write this variable with an umask in effect, so that unprivileged users can't see the token
1479 * and possibly get identification information or too much insight into the kernel's entropy pool
1480 * state. */
1481 RUN_WITH_UMASK(0077) {
1482 r = efi_set_variable(EFI_VENDOR_LOADER, "LoaderSystemToken", buffer, sz);
1483 if (r < 0) {
1484 if (!arg_graceful)
1485 return log_error_errno(r, "Failed to write 'LoaderSystemToken' EFI variable: %m");
1486
1487 if (r == -EINVAL)
1488 log_warning_errno(r, "Unable to write 'LoaderSystemToken' EFI variable (firmware problem?), ignoring: %m");
1489 else
1490 log_warning_errno(r, "Unable to write 'LoaderSystemToken' EFI variable, ignoring: %m");
1491 } else
1492 log_info("Successfully initialized system token in EFI variable with %zu bytes.", sz);
1493 }
1494
1495 return 0;
1496 }
1497
1498 static int sync_everything(void) {
1499 int ret = 0, k;
1500
1501 if (arg_esp_path) {
1502 k = syncfs_path(AT_FDCWD, arg_esp_path);
1503 if (k < 0)
1504 ret = log_error_errno(k, "Failed to synchronize the ESP '%s': %m", arg_esp_path);
1505 }
1506
1507 if (arg_xbootldr_path) {
1508 k = syncfs_path(AT_FDCWD, arg_xbootldr_path);
1509 if (k < 0)
1510 ret = log_error_errno(k, "Failed to synchronize $BOOT '%s': %m", arg_xbootldr_path);
1511 }
1512
1513 return ret;
1514 }
1515
1516 static int verb_install(int argc, char *argv[], void *userdata) {
1517 sd_id128_t uuid = SD_ID128_NULL;
1518 uint64_t pstart = 0, psize = 0;
1519 uint32_t part = 0;
1520 bool install;
1521 int r;
1522
1523 r = acquire_esp(false, &part, &pstart, &psize, &uuid);
1524 if (r < 0)
1525 return r;
1526
1527 r = acquire_xbootldr(false, NULL);
1528 if (r < 0)
1529 return r;
1530
1531 install = streq(argv[0], "install");
1532
1533 RUN_WITH_UMASK(0002) {
1534 if (install) {
1535 /* Don't create any of these directories when we are just updating. When we update
1536 * we'll drop-in our files (unless there are newer ones already), but we won't create
1537 * the directories for them in the first place. */
1538 r = create_subdirs(arg_esp_path, esp_subdirs);
1539 if (r < 0)
1540 return r;
1541
1542 r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
1543 if (r < 0)
1544 return r;
1545 }
1546
1547 r = install_binaries(arg_esp_path, install);
1548 if (r < 0)
1549 return r;
1550
1551 if (install) {
1552 r = install_loader_config(arg_esp_path);
1553 if (r < 0)
1554 return r;
1555
1556 r = install_random_seed(arg_esp_path);
1557 if (r < 0)
1558 return r;
1559 }
1560 }
1561
1562 (void) sync_everything();
1563
1564 if (arg_touch_variables)
1565 r = install_variables(arg_esp_path,
1566 part, pstart, psize, uuid,
1567 "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi",
1568 install);
1569
1570 return r;
1571 }
1572
1573 static int verb_remove(int argc, char *argv[], void *userdata) {
1574 sd_id128_t uuid = SD_ID128_NULL;
1575 int r, q;
1576
1577 r = acquire_esp(false, NULL, NULL, NULL, &uuid);
1578 if (r < 0)
1579 return r;
1580
1581 r = acquire_xbootldr(false, NULL);
1582 if (r < 0)
1583 return r;
1584
1585 r = remove_binaries(arg_esp_path);
1586
1587 q = remove_file(arg_esp_path, "/loader/loader.conf");
1588 if (q < 0 && r >= 0)
1589 r = q;
1590
1591 q = remove_file(arg_esp_path, "/loader/random-seed");
1592 if (q < 0 && r >= 0)
1593 r = q;
1594
1595 q = remove_subdirs(arg_esp_path, esp_subdirs);
1596 if (q < 0 && r >= 0)
1597 r = q;
1598
1599 q = remove_subdirs(arg_esp_path, dollar_boot_subdirs);
1600 if (q < 0 && r >= 0)
1601 r = q;
1602
1603 if (arg_xbootldr_path) {
1604 /* Remove the latter two also in the XBOOTLDR partition if it exists */
1605 q = remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs);
1606 if (q < 0 && r >= 0)
1607 r = q;
1608 }
1609
1610 (void) sync_everything();
1611
1612 if (!arg_touch_variables)
1613 return r;
1614
1615 q = remove_variables(uuid, "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi", true);
1616 if (q < 0 && r >= 0)
1617 r = q;
1618
1619 q = remove_loader_variables();
1620 if (q < 0 && r >= 0)
1621 r = q;
1622
1623 return r;
1624 }
1625
1626 static int verb_is_installed(int argc, char *argv[], void *userdata) {
1627 _cleanup_free_ char *p = NULL;
1628 int r;
1629
1630 r = acquire_esp(false, NULL, NULL, NULL, NULL);
1631 if (r < 0)
1632 return r;
1633
1634 /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
1635 * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
1636 * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
1637 * should be a suitable and very minimal check for a number of reasons:
1638 *
1639 * → The check is architecture independent (i.e. we check if any systemd-boot loader is installed, not a
1640 * specific one.)
1641 *
1642 * → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
1643 * /EFI/BOOT/BOOT*.EFI fallback binary.
1644 *
1645 * → It specifically checks for systemd-boot, not for other boot loaders (which a check for
1646 * /boot/loader/entries would do). */
1647
1648 p = path_join(arg_esp_path, "/EFI/systemd/");
1649 if (!p)
1650 return log_oom();
1651
1652 r = dir_is_empty(p);
1653 if (r > 0 || r == -ENOENT) {
1654 puts("no");
1655 return EXIT_FAILURE;
1656 }
1657 if (r < 0)
1658 return log_error_errno(r, "Failed to detect whether systemd-boot is installed: %m");
1659
1660 puts("yes");
1661 return EXIT_SUCCESS;
1662 }
1663
1664 static int parse_loader_entry_target_arg(const char *arg1, char16_t **ret_target, size_t *ret_target_size) {
1665 int r;
1666 if (streq(arg1, "@current")) {
1667 r = efi_get_variable(EFI_VENDOR_LOADER, "LoaderEntrySelected", NULL, (void *) ret_target, ret_target_size);
1668 if (r < 0)
1669 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntrySelected': %m");
1670 } else if (streq(arg1, "@oneshot")) {
1671 r = efi_get_variable(EFI_VENDOR_LOADER, "LoaderEntryOneShot", NULL, (void *) ret_target, ret_target_size);
1672 if (r < 0)
1673 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryOneShot': %m");
1674 } else if (streq(arg1, "@default")) {
1675 r = efi_get_variable(EFI_VENDOR_LOADER, "LoaderEntryDefault", NULL, (void *) ret_target, ret_target_size);
1676 if (r < 0)
1677 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryDefault': %m");
1678 } else {
1679 char16_t *encoded = NULL;
1680 encoded = utf8_to_utf16(arg1, strlen(arg1));
1681 if (!encoded)
1682 return log_oom();
1683 *ret_target = encoded;
1684 *ret_target_size = char16_strlen(encoded) * 2 + 2;
1685 }
1686 return 0;
1687 }
1688
1689 static int verb_set_default(int argc, char *argv[], void *userdata) {
1690 const char *name;
1691 int r;
1692
1693 if (!is_efi_boot())
1694 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1695 "Not booted with UEFI.");
1696
1697 if (access("/sys/firmware/efi/efivars/LoaderInfo-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f", F_OK) < 0) {
1698 if (errno == ENOENT) {
1699 log_error_errno(errno, "Not booted with a supported boot loader.");
1700 return -EOPNOTSUPP;
1701 }
1702
1703 return log_error_errno(errno, "Failed to detect whether boot loader supports '%s' operation: %m", argv[0]);
1704 }
1705
1706 if (detect_container() > 0)
1707 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1708 "'%s' operation not supported in a container.",
1709 argv[0]);
1710
1711 if (!arg_touch_variables)
1712 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1713 "'%s' operation cannot be combined with --touch-variables=no.",
1714 argv[0]);
1715
1716 name = streq(argv[0], "set-default") ? "LoaderEntryDefault" : "LoaderEntryOneShot";
1717
1718 if (isempty(argv[1])) {
1719 r = efi_set_variable(EFI_VENDOR_LOADER, name, NULL, 0);
1720 if (r < 0 && r != -ENOENT)
1721 return log_error_errno(r, "Failed to remove EFI variable '%s': %m", name);
1722 } else {
1723 _cleanup_free_ char16_t *target = NULL;
1724 size_t target_size = 0;
1725
1726 r = parse_loader_entry_target_arg(argv[1], &target, &target_size);
1727 if (r < 0)
1728 return r;
1729 r = efi_set_variable(EFI_VENDOR_LOADER, name, target, target_size);
1730 if (r < 0)
1731 return log_error_errno(r, "Failed to update EFI variable '%s': %m", name);
1732 }
1733
1734 return 0;
1735 }
1736
1737 static int verb_random_seed(int argc, char *argv[], void *userdata) {
1738 int r;
1739
1740 r = find_esp_and_warn(arg_esp_path, false, &arg_esp_path, NULL, NULL, NULL, NULL);
1741 if (r == -ENOKEY) {
1742 /* find_esp_and_warn() doesn't warn about ENOKEY, so let's do that on our own */
1743 if (!arg_graceful)
1744 return log_error_errno(r, "Unable to find ESP.");
1745
1746 log_notice("No ESP found, not initializing random seed.");
1747 return 0;
1748 }
1749 if (r < 0)
1750 return r;
1751
1752 r = install_random_seed(arg_esp_path);
1753 if (r < 0)
1754 return r;
1755
1756 (void) sync_everything();
1757 return 0;
1758 }
1759
1760 static int verb_systemd_efi_options(int argc, char *argv[], void *userdata) {
1761 int r;
1762
1763 if (argc == 1) {
1764 _cleanup_free_ char *line = NULL;
1765
1766 r = systemd_efi_options_variable(&line);
1767 if (r < 0)
1768 return log_error_errno(r, "Failed to query SystemdOptions EFI variable: %m");
1769
1770 puts(line);
1771
1772 } else {
1773 r = efi_set_variable_string(EFI_VENDOR_SYSTEMD, "SystemdOptions", argv[1]);
1774 if (r < 0)
1775 return log_error_errno(r, "Failed to set SystemdOptions EFI variable: %m");
1776 }
1777
1778 return 0;
1779 }
1780
1781 static int verb_reboot_to_firmware(int argc, char *argv[], void *userdata) {
1782 int r;
1783
1784 if (argc < 2) {
1785 r = efi_get_reboot_to_firmware();
1786 if (r > 0) {
1787 puts("active");
1788 return EXIT_SUCCESS; /* success */
1789 }
1790 if (r == 0) {
1791 puts("supported");
1792 return 1; /* recognizable error #1 */
1793 }
1794 if (r == -EOPNOTSUPP) {
1795 puts("not supported");
1796 return 2; /* recognizable error #2 */
1797 }
1798
1799 log_error_errno(r, "Failed to query reboot-to-firmware state: %m");
1800 return 3; /* other kind of error */
1801 } else {
1802 r = parse_boolean(argv[1]);
1803 if (r < 0)
1804 return log_error_errno(r, "Failed to parse argument: %s", argv[1]);
1805
1806 r = efi_set_reboot_to_firmware(r);
1807 if (r < 0)
1808 return log_error_errno(r, "Failed to set reboot-to-firmware option: %m");
1809
1810 return 0;
1811 }
1812 }
1813
1814 static int bootctl_main(int argc, char *argv[]) {
1815 static const Verb verbs[] = {
1816 { "help", VERB_ANY, VERB_ANY, 0, help },
1817 { "status", VERB_ANY, 1, VERB_DEFAULT, verb_status },
1818 { "install", VERB_ANY, 1, 0, verb_install },
1819 { "update", VERB_ANY, 1, 0, verb_install },
1820 { "remove", VERB_ANY, 1, 0, verb_remove },
1821 { "is-installed", VERB_ANY, 1, 0, verb_is_installed },
1822 { "list", VERB_ANY, 1, 0, verb_list },
1823 { "set-default", 2, 2, 0, verb_set_default },
1824 { "set-oneshot", 2, 2, 0, verb_set_default },
1825 { "random-seed", VERB_ANY, 1, 0, verb_random_seed },
1826 { "systemd-efi-options", VERB_ANY, 2, 0, verb_systemd_efi_options },
1827 { "reboot-to-firmware", VERB_ANY, 2, 0, verb_reboot_to_firmware },
1828 {}
1829 };
1830
1831 return dispatch_verb(argc, argv, verbs, NULL);
1832 }
1833
1834 static int run(int argc, char *argv[]) {
1835 int r;
1836
1837 log_parse_environment();
1838 log_open();
1839
1840 /* If we run in a container, automatically turn off EFI file system access */
1841 if (detect_container() > 0)
1842 arg_touch_variables = false;
1843
1844 r = parse_argv(argc, argv);
1845 if (r <= 0)
1846 return r;
1847
1848 return bootctl_main(argc, argv);
1849 }
1850
1851 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);