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
;
78 STATIC_DESTRUCTOR_REGISTER(arg_esp_path
, freep
);
79 STATIC_DESTRUCTOR_REGISTER(arg_xbootldr_path
, freep
);
80 STATIC_DESTRUCTOR_REGISTER(arg_install_layout
, freep
);
81 STATIC_DESTRUCTOR_REGISTER(arg_entry_token
, freep
);
83 static const char *arg_dollar_boot_path(void) {
84 /* $BOOT shall be the XBOOTLDR partition if it exists, and otherwise the ESP */
85 return arg_xbootldr_path
?: arg_esp_path
;
88 static int acquire_esp(
89 bool unprivileged_mode
,
100 /* Find the ESP, and log about errors. Note that find_esp_and_warn() will log in all error cases on
101 * its own, except for ENOKEY (which is good, we want to show our own message in that case,
102 * suggesting use of --esp-path=) and EACCESS (only when we request unprivileged mode; in this case
103 * we simply eat up the error here, so that --list and --status work too, without noise about
106 r
= find_esp_and_warn(arg_esp_path
, unprivileged_mode
, &np
, ret_part
, ret_pstart
, ret_psize
, ret_uuid
, ret_devid
);
109 return log_full_errno(arg_quiet
? LOG_DEBUG
: LOG_INFO
, r
,
110 "Couldn't find EFI system partition, skipping.");
112 return log_error_errno(r
,
113 "Couldn't find EFI system partition. It is recommended to mount it to /boot or /efi.\n"
114 "Alternatively, use --esp-path= to specify path to mount point.");
119 free_and_replace(arg_esp_path
, np
);
120 log_debug("Using EFI System Partition at %s.", arg_esp_path
);
125 static int acquire_xbootldr(
126 bool unprivileged_mode
,
127 sd_id128_t
*ret_uuid
,
133 r
= find_xbootldr_and_warn(arg_xbootldr_path
, unprivileged_mode
, &np
, ret_uuid
, ret_devid
);
135 log_debug_errno(r
, "Didn't find an XBOOTLDR partition, using the ESP as $BOOT.");
136 arg_xbootldr_path
= mfree(arg_xbootldr_path
);
139 *ret_uuid
= SD_ID128_NULL
;
147 free_and_replace(arg_xbootldr_path
, np
);
148 log_debug("Using XBOOTLDR partition at %s as $BOOT.", arg_xbootldr_path
);
153 static int load_etc_machine_id(void) {
156 r
= sd_id128_get_machine(&arg_machine_id
);
157 if (IN_SET(r
, -ENOENT
, -ENOMEDIUM
)) /* Not set or empty */
160 return log_error_errno(r
, "Failed to get machine-id: %m");
162 log_debug("Loaded machine ID %s from /etc/machine-id.", SD_ID128_TO_STRING(arg_machine_id
));
166 static int load_etc_machine_info(void) {
167 /* systemd v250 added support to store the kernel-install layout setting and the machine ID to use
168 * for setting up the ESP in /etc/machine-info. The newer /etc/kernel/entry-token file, as well as
169 * the $layout field in /etc/kernel/install.conf are better replacements for this though, hence this
170 * has been deprecated and is only returned for compatibility. */
171 _cleanup_free_
char *s
= NULL
, *layout
= NULL
;
174 r
= parse_env_file(NULL
, "/etc/machine-info",
175 "KERNEL_INSTALL_LAYOUT", &layout
,
176 "KERNEL_INSTALL_MACHINE_ID", &s
);
180 return log_error_errno(r
, "Failed to parse /etc/machine-info: %m");
184 log_notice("Read $KERNEL_INSTALL_MACHINE_ID from /etc/machine-info. "
185 "Please move it to /etc/kernel/entry-token.");
187 r
= sd_id128_from_string(s
, &arg_machine_id
);
189 return log_error_errno(r
, "Failed to parse KERNEL_INSTALL_MACHINE_ID=%s in /etc/machine-info: %m", s
);
191 log_debug("Loaded KERNEL_INSTALL_MACHINE_ID=%s from KERNEL_INSTALL_MACHINE_ID in /etc/machine-info.",
192 SD_ID128_TO_STRING(arg_machine_id
));
195 if (!isempty(layout
)) {
197 log_notice("Read $KERNEL_INSTALL_LAYOUT from /etc/machine-info. "
198 "Please move it to the layout= setting of /etc/kernel/install.conf.");
200 log_debug("KERNEL_INSTALL_LAYOUT=%s is specified in /etc/machine-info.", layout
);
201 free_and_replace(arg_install_layout
, layout
);
207 static int load_etc_kernel_install_conf(void) {
208 _cleanup_free_
char *layout
= NULL
;
211 r
= parse_env_file(NULL
, "/etc/kernel/install.conf",
216 return log_error_errno(r
, "Failed to parse /etc/kernel/install.conf: %m");
218 if (!isempty(layout
)) {
219 log_debug("layout=%s is specified in /etc/machine-info.", layout
);
220 free_and_replace(arg_install_layout
, layout
);
226 static int settle_entry_token(void) {
229 switch (arg_entry_token_type
) {
231 case ARG_ENTRY_TOKEN_AUTO
: {
232 _cleanup_free_
char *buf
= NULL
;
233 r
= read_one_line_file("/etc/kernel/entry-token", &buf
);
234 if (r
< 0 && r
!= -ENOENT
)
235 return log_error_errno(r
, "Failed to read /etc/kernel/entry-token: %m");
238 free_and_replace(arg_entry_token
, buf
);
239 arg_entry_token_type
= ARG_ENTRY_TOKEN_LITERAL
;
240 } else if (sd_id128_is_null(arg_machine_id
)) {
241 _cleanup_free_
char *id
= NULL
, *image_id
= NULL
;
243 r
= parse_os_release(NULL
,
244 "IMAGE_ID", &image_id
,
247 return log_error_errno(r
, "Failed to load /etc/os-release: %m");
249 if (!isempty(image_id
)) {
250 free_and_replace(arg_entry_token
, image_id
);
251 arg_entry_token_type
= ARG_ENTRY_TOKEN_OS_IMAGE_ID
;
252 } else if (!isempty(id
)) {
253 free_and_replace(arg_entry_token
, id
);
254 arg_entry_token_type
= ARG_ENTRY_TOKEN_OS_ID
;
256 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No machine ID set, and /etc/os-release carries no ID=/IMAGE_ID= fields.");
258 r
= free_and_strdup_warn(&arg_entry_token
, SD_ID128_TO_STRING(arg_machine_id
));
262 arg_entry_token_type
= ARG_ENTRY_TOKEN_MACHINE_ID
;
268 case ARG_ENTRY_TOKEN_MACHINE_ID
:
269 if (sd_id128_is_null(arg_machine_id
))
270 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No machine ID set.");
272 r
= free_and_strdup_warn(&arg_entry_token
, SD_ID128_TO_STRING(arg_machine_id
));
278 case ARG_ENTRY_TOKEN_OS_IMAGE_ID
: {
279 _cleanup_free_
char *buf
= NULL
;
281 r
= parse_os_release(NULL
, "IMAGE_ID", &buf
);
283 return log_error_errno(r
, "Failed to load /etc/os-release: %m");
286 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "IMAGE_ID= field not set in /etc/os-release.");
288 free_and_replace(arg_entry_token
, buf
);
292 case ARG_ENTRY_TOKEN_OS_ID
: {
293 _cleanup_free_
char *buf
= NULL
;
295 r
= parse_os_release(NULL
, "ID", &buf
);
297 return log_error_errno(r
, "Failed to load /etc/os-release: %m");
300 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "ID= field not set in /etc/os-release.");
302 free_and_replace(arg_entry_token
, buf
);
306 case ARG_ENTRY_TOKEN_LITERAL
:
307 assert(!isempty(arg_entry_token
)); /* already filled in by command line parser */
311 if (isempty(arg_entry_token
) || !string_is_safe(arg_entry_token
))
312 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Selected entry token not valid: %s", arg_entry_token
);
314 log_debug("Using entry token: %s", arg_entry_token
);
318 static bool use_boot_loader_spec_type1(void) {
319 /* If the layout is not specified, or if it is set explicitly to "bls" we assume Boot Loader
320 * Specification Type #1 is the chosen format for our boot loader entries */
321 return !arg_install_layout
|| streq(arg_install_layout
, "bls");
324 static int settle_make_entry_directory(void) {
327 r
= load_etc_machine_id();
331 r
= load_etc_machine_info();
335 r
= load_etc_kernel_install_conf();
339 r
= settle_entry_token();
343 bool layout_type1
= use_boot_loader_spec_type1();
344 if (arg_make_entry_directory
< 0) { /* Automatic mode */
346 if (arg_entry_token
== ARG_ENTRY_TOKEN_MACHINE_ID
) {
347 r
= path_is_temporary_fs("/etc/machine-id");
349 return log_debug_errno(r
, "Couldn't determine whether /etc/machine-id is on a temporary file system: %m");
351 arg_make_entry_directory
= r
== 0;
353 arg_make_entry_directory
= true;
355 arg_make_entry_directory
= false;
358 if (arg_make_entry_directory
> 0 && !layout_type1
)
359 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
360 "KERNEL_INSTALL_LAYOUT=%s is configured, but Boot Loader Specification Type #1 entry directory creation was requested.",
366 /* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */
367 static int get_file_version(int fd
, char **v
) {
377 if (fstat(fd
, &st
) < 0)
378 return log_error_errno(errno
, "Failed to stat EFI binary: %m");
380 r
= stat_verify_regular(&st
);
382 return log_error_errno(r
, "EFI binary is not a regular file: %m");
384 if (st
.st_size
< 27 || file_offset_beyond_memory_size(st
.st_size
)) {
389 buf
= mmap(NULL
, st
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
390 if (buf
== MAP_FAILED
)
391 return log_error_errno(errno
, "Failed to memory map EFI binary: %m");
393 s
= mempmem_safe(buf
, st
.st_size
- 8, "#### LoaderInfo: ", 17);
397 e
= memmem_safe(s
, st
.st_size
- (s
- buf
), " ####", 5);
398 if (!e
|| e
- s
< 3) {
399 r
= log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Malformed version string.");
403 x
= strndup(s
, e
- s
);
411 (void) munmap(buf
, st
.st_size
);
416 static int enumerate_binaries(const char *esp_path
, const char *path
, const char *prefix
) {
417 _cleanup_closedir_
DIR *d
= NULL
;
424 p
= prefix_roota(esp_path
, path
);
430 return log_error_errno(errno
, "Failed to read \"%s\": %m", p
);
433 FOREACH_DIRENT(de
, d
, break) {
434 _cleanup_free_
char *v
= NULL
;
435 _cleanup_close_
int fd
= -1;
437 if (!endswith_no_case(de
->d_name
, ".efi"))
440 if (prefix
&& !startswith_no_case(de
->d_name
, prefix
))
443 fd
= openat(dirfd(d
), de
->d_name
, O_RDONLY
|O_CLOEXEC
);
445 return log_error_errno(errno
, "Failed to open \"%s/%s\" for reading: %m", p
, de
->d_name
);
447 r
= get_file_version(fd
, &v
);
451 printf(" File: %s/%s/%s (%s%s%s)\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), path
, de
->d_name
, ansi_highlight(), v
, ansi_normal());
453 printf(" File: %s/%s/%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), path
, de
->d_name
);
461 static int status_binaries(const char *esp_path
, sd_id128_t partition
) {
464 printf("Available Boot Loaders on ESP:\n");
467 printf(" ESP: Cannot find or access mount point of ESP.\n\n");
471 printf(" ESP: %s", esp_path
);
472 if (!sd_id128_is_null(partition
))
473 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR
")", SD_ID128_FORMAT_VAL(partition
));
476 r
= enumerate_binaries(esp_path
, "EFI/systemd", NULL
);
479 if (r
== 0 && !arg_quiet
)
480 log_info("systemd-boot not installed in ESP.");
482 r
= enumerate_binaries(esp_path
, "EFI/BOOT", "boot");
485 if (r
== 0 && !arg_quiet
)
486 log_info("No default/fallback boot loader installed in ESP.");
495 static int print_efi_option(uint16_t id
, bool in_order
) {
496 _cleanup_free_
char *title
= NULL
;
497 _cleanup_free_
char *path
= NULL
;
498 sd_id128_t partition
;
502 r
= efi_get_boot_option(id
, &title
, &partition
, &path
, &active
);
506 /* print only configured entries with partition information */
507 if (!path
|| sd_id128_is_null(partition
))
510 efi_tilt_backslashes(path
);
512 printf(" Title: %s%s%s\n", ansi_highlight(), strna(title
), ansi_normal());
513 printf(" ID: 0x%04X\n", id
);
514 printf(" Status: %sactive%s\n", active
? "" : "in", in_order
? ", boot-order" : "");
515 printf(" Partition: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR
"\n",
516 SD_ID128_FORMAT_VAL(partition
));
517 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), path
);
523 static int status_variables(void) {
524 _cleanup_free_
uint16_t *options
= NULL
, *order
= NULL
;
525 int n_options
, n_order
;
527 n_options
= efi_get_boot_options(&options
);
528 if (n_options
== -ENOENT
)
529 return log_error_errno(n_options
,
530 "Failed to access EFI variables, efivarfs"
531 " needs to be available at /sys/firmware/efi/efivars/.");
533 return log_error_errno(n_options
, "Failed to read EFI boot entries: %m");
535 n_order
= efi_get_boot_order(&order
);
536 if (n_order
== -ENOENT
)
538 else if (n_order
< 0)
539 return log_error_errno(n_order
, "Failed to read EFI boot order: %m");
541 /* print entries in BootOrder first */
542 printf("Boot Loaders Listed in EFI Variables:\n");
543 for (int i
= 0; i
< n_order
; i
++)
544 print_efi_option(order
[i
], true);
546 /* print remaining entries */
547 for (int i
= 0; i
< n_options
; i
++) {
548 for (int j
= 0; j
< n_order
; j
++)
549 if (options
[i
] == order
[j
])
552 print_efi_option(options
[i
], false);
561 static int boot_config_load_and_select(
563 const char *esp_path
,
565 const char *xbootldr_path
,
566 dev_t xbootldr_devid
) {
568 _cleanup_strv_free_
char **efi_entries
= NULL
;
571 /* If XBOOTLDR and ESP actually refer to the same block device, suppress XBOOTLDR, since it would
572 * find the same entries twice. */
573 bool same
= esp_path
&& xbootldr_path
&& devnum_set_and_equal(esp_devid
, xbootldr_devid
);
575 r
= boot_config_load(config
, esp_path
, same
? NULL
: xbootldr_path
);
579 r
= efi_loader_get_entries(&efi_entries
);
580 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
581 log_debug_errno(r
, "Boot loader reported no entries.");
583 log_warning_errno(r
, "Failed to determine entries reported by boot loader, ignoring: %m");
585 (void) boot_config_augment_from_loader(config
, efi_entries
, /* only_auto= */ false);
587 return boot_config_select_special_entries(config
);
590 static int status_entries(
591 const BootConfig
*config
,
592 const char *esp_path
,
593 sd_id128_t esp_partition_uuid
,
594 const char *xbootldr_path
,
595 sd_id128_t xbootldr_partition_uuid
) {
597 sd_id128_t dollar_boot_partition_uuid
;
598 const char *dollar_boot_path
;
602 assert(esp_path
|| xbootldr_path
);
605 dollar_boot_path
= xbootldr_path
;
606 dollar_boot_partition_uuid
= xbootldr_partition_uuid
;
608 dollar_boot_path
= esp_path
;
609 dollar_boot_partition_uuid
= esp_partition_uuid
;
612 printf("Boot Loader Entries:\n"
613 " $BOOT: %s", dollar_boot_path
);
614 if (!sd_id128_is_null(dollar_boot_partition_uuid
))
615 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR
")",
616 SD_ID128_FORMAT_VAL(dollar_boot_partition_uuid
));
619 if (config
->default_entry
< 0)
620 printf("%zu entries, no entry could be determined as default.\n", config
->n_entries
);
622 printf("Default Boot Loader Entry:\n");
625 boot_config_default_entry(config
),
626 /* show_as_default= */ false,
627 /* show_as_selected= */ false,
628 /* show_discovered= */ false);
630 /* < 0 is already logged by the function itself, let's just emit an extra warning if
631 the default entry is broken */
632 printf("\nWARNING: default boot entry is broken\n");
638 static int compare_product(const char *a
, const char *b
) {
647 return x
< y
? -1 : x
> y
? 1 : 0;
649 return strncmp(a
, b
, x
);
652 static int compare_version(const char *a
, const char *b
) {
656 a
+= strcspn(a
, " ");
658 b
+= strcspn(b
, " ");
661 return strverscmp_improved(a
, b
);
664 static int version_check(int fd_from
, const char *from
, int fd_to
, const char *to
) {
665 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
668 assert(fd_from
>= 0);
673 r
= get_file_version(fd_from
, &a
);
677 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE
),
678 "Source file \"%s\" does not carry version information!",
681 r
= get_file_version(fd_to
, &b
);
684 if (r
== 0 || compare_product(a
, b
) != 0)
685 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE
),
686 "Skipping \"%s\", since it's owned by another boot loader.",
689 r
= compare_version(a
, b
);
691 return log_warning_errno(SYNTHETIC_ERRNO(ESTALE
), "Skipping \"%s\", since newer boot loader version in place already.", to
);
693 return log_info_errno(SYNTHETIC_ERRNO(ESTALE
), "Skipping \"%s\", since same boot loader version in place already.", to
);
698 static int copy_file_with_version_check(const char *from
, const char *to
, bool force
) {
699 _cleanup_close_
int fd_from
= -1, fd_to
= -1;
700 _cleanup_free_
char *t
= NULL
;
703 fd_from
= open(from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
705 return log_error_errno(errno
, "Failed to open \"%s\" for reading: %m", from
);
708 fd_to
= open(to
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
711 return log_error_errno(errno
, "Failed to open \"%s\" for reading: %m", to
);
713 r
= version_check(fd_from
, from
, fd_to
, to
);
717 if (lseek(fd_from
, 0, SEEK_SET
) == (off_t
) -1)
718 return log_error_errno(errno
, "Failed to seek in \"%s\": %m", from
);
720 fd_to
= safe_close(fd_to
);
724 r
= tempfn_random(to
, NULL
, &t
);
728 RUN_WITH_UMASK(0000) {
729 fd_to
= open(t
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_EXCL
|O_NOFOLLOW
, 0644);
731 return log_error_errno(errno
, "Failed to open \"%s\" for writing: %m", t
);
734 r
= copy_bytes(fd_from
, fd_to
, UINT64_MAX
, COPY_REFLINK
);
737 return log_error_errno(r
, "Failed to copy data from \"%s\" to \"%s\": %m", from
, t
);
740 (void) copy_times(fd_from
, fd_to
, 0);
742 r
= fsync_full(fd_to
);
744 (void) unlink_noerrno(t
);
745 return log_error_errno(r
, "Failed to copy data from \"%s\" to \"%s\": %m", from
, t
);
748 if (renameat(AT_FDCWD
, t
, AT_FDCWD
, to
) < 0) {
749 (void) unlink_noerrno(t
);
750 return log_error_errno(errno
, "Failed to rename \"%s\" to \"%s\": %m", t
, to
);
753 log_info("Copied \"%s\" to \"%s\".", from
, to
);
758 static int mkdir_one(const char *prefix
, const char *suffix
) {
759 _cleanup_free_
char *p
= NULL
;
761 p
= path_join(prefix
, suffix
);
762 if (mkdir(p
, 0700) < 0) {
764 return log_error_errno(errno
, "Failed to create \"%s\": %m", p
);
766 log_info("Created \"%s\".", p
);
771 static const char *const esp_subdirs
[] = {
772 /* The directories to place in the ESP */
780 static const char *const dollar_boot_subdirs
[] = {
781 /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
783 "loader/entries", /* Type #1 entries */
785 "EFI/Linux", /* Type #2 entries */
789 static int create_subdirs(const char *root
, const char * const *subdirs
) {
792 STRV_FOREACH(i
, subdirs
) {
793 r
= mkdir_one(root
, *i
);
801 static int copy_one_file(const char *esp_path
, const char *name
, bool force
) {
803 char *p
, *q
, *dest_name
, *s
;
806 dest_name
= strdupa_safe(name
);
807 s
= endswith_no_case(dest_name
, ".signed");
811 p
= strjoina(BOOTLIBDIR
"/", name
);
812 q
= strjoina(esp_path
, "/EFI/systemd/", dest_name
);
813 r
= copy_file_with_version_check(p
, q
, force
);
815 e
= startswith(dest_name
, "systemd-boot");
820 /* Create the EFI default boot loader name (specified for removable devices) */
821 v
= strjoina(esp_path
, "/EFI/BOOT/BOOT", e
);
822 ascii_strupper(strrchr(v
, '/') + 1);
824 k
= copy_file_with_version_check(p
, v
, force
);
832 static int install_binaries(const char *esp_path
, bool force
) {
833 _cleanup_closedir_
DIR *d
= NULL
;
836 d
= opendir(BOOTLIBDIR
);
838 return log_error_errno(errno
, "Failed to open \""BOOTLIBDIR
"\": %m
");
840 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read
\""BOOTLIBDIR"\": %m
")) {
843 if (!endswith_no_case(de->d_name, ".efi
") && !endswith_no_case(de->d_name, ".efi
.signed"))
846 /* skip the .efi file, if there's a .signed version of it */
847 if (endswith_no_case(de->d_name, ".efi
")) {
848 _cleanup_free_ const char *s = strjoin(de->d_name, ".signed");
851 if (faccessat(dirfd(d), s, F_OK, 0) >= 0)
855 k = copy_one_file(esp_path, de->d_name, force);
856 /* Don't propagate an error code if no update necessary, installed version already equal or
857 * newer version, or other boot loader in place. */
858 if (arg_graceful && IN_SET(k, -ESTALE, -EREMOTE))
867 static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
868 _cleanup_free_ char *opath = NULL;
872 r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
875 if (!sd_id128_equal(uuid, ouuid))
878 /* Some motherboards convert the path to uppercase under certain circumstances
879 * (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
880 * so use case-insensitive checking */
881 if (!strcaseeq_ptr(path, opath))
887 static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
888 _cleanup_free_ uint16_t *options = NULL;
891 n = efi_get_boot_options(&options);
895 /* find already existing systemd-boot entry */
896 for (i = 0; i < n; i++)
897 if (same_entry(options[i], uuid, path)) {
902 /* find free slot in the sorted BootXXXX variable list */
903 for (i = 0; i < n; i++)
904 if (i != options[i]) {
909 /* use the next one */
916 static int insert_into_order(uint16_t slot, bool first) {
917 _cleanup_free_ uint16_t *order = NULL;
921 n = efi_get_boot_order(&order);
923 /* no entry, add us */
924 return efi_set_boot_order(&slot, 1);
926 /* are we the first and only one? */
927 if (n == 1 && order[0] == slot)
930 /* are we already in the boot order? */
931 for (int i = 0; i < n; i++) {
932 if (order[i] != slot)
935 /* we do not require to be the first one, all is fine */
939 /* move us to the first slot */
940 memmove(order + 1, order, i * sizeof(uint16_t));
942 return efi_set_boot_order(order, n);
946 t = reallocarray(order, n + 1, sizeof(uint16_t));
951 /* add us to the top or end of the list */
953 memmove(order + 1, order, n * sizeof(uint16_t));
958 return efi_set_boot_order(order, n + 1);
961 static int remove_from_order(uint16_t slot) {
962 _cleanup_free_ uint16_t *order = NULL;
965 n = efi_get_boot_order(&order);
969 for (int i = 0; i < n; i++) {
970 if (order[i] != slot)
974 memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
975 return efi_set_boot_order(order, n - 1);
981 static int install_variables(const char *esp_path,
982 uint32_t part, uint64_t pstart, uint64_t psize,
983 sd_id128_t uuid, const char *path,
989 if (!is_efi_boot()) {
990 log_warning("Not booted with EFI
, skipping EFI variable setup
.");
994 p = prefix_roota(esp_path, path);
995 if (access(p, F_OK) < 0) {
999 return log_error_errno(errno, "Cannot access
\"%s
\": %m
", p);
1002 r = find_slot(uuid, path, &slot);
1004 return log_error_errno(r,
1006 "Failed to access EFI variables
. Is the
\"efivarfs
\" filesystem mounted
?" :
1007 "Failed to determine current boot order
: %m
");
1009 if (first || r == 0) {
1010 r = efi_add_boot_option(slot, "Linux Boot Manager
",
1011 part, pstart, psize,
1014 return log_error_errno(r, "Failed to create EFI Boot variable entry
: %m
");
1016 log_info("Created EFI boot entry
\"Linux Boot Manager
\".");
1019 return insert_into_order(slot, first);
1022 static int remove_boot_efi(const char *esp_path) {
1023 _cleanup_closedir_ DIR *d = NULL;
1027 p = prefix_roota(esp_path, "/EFI
/BOOT
");
1030 if (errno == ENOENT)
1033 return log_error_errno(errno, "Failed to open directory
\"%s
\": %m
", p);
1036 FOREACH_DIRENT(de, d, break) {
1037 _cleanup_close_ int fd = -1;
1038 _cleanup_free_ char *v = NULL;
1040 if (!endswith_no_case(de->d_name, ".efi
"))
1043 if (!startswith_no_case(de->d_name, "boot
"))
1046 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
1048 return log_error_errno(errno, "Failed to open
\"%s
/%s
\" for reading
: %m
", p, de->d_name);
1050 r = get_file_version(fd, &v);
1053 if (r > 0 && startswith(v, "systemd
-boot
")) {
1054 r = unlinkat(dirfd(d), de->d_name, 0);
1056 return log_error_errno(errno, "Failed to remove
\"%s
/%s
\": %m
", p, de->d_name);
1058 log_info("Removed
\"%s
/%s
\".", p, de->d_name);
1067 static int rmdir_one(const char *prefix, const char *suffix) {
1070 p = prefix_roota(prefix, suffix);
1072 bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
1074 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
1075 "Failed to remove directory
\"%s
\": %m
", p);
1079 log_info("Removed
\"%s
\".", p);
1084 static int remove_subdirs(const char *root, const char *const *subdirs) {
1087 /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
1088 * short the array is. */
1090 if (!subdirs[0]) /* A the end of the list */
1093 r = remove_subdirs(root, subdirs + 1);
1094 q = rmdir_one(root, subdirs[0]);
1096 return r < 0 ? r : q;
1099 static int remove_entry_directory(const char *root) {
1101 assert(arg_make_entry_directory >= 0);
1103 if (!arg_make_entry_directory || !arg_entry_token)
1106 return rmdir_one(root, arg_entry_token);
1109 static int remove_binaries(const char *esp_path) {
1113 p = prefix_roota(esp_path, "/EFI
/systemd
");
1114 r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
1116 q = remove_boot_efi(esp_path);
1117 if (q < 0 && r == 0)
1123 static int remove_file(const char *root, const char *file) {
1129 p = prefix_roota(root, file);
1130 if (unlink(p) < 0) {
1131 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
1132 "Failed to unlink file
\"%s
\": %m
", p);
1134 return errno == ENOENT ? 0 : -errno;
1137 log_info("Removed
\"%s
\".", p);
1141 static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
1148 r = find_slot(uuid, path, &slot);
1152 r = efi_remove_boot_option(slot);
1157 return remove_from_order(slot);
1162 static int remove_loader_variables(void) {
1165 /* Remove all persistent loader variables we define */
1168 EFI_LOADER_VARIABLE(LoaderConfigTimeout),
1169 EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot),
1170 EFI_LOADER_VARIABLE(LoaderEntryDefault),
1171 EFI_LOADER_VARIABLE(LoaderEntryOneShot),
1172 EFI_LOADER_VARIABLE(LoaderSystemToken)){
1176 q = efi_set_variable(var, NULL, 0);
1180 log_warning_errno(q, "Failed to remove EFI variable
%s
: %m
", var);
1184 log_info("Removed EFI variable
%s
.", var);
1190 static int install_loader_config(const char *esp_path) {
1191 _cleanup_(unlink_and_freep) char *t = NULL;
1192 _cleanup_fclose_ FILE *f = NULL;
1196 assert(arg_make_entry_directory >= 0);
1198 p = prefix_roota(esp_path, "/loader
/loader
.conf
");
1199 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
1202 r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
1204 return log_error_errno(r, "Failed to open
\"%s
\" for writing
: %m
", p);
1206 fprintf(f, "#timeout 3\n"
1207 "#console-mode keep\n");
1209 if (arg_make_entry_directory) {
1210 assert(arg_entry_token);
1211 fprintf(f, "default %s-*\n", arg_entry_token);
1214 r = flink_tmpfile(f, t, p);
1216 return 0; /* Silently skip creation if the file exists now (recheck) */
1218 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1224 static int install_loader_specification(const char *root) {
1225 _cleanup_(unlink_and_freep) char *t = NULL;
1226 _cleanup_fclose_ FILE *f = NULL;
1227 _cleanup_free_ char *p = NULL;
1230 p = path_join(root, "/loader/entries.srel");
1234 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
1237 r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
1239 return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
1241 fprintf(f, "type1\n");
1243 r = flink_tmpfile(f, t, p);
1245 return 0; /* Silently skip creation if the file exists now (recheck) */
1247 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1253 static int install_entry_directory(const char *root) {
1255 assert(arg_make_entry_directory >= 0);
1257 if (!arg_make_entry_directory)
1260 assert(arg_entry_token);
1261 return mkdir_one(root, arg_entry_token);
1264 static int install_entry_token(void) {
1267 assert(arg_make_entry_directory >= 0);
1268 assert(arg_entry_token);
1270 /* Let's save the used entry token in /etc/kernel/entry-token if we used it to create the entry
1271 * directory, or if anything else but the machine ID */
1273 if (!arg_make_entry_directory && arg_entry_token_type == ARG_ENTRY_TOKEN_MACHINE_ID)
1276 r = write_string_file("/etc/kernel/entry-token", arg_entry_token, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755);
1278 return log_error_errno(r, "Failed to write entry token '%s' to /etc/kernel/entry-token", arg_entry_token);
1283 static int help(int argc, char *argv[], void *userdata) {
1284 _cleanup_free_ char *link = NULL;
1287 r = terminal_urlify_man("bootctl", "1", &link);
1291 printf("%1$s [OPTIONS...] COMMAND ...\n"
1292 "\n%5$sControl EFI firmware boot settings and manage boot loader.%6$s\n"
1293 "\n%3$sGeneric EFI Firmware/Boot Loader Commands:%4$s\n"
1294 " status Show status of installed boot loader and EFI variables\n"
1295 " reboot-to-firmware [BOOL]\n"
1296 " Query or set reboot-to-firmware EFI flag\n"
1297 " systemd-efi-options [STRING]\n"
1298 " Query or set system options string in EFI variable\n"
1299 "\n%3$sBoot Loader Specification Commands:%4$s\n"
1300 " list List boot loader entries\n"
1301 " set-default ID Set default boot loader entry\n"
1302 " set-oneshot ID Set default boot loader entry, for next boot only\n"
1303 " set-timeout SECONDS Set the menu timeout\n"
1304 " set-timeout-oneshot SECONDS\n"
1305 " Set the menu timeout for the next boot only\n"
1306 "\n%3$ssystemd-boot Commands:%4$s\n"
1307 " install Install systemd-boot to the ESP and EFI variables\n"
1308 " update Update systemd-boot in the ESP and EFI variables\n"
1309 " remove Remove systemd-boot from the ESP and EFI variables\n"
1310 " is-installed Test whether systemd-boot is installed in the ESP\n"
1311 " random-seed Initialize random seed in ESP and EFI variables\n"
1312 "\n%3$sOptions:%4$s\n"
1313 " -h --help Show this help\n"
1314 " --version Print version\n"
1315 " --esp-path=PATH Path to the EFI System Partition (ESP)\n"
1316 " --boot-path=PATH Path to the $BOOT partition\n"
1317 " -p --print-esp-path Print path to the EFI System Partition\n"
1318 " -x --print-boot-path Print path to the $BOOT partition\n"
1319 " --no-variables Don't touch EFI variables\n"
1320 " --no-pager Do not pipe output into a pager\n"
1321 " --graceful Don't fail when the ESP cannot be found or EFI\n"
1322 " variables cannot be written\n"
1323 " -q --quiet Suppress output\n"
1324 " --make-entry-directory=yes|no|auto\n"
1325 " Create $BOOT/ENTRY-TOKEN/ directory\n"
1326 " --entry-token=machine-id|os-id|os-image-id|auto|literal:…\n"
1327 " Entry token to use for this installation\n"
1328 " --json=pretty|short|off\n"
1329 " Generate JSON output\n"
1330 "\nSee the %2$s for details.\n",
1331 program_invocation_short_name,
1341 static int parse_argv(int argc, char *argv[]) {
1343 ARG_ESP_PATH = 0x100,
1349 ARG_MAKE_ENTRY_DIRECTORY,
1354 static const struct option options[] = {
1355 { "help", no_argument, NULL, 'h' },
1356 { "version", no_argument, NULL, ARG_VERSION },
1357 { "esp-path", required_argument, NULL, ARG_ESP_PATH },
1358 { "path", required_argument, NULL, ARG_ESP_PATH }, /* Compatibility alias */
1359 { "boot-path", required_argument, NULL, ARG_BOOT_PATH },
1360 { "print-esp-path", no_argument, NULL, 'p' },
1361 { "print-path", no_argument, NULL, 'p' }, /* Compatibility alias */
1362 { "print-boot-path", no_argument, NULL, 'x' },
1363 { "no-variables", no_argument, NULL, ARG_NO_VARIABLES },
1364 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1365 { "graceful", no_argument, NULL, ARG_GRACEFUL },
1366 { "quiet", no_argument, NULL, 'q' },
1367 { "make-entry-directory", required_argument, NULL, ARG_MAKE_ENTRY_DIRECTORY },
1368 { "make-machine-id-directory", required_argument, NULL, ARG_MAKE_ENTRY_DIRECTORY }, /* Compatibility alias */
1369 { "entry-token", required_argument, NULL, ARG_ENTRY_TOKEN },
1370 { "json", required_argument, NULL, ARG_JSON },
1380 while ((c = getopt_long(argc, argv, "hpx", options, NULL)) >= 0)
1384 help(0, NULL, NULL);
1391 r = free_and_strdup(&arg_esp_path, optarg);
1397 r = free_and_strdup(&arg_xbootldr_path, optarg);
1403 if (arg_print_dollar_boot_path)
1404 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1405 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1406 arg_print_esp_path = true;
1410 if (arg_print_esp_path)
1411 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1412 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1413 arg_print_dollar_boot_path = true;
1416 case ARG_NO_VARIABLES:
1417 arg_touch_variables = false;
1421 arg_pager_flags |= PAGER_DISABLE;
1425 arg_graceful = true;
1432 case ARG_ENTRY_TOKEN: {
1435 if (streq(optarg, "machine-id")) {
1436 arg_entry_token_type = ARG_ENTRY_TOKEN_MACHINE_ID;
1437 arg_entry_token = mfree(arg_entry_token);
1438 } else if (streq(optarg, "os-image-id")) {
1439 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_IMAGE_ID;
1440 arg_entry_token = mfree(arg_entry_token);
1441 } else if (streq(optarg, "os-id")) {
1442 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_ID;
1443 arg_entry_token = mfree(arg_entry_token);
1444 } else if ((e = startswith(optarg, "literal:"))) {
1445 arg_entry_token_type = ARG_ENTRY_TOKEN_LITERAL;
1447 r = free_and_strdup_warn(&arg_entry_token, e);
1451 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1452 "Unexpected parameter for --entry-token=: %s", optarg);
1457 case ARG_MAKE_ENTRY_DIRECTORY:
1458 if (streq(optarg, "auto")) /* retained for backwards compatibility */
1459 arg_make_entry_directory = -1; /* yes if machine-id is permanent */
1461 r = parse_boolean_argument("--make-entry-directory=", optarg, &b);
1465 arg_make_entry_directory = b;
1470 r = parse_json_argument(optarg, &arg_json_format_flags);
1480 assert_not_reached();
1486 static void read_efi_var(const char *variable, char **ret) {
1489 r = efi_get_variable_string(variable, ret);
1490 if (r < 0 && r != -ENOENT)
1491 log_warning_errno(r, "Failed to read EFI variable %s: %m", variable);
1494 static void print_yes_no_line(bool first, bool good, const char *name) {
1496 first ? " Features: " : " ",
1497 COLOR_MARK_BOOL(good),
1501 static int are_we_installed(const char *esp_path) {
1504 /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
1505 * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
1506 * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
1507 * should be a suitable and very minimal check for a number of reasons:
1509 * → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
1510 * not a specific one.)
1512 * → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
1513 * /EFI/BOOT/BOOT*.EFI fallback binary.
1515 * → It specifically checks for systemd-boot, not for other boot loaders (which a check for
1516 * /boot/loader/entries would do). */
1518 _cleanup_free_ char *p = path_join(esp_path, "/EFI/systemd/");
1522 log_debug("Checking whether %s contains any files…", p);
1523 r = dir_is_empty(p, /* ignore_hidden_or_backup= */ false);
1524 if (r < 0 && r != -ENOENT)
1525 return log_error_errno(r, "Failed to check whether %s contains any files: %m", p);
1530 static int verb_status(int argc, char *argv[], void *userdata) {
1531 sd_id128_t esp_uuid = SD_ID128_NULL, xbootldr_uuid = SD_ID128_NULL;
1532 dev_t esp_devid = 0, xbootldr_devid = 0;
1535 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, &esp_uuid, &esp_devid);
1536 if (arg_print_esp_path) {
1537 if (r == -EACCES) /* If we couldn't acquire the ESP path, log about access errors (which is the only
1538 * error the find_esp_and_warn() won't log on its own) */
1539 return log_error_errno(r, "Failed to determine ESP location: %m");
1546 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, &xbootldr_uuid, &xbootldr_devid);
1547 if (arg_print_dollar_boot_path) {
1549 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1553 const char *path = arg_dollar_boot_path();
1555 return log_error_errno(SYNTHETIC_ERRNO(EACCES), "Failed to determine XBOOTLDR location: %m");
1560 if (arg_print_esp_path || arg_print_dollar_boot_path)
1563 r = 0; /* If we couldn't determine the path, then don't consider that a problem from here on, just
1564 * show what we can show */
1566 pager_open(arg_pager_flags);
1568 if (is_efi_boot()) {
1569 static const struct {
1573 { EFI_LOADER_FEATURE_BOOT_COUNTING, "Boot counting" },
1574 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT, "Menu timeout control" },
1575 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT, "One-shot menu timeout control" },
1576 { EFI_LOADER_FEATURE_ENTRY_DEFAULT, "Default entry control" },
1577 { EFI_LOADER_FEATURE_ENTRY_ONESHOT, "One-shot entry control" },
1578 { EFI_LOADER_FEATURE_XBOOTLDR, "Support for XBOOTLDR partition" },
1579 { EFI_LOADER_FEATURE_RANDOM_SEED, "Support for passing random seed to OS" },
1580 { EFI_LOADER_FEATURE_LOAD_DRIVER, "Load drop-in drivers" },
1582 _cleanup_free_ char *fw_type = NULL, *fw_info = NULL, *loader = NULL, *loader_path = NULL, *stub = NULL;
1583 sd_id128_t loader_part_uuid = SD_ID128_NULL;
1584 uint64_t loader_features = 0;
1588 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareType), &fw_type);
1589 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareInfo), &fw_info);
1590 read_efi_var(EFI_LOADER_VARIABLE(LoaderInfo), &loader);
1591 read_efi_var(EFI_LOADER_VARIABLE(StubInfo), &stub);
1592 read_efi_var(EFI_LOADER_VARIABLE(LoaderImageIdentifier), &loader_path);
1593 (void) efi_loader_get_features(&loader_features);
1596 efi_tilt_backslashes(loader_path);
1598 k = efi_loader_get_device_part_uuid(&loader_part_uuid);
1599 if (k < 0 && k != -ENOENT)
1600 r = log_warning_errno(k, "Failed to read EFI variable LoaderDevicePartUUID: %m");
1602 SecureBootMode secure = efi_get_secure_boot_mode();
1603 printf("System:\n");
1604 printf(" Firmware: %s%s (%s)%s\n", ansi_highlight(), strna(fw_type), strna(fw_info), ansi_normal());
1605 printf(" Secure Boot: %sd (%s)\n",
1606 enable_disable(IN_SET(secure, SECURE_BOOT_USER, SECURE_BOOT_DEPLOYED)),
1607 secure_boot_mode_to_string(secure));
1610 printf(" TPM2 Support: %s%s%s\n",
1611 FLAGS_SET(s, TPM2_SUPPORT_FIRMWARE|TPM2_SUPPORT_DRIVER) ? ansi_highlight_green() :
1612 (s & (TPM2_SUPPORT_FIRMWARE|TPM2_SUPPORT_DRIVER)) != 0 ? ansi_highlight_red() : ansi_highlight_yellow(),
1613 FLAGS_SET(s, TPM2_SUPPORT_FIRMWARE|TPM2_SUPPORT_DRIVER) ? "yes" :
1614 (s & TPM2_SUPPORT_FIRMWARE) ? "firmware only, driver unavailable" :
1615 (s & TPM2_SUPPORT_DRIVER) ? "driver only, firmware unavailable" : "no",
1618 k = efi_get_reboot_to_firmware();
1620 printf(" Boot into FW: %sactive%s\n", ansi_highlight_yellow(), ansi_normal());
1622 printf(" Boot into FW: supported\n");
1623 else if (k == -EOPNOTSUPP)
1624 printf(" Boot into FW: not supported\n");
1627 printf(" Boot into FW: %sfailed%s (%m)\n", ansi_highlight_red(), ansi_normal());
1631 printf("Current Boot Loader:\n");
1632 printf(" Product: %s%s%s\n", ansi_highlight(), strna(loader), ansi_normal());
1634 for (size_t i = 0; i < ELEMENTSOF(flags); i++)
1635 print_yes_no_line(i == 0, FLAGS_SET(loader_features, flags[i].flag), flags[i].name);
1637 sd_id128_t bootloader_esp_uuid;
1638 bool have_bootloader_esp_uuid = efi_loader_get_device_part_uuid(&bootloader_esp_uuid) >= 0;
1640 print_yes_no_line(false, have_bootloader_esp_uuid, "Boot loader sets ESP information");
1641 if (have_bootloader_esp_uuid && !sd_id128_equal(esp_uuid, bootloader_esp_uuid))
1642 printf("WARNING: The boot loader reports a different ESP UUID than detected!\n");
1645 printf(" Stub: %s\n", stub);
1646 if (!sd_id128_is_null(loader_part_uuid))
1647 printf(" ESP: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR "\n",
1648 SD_ID128_FORMAT_VAL(loader_part_uuid));
1650 printf(" ESP: n/a\n");
1651 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), strna(loader_path));
1654 printf("Random Seed:\n");
1655 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderRandomSeed)), F_OK) >= 0;
1656 printf(" Passed to OS: %s\n", yes_no(have));
1657 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderSystemToken)), F_OK) >= 0;
1658 printf(" System Token: %s\n", have ? "set" : "not set");
1661 _cleanup_free_ char *p = NULL;
1663 p = path_join(arg_esp_path, "/loader/random-seed");
1667 have = access(p, F_OK) >= 0;
1668 printf(" Exists: %s\n", yes_no(have));
1673 printf("System:\n Not booted with EFI\n\n");
1676 k = status_binaries(arg_esp_path, esp_uuid);
1681 if (is_efi_boot()) {
1682 k = status_variables();
1687 if (arg_esp_path || arg_xbootldr_path) {
1688 _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL;
1690 k = boot_config_load_and_select(&config,
1691 arg_esp_path, esp_devid,
1692 arg_xbootldr_path, xbootldr_devid);
1696 k = status_entries(&config,
1697 arg_esp_path, esp_uuid,
1698 arg_xbootldr_path, xbootldr_uuid);
1707 static int verb_list(int argc, char *argv[], void *userdata) {
1708 _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL;
1709 dev_t esp_devid = 0, xbootldr_devid = 0;
1712 /* If we lack privileges we invoke find_esp_and_warn() in "unprivileged mode" here, which does two
1713 * things: turn off logging about access errors and turn off potentially privileged device probing.
1714 * Here we're interested in the latter but not the former, hence request the mode, and log about
1717 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, NULL, &esp_devid);
1718 if (r == -EACCES) /* We really need the ESP path for this call, hence also log about access errors */
1719 return log_error_errno(r, "Failed to determine ESP location: %m");
1723 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, NULL, &xbootldr_devid);
1725 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1729 r = boot_config_load_and_select(&config, arg_esp_path, esp_devid, arg_xbootldr_path, xbootldr_devid);
1733 if (config.n_entries == 0 && FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
1734 log_info("No boot loader entries found.");
1738 pager_open(arg_pager_flags);
1739 return show_boot_entries(&config, arg_json_format_flags);
1742 static int install_random_seed(const char *esp) {
1743 _cleanup_(unlink_and_freep) char *tmp = NULL;
1744 _cleanup_free_ void *buffer = NULL;
1745 _cleanup_free_ char *path = NULL;
1746 _cleanup_close_ int fd = -1;
1747 size_t sz, token_size;
1753 path = path_join(esp, "/loader/random-seed");
1757 sz = random_pool_size();
1759 buffer = malloc(sz);
1763 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1765 return log_error_errno(r, "Failed to acquire random seed: %m");
1767 /* Normally create_subdirs() should already have created everything we need, but in case "bootctl
1768 * random
-seed
" is called we want to just create the minimum we need for it, and not the full
1770 r = mkdir_parents(path, 0755);
1772 return log_error_errno(r, "Failed to create parent directory
for %s
: %m
", path);
1774 r = tempfn_random(path, "bootctl
", &tmp);
1778 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|O_WRONLY|O_CLOEXEC, 0600);
1781 return log_error_errno(fd, "Failed to open random seed file
for writing
: %m
");
1784 n = write(fd, buffer, sz);
1786 return log_error_errno(errno, "Failed to write random seed file
: %m
");
1787 if ((size_t) n != sz)
1788 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write
while writing random seed file
.");
1790 if (rename(tmp, path) < 0)
1791 return log_error_errno(r, "Failed to move random seed file into place
: %m
");
1795 log_info("Random seed file
%s successfully
written (%zu bytes
).", path, sz);
1797 if (!arg_touch_variables)
1800 if (!is_efi_boot()) {
1801 log_notice("Not booted with EFI
, skipping EFI variable setup
.");
1805 r = getenv_bool("SYSTEMD_WRITE_SYSTEM_TOKEN
");
1808 log_warning_errno(r, "Failed to parse $SYSTEMD_WRITE_SYSTEM_TOKEN
, ignoring
.");
1810 if (detect_vm() > 0) {
1811 /* Let's not write a system token if we detect we are running in a VM
1812 * environment. Why? Our default security model for the random seed uses the system
1813 * token as a mechanism to ensure we are not vulnerable to golden master sloppiness
1814 * issues, i.e. that people initialize the random seed file, then copy the image to
1815 * many systems and end up with the same random seed in each that is assumed to be
1816 * valid but in reality is the same for all machines. By storing a system token in
1817 * the EFI variable space we can make sure that even though the random seeds on disk
1818 * are all the same they will be different on each system under the assumption that
1819 * the EFI variable space is maintained separate from the random seed storage. That
1820 * is generally the case on physical systems, as the ESP is stored on persistent
1821 * storage, and the EFI variables in NVRAM. However in virtualized environments this
1822 * is generally not true: the EFI variable set is typically stored along with the
1823 * disk image itself. For example, using the OVMF EFI firmware the EFI variables are
1824 * stored in a file in the ESP itself. */
1826 log_notice("Not installing system token
, since we are running in a virtualized environment
.");
1829 } else if (r == 0) {
1830 log_notice("Not writing system token
, because $SYSTEMD_WRITE_SYSTEM_TOKEN is set to
false.");
1834 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), NULL, NULL, &token_size);
1836 log_debug_errno(r, "LoaderSystemToken EFI variable is
invalid (too
short?), replacing
.");
1839 return log_error_errno(r, "Failed to test system token validity
: %m
");
1841 if (token_size >= sz) {
1842 /* Let's avoid writes if we can, and initialize this only once. */
1843 log_debug("System token already written
, not updating
.");
1847 log_debug("Existing system token
size (%zu
) does
not match our
expectations (%zu
), replacing
.", token_size, sz);
1850 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1852 return log_error_errno(r, "Failed to acquire random seed
: %m
");
1854 /* Let's write this variable with an umask in effect, so that unprivileged users can't see the token
1855 * and possibly get identification information or too much insight into the kernel's entropy pool
1857 RUN_WITH_UMASK(0077) {
1858 r = efi_set_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), buffer, sz);
1861 return log_error_errno(r, "Failed to write
'LoaderSystemToken' EFI variable
: %m
");
1864 log_warning_errno(r, "Unable to write
'LoaderSystemToken' EFI
variable (firmware problem
?), ignoring
: %m
");
1866 log_warning_errno(r, "Unable to write
'LoaderSystemToken' EFI variable
, ignoring
: %m
");
1868 log_info("Successfully initialized system token in EFI variable with
%zu bytes
.", sz);
1874 static int sync_everything(void) {
1878 k = syncfs_path(AT_FDCWD, arg_esp_path);
1880 ret = log_error_errno(k, "Failed to synchronize the ESP
'%s': %m
", arg_esp_path);
1883 if (arg_xbootldr_path) {
1884 k = syncfs_path(AT_FDCWD, arg_xbootldr_path);
1886 ret = log_error_errno(k, "Failed to synchronize $BOOT
'%s': %m
", arg_xbootldr_path);
1892 static int verb_install(int argc, char *argv[], void *userdata) {
1893 sd_id128_t uuid = SD_ID128_NULL;
1894 uint64_t pstart = 0, psize = 0;
1896 bool install, graceful;
1899 /* Invoked for both "update
" and "install
" */
1901 install = streq(argv[0], "install
");
1902 graceful = !install && arg_graceful; /* support graceful mode for updates */
1904 r = acquire_esp(/* unprivileged_mode= */ false, graceful, &part, &pstart, &psize, &uuid, NULL);
1905 if (graceful && r == -ENOKEY)
1906 return 0; /* If --graceful is specified and we can't find an ESP, handle this cleanly */
1911 /* If we are updating, don't do anything if sd-boot wasn't actually installed. */
1912 r = are_we_installed(arg_esp_path);
1916 log_debug("Skipping update because sd
-boot is
not installed in the ESP
.");
1921 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
1925 r = settle_make_entry_directory();
1929 RUN_WITH_UMASK(0002) {
1931 /* Don't create any of these directories when we are just updating. When we update
1932 * we'll drop-in our files (unless there are newer ones already), but we won't create
1933 * the directories for them in the first place. */
1934 r = create_subdirs(arg_esp_path, esp_subdirs);
1938 r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
1943 r = install_binaries(arg_esp_path, install);
1948 r = install_loader_config(arg_esp_path);
1952 r = install_entry_directory(arg_dollar_boot_path());
1956 r = install_entry_token();
1960 r = install_random_seed(arg_esp_path);
1965 r = install_loader_specification(arg_dollar_boot_path());
1970 (void) sync_everything();
1972 if (arg_touch_variables)
1973 r = install_variables(arg_esp_path,
1974 part, pstart, psize, uuid,
1975 "/EFI
/systemd
/systemd
-boot
" EFI_MACHINE_TYPE_NAME ".efi
",
1981 static int verb_remove(int argc, char *argv[], void *userdata) {
1982 sd_id128_t uuid = SD_ID128_NULL;
1985 r = acquire_esp(/* unprivileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, &uuid, NULL);
1989 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
1993 r = settle_make_entry_directory();
1997 r = remove_binaries(arg_esp_path);
1999 q = remove_file(arg_esp_path, "/loader
/loader
.conf
");
2000 if (q < 0 && r >= 0)
2003 q = remove_file(arg_esp_path, "/loader
/random
-seed
");
2004 if (q < 0 && r >= 0)
2007 q = remove_file(arg_esp_path, "/loader
/entries
.srel
");
2008 if (q < 0 && r >= 0)
2011 q = remove_subdirs(arg_esp_path, esp_subdirs);
2012 if (q < 0 && r >= 0)
2015 q = remove_subdirs(arg_esp_path, dollar_boot_subdirs);
2016 if (q < 0 && r >= 0)
2019 q = remove_entry_directory(arg_esp_path);
2020 if (q < 0 && r >= 0)
2023 if (arg_xbootldr_path) {
2024 /* Remove a subset of these also from the XBOOTLDR partition if it exists */
2026 q = remove_file(arg_xbootldr_path, "/loader
/entries
.srel
");
2027 if (q < 0 && r >= 0)
2030 q = remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs);
2031 if (q < 0 && r >= 0)
2034 q = remove_entry_directory(arg_xbootldr_path);
2035 if (q < 0 && r >= 0)
2039 (void) sync_everything();
2041 if (!arg_touch_variables)
2044 q = remove_variables(uuid, "/EFI
/systemd
/systemd
-boot
" EFI_MACHINE_TYPE_NAME ".efi
", true);
2045 if (q < 0 && r >= 0)
2048 q = remove_loader_variables();
2049 if (q < 0 && r >= 0)
2055 static int verb_is_installed(int argc, char *argv[], void *userdata) {
2058 r = acquire_esp(/* privileged_mode= */ false,
2059 /* graceful= */ arg_graceful,
2060 NULL, NULL, NULL, NULL, NULL);
2064 r = are_we_installed(arg_esp_path);
2071 return EXIT_SUCCESS;
2075 return EXIT_FAILURE;
2079 static int parse_timeout(const char *arg1, char16_t **ret_timeout, size_t *ret_timeout_size) {
2080 char utf8[DECIMAL_STR_MAX(usec_t)];
2086 assert(ret_timeout);
2087 assert(ret_timeout_size);
2089 if (streq(arg1, "menu
-force
"))
2090 timeout = USEC_INFINITY;
2091 else if (streq(arg1, "menu
-hidden
"))
2094 r = parse_time(arg1, &timeout, USEC_PER_SEC);
2096 return log_error_errno(r, "Failed to parse timeout
'%s': %m
", arg1);
2097 if (timeout != USEC_INFINITY && timeout > UINT32_MAX * USEC_PER_SEC)
2098 log_warning("Timeout is too
long and will be treated as
'menu-force' instead
.");
2101 xsprintf(utf8, USEC_FMT, MIN(timeout / USEC_PER_SEC, UINT32_MAX));
2103 encoded = utf8_to_utf16(utf8, strlen(utf8));
2107 *ret_timeout = encoded;
2108 *ret_timeout_size = char16_strlen(encoded) * 2 + 2;
2112 static int parse_loader_entry_target_arg(const char *arg1, char16_t **ret_target, size_t *ret_target_size) {
2113 char16_t *encoded = NULL;
2118 assert(ret_target_size);
2120 if (streq(arg1, "@current
")) {
2121 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntrySelected), NULL, (void *) ret_target, ret_target_size);
2123 return log_error_errno(r, "Failed to get EFI variable
'LoaderEntrySelected': %m
");
2125 } else if (streq(arg1, "@oneshot
")) {
2126 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryOneShot), NULL, (void *) ret_target, ret_target_size);
2128 return log_error_errno(r, "Failed to get EFI variable
'LoaderEntryOneShot': %m
");
2130 } else if (streq(arg1, "@
default")) {
2131 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryDefault), NULL, (void *) ret_target, ret_target_size);
2133 return log_error_errno(r, "Failed to get EFI variable
'LoaderEntryDefault': %m
");
2135 } else if (arg1[0] == '@' && !streq(arg1, "@saved
"))
2136 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unsupported special entry identifier
: %s
", arg1);
2138 encoded = utf8_to_utf16(arg1, strlen(arg1));
2142 *ret_target = encoded;
2143 *ret_target_size = char16_strlen(encoded) * 2 + 2;
2149 static int verb_set_efivar(int argc, char *argv[], void *userdata) {
2153 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2154 "Not booted with UEFI
.");
2156 if (access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderInfo)), F_OK) < 0) {
2157 if (errno == ENOENT) {
2158 log_error_errno(errno, "Not booted with a supported boot loader
.");
2162 return log_error_errno(errno, "Failed to detect whether boot loader supports
'%s' operation
: %m
", argv[0]);
2165 if (detect_container() > 0)
2166 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2167 "'%s' operation
not supported in a container
.",
2170 if (!arg_touch_variables)
2171 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2172 "'%s' operation cannot be combined with
--no
-variables
.",
2175 const char *variable;
2176 int (* arg_parser)(const char *, char16_t **, size_t *);
2178 if (streq(argv[0], "set
-default")) {
2179 variable = EFI_LOADER_VARIABLE(LoaderEntryDefault);
2180 arg_parser = parse_loader_entry_target_arg;
2181 } else if (streq(argv[0], "set
-oneshot
")) {
2182 variable = EFI_LOADER_VARIABLE(LoaderEntryOneShot);
2183 arg_parser = parse_loader_entry_target_arg;
2184 } else if (streq(argv[0], "set
-timeout
")) {
2185 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeout);
2186 arg_parser = parse_timeout;
2187 } else if (streq(argv[0], "set
-timeout
-oneshot
")) {
2188 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot);
2189 arg_parser = parse_timeout;
2191 assert_not_reached();
2193 if (isempty(argv[1])) {
2194 r = efi_set_variable(variable, NULL, 0);
2195 if (r < 0 && r != -ENOENT)
2196 return log_error_errno(r, "Failed to remove EFI variable
'%s': %m
", variable);
2198 _cleanup_free_ char16_t *value = NULL;
2199 size_t value_size = 0;
2201 r = arg_parser(argv[1], &value, &value_size);
2204 r = efi_set_variable(variable, value, value_size);
2206 return log_error_errno(r, "Failed to update EFI variable
'%s': %m
", variable);
2212 static int verb_random_seed(int argc, char *argv[], void *userdata) {
2215 r = find_esp_and_warn(arg_esp_path, false, &arg_esp_path, NULL, NULL, NULL, NULL, NULL);
2217 /* find_esp_and_warn() doesn't warn about ENOKEY, so let's do that on our own */
2219 return log_error_errno(r, "Unable to find ESP
.");
2221 log_notice("No ESP found
, not initializing random seed
.");
2227 r = install_random_seed(arg_esp_path);
2231 (void) sync_everything();
2235 static int verb_systemd_efi_options(int argc, char *argv[], void *userdata) {
2239 _cleanup_free_ char *line = NULL, *new = NULL;
2241 r = systemd_efi_options_variable(&line);
2243 log_debug("No SystemdOptions EFI variable present in cache
.");
2245 return log_error_errno(r, "Failed to read SystemdOptions EFI variable from cache
: %m
");
2249 r = systemd_efi_options_efivarfs_if_newer(&new);
2250 if (r == -ENODATA) {
2252 log_notice("Note
: SystemdOptions EFI variable has been removed since boot
.");
2254 log_warning_errno(r, "Failed to check SystemdOptions EFI variable in efivarfs
, ignoring
: %m
");
2255 else if (new && !streq_ptr(line, new))
2256 log_notice("Note
: SystemdOptions EFI variable has been modified since boot
. New value
: %s
",
2259 r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE(SystemdOptions), argv[1]);
2261 return log_error_errno(r, "Failed to set SystemdOptions EFI variable
: %m
");
2267 static int verb_reboot_to_firmware(int argc, char *argv[], void *userdata) {
2271 r = efi_get_reboot_to_firmware();
2274 return EXIT_SUCCESS; /* success */
2278 return 1; /* recognizable error #1 */
2280 if (r == -EOPNOTSUPP) {
2281 puts("not supported
");
2282 return 2; /* recognizable error #2 */
2285 log_error_errno(r, "Failed to query reboot
-to
-firmware state
: %m
");
2286 return 3; /* other kind of error */
2288 r = parse_boolean(argv[1]);
2290 return log_error_errno(r, "Failed to parse argument
: %s
", argv[1]);
2292 r = efi_set_reboot_to_firmware(r);
2294 return log_error_errno(r, "Failed to set reboot
-to
-firmware option
: %m
");
2300 static int bootctl_main(int argc, char *argv[]) {
2301 static const Verb verbs[] = {
2302 { "help
", VERB_ANY, VERB_ANY, 0, help },
2303 { "status
", VERB_ANY, 1, VERB_DEFAULT, verb_status },
2304 { "install
", VERB_ANY, 1, 0, verb_install },
2305 { "update
", VERB_ANY, 1, 0, verb_install },
2306 { "remove
", VERB_ANY, 1, 0, verb_remove },
2307 { "is
-installed
", VERB_ANY, 1, 0, verb_is_installed },
2308 { "list
", VERB_ANY, 1, 0, verb_list },
2309 { "set
-default", 2, 2, 0, verb_set_efivar },
2310 { "set
-oneshot
", 2, 2, 0, verb_set_efivar },
2311 { "set
-timeout
", 2, 2, 0, verb_set_efivar },
2312 { "set
-timeout
-oneshot
", 2, 2, 0, verb_set_efivar },
2313 { "random
-seed
", VERB_ANY, 1, 0, verb_random_seed },
2314 { "systemd
-efi
-options
", VERB_ANY, 2, 0, verb_systemd_efi_options },
2315 { "reboot
-to
-firmware
", VERB_ANY, 2, 0, verb_reboot_to_firmware },
2319 return dispatch_verb(argc, argv, verbs, NULL);
2322 static int run(int argc, char *argv[]) {
2325 log_parse_environment();
2328 /* If we run in a container, automatically turn off EFI file system access */
2329 if (detect_container() > 0)
2330 arg_touch_variables = false;
2332 r = parse_argv(argc, argv);
2336 return bootctl_main(argc, argv);
2339 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);