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 "devnum-util.h"
20 #include "dirent-util.h"
22 #include "efi-loader.h"
31 #include "glyph-util.h"
32 #include "main-func.h"
36 #include "parse-argument.h"
37 #include "parse-util.h"
38 #include "pretty-print.h"
39 #include "random-util.h"
41 #include "stat-util.h"
42 #include "stdio-util.h"
43 #include "string-table.h"
44 #include "string-util.h"
46 #include "sync-util.h"
47 #include "terminal-util.h"
48 #include "tmpfile-util.h"
49 #include "tmpfile-util-label.h"
50 #include "tpm2-util.h"
51 #include "umask-util.h"
57 static char *arg_esp_path
= NULL
;
58 static char *arg_xbootldr_path
= NULL
;
59 static bool arg_print_esp_path
= false;
60 static bool arg_print_dollar_boot_path
= false;
61 static bool arg_touch_variables
= true;
62 static PagerFlags arg_pager_flags
= 0;
63 static bool arg_graceful
= false;
64 static bool arg_quiet
= false;
65 static int arg_make_entry_directory
= false; /* tri-state: < 0 for automatic logic */
66 static sd_id128_t arg_machine_id
= SD_ID128_NULL
;
67 static char *arg_install_layout
= NULL
;
69 ARG_ENTRY_TOKEN_MACHINE_ID
,
70 ARG_ENTRY_TOKEN_OS_IMAGE_ID
,
71 ARG_ENTRY_TOKEN_OS_ID
,
72 ARG_ENTRY_TOKEN_LITERAL
,
74 } arg_entry_token_type
= ARG_ENTRY_TOKEN_AUTO
;
75 static char *arg_entry_token
= NULL
;
76 static JsonFormatFlags arg_json_format_flags
= JSON_FORMAT_OFF
;
77 static bool arg_arch_all
= false;
79 STATIC_DESTRUCTOR_REGISTER(arg_esp_path
, freep
);
80 STATIC_DESTRUCTOR_REGISTER(arg_xbootldr_path
, freep
);
81 STATIC_DESTRUCTOR_REGISTER(arg_install_layout
, freep
);
82 STATIC_DESTRUCTOR_REGISTER(arg_entry_token
, freep
);
84 static const char *arg_dollar_boot_path(void) {
85 /* $BOOT shall be the XBOOTLDR partition if it exists, and otherwise the ESP */
86 return arg_xbootldr_path
?: arg_esp_path
;
89 static int acquire_esp(
90 bool unprivileged_mode
,
101 /* Find the ESP, and log about errors. Note that find_esp_and_warn() will log in all error cases on
102 * its own, except for ENOKEY (which is good, we want to show our own message in that case,
103 * suggesting use of --esp-path=) and EACCESS (only when we request unprivileged mode; in this case
104 * we simply eat up the error here, so that --list and --status work too, without noise about
107 r
= find_esp_and_warn(arg_esp_path
, unprivileged_mode
, &np
, ret_part
, ret_pstart
, ret_psize
, ret_uuid
, ret_devid
);
110 return log_full_errno(arg_quiet
? LOG_DEBUG
: LOG_INFO
, r
,
111 "Couldn't find EFI system partition, skipping.");
113 return log_error_errno(r
,
114 "Couldn't find EFI system partition. It is recommended to mount it to /boot or /efi.\n"
115 "Alternatively, use --esp-path= to specify path to mount point.");
120 free_and_replace(arg_esp_path
, np
);
121 log_debug("Using EFI System Partition at %s.", arg_esp_path
);
126 static int acquire_xbootldr(
127 bool unprivileged_mode
,
128 sd_id128_t
*ret_uuid
,
134 r
= find_xbootldr_and_warn(arg_xbootldr_path
, unprivileged_mode
, &np
, ret_uuid
, ret_devid
);
136 log_debug_errno(r
, "Didn't find an XBOOTLDR partition, using the ESP as $BOOT.");
137 arg_xbootldr_path
= mfree(arg_xbootldr_path
);
140 *ret_uuid
= SD_ID128_NULL
;
148 free_and_replace(arg_xbootldr_path
, np
);
149 log_debug("Using XBOOTLDR partition at %s as $BOOT.", arg_xbootldr_path
);
154 static int load_etc_machine_id(void) {
157 r
= sd_id128_get_machine(&arg_machine_id
);
158 if (IN_SET(r
, -ENOENT
, -ENOMEDIUM
)) /* Not set or empty */
161 return log_error_errno(r
, "Failed to get machine-id: %m");
163 log_debug("Loaded machine ID %s from /etc/machine-id.", SD_ID128_TO_STRING(arg_machine_id
));
167 static int load_etc_machine_info(void) {
168 /* systemd v250 added support to store the kernel-install layout setting and the machine ID to use
169 * for setting up the ESP in /etc/machine-info. The newer /etc/kernel/entry-token file, as well as
170 * the $layout field in /etc/kernel/install.conf are better replacements for this though, hence this
171 * has been deprecated and is only returned for compatibility. */
172 _cleanup_free_
char *s
= NULL
, *layout
= NULL
;
175 r
= parse_env_file(NULL
, "/etc/machine-info",
176 "KERNEL_INSTALL_LAYOUT", &layout
,
177 "KERNEL_INSTALL_MACHINE_ID", &s
);
181 return log_error_errno(r
, "Failed to parse /etc/machine-info: %m");
185 log_notice("Read $KERNEL_INSTALL_MACHINE_ID from /etc/machine-info. "
186 "Please move it to /etc/kernel/entry-token.");
188 r
= sd_id128_from_string(s
, &arg_machine_id
);
190 return log_error_errno(r
, "Failed to parse KERNEL_INSTALL_MACHINE_ID=%s in /etc/machine-info: %m", s
);
192 log_debug("Loaded KERNEL_INSTALL_MACHINE_ID=%s from KERNEL_INSTALL_MACHINE_ID in /etc/machine-info.",
193 SD_ID128_TO_STRING(arg_machine_id
));
196 if (!isempty(layout
)) {
198 log_notice("Read $KERNEL_INSTALL_LAYOUT from /etc/machine-info. "
199 "Please move it to the layout= setting of /etc/kernel/install.conf.");
201 log_debug("KERNEL_INSTALL_LAYOUT=%s is specified in /etc/machine-info.", layout
);
202 free_and_replace(arg_install_layout
, layout
);
208 static int load_etc_kernel_install_conf(void) {
209 _cleanup_free_
char *layout
= NULL
;
212 r
= parse_env_file(NULL
, "/etc/kernel/install.conf",
217 return log_error_errno(r
, "Failed to parse /etc/kernel/install.conf: %m");
219 if (!isempty(layout
)) {
220 log_debug("layout=%s is specified in /etc/machine-info.", layout
);
221 free_and_replace(arg_install_layout
, layout
);
227 static int settle_entry_token(void) {
230 switch (arg_entry_token_type
) {
232 case ARG_ENTRY_TOKEN_AUTO
: {
233 _cleanup_free_
char *buf
= NULL
;
234 r
= read_one_line_file("/etc/kernel/entry-token", &buf
);
235 if (r
< 0 && r
!= -ENOENT
)
236 return log_error_errno(r
, "Failed to read /etc/kernel/entry-token: %m");
239 free_and_replace(arg_entry_token
, buf
);
240 arg_entry_token_type
= ARG_ENTRY_TOKEN_LITERAL
;
241 } else if (sd_id128_is_null(arg_machine_id
)) {
242 _cleanup_free_
char *id
= NULL
, *image_id
= NULL
;
244 r
= parse_os_release(NULL
,
245 "IMAGE_ID", &image_id
,
248 return log_error_errno(r
, "Failed to load /etc/os-release: %m");
250 if (!isempty(image_id
)) {
251 free_and_replace(arg_entry_token
, image_id
);
252 arg_entry_token_type
= ARG_ENTRY_TOKEN_OS_IMAGE_ID
;
253 } else if (!isempty(id
)) {
254 free_and_replace(arg_entry_token
, id
);
255 arg_entry_token_type
= ARG_ENTRY_TOKEN_OS_ID
;
257 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No machine ID set, and /etc/os-release carries no ID=/IMAGE_ID= fields.");
259 r
= free_and_strdup_warn(&arg_entry_token
, SD_ID128_TO_STRING(arg_machine_id
));
263 arg_entry_token_type
= ARG_ENTRY_TOKEN_MACHINE_ID
;
269 case ARG_ENTRY_TOKEN_MACHINE_ID
:
270 if (sd_id128_is_null(arg_machine_id
))
271 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No machine ID set.");
273 r
= free_and_strdup_warn(&arg_entry_token
, SD_ID128_TO_STRING(arg_machine_id
));
279 case ARG_ENTRY_TOKEN_OS_IMAGE_ID
: {
280 _cleanup_free_
char *buf
= NULL
;
282 r
= parse_os_release(NULL
, "IMAGE_ID", &buf
);
284 return log_error_errno(r
, "Failed to load /etc/os-release: %m");
287 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "IMAGE_ID= field not set in /etc/os-release.");
289 free_and_replace(arg_entry_token
, buf
);
293 case ARG_ENTRY_TOKEN_OS_ID
: {
294 _cleanup_free_
char *buf
= NULL
;
296 r
= parse_os_release(NULL
, "ID", &buf
);
298 return log_error_errno(r
, "Failed to load /etc/os-release: %m");
301 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "ID= field not set in /etc/os-release.");
303 free_and_replace(arg_entry_token
, buf
);
307 case ARG_ENTRY_TOKEN_LITERAL
:
308 assert(!isempty(arg_entry_token
)); /* already filled in by command line parser */
312 if (isempty(arg_entry_token
) || !string_is_safe(arg_entry_token
))
313 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Selected entry token not valid: %s", arg_entry_token
);
315 log_debug("Using entry token: %s", arg_entry_token
);
319 static bool use_boot_loader_spec_type1(void) {
320 /* If the layout is not specified, or if it is set explicitly to "bls" we assume Boot Loader
321 * Specification Type #1 is the chosen format for our boot loader entries */
322 return !arg_install_layout
|| streq(arg_install_layout
, "bls");
325 static int settle_make_entry_directory(void) {
328 r
= load_etc_machine_id();
332 r
= load_etc_machine_info();
336 r
= load_etc_kernel_install_conf();
340 r
= settle_entry_token();
344 bool layout_type1
= use_boot_loader_spec_type1();
345 if (arg_make_entry_directory
< 0) { /* Automatic mode */
347 if (arg_entry_token
== ARG_ENTRY_TOKEN_MACHINE_ID
) {
348 r
= path_is_temporary_fs("/etc/machine-id");
350 return log_debug_errno(r
, "Couldn't determine whether /etc/machine-id is on a temporary file system: %m");
352 arg_make_entry_directory
= r
== 0;
354 arg_make_entry_directory
= true;
356 arg_make_entry_directory
= false;
359 if (arg_make_entry_directory
> 0 && !layout_type1
)
360 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
361 "KERNEL_INSTALL_LAYOUT=%s is configured, but Boot Loader Specification Type #1 entry directory creation was requested.",
367 /* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */
368 static int get_file_version(int fd
, char **v
) {
378 if (fstat(fd
, &st
) < 0)
379 return log_error_errno(errno
, "Failed to stat EFI binary: %m");
381 r
= stat_verify_regular(&st
);
383 return log_error_errno(r
, "EFI binary is not a regular file: %m");
385 if (st
.st_size
< 27 || file_offset_beyond_memory_size(st
.st_size
)) {
390 buf
= mmap(NULL
, st
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
391 if (buf
== MAP_FAILED
)
392 return log_error_errno(errno
, "Failed to memory map EFI binary: %m");
394 s
= mempmem_safe(buf
, st
.st_size
- 8, "#### LoaderInfo: ", 17);
398 e
= memmem_safe(s
, st
.st_size
- (s
- buf
), " ####", 5);
399 if (!e
|| e
- s
< 3) {
400 r
= log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Malformed version string.");
404 x
= strndup(s
, e
- s
);
412 (void) munmap(buf
, st
.st_size
);
417 static const char *get_efi_arch(void) {
418 /* Detect EFI firmware architecture of the running system. On mixed mode systems, it could be 32bit
419 * while the kernel is running in 64bit. */
422 _cleanup_free_
char *platform_size
= NULL
;
425 r
= read_one_line_file("/sys/firmware/efi/fw_platform_size", &platform_size
);
427 return EFI_MACHINE_TYPE_NAME
;
429 log_warning_errno(r
, "Error reading EFI firmware word size, assuming '%u': %m", __WORDSIZE
);
430 return EFI_MACHINE_TYPE_NAME
;
433 if (streq(platform_size
, "64"))
434 return EFI_MACHINE_TYPE_NAME
;
435 if (streq(platform_size
, "32"))
439 "Unknown EFI firmware word size '%s', using default word size '%u' instead.",
444 return EFI_MACHINE_TYPE_NAME
;
447 static int enumerate_binaries(const char *esp_path
, const char *path
, const char *prefix
) {
448 _cleanup_closedir_
DIR *d
= NULL
;
455 p
= prefix_roota(esp_path
, path
);
461 return log_error_errno(errno
, "Failed to read \"%s\": %m", p
);
464 FOREACH_DIRENT(de
, d
, break) {
465 _cleanup_free_
char *v
= NULL
;
466 _cleanup_close_
int fd
= -1;
468 if (!endswith_no_case(de
->d_name
, ".efi"))
471 if (prefix
&& !startswith_no_case(de
->d_name
, prefix
))
474 fd
= openat(dirfd(d
), de
->d_name
, O_RDONLY
|O_CLOEXEC
);
476 return log_error_errno(errno
, "Failed to open \"%s/%s\" for reading: %m", p
, de
->d_name
);
478 r
= get_file_version(fd
, &v
);
482 printf(" File: %s/%s/%s (%s%s%s)\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), path
, de
->d_name
, ansi_highlight(), v
, ansi_normal());
484 printf(" File: %s/%s/%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), path
, de
->d_name
);
492 static int status_binaries(const char *esp_path
, sd_id128_t partition
) {
495 printf("Available Boot Loaders on ESP:\n");
498 printf(" ESP: Cannot find or access mount point of ESP.\n\n");
502 printf(" ESP: %s", esp_path
);
503 if (!sd_id128_is_null(partition
))
504 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR
")", SD_ID128_FORMAT_VAL(partition
));
507 r
= enumerate_binaries(esp_path
, "EFI/systemd", NULL
);
510 if (r
== 0 && !arg_quiet
)
511 log_info("systemd-boot not installed in ESP.");
513 r
= enumerate_binaries(esp_path
, "EFI/BOOT", "boot");
516 if (r
== 0 && !arg_quiet
)
517 log_info("No default/fallback boot loader installed in ESP.");
526 static int print_efi_option(uint16_t id
, bool in_order
) {
527 _cleanup_free_
char *title
= NULL
;
528 _cleanup_free_
char *path
= NULL
;
529 sd_id128_t partition
;
533 r
= efi_get_boot_option(id
, &title
, &partition
, &path
, &active
);
537 /* print only configured entries with partition information */
538 if (!path
|| sd_id128_is_null(partition
))
541 efi_tilt_backslashes(path
);
543 printf(" Title: %s%s%s\n", ansi_highlight(), strna(title
), ansi_normal());
544 printf(" ID: 0x%04X\n", id
);
545 printf(" Status: %sactive%s\n", active
? "" : "in", in_order
? ", boot-order" : "");
546 printf(" Partition: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR
"\n",
547 SD_ID128_FORMAT_VAL(partition
));
548 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), path
);
554 static int status_variables(void) {
555 _cleanup_free_
uint16_t *options
= NULL
, *order
= NULL
;
556 int n_options
, n_order
;
558 n_options
= efi_get_boot_options(&options
);
559 if (n_options
== -ENOENT
)
560 return log_error_errno(n_options
,
561 "Failed to access EFI variables, efivarfs"
562 " needs to be available at /sys/firmware/efi/efivars/.");
564 return log_error_errno(n_options
, "Failed to read EFI boot entries: %m");
566 n_order
= efi_get_boot_order(&order
);
567 if (n_order
== -ENOENT
)
569 else if (n_order
< 0)
570 return log_error_errno(n_order
, "Failed to read EFI boot order: %m");
572 /* print entries in BootOrder first */
573 printf("Boot Loaders Listed in EFI Variables:\n");
574 for (int i
= 0; i
< n_order
; i
++)
575 print_efi_option(order
[i
], true);
577 /* print remaining entries */
578 for (int i
= 0; i
< n_options
; i
++) {
579 for (int j
= 0; j
< n_order
; j
++)
580 if (options
[i
] == order
[j
])
583 print_efi_option(options
[i
], false);
592 static int boot_config_load_and_select(
594 const char *esp_path
,
596 const char *xbootldr_path
,
597 dev_t xbootldr_devid
) {
599 _cleanup_strv_free_
char **efi_entries
= NULL
;
602 /* If XBOOTLDR and ESP actually refer to the same block device, suppress XBOOTLDR, since it would
603 * find the same entries twice. */
604 bool same
= esp_path
&& xbootldr_path
&& devnum_set_and_equal(esp_devid
, xbootldr_devid
);
606 r
= boot_config_load(config
, esp_path
, same
? NULL
: xbootldr_path
);
610 r
= efi_loader_get_entries(&efi_entries
);
611 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
612 log_debug_errno(r
, "Boot loader reported no entries.");
614 log_warning_errno(r
, "Failed to determine entries reported by boot loader, ignoring: %m");
616 (void) boot_config_augment_from_loader(config
, efi_entries
, /* only_auto= */ false);
618 return boot_config_select_special_entries(config
);
621 static int status_entries(
622 const BootConfig
*config
,
623 const char *esp_path
,
624 sd_id128_t esp_partition_uuid
,
625 const char *xbootldr_path
,
626 sd_id128_t xbootldr_partition_uuid
) {
628 sd_id128_t dollar_boot_partition_uuid
;
629 const char *dollar_boot_path
;
633 assert(esp_path
|| xbootldr_path
);
636 dollar_boot_path
= xbootldr_path
;
637 dollar_boot_partition_uuid
= xbootldr_partition_uuid
;
639 dollar_boot_path
= esp_path
;
640 dollar_boot_partition_uuid
= esp_partition_uuid
;
643 printf("Boot Loader Entries:\n"
644 " $BOOT: %s", dollar_boot_path
);
645 if (!sd_id128_is_null(dollar_boot_partition_uuid
))
646 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR
")",
647 SD_ID128_FORMAT_VAL(dollar_boot_partition_uuid
));
650 if (config
->default_entry
< 0)
651 printf("%zu entries, no entry could be determined as default.\n", config
->n_entries
);
653 printf("Default Boot Loader Entry:\n");
656 boot_config_default_entry(config
),
657 /* show_as_default= */ false,
658 /* show_as_selected= */ false,
659 /* show_discovered= */ false);
661 /* < 0 is already logged by the function itself, let's just emit an extra warning if
662 the default entry is broken */
663 printf("\nWARNING: default boot entry is broken\n");
669 static int compare_product(const char *a
, const char *b
) {
678 return x
< y
? -1 : x
> y
? 1 : 0;
680 return strncmp(a
, b
, x
);
683 static int compare_version(const char *a
, const char *b
) {
687 a
+= strcspn(a
, " ");
689 b
+= strcspn(b
, " ");
692 return strverscmp_improved(a
, b
);
695 static int version_check(int fd_from
, const char *from
, int fd_to
, const char *to
) {
696 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
699 assert(fd_from
>= 0);
704 r
= get_file_version(fd_from
, &a
);
708 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE
),
709 "Source file \"%s\" does not carry version information!",
712 r
= get_file_version(fd_to
, &b
);
715 if (r
== 0 || compare_product(a
, b
) != 0)
716 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE
),
717 "Skipping \"%s\", since it's owned by another boot loader.",
720 r
= compare_version(a
, b
);
721 log_debug("Comparing versions: \"%s\" %s \"%s", a
, comparison_operator(r
), b
);
723 return log_warning_errno(SYNTHETIC_ERRNO(ESTALE
),
724 "Skipping \"%s\", since newer boot loader version in place already.", to
);
726 return log_info_errno(SYNTHETIC_ERRNO(ESTALE
),
727 "Skipping \"%s\", since same boot loader version in place already.", to
);
732 static int copy_file_with_version_check(const char *from
, const char *to
, bool force
) {
733 _cleanup_close_
int fd_from
= -1, fd_to
= -1;
734 _cleanup_free_
char *t
= NULL
;
737 fd_from
= open(from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
739 return log_error_errno(errno
, "Failed to open \"%s\" for reading: %m", from
);
742 fd_to
= open(to
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
745 return log_error_errno(errno
, "Failed to open \"%s\" for reading: %m", to
);
747 r
= version_check(fd_from
, from
, fd_to
, to
);
751 if (lseek(fd_from
, 0, SEEK_SET
) == (off_t
) -1)
752 return log_error_errno(errno
, "Failed to seek in \"%s\": %m", from
);
754 fd_to
= safe_close(fd_to
);
758 r
= tempfn_random(to
, NULL
, &t
);
762 RUN_WITH_UMASK(0000) {
763 fd_to
= open(t
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_EXCL
|O_NOFOLLOW
, 0644);
765 return log_error_errno(errno
, "Failed to open \"%s\" for writing: %m", t
);
768 r
= copy_bytes(fd_from
, fd_to
, UINT64_MAX
, COPY_REFLINK
);
771 return log_error_errno(r
, "Failed to copy data from \"%s\" to \"%s\": %m", from
, t
);
774 (void) copy_times(fd_from
, fd_to
, 0);
776 r
= fsync_full(fd_to
);
778 (void) unlink_noerrno(t
);
779 return log_error_errno(r
, "Failed to copy data from \"%s\" to \"%s\": %m", from
, t
);
782 if (renameat(AT_FDCWD
, t
, AT_FDCWD
, to
) < 0) {
783 (void) unlink_noerrno(t
);
784 return log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", t
, to
);
787 log_info("Copied \"%s\" to \"%s\".", from
, to
);
792 static int mkdir_one(const char *prefix
, const char *suffix
) {
793 _cleanup_free_
char *p
= NULL
;
795 p
= path_join(prefix
, suffix
);
796 if (mkdir(p
, 0700) < 0) {
798 return log_error_errno(errno
, "Failed to create \"%s\": %m", p
);
800 log_info("Created \"%s\".", p
);
805 static const char *const esp_subdirs
[] = {
806 /* The directories to place in the ESP */
814 static const char *const dollar_boot_subdirs
[] = {
815 /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
817 "loader/entries", /* Type #1 entries */
819 "EFI/Linux", /* Type #2 entries */
823 static int create_subdirs(const char *root
, const char * const *subdirs
) {
826 STRV_FOREACH(i
, subdirs
) {
827 r
= mkdir_one(root
, *i
);
835 static int copy_one_file(const char *esp_path
, const char *name
, bool force
) {
837 char *p
, *q
, *dest_name
, *s
;
840 dest_name
= strdupa_safe(name
);
841 s
= endswith_no_case(dest_name
, ".signed");
845 p
= strjoina(BOOTLIBDIR
"/", name
);
846 q
= strjoina(esp_path
, "/EFI/systemd/", dest_name
);
847 r
= copy_file_with_version_check(p
, q
, force
);
849 e
= startswith(dest_name
, "systemd-boot");
854 /* Create the EFI default boot loader name (specified for removable devices) */
855 v
= strjoina(esp_path
, "/EFI/BOOT/BOOT", e
);
856 ascii_strupper(strrchr(v
, '/') + 1);
858 k
= copy_file_with_version_check(p
, v
, force
);
866 static int install_binaries(const char *esp_path
, const char *arch
, bool force
) {
867 _cleanup_closedir_
DIR *d
= NULL
;
870 d
= opendir(BOOTLIBDIR
);
872 return log_error_errno(errno
, "Failed to open \""BOOTLIBDIR
"\": %m
");
874 const char *suffix = strjoina(arch, ".efi
");
875 const char *suffix_signed = strjoina(arch, ".efi
.signed");
877 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read
\""BOOTLIBDIR"\": %m
")) {
880 if (!endswith_no_case(de->d_name, suffix) && !endswith_no_case(de->d_name, suffix_signed))
883 /* skip the .efi file, if there's a .signed version of it */
884 if (endswith_no_case(de->d_name, ".efi
")) {
885 _cleanup_free_ const char *s = strjoin(de->d_name, ".signed");
888 if (faccessat(dirfd(d), s, F_OK, 0) >= 0)
892 k = copy_one_file(esp_path, de->d_name, force);
893 /* Don't propagate an error code if no update necessary, installed version already equal or
894 * newer version, or other boot loader in place. */
895 if (arg_graceful && IN_SET(k, -ESTALE, -EREMOTE))
904 static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
905 _cleanup_free_ char *opath = NULL;
909 r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
912 if (!sd_id128_equal(uuid, ouuid))
915 /* Some motherboards convert the path to uppercase under certain circumstances
916 * (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
917 * so use case-insensitive checking */
918 if (!strcaseeq_ptr(path, opath))
924 static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
925 _cleanup_free_ uint16_t *options = NULL;
928 n = efi_get_boot_options(&options);
932 /* find already existing systemd-boot entry */
933 for (i = 0; i < n; i++)
934 if (same_entry(options[i], uuid, path)) {
939 /* find free slot in the sorted BootXXXX variable list */
940 for (i = 0; i < n; i++)
941 if (i != options[i]) {
946 /* use the next one */
953 static int insert_into_order(uint16_t slot, bool first) {
954 _cleanup_free_ uint16_t *order = NULL;
958 n = efi_get_boot_order(&order);
960 /* no entry, add us */
961 return efi_set_boot_order(&slot, 1);
963 /* are we the first and only one? */
964 if (n == 1 && order[0] == slot)
967 /* are we already in the boot order? */
968 for (int i = 0; i < n; i++) {
969 if (order[i] != slot)
972 /* we do not require to be the first one, all is fine */
976 /* move us to the first slot */
977 memmove(order + 1, order, i * sizeof(uint16_t));
979 return efi_set_boot_order(order, n);
983 t = reallocarray(order, n + 1, sizeof(uint16_t));
988 /* add us to the top or end of the list */
990 memmove(order + 1, order, n * sizeof(uint16_t));
995 return efi_set_boot_order(order, n + 1);
998 static int remove_from_order(uint16_t slot) {
999 _cleanup_free_ uint16_t *order = NULL;
1002 n = efi_get_boot_order(&order);
1006 for (int i = 0; i < n; i++) {
1007 if (order[i] != slot)
1011 memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
1012 return efi_set_boot_order(order, n - 1);
1018 static int install_variables(const char *esp_path,
1019 uint32_t part, uint64_t pstart, uint64_t psize,
1020 sd_id128_t uuid, const char *path,
1026 if (!is_efi_boot()) {
1027 log_warning("Not booted with EFI
, skipping EFI variable setup
.");
1031 p = prefix_roota(esp_path, path);
1032 if (access(p, F_OK) < 0) {
1033 if (errno == ENOENT)
1036 return log_error_errno(errno, "Cannot access
\"%s
\": %m
", p);
1039 r = find_slot(uuid, path, &slot);
1041 return log_error_errno(r,
1043 "Failed to access EFI variables
. Is the
\"efivarfs
\" filesystem mounted
?" :
1044 "Failed to determine current boot order
: %m
");
1046 if (first || r == 0) {
1047 r = efi_add_boot_option(slot, "Linux Boot Manager
",
1048 part, pstart, psize,
1051 return log_error_errno(r, "Failed to create EFI Boot variable entry
: %m
");
1053 log_info("Created EFI boot entry
\"Linux Boot Manager
\".");
1056 return insert_into_order(slot, first);
1059 static int remove_boot_efi(const char *esp_path) {
1060 _cleanup_closedir_ DIR *d = NULL;
1064 p = prefix_roota(esp_path, "/EFI
/BOOT
");
1067 if (errno == ENOENT)
1070 return log_error_errno(errno, "Failed to open directory
\"%s
\": %m
", p);
1073 FOREACH_DIRENT(de, d, break) {
1074 _cleanup_close_ int fd = -1;
1075 _cleanup_free_ char *v = NULL;
1077 if (!endswith_no_case(de->d_name, ".efi
"))
1080 if (!startswith_no_case(de->d_name, "boot
"))
1083 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
1085 return log_error_errno(errno, "Failed to open
\"%s
/%s
\" for reading
: %m
", p, de->d_name);
1087 r = get_file_version(fd, &v);
1090 if (r > 0 && startswith(v, "systemd
-boot
")) {
1091 r = unlinkat(dirfd(d), de->d_name, 0);
1093 return log_error_errno(errno, "Failed to remove
\"%s
/%s
\": %m
", p, de->d_name);
1095 log_info("Removed
\"%s
/%s
\".", p, de->d_name);
1104 static int rmdir_one(const char *prefix, const char *suffix) {
1107 p = prefix_roota(prefix, suffix);
1109 bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
1111 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
1112 "Failed to remove directory
\"%s
\": %m
", p);
1116 log_info("Removed
\"%s
\".", p);
1121 static int remove_subdirs(const char *root, const char *const *subdirs) {
1124 /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
1125 * short the array is. */
1127 if (!subdirs[0]) /* A the end of the list */
1130 r = remove_subdirs(root, subdirs + 1);
1131 q = rmdir_one(root, subdirs[0]);
1133 return r < 0 ? r : q;
1136 static int remove_entry_directory(const char *root) {
1138 assert(arg_make_entry_directory >= 0);
1140 if (!arg_make_entry_directory || !arg_entry_token)
1143 return rmdir_one(root, arg_entry_token);
1146 static int remove_binaries(const char *esp_path) {
1150 p = prefix_roota(esp_path, "/EFI
/systemd
");
1151 r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
1153 q = remove_boot_efi(esp_path);
1154 if (q < 0 && r == 0)
1160 static int remove_file(const char *root, const char *file) {
1166 p = prefix_roota(root, file);
1167 if (unlink(p) < 0) {
1168 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
1169 "Failed to unlink file
\"%s
\": %m
", p);
1171 return errno == ENOENT ? 0 : -errno;
1174 log_info("Removed
\"%s
\".", p);
1178 static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
1185 r = find_slot(uuid, path, &slot);
1189 r = efi_remove_boot_option(slot);
1194 return remove_from_order(slot);
1199 static int remove_loader_variables(void) {
1202 /* Remove all persistent loader variables we define */
1205 EFI_LOADER_VARIABLE(LoaderConfigTimeout),
1206 EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot),
1207 EFI_LOADER_VARIABLE(LoaderEntryDefault),
1208 EFI_LOADER_VARIABLE(LoaderEntryOneShot),
1209 EFI_LOADER_VARIABLE(LoaderSystemToken)){
1213 q = efi_set_variable(var, NULL, 0);
1217 log_warning_errno(q, "Failed to remove EFI variable
%s
: %m
", var);
1221 log_info("Removed EFI variable
%s
.", var);
1227 static int install_loader_config(const char *esp_path) {
1228 _cleanup_(unlink_and_freep) char *t = NULL;
1229 _cleanup_fclose_ FILE *f = NULL;
1233 assert(arg_make_entry_directory >= 0);
1235 p = prefix_roota(esp_path, "/loader
/loader
.conf
");
1236 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
1239 r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
1241 return log_error_errno(r, "Failed to open
\"%s
\" for writing
: %m
", p);
1243 fprintf(f, "#timeout 3\n"
1244 "#console-mode keep\n");
1246 if (arg_make_entry_directory) {
1247 assert(arg_entry_token);
1248 fprintf(f, "default %s-*\n", arg_entry_token);
1251 r = flink_tmpfile(f, t, p);
1253 return 0; /* Silently skip creation if the file exists now (recheck) */
1255 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1261 static int install_loader_specification(const char *root) {
1262 _cleanup_(unlink_and_freep) char *t = NULL;
1263 _cleanup_fclose_ FILE *f = NULL;
1264 _cleanup_free_ char *p = NULL;
1267 p = path_join(root, "/loader/entries.srel");
1271 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
1274 r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
1276 return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
1278 fprintf(f, "type1\n");
1280 r = flink_tmpfile(f, t, p);
1282 return 0; /* Silently skip creation if the file exists now (recheck) */
1284 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1290 static int install_entry_directory(const char *root) {
1292 assert(arg_make_entry_directory >= 0);
1294 if (!arg_make_entry_directory)
1297 assert(arg_entry_token);
1298 return mkdir_one(root, arg_entry_token);
1301 static int install_entry_token(void) {
1304 assert(arg_make_entry_directory >= 0);
1305 assert(arg_entry_token);
1307 /* Let's save the used entry token in /etc/kernel/entry-token if we used it to create the entry
1308 * directory, or if anything else but the machine ID */
1310 if (!arg_make_entry_directory && arg_entry_token_type == ARG_ENTRY_TOKEN_MACHINE_ID)
1313 r = write_string_file("/etc/kernel/entry-token", arg_entry_token, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755);
1315 return log_error_errno(r, "Failed to write entry token '%s' to /etc/kernel/entry-token", arg_entry_token);
1320 static int help(int argc, char *argv[], void *userdata) {
1321 _cleanup_free_ char *link = NULL;
1324 r = terminal_urlify_man("bootctl", "1", &link);
1328 printf("%1$s [OPTIONS...] COMMAND ...\n"
1329 "\n%5$sControl EFI firmware boot settings and manage boot loader.%6$s\n"
1330 "\n%3$sGeneric EFI Firmware/Boot Loader Commands:%4$s\n"
1331 " status Show status of installed boot loader and EFI variables\n"
1332 " reboot-to-firmware [BOOL]\n"
1333 " Query or set reboot-to-firmware EFI flag\n"
1334 " systemd-efi-options [STRING]\n"
1335 " Query or set system options string in EFI variable\n"
1336 "\n%3$sBoot Loader Specification Commands:%4$s\n"
1337 " list List boot loader entries\n"
1338 " set-default ID Set default boot loader entry\n"
1339 " set-oneshot ID Set default boot loader entry, for next boot only\n"
1340 " set-timeout SECONDS Set the menu timeout\n"
1341 " set-timeout-oneshot SECONDS\n"
1342 " Set the menu timeout for the next boot only\n"
1343 "\n%3$ssystemd-boot Commands:%4$s\n"
1344 " install Install systemd-boot to the ESP and EFI variables\n"
1345 " update Update systemd-boot in the ESP and EFI variables\n"
1346 " remove Remove systemd-boot from the ESP and EFI variables\n"
1347 " is-installed Test whether systemd-boot is installed in the ESP\n"
1348 " random-seed Initialize random seed in ESP and EFI variables\n"
1349 "\n%3$sOptions:%4$s\n"
1350 " -h --help Show this help\n"
1351 " --version Print version\n"
1352 " --esp-path=PATH Path to the EFI System Partition (ESP)\n"
1353 " --boot-path=PATH Path to the $BOOT partition\n"
1354 " -p --print-esp-path Print path to the EFI System Partition\n"
1355 " -x --print-boot-path Print path to the $BOOT partition\n"
1356 " --no-variables Don't touch EFI variables\n"
1357 " --no-pager Do not pipe output into a pager\n"
1358 " --graceful Don't fail when the ESP cannot be found or EFI\n"
1359 " variables cannot be written\n"
1360 " -q --quiet Suppress output\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 " --json=pretty|short|off\n"
1366 " Generate JSON output\n"
1367 " --all-architectures\n"
1368 " Install all supported EFI architectures\n"
1369 "\nSee the %2$s for details.\n",
1370 program_invocation_short_name,
1380 static int parse_argv(int argc, char *argv[]) {
1382 ARG_ESP_PATH = 0x100,
1388 ARG_MAKE_ENTRY_DIRECTORY,
1394 static const struct option options[] = {
1395 { "help", no_argument, NULL, 'h' },
1396 { "version", no_argument, NULL, ARG_VERSION },
1397 { "esp-path", required_argument, NULL, ARG_ESP_PATH },
1398 { "path", required_argument, NULL, ARG_ESP_PATH }, /* Compatibility alias */
1399 { "boot-path", required_argument, NULL, ARG_BOOT_PATH },
1400 { "print-esp-path", no_argument, NULL, 'p' },
1401 { "print-path", no_argument, NULL, 'p' }, /* Compatibility alias */
1402 { "print-boot-path", no_argument, NULL, 'x' },
1403 { "no-variables", no_argument, NULL, ARG_NO_VARIABLES },
1404 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1405 { "graceful", no_argument, NULL, ARG_GRACEFUL },
1406 { "quiet", no_argument, NULL, 'q' },
1407 { "make-entry-directory", required_argument, NULL, ARG_MAKE_ENTRY_DIRECTORY },
1408 { "make-machine-id-directory", required_argument, NULL, ARG_MAKE_ENTRY_DIRECTORY }, /* Compatibility alias */
1409 { "entry-token", required_argument, NULL, ARG_ENTRY_TOKEN },
1410 { "json", required_argument, NULL, ARG_JSON },
1411 { "all-architectures", no_argument, NULL, ARG_ARCH_ALL },
1421 while ((c = getopt_long(argc, argv, "hpx", options, NULL)) >= 0)
1425 help(0, NULL, NULL);
1432 r = free_and_strdup(&arg_esp_path, optarg);
1438 r = free_and_strdup(&arg_xbootldr_path, optarg);
1444 if (arg_print_dollar_boot_path)
1445 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1446 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1447 arg_print_esp_path = true;
1451 if (arg_print_esp_path)
1452 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1453 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1454 arg_print_dollar_boot_path = true;
1457 case ARG_NO_VARIABLES:
1458 arg_touch_variables = false;
1462 arg_pager_flags |= PAGER_DISABLE;
1466 arg_graceful = true;
1473 case ARG_ENTRY_TOKEN: {
1476 if (streq(optarg, "machine-id")) {
1477 arg_entry_token_type = ARG_ENTRY_TOKEN_MACHINE_ID;
1478 arg_entry_token = mfree(arg_entry_token);
1479 } else if (streq(optarg, "os-image-id")) {
1480 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_IMAGE_ID;
1481 arg_entry_token = mfree(arg_entry_token);
1482 } else if (streq(optarg, "os-id")) {
1483 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_ID;
1484 arg_entry_token = mfree(arg_entry_token);
1485 } else if ((e = startswith(optarg, "literal:"))) {
1486 arg_entry_token_type = ARG_ENTRY_TOKEN_LITERAL;
1488 r = free_and_strdup_warn(&arg_entry_token, e);
1492 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1493 "Unexpected parameter for --entry-token=: %s", optarg);
1498 case ARG_MAKE_ENTRY_DIRECTORY:
1499 if (streq(optarg, "auto")) /* retained for backwards compatibility */
1500 arg_make_entry_directory = -1; /* yes if machine-id is permanent */
1502 r = parse_boolean_argument("--make-entry-directory=", optarg, &b);
1506 arg_make_entry_directory = b;
1511 r = parse_json_argument(optarg, &arg_json_format_flags);
1517 arg_arch_all = true;
1524 assert_not_reached();
1530 static void read_efi_var(const char *variable, char **ret) {
1533 r = efi_get_variable_string(variable, ret);
1534 if (r < 0 && r != -ENOENT)
1535 log_warning_errno(r, "Failed to read EFI variable %s: %m", variable);
1538 static void print_yes_no_line(bool first, bool good, const char *name) {
1540 first ? " Features: " : " ",
1541 COLOR_MARK_BOOL(good),
1545 static int are_we_installed(const char *esp_path) {
1548 /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
1549 * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
1550 * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
1551 * should be a suitable and very minimal check for a number of reasons:
1553 * → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
1554 * not a specific one.)
1556 * → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
1557 * /EFI/BOOT/BOOT*.EFI fallback binary.
1559 * → It specifically checks for systemd-boot, not for other boot loaders (which a check for
1560 * /boot/loader/entries would do). */
1562 _cleanup_free_ char *p = path_join(esp_path, "/EFI/systemd/");
1566 log_debug("Checking whether %s contains any files…", p);
1567 r = dir_is_empty(p, /* ignore_hidden_or_backup= */ false);
1568 if (r < 0 && r != -ENOENT)
1569 return log_error_errno(r, "Failed to check whether %s contains any files: %m", p);
1574 static int verb_status(int argc, char *argv[], void *userdata) {
1575 sd_id128_t esp_uuid = SD_ID128_NULL, xbootldr_uuid = SD_ID128_NULL;
1576 dev_t esp_devid = 0, xbootldr_devid = 0;
1579 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, &esp_uuid, &esp_devid);
1580 if (arg_print_esp_path) {
1581 if (r == -EACCES) /* If we couldn't acquire the ESP path, log about access errors (which is the only
1582 * error the find_esp_and_warn() won't log on its own) */
1583 return log_error_errno(r, "Failed to determine ESP location: %m");
1590 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, &xbootldr_uuid, &xbootldr_devid);
1591 if (arg_print_dollar_boot_path) {
1593 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1597 const char *path = arg_dollar_boot_path();
1599 return log_error_errno(SYNTHETIC_ERRNO(EACCES), "Failed to determine XBOOTLDR location: %m");
1604 if (arg_print_esp_path || arg_print_dollar_boot_path)
1607 r = 0; /* If we couldn't determine the path, then don't consider that a problem from here on, just
1608 * show what we can show */
1610 pager_open(arg_pager_flags);
1612 if (is_efi_boot()) {
1613 static const struct {
1617 { EFI_LOADER_FEATURE_BOOT_COUNTING, "Boot counting" },
1618 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT, "Menu timeout control" },
1619 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT, "One-shot menu timeout control" },
1620 { EFI_LOADER_FEATURE_ENTRY_DEFAULT, "Default entry control" },
1621 { EFI_LOADER_FEATURE_ENTRY_ONESHOT, "One-shot entry control" },
1622 { EFI_LOADER_FEATURE_XBOOTLDR, "Support for XBOOTLDR partition" },
1623 { EFI_LOADER_FEATURE_RANDOM_SEED, "Support for passing random seed to OS" },
1624 { EFI_LOADER_FEATURE_LOAD_DRIVER, "Load drop-in drivers" },
1626 _cleanup_free_ char *fw_type = NULL, *fw_info = NULL, *loader = NULL, *loader_path = NULL, *stub = NULL;
1627 sd_id128_t loader_part_uuid = SD_ID128_NULL;
1628 uint64_t loader_features = 0;
1632 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareType), &fw_type);
1633 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareInfo), &fw_info);
1634 read_efi_var(EFI_LOADER_VARIABLE(LoaderInfo), &loader);
1635 read_efi_var(EFI_LOADER_VARIABLE(StubInfo), &stub);
1636 read_efi_var(EFI_LOADER_VARIABLE(LoaderImageIdentifier), &loader_path);
1637 (void) efi_loader_get_features(&loader_features);
1640 efi_tilt_backslashes(loader_path);
1642 k = efi_loader_get_device_part_uuid(&loader_part_uuid);
1643 if (k < 0 && k != -ENOENT)
1644 r = log_warning_errno(k, "Failed to read EFI variable LoaderDevicePartUUID: %m");
1646 SecureBootMode secure = efi_get_secure_boot_mode();
1647 printf("System:\n");
1648 printf(" Firmware: %s%s (%s)%s\n", ansi_highlight(), strna(fw_type), strna(fw_info), ansi_normal());
1649 printf(" Firmware Arch: %s\n", get_efi_arch());
1650 printf(" Secure Boot: %sd (%s)\n",
1651 enable_disable(IN_SET(secure, SECURE_BOOT_USER, SECURE_BOOT_DEPLOYED)),
1652 secure_boot_mode_to_string(secure));
1655 printf(" TPM2 Support: %s%s%s\n",
1656 FLAGS_SET(s, TPM2_SUPPORT_FIRMWARE|TPM2_SUPPORT_DRIVER) ? ansi_highlight_green() :
1657 (s & (TPM2_SUPPORT_FIRMWARE|TPM2_SUPPORT_DRIVER)) != 0 ? ansi_highlight_red() : ansi_highlight_yellow(),
1658 FLAGS_SET(s, TPM2_SUPPORT_FIRMWARE|TPM2_SUPPORT_DRIVER) ? "yes" :
1659 (s & TPM2_SUPPORT_FIRMWARE) ? "firmware only, driver unavailable" :
1660 (s & TPM2_SUPPORT_DRIVER) ? "driver only, firmware unavailable" : "no",
1663 k = efi_get_reboot_to_firmware();
1665 printf(" Boot into FW: %sactive%s\n", ansi_highlight_yellow(), ansi_normal());
1667 printf(" Boot into FW: supported\n");
1668 else if (k == -EOPNOTSUPP)
1669 printf(" Boot into FW: not supported\n");
1672 printf(" Boot into FW: %sfailed%s (%m)\n", ansi_highlight_red(), ansi_normal());
1676 printf("Current Boot Loader:\n");
1677 printf(" Product: %s%s%s\n", ansi_highlight(), strna(loader), ansi_normal());
1679 for (size_t i = 0; i < ELEMENTSOF(flags); i++)
1680 print_yes_no_line(i == 0, FLAGS_SET(loader_features, flags[i].flag), flags[i].name);
1682 sd_id128_t bootloader_esp_uuid;
1683 bool have_bootloader_esp_uuid = efi_loader_get_device_part_uuid(&bootloader_esp_uuid) >= 0;
1685 print_yes_no_line(false, have_bootloader_esp_uuid, "Boot loader sets ESP information");
1686 if (have_bootloader_esp_uuid && !sd_id128_equal(esp_uuid, bootloader_esp_uuid))
1687 printf("WARNING: The boot loader reports a different ESP UUID than detected!\n");
1690 printf(" Stub: %s\n", stub);
1691 if (!sd_id128_is_null(loader_part_uuid))
1692 printf(" ESP: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR "\n",
1693 SD_ID128_FORMAT_VAL(loader_part_uuid));
1695 printf(" ESP: n/a\n");
1696 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), strna(loader_path));
1699 printf("Random Seed:\n");
1700 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderRandomSeed)), F_OK) >= 0;
1701 printf(" Passed to OS: %s\n", yes_no(have));
1702 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderSystemToken)), F_OK) >= 0;
1703 printf(" System Token: %s\n", have ? "set" : "not set");
1706 _cleanup_free_ char *p = NULL;
1708 p = path_join(arg_esp_path, "/loader/random-seed");
1712 have = access(p, F_OK) >= 0;
1713 printf(" Exists: %s\n", yes_no(have));
1718 printf("System:\n Not booted with EFI\n\n");
1721 k = status_binaries(arg_esp_path, esp_uuid);
1726 if (is_efi_boot()) {
1727 k = status_variables();
1732 if (arg_esp_path || arg_xbootldr_path) {
1733 _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL;
1735 k = boot_config_load_and_select(&config,
1736 arg_esp_path, esp_devid,
1737 arg_xbootldr_path, xbootldr_devid);
1741 k = status_entries(&config,
1742 arg_esp_path, esp_uuid,
1743 arg_xbootldr_path, xbootldr_uuid);
1752 static int verb_list(int argc, char *argv[], void *userdata) {
1753 _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL;
1754 dev_t esp_devid = 0, xbootldr_devid = 0;
1757 /* If we lack privileges we invoke find_esp_and_warn() in "unprivileged mode" here, which does two
1758 * things: turn off logging about access errors and turn off potentially privileged device probing.
1759 * Here we're interested in the latter but not the former, hence request the mode, and log about
1762 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, NULL, &esp_devid);
1763 if (r == -EACCES) /* We really need the ESP path for this call, hence also log about access errors */
1764 return log_error_errno(r, "Failed to determine ESP location: %m");
1768 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, NULL, &xbootldr_devid);
1770 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1774 r = boot_config_load_and_select(&config, arg_esp_path, esp_devid, arg_xbootldr_path, xbootldr_devid);
1778 if (config.n_entries == 0 && FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
1779 log_info("No boot loader entries found.");
1783 pager_open(arg_pager_flags);
1784 return show_boot_entries(&config, arg_json_format_flags);
1787 static int install_random_seed(const char *esp) {
1788 _cleanup_(unlink_and_freep) char *tmp = NULL;
1789 _cleanup_free_ void *buffer = NULL;
1790 _cleanup_free_ char *path = NULL;
1791 _cleanup_close_ int fd = -1;
1792 size_t sz, token_size;
1798 path = path_join(esp, "/loader/random-seed");
1802 sz = random_pool_size();
1804 buffer = malloc(sz);
1808 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1810 return log_error_errno(r, "Failed to acquire random seed: %m");
1812 /* Normally create_subdirs() should already have created everything we need, but in case "bootctl
1813 * random
-seed
" is called we want to just create the minimum we need for it, and not the full
1815 r = mkdir_parents(path, 0755);
1817 return log_error_errno(r, "Failed to create parent directory
for %s
: %m
", path);
1819 r = tempfn_random(path, "bootctl
", &tmp);
1823 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|O_WRONLY|O_CLOEXEC, 0600);
1826 return log_error_errno(fd, "Failed to open random seed file
for writing
: %m
");
1829 n = write(fd, buffer, sz);
1831 return log_error_errno(errno, "Failed to write random seed file
: %m
");
1832 if ((size_t) n != sz)
1833 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write
while writing random seed file
.");
1835 if (rename(tmp, path) < 0)
1836 return log_error_errno(r, "Failed to move random seed file into place
: %m
");
1840 log_info("Random seed file
%s successfully
written (%zu bytes
).", path, sz);
1842 if (!arg_touch_variables)
1845 if (!is_efi_boot()) {
1846 log_notice("Not booted with EFI
, skipping EFI variable setup
.");
1850 r = getenv_bool("SYSTEMD_WRITE_SYSTEM_TOKEN
");
1853 log_warning_errno(r, "Failed to parse $SYSTEMD_WRITE_SYSTEM_TOKEN
, ignoring
.");
1855 if (detect_vm() > 0) {
1856 /* Let's not write a system token if we detect we are running in a VM
1857 * environment. Why? Our default security model for the random seed uses the system
1858 * token as a mechanism to ensure we are not vulnerable to golden master sloppiness
1859 * issues, i.e. that people initialize the random seed file, then copy the image to
1860 * many systems and end up with the same random seed in each that is assumed to be
1861 * valid but in reality is the same for all machines. By storing a system token in
1862 * the EFI variable space we can make sure that even though the random seeds on disk
1863 * are all the same they will be different on each system under the assumption that
1864 * the EFI variable space is maintained separate from the random seed storage. That
1865 * is generally the case on physical systems, as the ESP is stored on persistent
1866 * storage, and the EFI variables in NVRAM. However in virtualized environments this
1867 * is generally not true: the EFI variable set is typically stored along with the
1868 * disk image itself. For example, using the OVMF EFI firmware the EFI variables are
1869 * stored in a file in the ESP itself. */
1871 log_notice("Not installing system token
, since we are running in a virtualized environment
.");
1874 } else if (r == 0) {
1875 log_notice("Not writing system token
, because $SYSTEMD_WRITE_SYSTEM_TOKEN is set to
false.");
1879 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), NULL, NULL, &token_size);
1881 log_debug_errno(r, "LoaderSystemToken EFI variable is
invalid (too
short?), replacing
.");
1884 return log_error_errno(r, "Failed to test system token validity
: %m
");
1886 if (token_size >= sz) {
1887 /* Let's avoid writes if we can, and initialize this only once. */
1888 log_debug("System token already written
, not updating
.");
1892 log_debug("Existing system token
size (%zu
) does
not match our
expectations (%zu
), replacing
.", token_size, sz);
1895 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1897 return log_error_errno(r, "Failed to acquire random seed
: %m
");
1899 /* Let's write this variable with an umask in effect, so that unprivileged users can't see the token
1900 * and possibly get identification information or too much insight into the kernel's entropy pool
1902 RUN_WITH_UMASK(0077) {
1903 r = efi_set_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), buffer, sz);
1906 return log_error_errno(r, "Failed to write
'LoaderSystemToken' EFI variable
: %m
");
1909 log_warning_errno(r, "Unable to write
'LoaderSystemToken' EFI
variable (firmware problem
?), ignoring
: %m
");
1911 log_warning_errno(r, "Unable to write
'LoaderSystemToken' EFI variable
, ignoring
: %m
");
1913 log_info("Successfully initialized system token in EFI variable with
%zu bytes
.", sz);
1919 static int sync_everything(void) {
1923 k = syncfs_path(AT_FDCWD, arg_esp_path);
1925 ret = log_error_errno(k, "Failed to synchronize the ESP
'%s': %m
", arg_esp_path);
1928 if (arg_xbootldr_path) {
1929 k = syncfs_path(AT_FDCWD, arg_xbootldr_path);
1931 ret = log_error_errno(k, "Failed to synchronize $BOOT
'%s': %m
", arg_xbootldr_path);
1937 static int verb_install(int argc, char *argv[], void *userdata) {
1938 sd_id128_t uuid = SD_ID128_NULL;
1939 uint64_t pstart = 0, psize = 0;
1941 bool install, graceful;
1944 /* Invoked for both "update
" and "install
" */
1946 install = streq(argv[0], "install
");
1947 graceful = !install && arg_graceful; /* support graceful mode for updates */
1949 r = acquire_esp(/* unprivileged_mode= */ false, graceful, &part, &pstart, &psize, &uuid, NULL);
1950 if (graceful && r == -ENOKEY)
1951 return 0; /* If --graceful is specified and we can't find an ESP, handle this cleanly */
1956 /* If we are updating, don't do anything if sd-boot wasn't actually installed. */
1957 r = are_we_installed(arg_esp_path);
1961 log_debug("Skipping update because sd
-boot is
not installed in the ESP
.");
1966 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
1970 r = settle_make_entry_directory();
1974 const char *arch = arg_arch_all ? "" : get_efi_arch();
1976 RUN_WITH_UMASK(0002) {
1978 /* Don't create any of these directories when we are just updating. When we update
1979 * we'll drop-in our files (unless there are newer ones already), but we won't create
1980 * the directories for them in the first place. */
1981 r = create_subdirs(arg_esp_path, esp_subdirs);
1985 r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
1990 r = install_binaries(arg_esp_path, arch, install);
1995 r = install_loader_config(arg_esp_path);
1999 r = install_entry_directory(arg_dollar_boot_path());
2003 r = install_entry_token();
2007 r = install_random_seed(arg_esp_path);
2012 r = install_loader_specification(arg_dollar_boot_path());
2017 (void) sync_everything();
2019 if (!arg_touch_variables)
2023 log_info("Not changing EFI variables with
--all
-architectures
.");
2027 char *path = strjoina("/EFI
/systemd
/systemd
-boot
", arch, ".efi
");
2028 return install_variables(arg_esp_path, part, pstart, psize, uuid, path, install);
2031 static int verb_remove(int argc, char *argv[], void *userdata) {
2032 sd_id128_t uuid = SD_ID128_NULL;
2035 r = acquire_esp(/* unprivileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, &uuid, NULL);
2039 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
2043 r = settle_make_entry_directory();
2047 r = remove_binaries(arg_esp_path);
2049 q = remove_file(arg_esp_path, "/loader
/loader
.conf
");
2050 if (q < 0 && r >= 0)
2053 q = remove_file(arg_esp_path, "/loader
/random
-seed
");
2054 if (q < 0 && r >= 0)
2057 q = remove_file(arg_esp_path, "/loader
/entries
.srel
");
2058 if (q < 0 && r >= 0)
2061 q = remove_subdirs(arg_esp_path, esp_subdirs);
2062 if (q < 0 && r >= 0)
2065 q = remove_subdirs(arg_esp_path, dollar_boot_subdirs);
2066 if (q < 0 && r >= 0)
2069 q = remove_entry_directory(arg_esp_path);
2070 if (q < 0 && r >= 0)
2073 if (arg_xbootldr_path) {
2074 /* Remove a subset of these also from the XBOOTLDR partition if it exists */
2076 q = remove_file(arg_xbootldr_path, "/loader
/entries
.srel
");
2077 if (q < 0 && r >= 0)
2080 q = remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs);
2081 if (q < 0 && r >= 0)
2084 q = remove_entry_directory(arg_xbootldr_path);
2085 if (q < 0 && r >= 0)
2089 (void) sync_everything();
2091 if (!arg_touch_variables)
2095 log_info("Not changing EFI variables with
--all
-architectures
.");
2099 char *path = strjoina("/EFI
/systemd
/systemd
-boot
", get_efi_arch(), ".efi
");
2100 q = remove_variables(uuid, path, true);
2101 if (q < 0 && r >= 0)
2104 q = remove_loader_variables();
2105 if (q < 0 && r >= 0)
2111 static int verb_is_installed(int argc, char *argv[], void *userdata) {
2114 r = acquire_esp(/* privileged_mode= */ false,
2115 /* graceful= */ arg_graceful,
2116 NULL, NULL, NULL, NULL, NULL);
2120 r = are_we_installed(arg_esp_path);
2127 return EXIT_SUCCESS;
2131 return EXIT_FAILURE;
2135 static int parse_timeout(const char *arg1, char16_t **ret_timeout, size_t *ret_timeout_size) {
2136 char utf8[DECIMAL_STR_MAX(usec_t)];
2142 assert(ret_timeout);
2143 assert(ret_timeout_size);
2145 if (streq(arg1, "menu
-force
"))
2146 timeout = USEC_INFINITY;
2147 else if (streq(arg1, "menu
-hidden
"))
2150 r = parse_time(arg1, &timeout, USEC_PER_SEC);
2152 return log_error_errno(r, "Failed to parse timeout
'%s': %m
", arg1);
2153 if (timeout != USEC_INFINITY && timeout > UINT32_MAX * USEC_PER_SEC)
2154 log_warning("Timeout is too
long and will be treated as
'menu-force' instead
.");
2157 xsprintf(utf8, USEC_FMT, MIN(timeout / USEC_PER_SEC, UINT32_MAX));
2159 encoded = utf8_to_utf16(utf8, strlen(utf8));
2163 *ret_timeout = encoded;
2164 *ret_timeout_size = char16_strlen(encoded) * 2 + 2;
2168 static int parse_loader_entry_target_arg(const char *arg1, char16_t **ret_target, size_t *ret_target_size) {
2169 char16_t *encoded = NULL;
2174 assert(ret_target_size);
2176 if (streq(arg1, "@current
")) {
2177 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntrySelected), NULL, (void *) ret_target, ret_target_size);
2179 return log_error_errno(r, "Failed to get EFI variable
'LoaderEntrySelected': %m
");
2181 } else if (streq(arg1, "@oneshot
")) {
2182 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryOneShot), NULL, (void *) ret_target, ret_target_size);
2184 return log_error_errno(r, "Failed to get EFI variable
'LoaderEntryOneShot': %m
");
2186 } else if (streq(arg1, "@
default")) {
2187 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryDefault), NULL, (void *) ret_target, ret_target_size);
2189 return log_error_errno(r, "Failed to get EFI variable
'LoaderEntryDefault': %m
");
2191 } else if (arg1[0] == '@' && !streq(arg1, "@saved
"))
2192 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unsupported special entry identifier
: %s
", arg1);
2194 encoded = utf8_to_utf16(arg1, strlen(arg1));
2198 *ret_target = encoded;
2199 *ret_target_size = char16_strlen(encoded) * 2 + 2;
2205 static int verb_set_efivar(int argc, char *argv[], void *userdata) {
2209 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2210 "Not booted with UEFI
.");
2212 if (access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderInfo)), F_OK) < 0) {
2213 if (errno == ENOENT) {
2214 log_error_errno(errno, "Not booted with a supported boot loader
.");
2218 return log_error_errno(errno, "Failed to detect whether boot loader supports
'%s' operation
: %m
", argv[0]);
2221 if (detect_container() > 0)
2222 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2223 "'%s' operation
not supported in a container
.",
2226 if (!arg_touch_variables)
2227 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2228 "'%s' operation cannot be combined with
--no
-variables
.",
2231 const char *variable;
2232 int (* arg_parser)(const char *, char16_t **, size_t *);
2234 if (streq(argv[0], "set
-default")) {
2235 variable = EFI_LOADER_VARIABLE(LoaderEntryDefault);
2236 arg_parser = parse_loader_entry_target_arg;
2237 } else if (streq(argv[0], "set
-oneshot
")) {
2238 variable = EFI_LOADER_VARIABLE(LoaderEntryOneShot);
2239 arg_parser = parse_loader_entry_target_arg;
2240 } else if (streq(argv[0], "set
-timeout
")) {
2241 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeout);
2242 arg_parser = parse_timeout;
2243 } else if (streq(argv[0], "set
-timeout
-oneshot
")) {
2244 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot);
2245 arg_parser = parse_timeout;
2247 assert_not_reached();
2249 if (isempty(argv[1])) {
2250 r = efi_set_variable(variable, NULL, 0);
2251 if (r < 0 && r != -ENOENT)
2252 return log_error_errno(r, "Failed to remove EFI variable
'%s': %m
", variable);
2254 _cleanup_free_ char16_t *value = NULL;
2255 size_t value_size = 0;
2257 r = arg_parser(argv[1], &value, &value_size);
2260 r = efi_set_variable(variable, value, value_size);
2262 return log_error_errno(r, "Failed to update EFI variable
'%s': %m
", variable);
2268 static int verb_random_seed(int argc, char *argv[], void *userdata) {
2271 r = find_esp_and_warn(arg_esp_path, false, &arg_esp_path, NULL, NULL, NULL, NULL, NULL);
2273 /* find_esp_and_warn() doesn't warn about ENOKEY, so let's do that on our own */
2275 return log_error_errno(r, "Unable to find ESP
.");
2277 log_notice("No ESP found
, not initializing random seed
.");
2283 r = install_random_seed(arg_esp_path);
2287 (void) sync_everything();
2291 static int verb_systemd_efi_options(int argc, char *argv[], void *userdata) {
2295 _cleanup_free_ char *line = NULL, *new = NULL;
2297 r = systemd_efi_options_variable(&line);
2299 log_debug("No SystemdOptions EFI variable present in cache
.");
2301 return log_error_errno(r, "Failed to read SystemdOptions EFI variable from cache
: %m
");
2305 r = systemd_efi_options_efivarfs_if_newer(&new);
2306 if (r == -ENODATA) {
2308 log_notice("Note
: SystemdOptions EFI variable has been removed since boot
.");
2310 log_warning_errno(r, "Failed to check SystemdOptions EFI variable in efivarfs
, ignoring
: %m
");
2311 else if (new && !streq_ptr(line, new))
2312 log_notice("Note
: SystemdOptions EFI variable has been modified since boot
. New value
: %s
",
2315 r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE(SystemdOptions), argv[1]);
2317 return log_error_errno(r, "Failed to set SystemdOptions EFI variable
: %m
");
2323 static int verb_reboot_to_firmware(int argc, char *argv[], void *userdata) {
2327 r = efi_get_reboot_to_firmware();
2330 return EXIT_SUCCESS; /* success */
2334 return 1; /* recognizable error #1 */
2336 if (r == -EOPNOTSUPP) {
2337 puts("not supported
");
2338 return 2; /* recognizable error #2 */
2341 log_error_errno(r, "Failed to query reboot
-to
-firmware state
: %m
");
2342 return 3; /* other kind of error */
2344 r = parse_boolean(argv[1]);
2346 return log_error_errno(r, "Failed to parse argument
: %s
", argv[1]);
2348 r = efi_set_reboot_to_firmware(r);
2350 return log_error_errno(r, "Failed to set reboot
-to
-firmware option
: %m
");
2356 static int bootctl_main(int argc, char *argv[]) {
2357 static const Verb verbs[] = {
2358 { "help
", VERB_ANY, VERB_ANY, 0, help },
2359 { "status
", VERB_ANY, 1, VERB_DEFAULT, verb_status },
2360 { "install
", VERB_ANY, 1, 0, verb_install },
2361 { "update
", VERB_ANY, 1, 0, verb_install },
2362 { "remove
", VERB_ANY, 1, 0, verb_remove },
2363 { "is
-installed
", VERB_ANY, 1, 0, verb_is_installed },
2364 { "list
", VERB_ANY, 1, 0, verb_list },
2365 { "set
-default", 2, 2, 0, verb_set_efivar },
2366 { "set
-oneshot
", 2, 2, 0, verb_set_efivar },
2367 { "set
-timeout
", 2, 2, 0, verb_set_efivar },
2368 { "set
-timeout
-oneshot
", 2, 2, 0, verb_set_efivar },
2369 { "random
-seed
", VERB_ANY, 1, 0, verb_random_seed },
2370 { "systemd
-efi
-options
", VERB_ANY, 2, 0, verb_systemd_efi_options },
2371 { "reboot
-to
-firmware
", VERB_ANY, 2, 0, verb_reboot_to_firmware },
2375 return dispatch_verb(argc, argv, verbs, NULL);
2378 static int run(int argc, char *argv[]) {
2381 log_parse_environment();
2384 /* If we run in a container, automatically turn off EFI file system access */
2385 if (detect_container() > 0)
2386 arg_touch_variables = false;
2388 r = parse_argv(argc, argv);
2392 return bootctl_main(argc, argv);
2395 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);