1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include <linux/magic.h>
15 #include "alloc-util.h"
16 #include "blkid-util.h"
19 #include "dirent-util.h"
20 #include "efi-loader.h"
29 #include "glyph-util.h"
30 #include "main-func.h"
34 #include "parse-argument.h"
35 #include "parse-util.h"
36 #include "pretty-print.h"
37 #include "random-util.h"
39 #include "stat-util.h"
40 #include "stdio-util.h"
41 #include "string-table.h"
42 #include "string-util.h"
44 #include "sync-util.h"
45 #include "terminal-util.h"
46 #include "tmpfile-util.h"
47 #include "tmpfile-util-label.h"
48 #include "umask-util.h"
54 static char *arg_esp_path
= NULL
;
55 static char *arg_xbootldr_path
= NULL
;
56 static bool arg_print_esp_path
= false;
57 static bool arg_print_dollar_boot_path
= false;
58 static bool arg_touch_variables
= true;
59 static PagerFlags arg_pager_flags
= 0;
60 static bool arg_graceful
= false;
61 static int arg_make_entry_directory
= false; /* tri-state: < 0 for automatic logic */
62 static sd_id128_t arg_machine_id
= SD_ID128_NULL
;
63 static char *arg_install_layout
= NULL
;
65 ARG_ENTRY_TOKEN_MACHINE_ID
,
66 ARG_ENTRY_TOKEN_OS_IMAGE_ID
,
67 ARG_ENTRY_TOKEN_OS_ID
,
68 ARG_ENTRY_TOKEN_LITERAL
,
70 } arg_entry_token_type
= ARG_ENTRY_TOKEN_AUTO
;
71 static char *arg_entry_token
= NULL
;
73 STATIC_DESTRUCTOR_REGISTER(arg_esp_path
, freep
);
74 STATIC_DESTRUCTOR_REGISTER(arg_xbootldr_path
, freep
);
75 STATIC_DESTRUCTOR_REGISTER(arg_install_layout
, freep
);
76 STATIC_DESTRUCTOR_REGISTER(arg_entry_token
, freep
);
78 static const char *arg_dollar_boot_path(void) {
79 /* $BOOT shall be the XBOOTLDR partition if it exists, and otherwise the ESP */
80 return arg_xbootldr_path
?: arg_esp_path
;
83 static int acquire_esp(
84 bool unprivileged_mode
,
95 /* Find the ESP, and log about errors. Note that find_esp_and_warn() will log in all error cases on
96 * its own, except for ENOKEY (which is good, we want to show our own message in that case,
97 * suggesting use of --esp-path=) and EACCESS (only when we request unprivileged mode; in this case
98 * we simply eat up the error here, so that --list and --status work too, without noise about
101 r
= find_esp_and_warn(arg_esp_path
, unprivileged_mode
, &np
, ret_part
, ret_pstart
, ret_psize
, ret_uuid
, ret_devid
);
104 return log_info_errno(r
, "Couldn't find EFI system partition, skipping.");
106 return log_error_errno(r
,
107 "Couldn't find EFI system partition. It is recommended to mount it to /boot or /efi.\n"
108 "Alternatively, use --esp-path= to specify path to mount point.");
113 free_and_replace(arg_esp_path
, np
);
114 log_debug("Using EFI System Partition at %s.", arg_esp_path
);
119 static int acquire_xbootldr(
120 bool unprivileged_mode
,
121 sd_id128_t
*ret_uuid
,
127 r
= find_xbootldr_and_warn(arg_xbootldr_path
, unprivileged_mode
, &np
, ret_uuid
, ret_devid
);
129 log_debug_errno(r
, "Didn't find an XBOOTLDR partition, using the ESP as $BOOT.");
130 arg_xbootldr_path
= mfree(arg_xbootldr_path
);
133 *ret_uuid
= SD_ID128_NULL
;
141 free_and_replace(arg_xbootldr_path
, np
);
142 log_debug("Using XBOOTLDR partition at %s as $BOOT.", arg_xbootldr_path
);
147 static int load_install_machine_id_and_layout(void) {
148 /* Figure out the right machine-id for operations. If KERNEL_INSTALL_MACHINE_ID is configured in
149 * /etc/machine-info, let's use that. Otherwise, just use the real machine-id.
151 * Also load KERNEL_INSTALL_LAYOUT.
153 _cleanup_free_
char *s
= NULL
, *layout
= NULL
;
156 r
= parse_env_file(NULL
, "/etc/machine-info",
157 "KERNEL_INSTALL_LAYOUT", &layout
,
158 "KERNEL_INSTALL_MACHINE_ID", &s
);
159 if (r
< 0 && r
!= -ENOENT
)
160 return log_error_errno(r
, "Failed to parse /etc/machine-info: %m");
163 r
= sd_id128_get_machine(&arg_machine_id
);
164 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENOMEDIUM
))
165 return log_error_errno(r
, "Failed to get machine-id: %m");
167 r
= sd_id128_from_string(s
, &arg_machine_id
);
169 return log_error_errno(r
, "Failed to parse KERNEL_INSTALL_MACHINE_ID=%s in /etc/machine-info: %m", s
);
172 log_debug("Using KERNEL_INSTALL_MACHINE_ID=%s from %s.",
173 SD_ID128_TO_STRING(arg_machine_id
),
174 isempty(s
) ? "/etc/machine_id" : "KERNEL_INSTALL_MACHINE_ID in /etc/machine-info");
176 if (!isempty(layout
)) {
177 log_debug("KERNEL_INSTALL_LAYOUT=%s is specified in /etc/machine-info.", layout
);
178 arg_install_layout
= TAKE_PTR(layout
);
184 static int settle_entry_token(void) {
187 switch (arg_entry_token_type
) {
189 case ARG_ENTRY_TOKEN_AUTO
: {
190 _cleanup_free_
char *buf
= NULL
;
191 r
= read_one_line_file("/etc/kernel/entry-token", &buf
);
192 if (r
< 0 && r
!= -ENOENT
)
193 return log_error_errno(r
, "Failed to read /etc/kernel/entry-token: %m");
196 free_and_replace(arg_entry_token
, buf
);
197 arg_entry_token_type
= ARG_ENTRY_TOKEN_LITERAL
;
198 } else if (sd_id128_is_null(arg_machine_id
)) {
199 _cleanup_free_
char *id
= NULL
, *image_id
= NULL
;
201 r
= parse_os_release(NULL
,
202 "IMAGE_ID", &image_id
,
205 return log_error_errno(r
, "Failed to load /etc/os-release: %m");
207 if (!isempty(image_id
)) {
208 free_and_replace(arg_entry_token
, image_id
);
209 arg_entry_token_type
= ARG_ENTRY_TOKEN_OS_IMAGE_ID
;
210 } else if (!isempty(id
)) {
211 free_and_replace(arg_entry_token
, id
);
212 arg_entry_token_type
= ARG_ENTRY_TOKEN_OS_ID
;
214 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No machine ID set, and /etc/os-release carries no ID=/IMAGE_ID= fields.");
216 r
= free_and_strdup_warn(&arg_entry_token
, SD_ID128_TO_STRING(arg_machine_id
));
220 arg_entry_token_type
= ARG_ENTRY_TOKEN_MACHINE_ID
;
226 case ARG_ENTRY_TOKEN_MACHINE_ID
:
227 if (sd_id128_is_null(arg_machine_id
))
228 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No machine ID set.");
230 r
= free_and_strdup_warn(&arg_entry_token
, SD_ID128_TO_STRING(arg_machine_id
));
236 case ARG_ENTRY_TOKEN_OS_IMAGE_ID
: {
237 _cleanup_free_
char *buf
= NULL
;
239 r
= parse_os_release(NULL
, "IMAGE_ID", &buf
);
241 return log_error_errno(r
, "Failed to load /etc/os-release: %m");
244 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "IMAGE_ID= field not set in /etc/os-release.");
246 free_and_replace(arg_entry_token
, buf
);
250 case ARG_ENTRY_TOKEN_OS_ID
: {
251 _cleanup_free_
char *buf
= NULL
;
253 r
= parse_os_release(NULL
, "ID", &buf
);
255 return log_error_errno(r
, "Failed to load /etc/os-release: %m");
258 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "ID= field not set in /etc/os-release.");
260 free_and_replace(arg_entry_token
, buf
);
264 case ARG_ENTRY_TOKEN_LITERAL
:
265 assert(!isempty(arg_entry_token
)); /* already filled in by command line parser */
269 if (isempty(arg_entry_token
) || !string_is_safe(arg_entry_token
))
270 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Selected entry token not valid: %s", arg_entry_token
);
272 log_debug("Using entry token: %s", arg_entry_token
);
276 static bool use_boot_loader_spec_type1(void) {
277 /* If the layout is not specified, or if it is set explicitly to "bls" we assume Boot Loader
278 * Specification Type #1 is the chosen format for our boot loader entries */
279 return !arg_install_layout
|| streq(arg_install_layout
, "bls");
282 static int settle_make_entry_directory(void) {
285 r
= load_install_machine_id_and_layout();
289 r
= settle_entry_token();
293 bool layout_type1
= use_boot_loader_spec_type1();
294 if (arg_make_entry_directory
< 0) { /* Automatic mode */
296 if (arg_entry_token
== ARG_ENTRY_TOKEN_MACHINE_ID
) {
297 r
= path_is_temporary_fs("/etc/machine-id");
299 return log_debug_errno(r
, "Couldn't determine whether /etc/machine-id is on a temporary file system: %m");
301 arg_make_entry_directory
= r
== 0;
303 arg_make_entry_directory
= true;
305 arg_make_entry_directory
= false;
308 if (arg_make_entry_directory
> 0 && !layout_type1
)
309 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
310 "KERNEL_INSTALL_LAYOUT=%s is configured, but Boot Loader Specification Type #1 entry directory creation was requested.",
316 /* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */
317 static int get_file_version(int fd
, char **v
) {
327 if (fstat(fd
, &st
) < 0)
328 return log_error_errno(errno
, "Failed to stat EFI binary: %m");
330 r
= stat_verify_regular(&st
);
332 return log_error_errno(r
, "EFI binary is not a regular file: %m");
334 if (st
.st_size
< 27 || file_offset_beyond_memory_size(st
.st_size
)) {
339 buf
= mmap(NULL
, st
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
340 if (buf
== MAP_FAILED
)
341 return log_error_errno(errno
, "Failed to memory map EFI binary: %m");
343 s
= mempmem_safe(buf
, st
.st_size
- 8, "#### LoaderInfo: ", 17);
347 e
= memmem_safe(s
, st
.st_size
- (s
- buf
), " ####", 5);
348 if (!e
|| e
- s
< 3) {
349 r
= log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Malformed version string.");
353 x
= strndup(s
, e
- s
);
361 (void) munmap(buf
, st
.st_size
);
366 static int enumerate_binaries(const char *esp_path
, const char *path
, const char *prefix
) {
367 _cleanup_closedir_
DIR *d
= NULL
;
374 p
= prefix_roota(esp_path
, path
);
380 return log_error_errno(errno
, "Failed to read \"%s\": %m", p
);
383 FOREACH_DIRENT(de
, d
, break) {
384 _cleanup_free_
char *v
= NULL
;
385 _cleanup_close_
int fd
= -1;
387 if (!endswith_no_case(de
->d_name
, ".efi"))
390 if (prefix
&& !startswith_no_case(de
->d_name
, prefix
))
393 fd
= openat(dirfd(d
), de
->d_name
, O_RDONLY
|O_CLOEXEC
);
395 return log_error_errno(errno
, "Failed to open \"%s/%s\" for reading: %m", p
, de
->d_name
);
397 r
= get_file_version(fd
, &v
);
401 printf(" File: %s/%s/%s (%s%s%s)\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), path
, de
->d_name
, ansi_highlight(), v
, ansi_normal());
403 printf(" File: %s/%s/%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), path
, de
->d_name
);
411 static int status_binaries(const char *esp_path
, sd_id128_t partition
) {
414 printf("Available Boot Loaders on ESP:\n");
417 printf(" ESP: Cannot find or access mount point of ESP.\n\n");
421 printf(" ESP: %s", esp_path
);
422 if (!sd_id128_is_null(partition
))
423 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR
")", SD_ID128_FORMAT_VAL(partition
));
426 r
= enumerate_binaries(esp_path
, "EFI/systemd", NULL
);
430 log_info("systemd-boot not installed in ESP.");
432 r
= enumerate_binaries(esp_path
, "EFI/BOOT", "boot");
436 log_info("No default/fallback boot loader installed in ESP.");
445 static int print_efi_option(uint16_t id
, bool in_order
) {
446 _cleanup_free_
char *title
= NULL
;
447 _cleanup_free_
char *path
= NULL
;
448 sd_id128_t partition
;
452 r
= efi_get_boot_option(id
, &title
, &partition
, &path
, &active
);
456 /* print only configured entries with partition information */
457 if (!path
|| sd_id128_is_null(partition
))
460 efi_tilt_backslashes(path
);
462 printf(" Title: %s%s%s\n", ansi_highlight(), strna(title
), ansi_normal());
463 printf(" ID: 0x%04X\n", id
);
464 printf(" Status: %sactive%s\n", active
? "" : "in", in_order
? ", boot-order" : "");
465 printf(" Partition: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR
"\n",
466 SD_ID128_FORMAT_VAL(partition
));
467 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), path
);
473 static int status_variables(void) {
474 _cleanup_free_
uint16_t *options
= NULL
, *order
= NULL
;
475 int n_options
, n_order
;
477 n_options
= efi_get_boot_options(&options
);
478 if (n_options
== -ENOENT
)
479 return log_error_errno(n_options
,
480 "Failed to access EFI variables, efivarfs"
481 " needs to be available at /sys/firmware/efi/efivars/.");
483 return log_error_errno(n_options
, "Failed to read EFI boot entries: %m");
485 n_order
= efi_get_boot_order(&order
);
486 if (n_order
== -ENOENT
)
488 else if (n_order
< 0)
489 return log_error_errno(n_order
, "Failed to read EFI boot order: %m");
491 /* print entries in BootOrder first */
492 printf("Boot Loaders Listed in EFI Variables:\n");
493 for (int i
= 0; i
< n_order
; i
++)
494 print_efi_option(order
[i
], true);
496 /* print remaining entries */
497 for (int i
= 0; i
< n_options
; i
++) {
498 for (int j
= 0; j
< n_order
; j
++)
499 if (options
[i
] == order
[j
])
502 print_efi_option(options
[i
], false);
511 static int boot_entry_file_check(const char *root
, const char *p
) {
512 _cleanup_free_
char *path
= NULL
;
514 path
= path_join(root
, p
);
518 return RET_NERRNO(access(path
, F_OK
));
521 static void boot_entry_file_list(const char *field
, const char *root
, const char *p
, int *ret_status
) {
522 int status
= boot_entry_file_check(root
, p
);
524 printf("%13s%s ", strempty(field
), field
? ":" : " ");
527 printf("%s%s%s (%m)\n", ansi_highlight_red(), p
, ansi_normal());
531 if (*ret_status
== 0 && status
< 0)
532 *ret_status
= status
;
535 static const char* const boot_entry_type_table
[_BOOT_ENTRY_TYPE_MAX
] = {
536 [BOOT_ENTRY_CONF
] = "Boot Loader Specification Type #1 (.conf)",
537 [BOOT_ENTRY_UNIFIED
] = "Boot Loader Specification Type #2 (.efi)",
538 [BOOT_ENTRY_LOADER
] = "Reported by Boot Loader",
539 [BOOT_ENTRY_LOADER_AUTO
] = "Automatic",
542 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(boot_entry_type
, BootEntryType
);
544 static int boot_entry_show(
546 bool show_as_default
,
547 bool show_as_selected
,
548 bool show_reported
) {
552 /* Returns 0 on success, negative on processing error, and positive if something is wrong with the
553 boot entry itself. */
557 printf(" type: %s\n",
558 boot_entry_type_to_string(e
->type
));
560 printf(" title: %s%s%s",
561 ansi_highlight(), boot_entry_title(e
), ansi_normal());
564 printf(" %s(default)%s",
565 ansi_highlight_green(), ansi_normal());
567 if (show_as_selected
)
568 printf(" %s(selected)%s",
569 ansi_highlight_magenta(), ansi_normal());
572 if (e
->type
== BOOT_ENTRY_LOADER
)
573 printf(" %s(reported/absent)%s",
574 ansi_highlight_red(), ansi_normal());
575 else if (!e
->reported_by_loader
&& e
->type
!= BOOT_ENTRY_LOADER_AUTO
)
576 printf(" %s(not reported/new)%s",
577 ansi_highlight_green(), ansi_normal());
583 printf(" id: %s\n", e
->id
);
585 _cleanup_free_
char *link
= NULL
;
587 /* Let's urlify the link to make it easy to view in an editor, but only if it is a text
588 * file. Unified images are binary ELFs, and EFI variables are not pure text either. */
589 if (e
->type
== BOOT_ENTRY_CONF
)
590 (void) terminal_urlify_path(e
->path
, NULL
, &link
);
592 printf(" source: %s\n", link
?: e
->path
);
595 printf(" sort-key: %s\n", e
->sort_key
);
597 printf(" version: %s\n", e
->version
);
599 printf(" machine-id: %s\n", e
->machine_id
);
601 printf(" architecture: %s\n", e
->architecture
);
603 boot_entry_file_list("linux", e
->root
, e
->kernel
, &status
);
606 STRV_FOREACH(s
, e
->initrd
)
607 boot_entry_file_list(s
== e
->initrd
? "initrd" : NULL
,
612 if (!strv_isempty(e
->options
)) {
613 _cleanup_free_
char *t
= NULL
, *t2
= NULL
;
614 _cleanup_strv_free_
char **ts
= NULL
;
616 t
= strv_join(e
->options
, " ");
620 ts
= strv_split_newlines(t
);
624 t2
= strv_join(ts
, "\n ");
628 printf(" options: %s\n", t2
);
632 boot_entry_file_list("devicetree", e
->root
, e
->device_tree
, &status
);
634 STRV_FOREACH(s
, e
->device_tree_overlay
)
635 boot_entry_file_list(s
== e
->device_tree_overlay
? "devicetree-overlay" : NULL
,
643 static int status_entries(
644 const char *esp_path
,
645 sd_id128_t esp_partition_uuid
,
646 const char *xbootldr_path
,
647 sd_id128_t xbootldr_partition_uuid
) {
649 _cleanup_(boot_config_free
) BootConfig config
= {};
650 sd_id128_t dollar_boot_partition_uuid
;
651 const char *dollar_boot_path
;
654 assert(esp_path
|| xbootldr_path
);
657 dollar_boot_path
= xbootldr_path
;
658 dollar_boot_partition_uuid
= xbootldr_partition_uuid
;
660 dollar_boot_path
= esp_path
;
661 dollar_boot_partition_uuid
= esp_partition_uuid
;
664 printf("Boot Loader Entries:\n"
665 " $BOOT: %s", dollar_boot_path
);
666 if (!sd_id128_is_null(dollar_boot_partition_uuid
))
667 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR
")",
668 SD_ID128_FORMAT_VAL(dollar_boot_partition_uuid
));
671 r
= boot_entries_load_config(esp_path
, xbootldr_path
, &config
);
675 if (config
.default_entry
< 0)
676 printf("%zu entries, no entry could be determined as default.\n", config
.n_entries
);
678 printf("Default Boot Loader Entry:\n");
681 config
.entries
+ config
.default_entry
,
682 /* show_as_default= */ false,
683 /* show_as_selected= */ false,
684 /* show_discovered= */ false);
686 /* < 0 is already logged by the function itself, let's just emit an extra warning if
687 the default entry is broken */
688 printf("\nWARNING: default boot entry is broken\n");
694 static int compare_product(const char *a
, const char *b
) {
703 return x
< y
? -1 : x
> y
? 1 : 0;
705 return strncmp(a
, b
, x
);
708 static int compare_version(const char *a
, const char *b
) {
712 a
+= strcspn(a
, " ");
714 b
+= strcspn(b
, " ");
717 return strverscmp_improved(a
, b
);
720 static int version_check(int fd_from
, const char *from
, int fd_to
, const char *to
) {
721 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
724 assert(fd_from
>= 0);
729 r
= get_file_version(fd_from
, &a
);
733 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE
),
734 "Source file \"%s\" does not carry version information!",
737 r
= get_file_version(fd_to
, &b
);
740 if (r
== 0 || compare_product(a
, b
) != 0)
741 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE
),
742 "Skipping \"%s\", since it's owned by another boot loader.",
745 r
= compare_version(a
, b
);
747 return log_warning_errno(SYNTHETIC_ERRNO(ESTALE
), "Skipping \"%s\", since newer boot loader version in place already.", to
);
749 return log_info_errno(SYNTHETIC_ERRNO(ESTALE
), "Skipping \"%s\", since same boot loader version in place already.", to
);
754 static int copy_file_with_version_check(const char *from
, const char *to
, bool force
) {
755 _cleanup_close_
int fd_from
= -1, fd_to
= -1;
756 _cleanup_free_
char *t
= NULL
;
759 fd_from
= open(from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
761 return log_error_errno(errno
, "Failed to open \"%s\" for reading: %m", from
);
764 fd_to
= open(to
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
767 return log_error_errno(errno
, "Failed to open \"%s\" for reading: %m", to
);
769 r
= version_check(fd_from
, from
, fd_to
, to
);
773 if (lseek(fd_from
, 0, SEEK_SET
) == (off_t
) -1)
774 return log_error_errno(errno
, "Failed to seek in \"%s\": %m", from
);
776 fd_to
= safe_close(fd_to
);
780 r
= tempfn_random(to
, NULL
, &t
);
784 RUN_WITH_UMASK(0000) {
785 fd_to
= open(t
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_EXCL
|O_NOFOLLOW
, 0644);
787 return log_error_errno(errno
, "Failed to open \"%s\" for writing: %m", t
);
790 r
= copy_bytes(fd_from
, fd_to
, UINT64_MAX
, COPY_REFLINK
);
793 return log_error_errno(r
, "Failed to copy data from \"%s\" to \"%s\": %m", from
, t
);
796 (void) copy_times(fd_from
, fd_to
, 0);
798 r
= fsync_full(fd_to
);
800 (void) unlink_noerrno(t
);
801 return log_error_errno(r
, "Failed to copy data from \"%s\" to \"%s\": %m", from
, t
);
804 if (renameat(AT_FDCWD
, t
, AT_FDCWD
, to
) < 0) {
805 (void) unlink_noerrno(t
);
806 return log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", t
, to
);
809 log_info("Copied \"%s\" to \"%s\".", from
, to
);
814 static int mkdir_one(const char *prefix
, const char *suffix
) {
815 _cleanup_free_
char *p
= NULL
;
817 p
= path_join(prefix
, suffix
);
818 if (mkdir(p
, 0700) < 0) {
820 return log_error_errno(errno
, "Failed to create \"%s\": %m", p
);
822 log_info("Created \"%s\".", p
);
827 static const char *const esp_subdirs
[] = {
828 /* The directories to place in the ESP */
836 static const char *const dollar_boot_subdirs
[] = {
837 /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
839 "loader/entries", /* Type #1 entries */
841 "EFI/Linux", /* Type #2 entries */
845 static int create_subdirs(const char *root
, const char * const *subdirs
) {
846 const char *const *i
;
849 STRV_FOREACH(i
, subdirs
) {
850 r
= mkdir_one(root
, *i
);
858 static int copy_one_file(const char *esp_path
, const char *name
, bool force
) {
860 char *p
, *q
, *dest_name
, *s
;
863 dest_name
= strdupa_safe(name
);
864 s
= endswith_no_case(dest_name
, ".signed");
868 p
= strjoina(BOOTLIBDIR
"/", name
);
869 q
= strjoina(esp_path
, "/EFI/systemd/", dest_name
);
870 r
= copy_file_with_version_check(p
, q
, force
);
872 e
= startswith(dest_name
, "systemd-boot");
877 /* Create the EFI default boot loader name (specified for removable devices) */
878 v
= strjoina(esp_path
, "/EFI/BOOT/BOOT", e
);
879 ascii_strupper(strrchr(v
, '/') + 1);
881 k
= copy_file_with_version_check(p
, v
, force
);
889 static int install_binaries(const char *esp_path
, bool force
) {
890 _cleanup_closedir_
DIR *d
= NULL
;
893 d
= opendir(BOOTLIBDIR
);
895 return log_error_errno(errno
, "Failed to open \""BOOTLIBDIR
"\": %m
");
897 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read
\""BOOTLIBDIR"\": %m
")) {
900 if (!endswith_no_case(de->d_name, ".efi
") && !endswith_no_case(de->d_name, ".efi
.signed"))
903 /* skip the .efi file, if there's a .signed version of it */
904 if (endswith_no_case(de->d_name, ".efi
")) {
905 _cleanup_free_ const char *s = strjoin(de->d_name, ".signed");
908 if (faccessat(dirfd(d), s, F_OK, 0) >= 0)
912 k = copy_one_file(esp_path, de->d_name, force);
913 /* Don't propagate an error code if no update necessary, installed version already equal or
914 * newer version, or other boot loader in place. */
915 if (arg_graceful && IN_SET(k, -ESTALE, -EREMOTE))
924 static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
925 _cleanup_free_ char *opath = NULL;
929 r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
932 if (!sd_id128_equal(uuid, ouuid))
935 /* Some motherboards convert the path to uppercase under certain circumstances
936 * (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
937 * so use case-insensitive checking */
938 if (!strcaseeq_ptr(path, opath))
944 static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
945 _cleanup_free_ uint16_t *options = NULL;
948 n = efi_get_boot_options(&options);
952 /* find already existing systemd-boot entry */
953 for (i = 0; i < n; i++)
954 if (same_entry(options[i], uuid, path)) {
959 /* find free slot in the sorted BootXXXX variable list */
960 for (i = 0; i < n; i++)
961 if (i != options[i]) {
966 /* use the next one */
973 static int insert_into_order(uint16_t slot, bool first) {
974 _cleanup_free_ uint16_t *order = NULL;
978 n = efi_get_boot_order(&order);
980 /* no entry, add us */
981 return efi_set_boot_order(&slot, 1);
983 /* are we the first and only one? */
984 if (n == 1 && order[0] == slot)
987 /* are we already in the boot order? */
988 for (int i = 0; i < n; i++) {
989 if (order[i] != slot)
992 /* we do not require to be the first one, all is fine */
996 /* move us to the first slot */
997 memmove(order + 1, order, i * sizeof(uint16_t));
999 return efi_set_boot_order(order, n);
1003 t = reallocarray(order, n + 1, sizeof(uint16_t));
1008 /* add us to the top or end of the list */
1010 memmove(order + 1, order, n * sizeof(uint16_t));
1015 return efi_set_boot_order(order, n + 1);
1018 static int remove_from_order(uint16_t slot) {
1019 _cleanup_free_ uint16_t *order = NULL;
1022 n = efi_get_boot_order(&order);
1026 for (int i = 0; i < n; i++) {
1027 if (order[i] != slot)
1031 memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
1032 return efi_set_boot_order(order, n - 1);
1038 static int install_variables(const char *esp_path,
1039 uint32_t part, uint64_t pstart, uint64_t psize,
1040 sd_id128_t uuid, const char *path,
1046 if (!is_efi_boot()) {
1047 log_warning("Not booted with EFI
, skipping EFI variable setup
.");
1051 p = prefix_roota(esp_path, path);
1052 if (access(p, F_OK) < 0) {
1053 if (errno == ENOENT)
1056 return log_error_errno(errno, "Cannot access
\"%s
\": %m
", p);
1059 r = find_slot(uuid, path, &slot);
1061 return log_error_errno(r,
1063 "Failed to access EFI variables
. Is the
\"efivarfs
\" filesystem mounted
?" :
1064 "Failed to determine current boot order
: %m
");
1066 if (first || r == 0) {
1067 r = efi_add_boot_option(slot, "Linux Boot Manager
",
1068 part, pstart, psize,
1071 return log_error_errno(r, "Failed to create EFI Boot variable entry
: %m
");
1073 log_info("Created EFI boot entry
\"Linux Boot Manager
\".");
1076 return insert_into_order(slot, first);
1079 static int remove_boot_efi(const char *esp_path) {
1080 _cleanup_closedir_ DIR *d = NULL;
1084 p = prefix_roota(esp_path, "/EFI
/BOOT
");
1087 if (errno == ENOENT)
1090 return log_error_errno(errno, "Failed to open directory
\"%s
\": %m
", p);
1093 FOREACH_DIRENT(de, d, break) {
1094 _cleanup_close_ int fd = -1;
1095 _cleanup_free_ char *v = NULL;
1097 if (!endswith_no_case(de->d_name, ".efi
"))
1100 if (!startswith_no_case(de->d_name, "boot
"))
1103 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
1105 return log_error_errno(errno, "Failed to open
\"%s
/%s
\" for reading
: %m
", p, de->d_name);
1107 r = get_file_version(fd, &v);
1110 if (r > 0 && startswith(v, "systemd
-boot
")) {
1111 r = unlinkat(dirfd(d), de->d_name, 0);
1113 return log_error_errno(errno, "Failed to remove
\"%s
/%s
\": %m
", p, de->d_name);
1115 log_info("Removed
\"%s
/%s
\".", p, de->d_name);
1124 static int rmdir_one(const char *prefix, const char *suffix) {
1127 p = prefix_roota(prefix, suffix);
1129 bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
1131 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
1132 "Failed to remove directory
\"%s
\": %m
", p);
1136 log_info("Removed
\"%s
\".", p);
1141 static int remove_subdirs(const char *root, const char *const *subdirs) {
1144 /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
1145 * short the array is. */
1147 if (!subdirs[0]) /* A the end of the list */
1150 r = remove_subdirs(root, subdirs + 1);
1151 q = rmdir_one(root, subdirs[0]);
1153 return r < 0 ? r : q;
1156 static int remove_entry_directory(const char *root) {
1158 assert(arg_make_entry_directory >= 0);
1160 if (!arg_make_entry_directory || !arg_entry_token)
1163 return rmdir_one(root, arg_entry_token);
1166 static int remove_binaries(const char *esp_path) {
1170 p = prefix_roota(esp_path, "/EFI
/systemd
");
1171 r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
1173 q = remove_boot_efi(esp_path);
1174 if (q < 0 && r == 0)
1180 static int remove_file(const char *root, const char *file) {
1186 p = prefix_roota(root, file);
1187 if (unlink(p) < 0) {
1188 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
1189 "Failed to unlink file
\"%s
\": %m
", p);
1191 return errno == ENOENT ? 0 : -errno;
1194 log_info("Removed
\"%s
\".", p);
1198 static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
1205 r = find_slot(uuid, path, &slot);
1209 r = efi_remove_boot_option(slot);
1214 return remove_from_order(slot);
1219 static int remove_loader_variables(void) {
1220 const char *variable;
1223 /* Remove all persistent loader variables we define */
1225 FOREACH_STRING(variable,
1226 EFI_LOADER_VARIABLE(LoaderConfigTimeout),
1227 EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot),
1228 EFI_LOADER_VARIABLE(LoaderEntryDefault),
1229 EFI_LOADER_VARIABLE(LoaderEntryOneShot),
1230 EFI_LOADER_VARIABLE(LoaderSystemToken)){
1234 q = efi_set_variable(variable, NULL, 0);
1238 log_warning_errno(q, "Failed to remove EFI variable
%s
: %m
", variable);
1242 log_info("Removed EFI variable
%s
.", variable);
1248 static int install_loader_config(const char *esp_path) {
1249 _cleanup_(unlink_and_freep) char *t = NULL;
1250 _cleanup_fclose_ FILE *f = NULL;
1251 _cleanup_close_ int fd = -1;
1255 assert(arg_make_entry_directory >= 0);
1257 p = prefix_roota(esp_path, "/loader
/loader
.conf
");
1258 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
1261 fd = open_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t);
1263 return log_error_errno(fd, "Failed to open
\"%s
\" for writing
: %m
", p);
1265 f = take_fdopen(&fd, "w
");
1269 fprintf(f, "#timeout 3\n"
1270 "#console-mode keep\n");
1272 if (arg_make_entry_directory) {
1273 assert(arg_entry_token);
1274 fprintf(f, "default %s-*\n", arg_entry_token);
1277 r = fflush_sync_and_check(f);
1279 return log_error_errno(r, "Failed to write \"%s\": %m", p);
1281 r = link_tmpfile(fileno(f), t, p);
1283 return 0; /* Silently skip creation if the file exists now (recheck) */
1285 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1291 static int install_entry_directory(const char *root) {
1293 assert(arg_make_entry_directory >= 0);
1295 if (!arg_make_entry_directory)
1298 assert(arg_entry_token);
1299 return mkdir_one(root, arg_entry_token);
1302 static int install_entry_token(void) {
1305 assert(arg_make_entry_directory >= 0);
1306 assert(arg_entry_token);
1308 /* Let's save the used entry token in /etc/kernel/entry-token if we used it to create the entry
1309 * directory, or if anything else but the machine ID */
1311 if (!arg_make_entry_directory && arg_entry_token_type == ARG_ENTRY_TOKEN_MACHINE_ID)
1314 r = write_string_file("/etc/kernel/entry-token", arg_entry_token, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755);
1316 return log_error_errno(r, "Failed to write entry token '%s' to /etc/kernel/entry-token", arg_entry_token);
1321 static int help(int argc, char *argv[], void *userdata) {
1322 _cleanup_free_ char *link = NULL;
1325 r = terminal_urlify_man("bootctl", "1", &link);
1329 printf("%1$s [OPTIONS...] COMMAND ...\n"
1330 "\n%5$sControl EFI firmware boot settings and manage boot loader.%6$s\n"
1331 "\n%3$sGeneric EFI Firmware/Boot Loader Commands:%4$s\n"
1332 " status Show status of installed boot loader and EFI variables\n"
1333 " reboot-to-firmware [BOOL]\n"
1334 " Query or set reboot-to-firmware EFI flag\n"
1335 " systemd-efi-options [STRING]\n"
1336 " Query or set system options string in EFI variable\n"
1337 "\n%3$sBoot Loader Specification Commands:%4$s\n"
1338 " list List boot loader entries\n"
1339 " set-default ID Set default boot loader entry\n"
1340 " set-oneshot ID Set default boot loader entry, for next boot only\n"
1341 " set-timeout SECONDS Set the menu timeout\n"
1342 " set-timeout-oneshot SECONDS\n"
1343 " Set the menu timeout for the next boot only\n"
1344 "\n%3$ssystemd-boot Commands:%4$s\n"
1345 " install Install systemd-boot to the ESP and EFI variables\n"
1346 " update Update systemd-boot in the ESP and EFI variables\n"
1347 " remove Remove systemd-boot from the ESP and EFI variables\n"
1348 " is-installed Test whether systemd-boot is installed in the ESP\n"
1349 " random-seed Initialize random seed in ESP and EFI variables\n"
1350 "\n%3$sOptions:%4$s\n"
1351 " -h --help Show this help\n"
1352 " --version Print version\n"
1353 " --esp-path=PATH Path to the EFI System Partition (ESP)\n"
1354 " --boot-path=PATH Path to the $BOOT partition\n"
1355 " -p --print-esp-path Print path to the EFI System Partition\n"
1356 " -x --print-boot-path Print path to the $BOOT partition\n"
1357 " --no-variables Don't touch EFI variables\n"
1358 " --no-pager Do not pipe output into a pager\n"
1359 " --graceful Don't fail when the ESP cannot be found or EFI\n"
1360 " variables cannot be written\n"
1361 " --make-entry-directory=yes|no|auto\n"
1362 " Create $BOOT/ENTRY-TOKEN/ directory\n"
1363 " --entry-token=machine-id|os-id|os-image-id|auto|literal:…\n"
1364 " Entry token to use for this installation\n"
1365 "\nSee the %2$s for details.\n",
1366 program_invocation_short_name,
1376 static int parse_argv(int argc, char *argv[]) {
1378 ARG_ESP_PATH = 0x100,
1384 ARG_MAKE_ENTRY_DIRECTORY,
1388 static const struct option options[] = {
1389 { "help", no_argument, NULL, 'h' },
1390 { "version", no_argument, NULL, ARG_VERSION },
1391 { "esp-path", required_argument, NULL, ARG_ESP_PATH },
1392 { "path", required_argument, NULL, ARG_ESP_PATH }, /* Compatibility alias */
1393 { "boot-path", required_argument, NULL, ARG_BOOT_PATH },
1394 { "print-esp-path", no_argument, NULL, 'p' },
1395 { "print-path", no_argument, NULL, 'p' }, /* Compatibility alias */
1396 { "print-boot-path", no_argument, NULL, 'x' },
1397 { "no-variables", no_argument, NULL, ARG_NO_VARIABLES },
1398 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1399 { "graceful", no_argument, NULL, ARG_GRACEFUL },
1400 { "make-entry-directory", required_argument, NULL, ARG_MAKE_ENTRY_DIRECTORY },
1401 { "make-machine-id-directory", required_argument, NULL, ARG_MAKE_ENTRY_DIRECTORY }, /* Compatibility alias */
1402 { "entry-token", required_argument, NULL, ARG_ENTRY_TOKEN },
1412 while ((c = getopt_long(argc, argv, "hpx", options, NULL)) >= 0)
1416 help(0, NULL, NULL);
1423 r = free_and_strdup(&arg_esp_path, optarg);
1429 r = free_and_strdup(&arg_xbootldr_path, optarg);
1435 if (arg_print_dollar_boot_path)
1436 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1437 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1438 arg_print_esp_path = true;
1442 if (arg_print_esp_path)
1443 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1444 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1445 arg_print_dollar_boot_path = true;
1448 case ARG_NO_VARIABLES:
1449 arg_touch_variables = false;
1453 arg_pager_flags |= PAGER_DISABLE;
1457 arg_graceful = true;
1460 case ARG_ENTRY_TOKEN: {
1463 if (streq(optarg, "machine-id")) {
1464 arg_entry_token_type = ARG_ENTRY_TOKEN_MACHINE_ID;
1465 arg_entry_token = mfree(arg_entry_token);
1466 } else if (streq(optarg, "os-image-id")) {
1467 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_IMAGE_ID;
1468 arg_entry_token = mfree(arg_entry_token);
1469 } else if (streq(optarg, "os-id")) {
1470 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_ID;
1471 arg_entry_token = mfree(arg_entry_token);
1472 } else if ((e = startswith(optarg, "literal:"))) {
1473 arg_entry_token_type = ARG_ENTRY_TOKEN_LITERAL;
1475 r = free_and_strdup_warn(&arg_entry_token, e);
1479 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1480 "Unexpected parameter for --entry-token=: %s", optarg);
1485 case ARG_MAKE_ENTRY_DIRECTORY:
1486 if (streq(optarg, "auto")) /* retained for backwards compatibility */
1487 arg_make_entry_directory = -1; /* yes if machine-id is permanent */
1489 r = parse_boolean_argument("--make-entry-directory=", optarg, &b);
1493 arg_make_entry_directory = b;
1501 assert_not_reached();
1507 static void read_efi_var(const char *variable, char **ret) {
1510 r = efi_get_variable_string(variable, ret);
1511 if (r < 0 && r != -ENOENT)
1512 log_warning_errno(r, "Failed to read EFI variable %s: %m", variable);
1515 static void print_yes_no_line(bool first, bool good, const char *name) {
1517 first ? " Features: " : " ",
1518 COLOR_MARK_BOOL(good),
1522 static int are_we_installed(void) {
1525 r = acquire_esp(/* privileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, NULL, NULL);
1529 /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
1530 * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
1531 * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
1532 * should be a suitable and very minimal check for a number of reasons:
1534 * → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
1535 * not a specific one.)
1537 * → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
1538 * /EFI/BOOT/BOOT*.EFI fallback binary.
1540 * → It specifically checks for systemd-boot, not for other boot loaders (which a check for
1541 * /boot/loader/entries would do). */
1543 _cleanup_free_ char *p = path_join(arg_esp_path, "/EFI/systemd/");
1547 log_debug("Checking whether %s contains any files…", p);
1548 r = dir_is_empty(p);
1549 if (r < 0 && r != -ENOENT)
1550 return log_error_errno(r, "Failed to check whether %s contains any files: %m", p);
1555 static int verb_status(int argc, char *argv[], void *userdata) {
1556 sd_id128_t esp_uuid = SD_ID128_NULL, xbootldr_uuid = SD_ID128_NULL;
1557 dev_t esp_devid = 0, xbootldr_devid = 0;
1560 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, &esp_uuid, &esp_devid);
1561 if (arg_print_esp_path) {
1562 if (r == -EACCES) /* If we couldn't acquire the ESP path, log about access errors (which is the only
1563 * error the find_esp_and_warn() won't log on its own) */
1564 return log_error_errno(r, "Failed to determine ESP location: %m");
1571 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, &xbootldr_uuid, &xbootldr_devid);
1572 if (arg_print_dollar_boot_path) {
1574 return log_error_errno(r, "Failed to determine XBOOTLDR location: %m");
1578 const char *path = arg_dollar_boot_path();
1580 return log_error_errno(SYNTHETIC_ERRNO(EACCES), "Failed to determine XBOOTLDR location: %m");
1585 if (arg_print_esp_path || arg_print_dollar_boot_path)
1588 r = 0; /* If we couldn't determine the path, then don't consider that a problem from here on, just show what we
1591 pager_open(arg_pager_flags);
1593 if (is_efi_boot()) {
1594 static const struct {
1598 { EFI_LOADER_FEATURE_BOOT_COUNTING, "Boot counting" },
1599 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT, "Menu timeout control" },
1600 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT, "One-shot menu timeout control" },
1601 { EFI_LOADER_FEATURE_ENTRY_DEFAULT, "Default entry control" },
1602 { EFI_LOADER_FEATURE_ENTRY_ONESHOT, "One-shot entry control" },
1603 { EFI_LOADER_FEATURE_XBOOTLDR, "Support for XBOOTLDR partition" },
1604 { EFI_LOADER_FEATURE_RANDOM_SEED, "Support for passing random seed to OS" },
1605 { EFI_LOADER_FEATURE_LOAD_DRIVER, "Load drop-in drivers" },
1608 _cleanup_free_ char *fw_type = NULL, *fw_info = NULL, *loader = NULL, *loader_path = NULL, *stub = NULL;
1609 sd_id128_t loader_part_uuid = SD_ID128_NULL;
1610 uint64_t loader_features = 0;
1613 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareType), &fw_type);
1614 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareInfo), &fw_info);
1615 read_efi_var(EFI_LOADER_VARIABLE(LoaderInfo), &loader);
1616 read_efi_var(EFI_LOADER_VARIABLE(StubInfo), &stub);
1617 read_efi_var(EFI_LOADER_VARIABLE(LoaderImageIdentifier), &loader_path);
1618 (void) efi_loader_get_features(&loader_features);
1621 efi_tilt_backslashes(loader_path);
1623 k = efi_loader_get_device_part_uuid(&loader_part_uuid);
1624 if (k < 0 && k != -ENOENT)
1625 r = log_warning_errno(k, "Failed to read EFI variable LoaderDevicePartUUID: %m");
1627 SecureBootMode secure = efi_get_secure_boot_mode();
1628 printf("System:\n");
1629 printf(" Firmware: %s%s (%s)%s\n", ansi_highlight(), strna(fw_type), strna(fw_info), ansi_normal());
1630 printf(" Secure Boot: %sd (%s)\n",
1631 enable_disable(IN_SET(secure, SECURE_BOOT_USER, SECURE_BOOT_DEPLOYED)),
1632 secure_boot_mode_to_string(secure));
1633 printf(" TPM2 Support: %s\n", yes_no(efi_has_tpm2()));
1635 k = efi_get_reboot_to_firmware();
1637 printf(" Boot into FW: %sactive%s\n", ansi_highlight_yellow(), ansi_normal());
1639 printf(" Boot into FW: supported\n");
1640 else if (k == -EOPNOTSUPP)
1641 printf(" Boot into FW: not supported\n");
1644 printf(" Boot into FW: %sfailed%s (%m)\n", ansi_highlight_red(), ansi_normal());
1648 printf("Current Boot Loader:\n");
1649 printf(" Product: %s%s%s\n", ansi_highlight(), strna(loader), ansi_normal());
1651 for (size_t i = 0; i < ELEMENTSOF(flags); i++)
1652 print_yes_no_line(i == 0, FLAGS_SET(loader_features, flags[i].flag), flags[i].name);
1654 sd_id128_t bootloader_esp_uuid;
1655 bool have_bootloader_esp_uuid = efi_loader_get_device_part_uuid(&bootloader_esp_uuid) >= 0;
1657 print_yes_no_line(false, have_bootloader_esp_uuid, "Boot loader sets ESP information");
1658 if (have_bootloader_esp_uuid && !sd_id128_equal(esp_uuid, bootloader_esp_uuid))
1659 printf("WARNING: The boot loader reports a different ESP UUID than detected!\n");
1662 printf(" Stub: %s\n", stub);
1663 if (!sd_id128_is_null(loader_part_uuid))
1664 printf(" ESP: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR "\n",
1665 SD_ID128_FORMAT_VAL(loader_part_uuid));
1667 printf(" ESP: n/a\n");
1668 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), strna(loader_path));
1671 printf("Random Seed:\n");
1672 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderRandomSeed)), F_OK) >= 0;
1673 printf(" Passed to OS: %s\n", yes_no(have));
1674 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderSystemToken)), F_OK) >= 0;
1675 printf(" System Token: %s\n", have ? "set" : "not set");
1678 _cleanup_free_ char *p = NULL;
1680 p = path_join(arg_esp_path, "/loader/random-seed");
1684 have = access(p, F_OK) >= 0;
1685 printf(" Exists: %s\n", yes_no(have));
1690 printf("System:\n Not booted with EFI\n\n");
1693 k = status_binaries(arg_esp_path, esp_uuid);
1698 if (is_efi_boot()) {
1699 k = status_variables();
1704 if (arg_esp_path || arg_xbootldr_path) {
1705 /* If XBOOTLDR and ESP actually refer to the same block device, suppress XBOOTLDR, since it would find the same entries twice */
1706 bool same = arg_esp_path && arg_xbootldr_path && devid_set_and_equal(esp_devid, xbootldr_devid);
1711 same ? NULL : arg_xbootldr_path,
1712 same ? SD_ID128_NULL : xbootldr_uuid);
1720 static int verb_list(int argc, char *argv[], void *userdata) {
1721 _cleanup_(boot_config_free) BootConfig config = {};
1722 _cleanup_strv_free_ char **efi_entries = NULL;
1723 dev_t esp_devid = 0, xbootldr_devid = 0;
1726 /* If we lack privileges we invoke find_esp_and_warn() in "unprivileged mode" here, which does two things: turn
1727 * off logging about access errors and turn off potentially privileged device probing. Here we're interested in
1728 * the latter but not the former, hence request the mode, and log about EACCES. */
1730 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, NULL, &esp_devid);
1731 if (r == -EACCES) /* We really need the ESP path for this call, hence also log about access errors */
1732 return log_error_errno(r, "Failed to determine ESP: %m");
1736 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, NULL, &xbootldr_devid);
1738 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1742 /* If XBOOTLDR and ESP actually refer to the same block device, suppress XBOOTLDR, since it would find the same entries twice */
1743 bool same = arg_esp_path && arg_xbootldr_path && devid_set_and_equal(esp_devid, xbootldr_devid);
1745 r = boot_entries_load_config(arg_esp_path, same ? NULL : arg_xbootldr_path, &config);
1749 r = efi_loader_get_entries(&efi_entries);
1750 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
1751 log_debug_errno(r, "Boot loader reported no entries.");
1753 log_warning_errno(r, "Failed to determine entries reported by boot loader, ignoring: %m");
1755 (void) boot_entries_augment_from_loader(&config, efi_entries, /* only_auto= */ false);
1757 if (config.n_entries == 0)
1758 log_info("No boot loader entries found.");
1760 pager_open(arg_pager_flags);
1762 printf("Boot Loader Entries:\n");
1764 for (size_t n = 0; n < config.n_entries; n++) {
1765 r = boot_entry_show(
1767 /* show_as_default= */ n == (size_t) config.default_entry,
1768 /* show_as_selected= */ n == (size_t) config.selected_entry,
1769 /* show_discovered= */ true);
1773 if (n+1 < config.n_entries)
1781 static int install_random_seed(const char *esp) {
1782 _cleanup_(unlink_and_freep) char *tmp = NULL;
1783 _cleanup_free_ void *buffer = NULL;
1784 _cleanup_free_ char *path = NULL;
1785 _cleanup_close_ int fd = -1;
1786 size_t sz, token_size;
1792 path = path_join(esp, "/loader/random-seed");
1796 sz = random_pool_size();
1798 buffer = malloc(sz);
1802 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1804 return log_error_errno(r, "Failed to acquire random seed: %m");
1806 /* Normally create_subdirs() should already have created everything we need, but in case "bootctl
1807 * random
-seed
" is called we want to just create the minimum we need for it, and not the full
1809 r = mkdir_parents(path, 0755);
1811 return log_error_errno(r, "Failed to create parent directory
for %s
: %m
", path);
1813 r = tempfn_random(path, "bootctl
", &tmp);
1817 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|O_WRONLY|O_CLOEXEC, 0600);
1820 return log_error_errno(fd, "Failed to open random seed file
for writing
: %m
");
1823 n = write(fd, buffer, sz);
1825 return log_error_errno(errno, "Failed to write random seed file
: %m
");
1826 if ((size_t) n != sz)
1827 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write
while writing random seed file
.");
1829 if (rename(tmp, path) < 0)
1830 return log_error_errno(r, "Failed to move random seed file into place
: %m
");
1834 log_info("Random seed file
%s successfully
written (%zu bytes
).", path, sz);
1836 if (!arg_touch_variables)
1839 if (!is_efi_boot()) {
1840 log_notice("Not booted with EFI
, skipping EFI variable setup
.");
1844 r = getenv_bool("SYSTEMD_WRITE_SYSTEM_TOKEN
");
1847 log_warning_errno(r, "Failed to parse $SYSTEMD_WRITE_SYSTEM_TOKEN
, ignoring
.");
1849 if (detect_vm() > 0) {
1850 /* Let's not write a system token if we detect we are running in a VM
1851 * environment. Why? Our default security model for the random seed uses the system
1852 * token as a mechanism to ensure we are not vulnerable to golden master sloppiness
1853 * issues, i.e. that people initialize the random seed file, then copy the image to
1854 * many systems and end up with the same random seed in each that is assumed to be
1855 * valid but in reality is the same for all machines. By storing a system token in
1856 * the EFI variable space we can make sure that even though the random seeds on disk
1857 * are all the same they will be different on each system under the assumption that
1858 * the EFI variable space is maintained separate from the random seed storage. That
1859 * is generally the case on physical systems, as the ESP is stored on persistent
1860 * storage, and the EFI variables in NVRAM. However in virtualized environments this
1861 * is generally not true: the EFI variable set is typically stored along with the
1862 * disk image itself. For example, using the OVMF EFI firmware the EFI variables are
1863 * stored in a file in the ESP itself. */
1865 log_notice("Not installing system token
, since we are running in a virtualized environment
.");
1868 } else if (r == 0) {
1869 log_notice("Not writing system token
, because $SYSTEMD_WRITE_SYSTEM_TOKEN is set to
false.");
1873 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), NULL, NULL, &token_size);
1875 log_debug_errno(r, "LoaderSystemToken EFI variable is
invalid (too
short?), replacing
.");
1878 return log_error_errno(r, "Failed to test system token validity
: %m
");
1880 if (token_size >= sz) {
1881 /* Let's avoid writes if we can, and initialize this only once. */
1882 log_debug("System token already written
, not updating
.");
1886 log_debug("Existing system token
size (%zu
) does
not match our
expectations (%zu
), replacing
.", token_size, sz);
1889 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1891 return log_error_errno(r, "Failed to acquire random seed
: %m
");
1893 /* Let's write this variable with an umask in effect, so that unprivileged users can't see the token
1894 * and possibly get identification information or too much insight into the kernel's entropy pool
1896 RUN_WITH_UMASK(0077) {
1897 r = efi_set_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), buffer, sz);
1900 return log_error_errno(r, "Failed to write
'LoaderSystemToken' EFI variable
: %m
");
1903 log_warning_errno(r, "Unable to write
'LoaderSystemToken' EFI
variable (firmware problem
?), ignoring
: %m
");
1905 log_warning_errno(r, "Unable to write
'LoaderSystemToken' EFI variable
, ignoring
: %m
");
1907 log_info("Successfully initialized system token in EFI variable with
%zu bytes
.", sz);
1913 static int sync_everything(void) {
1917 k = syncfs_path(AT_FDCWD, arg_esp_path);
1919 ret = log_error_errno(k, "Failed to synchronize the ESP
'%s': %m
", arg_esp_path);
1922 if (arg_xbootldr_path) {
1923 k = syncfs_path(AT_FDCWD, arg_xbootldr_path);
1925 ret = log_error_errno(k, "Failed to synchronize $BOOT
'%s': %m
", arg_xbootldr_path);
1931 static int verb_install(int argc, char *argv[], void *userdata) {
1932 sd_id128_t uuid = SD_ID128_NULL;
1933 uint64_t pstart = 0, psize = 0;
1935 bool install, graceful;
1938 /* Invoked for both "update
" and "install
" */
1940 install = streq(argv[0], "install
");
1941 graceful = !install && arg_graceful; /* support graceful mode for updates */
1943 r = acquire_esp(/* unprivileged_mode= */ false, graceful, &part, &pstart, &psize, &uuid, NULL);
1944 if (graceful && r == -ENOKEY)
1945 return 0; /* If --graceful is specified and we can't find an ESP, handle this cleanly */
1950 /* If we are updating, don't do anything if sd-boot wasn't actually installed. */
1951 r = are_we_installed();
1955 log_debug("Skipping update because sd
-boot is
not installed in the ESP
.");
1960 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
1964 r = settle_make_entry_directory();
1968 RUN_WITH_UMASK(0002) {
1970 /* Don't create any of these directories when we are just updating. When we update
1971 * we'll drop-in our files (unless there are newer ones already), but we won't create
1972 * the directories for them in the first place. */
1973 r = create_subdirs(arg_esp_path, esp_subdirs);
1977 r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
1982 r = install_binaries(arg_esp_path, install);
1987 r = install_loader_config(arg_esp_path);
1991 r = install_entry_directory(arg_dollar_boot_path());
1995 r = install_entry_token();
1999 r = install_random_seed(arg_esp_path);
2005 (void) sync_everything();
2007 if (arg_touch_variables)
2008 r = install_variables(arg_esp_path,
2009 part, pstart, psize, uuid,
2010 "/EFI
/systemd
/systemd
-boot
" EFI_MACHINE_TYPE_NAME ".efi
",
2016 static int verb_remove(int argc, char *argv[], void *userdata) {
2017 sd_id128_t uuid = SD_ID128_NULL;
2020 r = acquire_esp(/* unprivileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, &uuid, NULL);
2024 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
2028 r = settle_make_entry_directory();
2032 r = remove_binaries(arg_esp_path);
2034 q = remove_file(arg_esp_path, "/loader
/loader
.conf
");
2035 if (q < 0 && r >= 0)
2038 q = remove_file(arg_esp_path, "/loader
/random
-seed
");
2039 if (q < 0 && r >= 0)
2042 q = remove_subdirs(arg_esp_path, esp_subdirs);
2043 if (q < 0 && r >= 0)
2046 q = remove_subdirs(arg_esp_path, dollar_boot_subdirs);
2047 if (q < 0 && r >= 0)
2050 q = remove_entry_directory(arg_esp_path);
2051 if (q < 0 && r >= 0)
2054 if (arg_xbootldr_path) {
2055 /* Remove the latter two also in the XBOOTLDR partition if it exists */
2056 q = remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs);
2057 if (q < 0 && r >= 0)
2060 q = remove_entry_directory(arg_xbootldr_path);
2061 if (q < 0 && r >= 0)
2065 (void) sync_everything();
2067 if (!arg_touch_variables)
2070 q = remove_variables(uuid, "/EFI
/systemd
/systemd
-boot
" EFI_MACHINE_TYPE_NAME ".efi
", true);
2071 if (q < 0 && r >= 0)
2074 q = remove_loader_variables();
2075 if (q < 0 && r >= 0)
2081 static int verb_is_installed(int argc, char *argv[], void *userdata) {
2084 r = are_we_installed();
2090 return EXIT_SUCCESS;
2093 return EXIT_FAILURE;
2097 static int parse_timeout(const char *arg1, char16_t **ret_timeout, size_t *ret_timeout_size) {
2098 char utf8[DECIMAL_STR_MAX(usec_t)];
2104 assert(ret_timeout);
2105 assert(ret_timeout_size);
2107 if (streq(arg1, "menu
-force
"))
2108 timeout = USEC_INFINITY;
2109 else if (streq(arg1, "menu
-hidden
"))
2112 r = parse_time(arg1, &timeout, USEC_PER_SEC);
2114 return log_error_errno(r, "Failed to parse timeout
'%s': %m
", arg1);
2115 if (timeout != USEC_INFINITY && timeout > UINT32_MAX * USEC_PER_SEC)
2116 log_warning("Timeout is too
long and will be treated as
'menu-force' instead
.");
2119 xsprintf(utf8, USEC_FMT, MIN(timeout / USEC_PER_SEC, UINT32_MAX));
2121 encoded = utf8_to_utf16(utf8, strlen(utf8));
2125 *ret_timeout = encoded;
2126 *ret_timeout_size = char16_strlen(encoded) * 2 + 2;
2130 static int parse_loader_entry_target_arg(const char *arg1, char16_t **ret_target, size_t *ret_target_size) {
2131 char16_t *encoded = NULL;
2136 assert(ret_target_size);
2138 if (streq(arg1, "@current
")) {
2139 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntrySelected), NULL, (void *) ret_target, ret_target_size);
2141 return log_error_errno(r, "Failed to get EFI variable
'LoaderEntrySelected': %m
");
2143 } else if (streq(arg1, "@oneshot
")) {
2144 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryOneShot), NULL, (void *) ret_target, ret_target_size);
2146 return log_error_errno(r, "Failed to get EFI variable
'LoaderEntryOneShot': %m
");
2148 } else if (streq(arg1, "@
default")) {
2149 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryDefault), NULL, (void *) ret_target, ret_target_size);
2151 return log_error_errno(r, "Failed to get EFI variable
'LoaderEntryDefault': %m
");
2153 } else if (arg1[0] == '@' && !streq(arg1, "@saved
"))
2154 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unsupported special entry identifier
: %s
", arg1);
2156 encoded = utf8_to_utf16(arg1, strlen(arg1));
2160 *ret_target = encoded;
2161 *ret_target_size = char16_strlen(encoded) * 2 + 2;
2167 static int verb_set_efivar(int argc, char *argv[], void *userdata) {
2171 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2172 "Not booted with UEFI
.");
2174 if (access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderInfo)), F_OK) < 0) {
2175 if (errno == ENOENT) {
2176 log_error_errno(errno, "Not booted with a supported boot loader
.");
2180 return log_error_errno(errno, "Failed to detect whether boot loader supports
'%s' operation
: %m
", argv[0]);
2183 if (detect_container() > 0)
2184 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2185 "'%s' operation
not supported in a container
.",
2188 if (!arg_touch_variables)
2189 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2190 "'%s' operation cannot be combined with
--no
-variables
.",
2193 const char *variable;
2194 int (* arg_parser)(const char *, char16_t **, size_t *);
2196 if (streq(argv[0], "set
-default")) {
2197 variable = EFI_LOADER_VARIABLE(LoaderEntryDefault);
2198 arg_parser = parse_loader_entry_target_arg;
2199 } else if (streq(argv[0], "set
-oneshot
")) {
2200 variable = EFI_LOADER_VARIABLE(LoaderEntryOneShot);
2201 arg_parser = parse_loader_entry_target_arg;
2202 } else if (streq(argv[0], "set
-timeout
")) {
2203 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeout);
2204 arg_parser = parse_timeout;
2205 } else if (streq(argv[0], "set
-timeout
-oneshot
")) {
2206 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot);
2207 arg_parser = parse_timeout;
2209 assert_not_reached();
2211 if (isempty(argv[1])) {
2212 r = efi_set_variable(variable, NULL, 0);
2213 if (r < 0 && r != -ENOENT)
2214 return log_error_errno(r, "Failed to remove EFI variable
'%s': %m
", variable);
2216 _cleanup_free_ char16_t *value = NULL;
2217 size_t value_size = 0;
2219 r = arg_parser(argv[1], &value, &value_size);
2222 r = efi_set_variable(variable, value, value_size);
2224 return log_error_errno(r, "Failed to update EFI variable
'%s': %m
", variable);
2230 static int verb_random_seed(int argc, char *argv[], void *userdata) {
2233 r = find_esp_and_warn(arg_esp_path, false, &arg_esp_path, NULL, NULL, NULL, NULL, NULL);
2235 /* find_esp_and_warn() doesn't warn about ENOKEY, so let's do that on our own */
2237 return log_error_errno(r, "Unable to find ESP
.");
2239 log_notice("No ESP found
, not initializing random seed
.");
2245 r = install_random_seed(arg_esp_path);
2249 (void) sync_everything();
2253 static int verb_systemd_efi_options(int argc, char *argv[], void *userdata) {
2257 _cleanup_free_ char *line = NULL, *new = NULL;
2259 r = systemd_efi_options_variable(&line);
2261 log_debug("No SystemdOptions EFI variable present in cache
.");
2263 return log_error_errno(r, "Failed to read SystemdOptions EFI variable from cache
: %m
");
2267 r = systemd_efi_options_efivarfs_if_newer(&new);
2268 if (r == -ENODATA) {
2270 log_notice("Note
: SystemdOptions EFI variable has been removed since boot
.");
2272 log_warning_errno(r, "Failed to check SystemdOptions EFI variable in efivarfs
, ignoring
: %m
");
2273 else if (new && !streq_ptr(line, new))
2274 log_notice("Note
: SystemdOptions EFI variable has been modified since boot
. New value
: %s
",
2277 r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE(SystemdOptions), argv[1]);
2279 return log_error_errno(r, "Failed to set SystemdOptions EFI variable
: %m
");
2285 static int verb_reboot_to_firmware(int argc, char *argv[], void *userdata) {
2289 r = efi_get_reboot_to_firmware();
2292 return EXIT_SUCCESS; /* success */
2296 return 1; /* recognizable error #1 */
2298 if (r == -EOPNOTSUPP) {
2299 puts("not supported
");
2300 return 2; /* recognizable error #2 */
2303 log_error_errno(r, "Failed to query reboot
-to
-firmware state
: %m
");
2304 return 3; /* other kind of error */
2306 r = parse_boolean(argv[1]);
2308 return log_error_errno(r, "Failed to parse argument
: %s
", argv[1]);
2310 r = efi_set_reboot_to_firmware(r);
2312 return log_error_errno(r, "Failed to set reboot
-to
-firmware option
: %m
");
2318 static int bootctl_main(int argc, char *argv[]) {
2319 static const Verb verbs[] = {
2320 { "help
", VERB_ANY, VERB_ANY, 0, help },
2321 { "status
", VERB_ANY, 1, VERB_DEFAULT, verb_status },
2322 { "install
", VERB_ANY, 1, 0, verb_install },
2323 { "update
", VERB_ANY, 1, 0, verb_install },
2324 { "remove
", VERB_ANY, 1, 0, verb_remove },
2325 { "is
-installed
", VERB_ANY, 1, 0, verb_is_installed },
2326 { "list
", VERB_ANY, 1, 0, verb_list },
2327 { "set
-default", 2, 2, 0, verb_set_efivar },
2328 { "set
-oneshot
", 2, 2, 0, verb_set_efivar },
2329 { "set
-timeout
", 2, 2, 0, verb_set_efivar },
2330 { "set
-timeout
-oneshot
", 2, 2, 0, verb_set_efivar },
2331 { "random
-seed
", VERB_ANY, 1, 0, verb_random_seed },
2332 { "systemd
-efi
-options
", VERB_ANY, 2, 0, verb_systemd_efi_options },
2333 { "reboot
-to
-firmware
", VERB_ANY, 2, 0, verb_reboot_to_firmware },
2337 return dispatch_verb(argc, argv, verbs, NULL);
2340 static int run(int argc, char *argv[]) {
2343 log_parse_environment();
2346 /* If we run in a container, automatically turn off EFI file system access */
2347 if (detect_container() > 0)
2348 arg_touch_variables = false;
2350 r = parse_argv(argc, argv);
2354 return bootctl_main(argc, argv);
2357 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);