]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/boot/bootctl.c
Merge pull request #23517 from mrc0mmand/cryptsetup-switchroot-transition
[thirdparty/systemd.git] / src / boot / bootctl.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <ctype.h>
4 #include <errno.h>
5 #include <getopt.h>
6 #include <limits.h>
7 #include <linux/magic.h>
8 #include <stdbool.h>
9 #include <stdlib.h>
10 #include <sys/mman.h>
11 #include <unistd.h>
12
13 #include "sd-id128.h"
14
15 #include "alloc-util.h"
16 #include "blkid-util.h"
17 #include "bootspec.h"
18 #include "copy.h"
19 #include "devnum-util.h"
20 #include "dirent-util.h"
21 #include "efi-api.h"
22 #include "efi-loader.h"
23 #include "efivars.h"
24 #include "env-file.h"
25 #include "env-util.h"
26 #include "escape.h"
27 #include "fd-util.h"
28 #include "fileio.h"
29 #include "find-esp.h"
30 #include "fs-util.h"
31 #include "glyph-util.h"
32 #include "main-func.h"
33 #include "mkdir.h"
34 #include "os-util.h"
35 #include "pager.h"
36 #include "parse-argument.h"
37 #include "parse-util.h"
38 #include "pretty-print.h"
39 #include "random-util.h"
40 #include "rm-rf.h"
41 #include "stat-util.h"
42 #include "stdio-util.h"
43 #include "string-table.h"
44 #include "string-util.h"
45 #include "strv.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"
52 #include "utf8.h"
53 #include "util.h"
54 #include "verbs.h"
55 #include "virt.h"
56
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;
68 static enum {
69 ARG_ENTRY_TOKEN_MACHINE_ID,
70 ARG_ENTRY_TOKEN_OS_IMAGE_ID,
71 ARG_ENTRY_TOKEN_OS_ID,
72 ARG_ENTRY_TOKEN_LITERAL,
73 ARG_ENTRY_TOKEN_AUTO,
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;
78
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);
83
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;
87 }
88
89 static int acquire_esp(
90 bool unprivileged_mode,
91 bool graceful,
92 uint32_t *ret_part,
93 uint64_t *ret_pstart,
94 uint64_t *ret_psize,
95 sd_id128_t *ret_uuid,
96 dev_t *ret_devid) {
97
98 char *np;
99 int r;
100
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
105 * this). */
106
107 r = find_esp_and_warn(arg_esp_path, unprivileged_mode, &np, ret_part, ret_pstart, ret_psize, ret_uuid, ret_devid);
108 if (r == -ENOKEY) {
109 if (graceful)
110 return log_full_errno(arg_quiet ? LOG_DEBUG : LOG_INFO, r,
111 "Couldn't find EFI system partition, skipping.");
112
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.");
116 }
117 if (r < 0)
118 return r;
119
120 free_and_replace(arg_esp_path, np);
121 log_debug("Using EFI System Partition at %s.", arg_esp_path);
122
123 return 0;
124 }
125
126 static int acquire_xbootldr(
127 bool unprivileged_mode,
128 sd_id128_t *ret_uuid,
129 dev_t *ret_devid) {
130
131 char *np;
132 int r;
133
134 r = find_xbootldr_and_warn(arg_xbootldr_path, unprivileged_mode, &np, ret_uuid, ret_devid);
135 if (r == -ENOKEY) {
136 log_debug_errno(r, "Didn't find an XBOOTLDR partition, using the ESP as $BOOT.");
137 arg_xbootldr_path = mfree(arg_xbootldr_path);
138
139 if (ret_uuid)
140 *ret_uuid = SD_ID128_NULL;
141 if (ret_devid)
142 *ret_devid = 0;
143 return 0;
144 }
145 if (r < 0)
146 return r;
147
148 free_and_replace(arg_xbootldr_path, np);
149 log_debug("Using XBOOTLDR partition at %s as $BOOT.", arg_xbootldr_path);
150
151 return 1;
152 }
153
154 static int load_etc_machine_id(void) {
155 int r;
156
157 r = sd_id128_get_machine(&arg_machine_id);
158 if (IN_SET(r, -ENOENT, -ENOMEDIUM)) /* Not set or empty */
159 return 0;
160 if (r < 0)
161 return log_error_errno(r, "Failed to get machine-id: %m");
162
163 log_debug("Loaded machine ID %s from /etc/machine-id.", SD_ID128_TO_STRING(arg_machine_id));
164 return 0;
165 }
166
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;
173 int r;
174
175 r = parse_env_file(NULL, "/etc/machine-info",
176 "KERNEL_INSTALL_LAYOUT", &layout,
177 "KERNEL_INSTALL_MACHINE_ID", &s);
178 if (r == -ENOENT)
179 return 0;
180 if (r < 0)
181 return log_error_errno(r, "Failed to parse /etc/machine-info: %m");
182
183 if (!isempty(s)) {
184 if (!arg_quiet)
185 log_notice("Read $KERNEL_INSTALL_MACHINE_ID from /etc/machine-info. "
186 "Please move it to /etc/kernel/entry-token.");
187
188 r = sd_id128_from_string(s, &arg_machine_id);
189 if (r < 0)
190 return log_error_errno(r, "Failed to parse KERNEL_INSTALL_MACHINE_ID=%s in /etc/machine-info: %m", s);
191
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));
194 }
195
196 if (!isempty(layout)) {
197 if (!arg_quiet)
198 log_notice("Read $KERNEL_INSTALL_LAYOUT from /etc/machine-info. "
199 "Please move it to the layout= setting of /etc/kernel/install.conf.");
200
201 log_debug("KERNEL_INSTALL_LAYOUT=%s is specified in /etc/machine-info.", layout);
202 free_and_replace(arg_install_layout, layout);
203 }
204
205 return 0;
206 }
207
208 static int load_etc_kernel_install_conf(void) {
209 _cleanup_free_ char *layout = NULL;
210 int r;
211
212 r = parse_env_file(NULL, "/etc/kernel/install.conf",
213 "layout", &layout);
214 if (r == -ENOENT)
215 return 0;
216 if (r < 0)
217 return log_error_errno(r, "Failed to parse /etc/kernel/install.conf: %m");
218
219 if (!isempty(layout)) {
220 log_debug("layout=%s is specified in /etc/machine-info.", layout);
221 free_and_replace(arg_install_layout, layout);
222 }
223
224 return 0;
225 }
226
227 static int settle_entry_token(void) {
228 int r;
229
230 switch (arg_entry_token_type) {
231
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");
237
238 if (!isempty(buf)) {
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;
243
244 r = parse_os_release(NULL,
245 "IMAGE_ID", &image_id,
246 "ID", &id);
247 if (r < 0)
248 return log_error_errno(r, "Failed to load /etc/os-release: %m");
249
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;
256 } else
257 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No machine ID set, and /etc/os-release carries no ID=/IMAGE_ID= fields.");
258 } else {
259 r = free_and_strdup_warn(&arg_entry_token, SD_ID128_TO_STRING(arg_machine_id));
260 if (r < 0)
261 return r;
262
263 arg_entry_token_type = ARG_ENTRY_TOKEN_MACHINE_ID;
264 }
265
266 break;
267 }
268
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.");
272
273 r = free_and_strdup_warn(&arg_entry_token, SD_ID128_TO_STRING(arg_machine_id));
274 if (r < 0)
275 return r;
276
277 break;
278
279 case ARG_ENTRY_TOKEN_OS_IMAGE_ID: {
280 _cleanup_free_ char *buf = NULL;
281
282 r = parse_os_release(NULL, "IMAGE_ID", &buf);
283 if (r < 0)
284 return log_error_errno(r, "Failed to load /etc/os-release: %m");
285
286 if (isempty(buf))
287 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "IMAGE_ID= field not set in /etc/os-release.");
288
289 free_and_replace(arg_entry_token, buf);
290 break;
291 }
292
293 case ARG_ENTRY_TOKEN_OS_ID: {
294 _cleanup_free_ char *buf = NULL;
295
296 r = parse_os_release(NULL, "ID", &buf);
297 if (r < 0)
298 return log_error_errno(r, "Failed to load /etc/os-release: %m");
299
300 if (isempty(buf))
301 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "ID= field not set in /etc/os-release.");
302
303 free_and_replace(arg_entry_token, buf);
304 break;
305 }
306
307 case ARG_ENTRY_TOKEN_LITERAL:
308 assert(!isempty(arg_entry_token)); /* already filled in by command line parser */
309 break;
310 }
311
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);
314
315 log_debug("Using entry token: %s", arg_entry_token);
316 return 0;
317 }
318
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");
323 }
324
325 static int settle_make_entry_directory(void) {
326 int r;
327
328 r = load_etc_machine_id();
329 if (r < 0)
330 return r;
331
332 r = load_etc_machine_info();
333 if (r < 0)
334 return r;
335
336 r = load_etc_kernel_install_conf();
337 if (r < 0)
338 return r;
339
340 r = settle_entry_token();
341 if (r < 0)
342 return r;
343
344 bool layout_type1 = use_boot_loader_spec_type1();
345 if (arg_make_entry_directory < 0) { /* Automatic mode */
346 if (layout_type1) {
347 if (arg_entry_token == ARG_ENTRY_TOKEN_MACHINE_ID) {
348 r = path_is_temporary_fs("/etc/machine-id");
349 if (r < 0)
350 return log_debug_errno(r, "Couldn't determine whether /etc/machine-id is on a temporary file system: %m");
351
352 arg_make_entry_directory = r == 0;
353 } else
354 arg_make_entry_directory = true;
355 } else
356 arg_make_entry_directory = false;
357 }
358
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.",
362 arg_install_layout);
363
364 return 0;
365 }
366
367 /* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */
368 static int get_file_version(int fd, char **v) {
369 struct stat st;
370 char *buf;
371 const char *s, *e;
372 char *x = NULL;
373 int r;
374
375 assert(fd >= 0);
376 assert(v);
377
378 if (fstat(fd, &st) < 0)
379 return log_error_errno(errno, "Failed to stat EFI binary: %m");
380
381 r = stat_verify_regular(&st);
382 if (r < 0)
383 return log_error_errno(r, "EFI binary is not a regular file: %m");
384
385 if (st.st_size < 27 || file_offset_beyond_memory_size(st.st_size)) {
386 *v = NULL;
387 return 0;
388 }
389
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");
393
394 s = mempmem_safe(buf, st.st_size - 8, "#### LoaderInfo: ", 17);
395 if (!s)
396 goto finish;
397
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.");
401 goto finish;
402 }
403
404 x = strndup(s, e - s);
405 if (!x) {
406 r = log_oom();
407 goto finish;
408 }
409 r = 1;
410
411 finish:
412 (void) munmap(buf, st.st_size);
413 *v = x;
414 return r;
415 }
416
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. */
420
421 #ifdef __x86_64__
422 _cleanup_free_ char *platform_size = NULL;
423 int r;
424
425 r = read_one_line_file("/sys/firmware/efi/fw_platform_size", &platform_size);
426 if (r == -ENOENT)
427 return EFI_MACHINE_TYPE_NAME;
428 if (r < 0) {
429 log_warning_errno(r, "Error reading EFI firmware word size, assuming '%u': %m", __WORDSIZE);
430 return EFI_MACHINE_TYPE_NAME;
431 }
432
433 if (streq(platform_size, "64"))
434 return EFI_MACHINE_TYPE_NAME;
435 if (streq(platform_size, "32"))
436 return "ia32";
437
438 log_warning(
439 "Unknown EFI firmware word size '%s', using default word size '%u' instead.",
440 platform_size,
441 __WORDSIZE);
442 #endif
443
444 return EFI_MACHINE_TYPE_NAME;
445 }
446
447 static int enumerate_binaries(const char *esp_path, const char *path, const char *prefix) {
448 _cleanup_closedir_ DIR *d = NULL;
449 const char *p;
450 int c = 0, r;
451
452 assert(esp_path);
453 assert(path);
454
455 p = prefix_roota(esp_path, path);
456 d = opendir(p);
457 if (!d) {
458 if (errno == ENOENT)
459 return 0;
460
461 return log_error_errno(errno, "Failed to read \"%s\": %m", p);
462 }
463
464 FOREACH_DIRENT(de, d, break) {
465 _cleanup_free_ char *v = NULL;
466 _cleanup_close_ int fd = -1;
467
468 if (!endswith_no_case(de->d_name, ".efi"))
469 continue;
470
471 if (prefix && !startswith_no_case(de->d_name, prefix))
472 continue;
473
474 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
475 if (fd < 0)
476 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
477
478 r = get_file_version(fd, &v);
479 if (r < 0)
480 return r;
481 if (r > 0)
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());
483 else
484 printf(" File: %s/%s/%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path, de->d_name);
485
486 c++;
487 }
488
489 return c;
490 }
491
492 static int status_binaries(const char *esp_path, sd_id128_t partition) {
493 int r;
494
495 printf("Available Boot Loaders on ESP:\n");
496
497 if (!esp_path) {
498 printf(" ESP: Cannot find or access mount point of ESP.\n\n");
499 return -ENOENT;
500 }
501
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));
505 printf("\n");
506
507 r = enumerate_binaries(esp_path, "EFI/systemd", NULL);
508 if (r < 0)
509 goto finish;
510 if (r == 0 && !arg_quiet)
511 log_info("systemd-boot not installed in ESP.");
512
513 r = enumerate_binaries(esp_path, "EFI/BOOT", "boot");
514 if (r < 0)
515 goto finish;
516 if (r == 0 && !arg_quiet)
517 log_info("No default/fallback boot loader installed in ESP.");
518
519 r = 0;
520
521 finish:
522 printf("\n");
523 return r;
524 }
525
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;
530 bool active;
531 int r;
532
533 r = efi_get_boot_option(id, &title, &partition, &path, &active);
534 if (r < 0)
535 return r;
536
537 /* print only configured entries with partition information */
538 if (!path || sd_id128_is_null(partition))
539 return 0;
540
541 efi_tilt_backslashes(path);
542
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);
549 printf("\n");
550
551 return 0;
552 }
553
554 static int status_variables(void) {
555 _cleanup_free_ uint16_t *options = NULL, *order = NULL;
556 int n_options, n_order;
557
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/.");
563 if (n_options < 0)
564 return log_error_errno(n_options, "Failed to read EFI boot entries: %m");
565
566 n_order = efi_get_boot_order(&order);
567 if (n_order == -ENOENT)
568 n_order = 0;
569 else if (n_order < 0)
570 return log_error_errno(n_order, "Failed to read EFI boot order: %m");
571
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);
576
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])
581 goto next_option;
582
583 print_efi_option(options[i], false);
584
585 next_option:
586 continue;
587 }
588
589 return 0;
590 }
591
592 static int boot_config_load_and_select(
593 BootConfig *config,
594 const char *esp_path,
595 dev_t esp_devid,
596 const char *xbootldr_path,
597 dev_t xbootldr_devid) {
598
599 _cleanup_strv_free_ char **efi_entries = NULL;
600 int r;
601
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);
605
606 r = boot_config_load(config, esp_path, same ? NULL : xbootldr_path);
607 if (r < 0)
608 return r;
609
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.");
613 else if (r < 0)
614 log_warning_errno(r, "Failed to determine entries reported by boot loader, ignoring: %m");
615 else
616 (void) boot_config_augment_from_loader(config, efi_entries, /* only_auto= */ false);
617
618 return boot_config_select_special_entries(config);
619 }
620
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) {
627
628 sd_id128_t dollar_boot_partition_uuid;
629 const char *dollar_boot_path;
630 int r;
631
632 assert(config);
633 assert(esp_path || xbootldr_path);
634
635 if (xbootldr_path) {
636 dollar_boot_path = xbootldr_path;
637 dollar_boot_partition_uuid = xbootldr_partition_uuid;
638 } else {
639 dollar_boot_path = esp_path;
640 dollar_boot_partition_uuid = esp_partition_uuid;
641 }
642
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));
648 printf("\n\n");
649
650 if (config->default_entry < 0)
651 printf("%zu entries, no entry could be determined as default.\n", config->n_entries);
652 else {
653 printf("Default Boot Loader Entry:\n");
654
655 r = show_boot_entry(
656 boot_config_default_entry(config),
657 /* show_as_default= */ false,
658 /* show_as_selected= */ false,
659 /* show_discovered= */ false);
660 if (r > 0)
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");
664 }
665
666 return 0;
667 }
668
669 static int compare_product(const char *a, const char *b) {
670 size_t x, y;
671
672 assert(a);
673 assert(b);
674
675 x = strcspn(a, " ");
676 y = strcspn(b, " ");
677 if (x != y)
678 return x < y ? -1 : x > y ? 1 : 0;
679
680 return strncmp(a, b, x);
681 }
682
683 static int compare_version(const char *a, const char *b) {
684 assert(a);
685 assert(b);
686
687 a += strcspn(a, " ");
688 a += strspn(a, " ");
689 b += strcspn(b, " ");
690 b += strspn(b, " ");
691
692 return strverscmp_improved(a, b);
693 }
694
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;
697 int r;
698
699 assert(fd_from >= 0);
700 assert(from);
701 assert(fd_to >= 0);
702 assert(to);
703
704 r = get_file_version(fd_from, &a);
705 if (r < 0)
706 return r;
707 if (r == 0)
708 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE),
709 "Source file \"%s\" does not carry version information!",
710 from);
711
712 r = get_file_version(fd_to, &b);
713 if (r < 0)
714 return r;
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.",
718 to);
719
720 r = compare_version(a, b);
721 log_debug("Comparing versions: \"%s\" %s \"%s", a, comparison_operator(r), b);
722 if (r < 0)
723 return log_warning_errno(SYNTHETIC_ERRNO(ESTALE),
724 "Skipping \"%s\", since newer boot loader version in place already.", to);
725 if (r == 0)
726 return log_info_errno(SYNTHETIC_ERRNO(ESTALE),
727 "Skipping \"%s\", since same boot loader version in place already.", to);
728
729 return 0;
730 }
731
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;
735 int r;
736
737 fd_from = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
738 if (fd_from < 0)
739 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", from);
740
741 if (!force) {
742 fd_to = open(to, O_RDONLY|O_CLOEXEC|O_NOCTTY);
743 if (fd_to < 0) {
744 if (errno != ENOENT)
745 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", to);
746 } else {
747 r = version_check(fd_from, from, fd_to, to);
748 if (r < 0)
749 return r;
750
751 if (lseek(fd_from, 0, SEEK_SET) == (off_t) -1)
752 return log_error_errno(errno, "Failed to seek in \"%s\": %m", from);
753
754 fd_to = safe_close(fd_to);
755 }
756 }
757
758 r = tempfn_random(to, NULL, &t);
759 if (r < 0)
760 return log_oom();
761
762 RUN_WITH_UMASK(0000) {
763 fd_to = open(t, O_WRONLY|O_CREAT|O_CLOEXEC|O_EXCL|O_NOFOLLOW, 0644);
764 if (fd_to < 0)
765 return log_error_errno(errno, "Failed to open \"%s\" for writing: %m", t);
766 }
767
768 r = copy_bytes(fd_from, fd_to, UINT64_MAX, COPY_REFLINK);
769 if (r < 0) {
770 (void) unlink(t);
771 return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
772 }
773
774 (void) copy_times(fd_from, fd_to, 0);
775
776 r = fsync_full(fd_to);
777 if (r < 0) {
778 (void) unlink_noerrno(t);
779 return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
780 }
781
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);
785 }
786
787 log_info("Copied \"%s\" to \"%s\".", from, to);
788
789 return 0;
790 }
791
792 static int mkdir_one(const char *prefix, const char *suffix) {
793 _cleanup_free_ char *p = NULL;
794
795 p = path_join(prefix, suffix);
796 if (mkdir(p, 0700) < 0) {
797 if (errno != EEXIST)
798 return log_error_errno(errno, "Failed to create \"%s\": %m", p);
799 } else
800 log_info("Created \"%s\".", p);
801
802 return 0;
803 }
804
805 static const char *const esp_subdirs[] = {
806 /* The directories to place in the ESP */
807 "EFI",
808 "EFI/systemd",
809 "EFI/BOOT",
810 "loader",
811 NULL
812 };
813
814 static const char *const dollar_boot_subdirs[] = {
815 /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
816 "loader",
817 "loader/entries", /* Type #1 entries */
818 "EFI",
819 "EFI/Linux", /* Type #2 entries */
820 NULL
821 };
822
823 static int create_subdirs(const char *root, const char * const *subdirs) {
824 int r;
825
826 STRV_FOREACH(i, subdirs) {
827 r = mkdir_one(root, *i);
828 if (r < 0)
829 return r;
830 }
831
832 return 0;
833 }
834
835 static int copy_one_file(const char *esp_path, const char *name, bool force) {
836 const char *e;
837 char *p, *q, *dest_name, *s;
838 int r;
839
840 dest_name = strdupa_safe(name);
841 s = endswith_no_case(dest_name, ".signed");
842 if (s)
843 *s = 0;
844
845 p = strjoina(BOOTLIBDIR "/", name);
846 q = strjoina(esp_path, "/EFI/systemd/", dest_name);
847 r = copy_file_with_version_check(p, q, force);
848
849 e = startswith(dest_name, "systemd-boot");
850 if (e) {
851 int k;
852 char *v;
853
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);
857
858 k = copy_file_with_version_check(p, v, force);
859 if (k < 0 && r == 0)
860 r = k;
861 }
862
863 return r;
864 }
865
866 static int install_binaries(const char *esp_path, const char *arch, bool force) {
867 _cleanup_closedir_ DIR *d = NULL;
868 int r = 0;
869
870 d = opendir(BOOTLIBDIR);
871 if (!d)
872 return log_error_errno(errno, "Failed to open \""BOOTLIBDIR"\": %m");
873
874 const char *suffix = strjoina(arch, ".efi");
875 const char *suffix_signed = strjoina(arch, ".efi.signed");
876
877 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read \""BOOTLIBDIR"\": %m")) {
878 int k;
879
880 if (!endswith_no_case(de->d_name, suffix) && !endswith_no_case(de->d_name, suffix_signed))
881 continue;
882
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");
886 if (!s)
887 return log_oom();
888 if (faccessat(dirfd(d), s, F_OK, 0) >= 0)
889 continue;
890 }
891
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))
896 continue;
897 if (k < 0 && r == 0)
898 r = k;
899 }
900
901 return r;
902 }
903
904 static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
905 _cleanup_free_ char *opath = NULL;
906 sd_id128_t ouuid;
907 int r;
908
909 r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
910 if (r < 0)
911 return false;
912 if (!sd_id128_equal(uuid, ouuid))
913 return false;
914
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))
919 return false;
920
921 return true;
922 }
923
924 static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
925 _cleanup_free_ uint16_t *options = NULL;
926 int n, i;
927
928 n = efi_get_boot_options(&options);
929 if (n < 0)
930 return n;
931
932 /* find already existing systemd-boot entry */
933 for (i = 0; i < n; i++)
934 if (same_entry(options[i], uuid, path)) {
935 *id = options[i];
936 return 1;
937 }
938
939 /* find free slot in the sorted BootXXXX variable list */
940 for (i = 0; i < n; i++)
941 if (i != options[i]) {
942 *id = i;
943 return 0;
944 }
945
946 /* use the next one */
947 if (i == 0xffff)
948 return -ENOSPC;
949 *id = i;
950 return 0;
951 }
952
953 static int insert_into_order(uint16_t slot, bool first) {
954 _cleanup_free_ uint16_t *order = NULL;
955 uint16_t *t;
956 int n;
957
958 n = efi_get_boot_order(&order);
959 if (n <= 0)
960 /* no entry, add us */
961 return efi_set_boot_order(&slot, 1);
962
963 /* are we the first and only one? */
964 if (n == 1 && order[0] == slot)
965 return 0;
966
967 /* are we already in the boot order? */
968 for (int i = 0; i < n; i++) {
969 if (order[i] != slot)
970 continue;
971
972 /* we do not require to be the first one, all is fine */
973 if (!first)
974 return 0;
975
976 /* move us to the first slot */
977 memmove(order + 1, order, i * sizeof(uint16_t));
978 order[0] = slot;
979 return efi_set_boot_order(order, n);
980 }
981
982 /* extend array */
983 t = reallocarray(order, n + 1, sizeof(uint16_t));
984 if (!t)
985 return -ENOMEM;
986 order = t;
987
988 /* add us to the top or end of the list */
989 if (first) {
990 memmove(order + 1, order, n * sizeof(uint16_t));
991 order[0] = slot;
992 } else
993 order[n] = slot;
994
995 return efi_set_boot_order(order, n + 1);
996 }
997
998 static int remove_from_order(uint16_t slot) {
999 _cleanup_free_ uint16_t *order = NULL;
1000 int n;
1001
1002 n = efi_get_boot_order(&order);
1003 if (n <= 0)
1004 return n;
1005
1006 for (int i = 0; i < n; i++) {
1007 if (order[i] != slot)
1008 continue;
1009
1010 if (i + 1 < n)
1011 memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
1012 return efi_set_boot_order(order, n - 1);
1013 }
1014
1015 return 0;
1016 }
1017
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,
1021 bool first) {
1022 const char *p;
1023 uint16_t slot;
1024 int r;
1025
1026 if (!is_efi_boot()) {
1027 log_warning("Not booted with EFI, skipping EFI variable setup.");
1028 return 0;
1029 }
1030
1031 p = prefix_roota(esp_path, path);
1032 if (access(p, F_OK) < 0) {
1033 if (errno == ENOENT)
1034 return 0;
1035
1036 return log_error_errno(errno, "Cannot access \"%s\": %m", p);
1037 }
1038
1039 r = find_slot(uuid, path, &slot);
1040 if (r < 0)
1041 return log_error_errno(r,
1042 r == -ENOENT ?
1043 "Failed to access EFI variables. Is the \"efivarfs\" filesystem mounted?" :
1044 "Failed to determine current boot order: %m");
1045
1046 if (first || r == 0) {
1047 r = efi_add_boot_option(slot, "Linux Boot Manager",
1048 part, pstart, psize,
1049 uuid, path);
1050 if (r < 0)
1051 return log_error_errno(r, "Failed to create EFI Boot variable entry: %m");
1052
1053 log_info("Created EFI boot entry \"Linux Boot Manager\".");
1054 }
1055
1056 return insert_into_order(slot, first);
1057 }
1058
1059 static int remove_boot_efi(const char *esp_path) {
1060 _cleanup_closedir_ DIR *d = NULL;
1061 const char *p;
1062 int r, c = 0;
1063
1064 p = prefix_roota(esp_path, "/EFI/BOOT");
1065 d = opendir(p);
1066 if (!d) {
1067 if (errno == ENOENT)
1068 return 0;
1069
1070 return log_error_errno(errno, "Failed to open directory \"%s\": %m", p);
1071 }
1072
1073 FOREACH_DIRENT(de, d, break) {
1074 _cleanup_close_ int fd = -1;
1075 _cleanup_free_ char *v = NULL;
1076
1077 if (!endswith_no_case(de->d_name, ".efi"))
1078 continue;
1079
1080 if (!startswith_no_case(de->d_name, "boot"))
1081 continue;
1082
1083 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
1084 if (fd < 0)
1085 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
1086
1087 r = get_file_version(fd, &v);
1088 if (r < 0)
1089 return r;
1090 if (r > 0 && startswith(v, "systemd-boot ")) {
1091 r = unlinkat(dirfd(d), de->d_name, 0);
1092 if (r < 0)
1093 return log_error_errno(errno, "Failed to remove \"%s/%s\": %m", p, de->d_name);
1094
1095 log_info("Removed \"%s/%s\".", p, de->d_name);
1096 }
1097
1098 c++;
1099 }
1100
1101 return c;
1102 }
1103
1104 static int rmdir_one(const char *prefix, const char *suffix) {
1105 const char *p;
1106
1107 p = prefix_roota(prefix, suffix);
1108 if (rmdir(p) < 0) {
1109 bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
1110
1111 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
1112 "Failed to remove directory \"%s\": %m", p);
1113 if (!ignore)
1114 return -errno;
1115 } else
1116 log_info("Removed \"%s\".", p);
1117
1118 return 0;
1119 }
1120
1121 static int remove_subdirs(const char *root, const char *const *subdirs) {
1122 int r, q;
1123
1124 /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
1125 * short the array is. */
1126
1127 if (!subdirs[0]) /* A the end of the list */
1128 return 0;
1129
1130 r = remove_subdirs(root, subdirs + 1);
1131 q = rmdir_one(root, subdirs[0]);
1132
1133 return r < 0 ? r : q;
1134 }
1135
1136 static int remove_entry_directory(const char *root) {
1137 assert(root);
1138 assert(arg_make_entry_directory >= 0);
1139
1140 if (!arg_make_entry_directory || !arg_entry_token)
1141 return 0;
1142
1143 return rmdir_one(root, arg_entry_token);
1144 }
1145
1146 static int remove_binaries(const char *esp_path) {
1147 const char *p;
1148 int r, q;
1149
1150 p = prefix_roota(esp_path, "/EFI/systemd");
1151 r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
1152
1153 q = remove_boot_efi(esp_path);
1154 if (q < 0 && r == 0)
1155 r = q;
1156
1157 return r;
1158 }
1159
1160 static int remove_file(const char *root, const char *file) {
1161 const char *p;
1162
1163 assert(root);
1164 assert(file);
1165
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);
1170
1171 return errno == ENOENT ? 0 : -errno;
1172 }
1173
1174 log_info("Removed \"%s\".", p);
1175 return 1;
1176 }
1177
1178 static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
1179 uint16_t slot;
1180 int r;
1181
1182 if (!is_efi_boot())
1183 return 0;
1184
1185 r = find_slot(uuid, path, &slot);
1186 if (r != 1)
1187 return 0;
1188
1189 r = efi_remove_boot_option(slot);
1190 if (r < 0)
1191 return r;
1192
1193 if (in_order)
1194 return remove_from_order(slot);
1195
1196 return 0;
1197 }
1198
1199 static int remove_loader_variables(void) {
1200 int r = 0;
1201
1202 /* Remove all persistent loader variables we define */
1203
1204 FOREACH_STRING(var,
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)){
1210
1211 int q;
1212
1213 q = efi_set_variable(var, NULL, 0);
1214 if (q == -ENOENT)
1215 continue;
1216 if (q < 0) {
1217 log_warning_errno(q, "Failed to remove EFI variable %s: %m", var);
1218 if (r >= 0)
1219 r = q;
1220 } else
1221 log_info("Removed EFI variable %s.", var);
1222 }
1223
1224 return r;
1225 }
1226
1227 static int install_loader_config(const char *esp_path) {
1228 _cleanup_(unlink_and_freep) char *t = NULL;
1229 _cleanup_fclose_ FILE *f = NULL;
1230 const char *p;
1231 int r;
1232
1233 assert(arg_make_entry_directory >= 0);
1234
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) */
1237 return 0;
1238
1239 r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
1240 if (r < 0)
1241 return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
1242
1243 fprintf(f, "#timeout 3\n"
1244 "#console-mode keep\n");
1245
1246 if (arg_make_entry_directory) {
1247 assert(arg_entry_token);
1248 fprintf(f, "default %s-*\n", arg_entry_token);
1249 }
1250
1251 r = flink_tmpfile(f, t, p);
1252 if (r == -EEXIST)
1253 return 0; /* Silently skip creation if the file exists now (recheck) */
1254 if (r < 0)
1255 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1256
1257 t = mfree(t);
1258 return 1;
1259 }
1260
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;
1265 int r;
1266
1267 p = path_join(root, "/loader/entries.srel");
1268 if (!p)
1269 return log_oom();
1270
1271 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
1272 return 0;
1273
1274 r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
1275 if (r < 0)
1276 return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
1277
1278 fprintf(f, "type1\n");
1279
1280 r = flink_tmpfile(f, t, p);
1281 if (r == -EEXIST)
1282 return 0; /* Silently skip creation if the file exists now (recheck) */
1283 if (r < 0)
1284 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1285
1286 t = mfree(t);
1287 return 1;
1288 }
1289
1290 static int install_entry_directory(const char *root) {
1291 assert(root);
1292 assert(arg_make_entry_directory >= 0);
1293
1294 if (!arg_make_entry_directory)
1295 return 0;
1296
1297 assert(arg_entry_token);
1298 return mkdir_one(root, arg_entry_token);
1299 }
1300
1301 static int install_entry_token(void) {
1302 int r;
1303
1304 assert(arg_make_entry_directory >= 0);
1305 assert(arg_entry_token);
1306
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 */
1309
1310 if (!arg_make_entry_directory && arg_entry_token_type == ARG_ENTRY_TOKEN_MACHINE_ID)
1311 return 0;
1312
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);
1314 if (r < 0)
1315 return log_error_errno(r, "Failed to write entry token '%s' to /etc/kernel/entry-token", arg_entry_token);
1316
1317 return 0;
1318 }
1319
1320 static int help(int argc, char *argv[], void *userdata) {
1321 _cleanup_free_ char *link = NULL;
1322 int r;
1323
1324 r = terminal_urlify_man("bootctl", "1", &link);
1325 if (r < 0)
1326 return log_oom();
1327
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,
1371 link,
1372 ansi_underline(),
1373 ansi_normal(),
1374 ansi_highlight(),
1375 ansi_normal());
1376
1377 return 0;
1378 }
1379
1380 static int parse_argv(int argc, char *argv[]) {
1381 enum {
1382 ARG_ESP_PATH = 0x100,
1383 ARG_BOOT_PATH,
1384 ARG_VERSION,
1385 ARG_NO_VARIABLES,
1386 ARG_NO_PAGER,
1387 ARG_GRACEFUL,
1388 ARG_MAKE_ENTRY_DIRECTORY,
1389 ARG_ENTRY_TOKEN,
1390 ARG_JSON,
1391 ARG_ARCH_ALL,
1392 };
1393
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 },
1412 {}
1413 };
1414
1415 int c, r;
1416 bool b;
1417
1418 assert(argc >= 0);
1419 assert(argv);
1420
1421 while ((c = getopt_long(argc, argv, "hpx", options, NULL)) >= 0)
1422 switch (c) {
1423
1424 case 'h':
1425 help(0, NULL, NULL);
1426 return 0;
1427
1428 case ARG_VERSION:
1429 return version();
1430
1431 case ARG_ESP_PATH:
1432 r = free_and_strdup(&arg_esp_path, optarg);
1433 if (r < 0)
1434 return log_oom();
1435 break;
1436
1437 case ARG_BOOT_PATH:
1438 r = free_and_strdup(&arg_xbootldr_path, optarg);
1439 if (r < 0)
1440 return log_oom();
1441 break;
1442
1443 case 'p':
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;
1448 break;
1449
1450 case 'x':
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;
1455 break;
1456
1457 case ARG_NO_VARIABLES:
1458 arg_touch_variables = false;
1459 break;
1460
1461 case ARG_NO_PAGER:
1462 arg_pager_flags |= PAGER_DISABLE;
1463 break;
1464
1465 case ARG_GRACEFUL:
1466 arg_graceful = true;
1467 break;
1468
1469 case 'q':
1470 arg_quiet = true;
1471 break;
1472
1473 case ARG_ENTRY_TOKEN: {
1474 const char *e;
1475
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;
1487
1488 r = free_and_strdup_warn(&arg_entry_token, e);
1489 if (r < 0)
1490 return r;
1491 } else
1492 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1493 "Unexpected parameter for --entry-token=: %s", optarg);
1494
1495 break;
1496 }
1497
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 */
1501 else {
1502 r = parse_boolean_argument("--make-entry-directory=", optarg, &b);
1503 if (r < 0)
1504 return r;
1505
1506 arg_make_entry_directory = b;
1507 }
1508 break;
1509
1510 case ARG_JSON:
1511 r = parse_json_argument(optarg, &arg_json_format_flags);
1512 if (r <= 0)
1513 return r;
1514 break;
1515
1516 case ARG_ARCH_ALL:
1517 arg_arch_all = true;
1518 break;
1519
1520 case '?':
1521 return -EINVAL;
1522
1523 default:
1524 assert_not_reached();
1525 }
1526
1527 return 1;
1528 }
1529
1530 static void read_efi_var(const char *variable, char **ret) {
1531 int r;
1532
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);
1536 }
1537
1538 static void print_yes_no_line(bool first, bool good, const char *name) {
1539 printf("%s%s %s\n",
1540 first ? " Features: " : " ",
1541 COLOR_MARK_BOOL(good),
1542 name);
1543 }
1544
1545 static int are_we_installed(const char *esp_path) {
1546 int r;
1547
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:
1552 *
1553 * → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
1554 * not a specific one.)
1555 *
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.
1558 *
1559 * → It specifically checks for systemd-boot, not for other boot loaders (which a check for
1560 * /boot/loader/entries would do). */
1561
1562 _cleanup_free_ char *p = path_join(esp_path, "/EFI/systemd/");
1563 if (!p)
1564 return log_oom();
1565
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);
1570
1571 return r == 0;
1572 }
1573
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;
1577 int r, k;
1578
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");
1584 if (r < 0)
1585 return r;
1586
1587 puts(arg_esp_path);
1588 }
1589
1590 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, &xbootldr_uuid, &xbootldr_devid);
1591 if (arg_print_dollar_boot_path) {
1592 if (r == -EACCES)
1593 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1594 if (r < 0)
1595 return r;
1596
1597 const char *path = arg_dollar_boot_path();
1598 if (!path)
1599 return log_error_errno(SYNTHETIC_ERRNO(EACCES), "Failed to determine XBOOTLDR location: %m");
1600
1601 puts(path);
1602 }
1603
1604 if (arg_print_esp_path || arg_print_dollar_boot_path)
1605 return 0;
1606
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 */
1609
1610 pager_open(arg_pager_flags);
1611
1612 if (is_efi_boot()) {
1613 static const struct {
1614 uint64_t flag;
1615 const char *name;
1616 } flags[] = {
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" },
1625 };
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;
1629 Tpm2Support s;
1630 int have;
1631
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);
1638
1639 if (loader_path)
1640 efi_tilt_backslashes(loader_path);
1641
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");
1645
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));
1653
1654 s = tpm2_support();
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",
1661 ansi_normal());
1662
1663 k = efi_get_reboot_to_firmware();
1664 if (k > 0)
1665 printf(" Boot into FW: %sactive%s\n", ansi_highlight_yellow(), ansi_normal());
1666 else if (k == 0)
1667 printf(" Boot into FW: supported\n");
1668 else if (k == -EOPNOTSUPP)
1669 printf(" Boot into FW: not supported\n");
1670 else {
1671 errno = -k;
1672 printf(" Boot into FW: %sfailed%s (%m)\n", ansi_highlight_red(), ansi_normal());
1673 }
1674 printf("\n");
1675
1676 printf("Current Boot Loader:\n");
1677 printf(" Product: %s%s%s\n", ansi_highlight(), strna(loader), ansi_normal());
1678
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);
1681
1682 sd_id128_t bootloader_esp_uuid;
1683 bool have_bootloader_esp_uuid = efi_loader_get_device_part_uuid(&bootloader_esp_uuid) >= 0;
1684
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");
1688
1689 if (stub)
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));
1694 else
1695 printf(" ESP: n/a\n");
1696 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), strna(loader_path));
1697 printf("\n");
1698
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");
1704
1705 if (arg_esp_path) {
1706 _cleanup_free_ char *p = NULL;
1707
1708 p = path_join(arg_esp_path, "/loader/random-seed");
1709 if (!p)
1710 return log_oom();
1711
1712 have = access(p, F_OK) >= 0;
1713 printf(" Exists: %s\n", yes_no(have));
1714 }
1715
1716 printf("\n");
1717 } else
1718 printf("System:\n Not booted with EFI\n\n");
1719
1720 if (arg_esp_path) {
1721 k = status_binaries(arg_esp_path, esp_uuid);
1722 if (k < 0)
1723 r = k;
1724 }
1725
1726 if (is_efi_boot()) {
1727 k = status_variables();
1728 if (k < 0)
1729 r = k;
1730 }
1731
1732 if (arg_esp_path || arg_xbootldr_path) {
1733 _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL;
1734
1735 k = boot_config_load_and_select(&config,
1736 arg_esp_path, esp_devid,
1737 arg_xbootldr_path, xbootldr_devid);
1738 if (k < 0)
1739 r = k;
1740 else {
1741 k = status_entries(&config,
1742 arg_esp_path, esp_uuid,
1743 arg_xbootldr_path, xbootldr_uuid);
1744 if (k < 0)
1745 r = k;
1746 }
1747 }
1748
1749 return r;
1750 }
1751
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;
1755 int r;
1756
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
1760 * EACCES. */
1761
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");
1765 if (r < 0)
1766 return r;
1767
1768 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, NULL, &xbootldr_devid);
1769 if (r == -EACCES)
1770 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1771 if (r < 0)
1772 return r;
1773
1774 r = boot_config_load_and_select(&config, arg_esp_path, esp_devid, arg_xbootldr_path, xbootldr_devid);
1775 if (r < 0)
1776 return r;
1777
1778 if (config.n_entries == 0 && FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
1779 log_info("No boot loader entries found.");
1780 return 0;
1781 }
1782
1783 pager_open(arg_pager_flags);
1784 return show_boot_entries(&config, arg_json_format_flags);
1785 }
1786
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;
1793 ssize_t n;
1794 int r;
1795
1796 assert(esp);
1797
1798 path = path_join(esp, "/loader/random-seed");
1799 if (!path)
1800 return log_oom();
1801
1802 sz = random_pool_size();
1803
1804 buffer = malloc(sz);
1805 if (!buffer)
1806 return log_oom();
1807
1808 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1809 if (r < 0)
1810 return log_error_errno(r, "Failed to acquire random seed: %m");
1811
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
1814 * list. */
1815 r = mkdir_parents(path, 0755);
1816 if (r < 0)
1817 return log_error_errno(r, "Failed to create parent directory for %s: %m", path);
1818
1819 r = tempfn_random(path, "bootctl", &tmp);
1820 if (r < 0)
1821 return log_oom();
1822
1823 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|O_WRONLY|O_CLOEXEC, 0600);
1824 if (fd < 0) {
1825 tmp = mfree(tmp);
1826 return log_error_errno(fd, "Failed to open random seed file for writing: %m");
1827 }
1828
1829 n = write(fd, buffer, sz);
1830 if (n < 0)
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.");
1834
1835 if (rename(tmp, path) < 0)
1836 return log_error_errno(r, "Failed to move random seed file into place: %m");
1837
1838 tmp = mfree(tmp);
1839
1840 log_info("Random seed file %s successfully written (%zu bytes).", path, sz);
1841
1842 if (!arg_touch_variables)
1843 return 0;
1844
1845 if (!is_efi_boot()) {
1846 log_notice("Not booted with EFI, skipping EFI variable setup.");
1847 return 0;
1848 }
1849
1850 r = getenv_bool("SYSTEMD_WRITE_SYSTEM_TOKEN");
1851 if (r < 0) {
1852 if (r != -ENXIO)
1853 log_warning_errno(r, "Failed to parse $SYSTEMD_WRITE_SYSTEM_TOKEN, ignoring.");
1854
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. */
1870
1871 log_notice("Not installing system token, since we are running in a virtualized environment.");
1872 return 0;
1873 }
1874 } else if (r == 0) {
1875 log_notice("Not writing system token, because $SYSTEMD_WRITE_SYSTEM_TOKEN is set to false.");
1876 return 0;
1877 }
1878
1879 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), NULL, NULL, &token_size);
1880 if (r == -ENODATA)
1881 log_debug_errno(r, "LoaderSystemToken EFI variable is invalid (too short?), replacing.");
1882 else if (r < 0) {
1883 if (r != -ENOENT)
1884 return log_error_errno(r, "Failed to test system token validity: %m");
1885 } else {
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.");
1889 return 0;
1890 }
1891
1892 log_debug("Existing system token size (%zu) does not match our expectations (%zu), replacing.", token_size, sz);
1893 }
1894
1895 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1896 if (r < 0)
1897 return log_error_errno(r, "Failed to acquire random seed: %m");
1898
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
1901 * state. */
1902 RUN_WITH_UMASK(0077) {
1903 r = efi_set_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), buffer, sz);
1904 if (r < 0) {
1905 if (!arg_graceful)
1906 return log_error_errno(r, "Failed to write 'LoaderSystemToken' EFI variable: %m");
1907
1908 if (r == -EINVAL)
1909 log_warning_errno(r, "Unable to write 'LoaderSystemToken' EFI variable (firmware problem?), ignoring: %m");
1910 else
1911 log_warning_errno(r, "Unable to write 'LoaderSystemToken' EFI variable, ignoring: %m");
1912 } else
1913 log_info("Successfully initialized system token in EFI variable with %zu bytes.", sz);
1914 }
1915
1916 return 0;
1917 }
1918
1919 static int sync_everything(void) {
1920 int ret = 0, k;
1921
1922 if (arg_esp_path) {
1923 k = syncfs_path(AT_FDCWD, arg_esp_path);
1924 if (k < 0)
1925 ret = log_error_errno(k, "Failed to synchronize the ESP '%s': %m", arg_esp_path);
1926 }
1927
1928 if (arg_xbootldr_path) {
1929 k = syncfs_path(AT_FDCWD, arg_xbootldr_path);
1930 if (k < 0)
1931 ret = log_error_errno(k, "Failed to synchronize $BOOT '%s': %m", arg_xbootldr_path);
1932 }
1933
1934 return ret;
1935 }
1936
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;
1940 uint32_t part = 0;
1941 bool install, graceful;
1942 int r;
1943
1944 /* Invoked for both "update" and "install" */
1945
1946 install = streq(argv[0], "install");
1947 graceful = !install && arg_graceful; /* support graceful mode for updates */
1948
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 */
1952 if (r < 0)
1953 return r;
1954
1955 if (!install) {
1956 /* If we are updating, don't do anything if sd-boot wasn't actually installed. */
1957 r = are_we_installed(arg_esp_path);
1958 if (r < 0)
1959 return r;
1960 if (r == 0) {
1961 log_debug("Skipping update because sd-boot is not installed in the ESP.");
1962 return 0;
1963 }
1964 }
1965
1966 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
1967 if (r < 0)
1968 return r;
1969
1970 r = settle_make_entry_directory();
1971 if (r < 0)
1972 return r;
1973
1974 const char *arch = arg_arch_all ? "" : get_efi_arch();
1975
1976 RUN_WITH_UMASK(0002) {
1977 if (install) {
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);
1982 if (r < 0)
1983 return r;
1984
1985 r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
1986 if (r < 0)
1987 return r;
1988 }
1989
1990 r = install_binaries(arg_esp_path, arch, install);
1991 if (r < 0)
1992 return r;
1993
1994 if (install) {
1995 r = install_loader_config(arg_esp_path);
1996 if (r < 0)
1997 return r;
1998
1999 r = install_entry_directory(arg_dollar_boot_path());
2000 if (r < 0)
2001 return r;
2002
2003 r = install_entry_token();
2004 if (r < 0)
2005 return r;
2006
2007 r = install_random_seed(arg_esp_path);
2008 if (r < 0)
2009 return r;
2010 }
2011
2012 r = install_loader_specification(arg_dollar_boot_path());
2013 if (r < 0)
2014 return r;
2015 }
2016
2017 (void) sync_everything();
2018
2019 if (!arg_touch_variables)
2020 return 0;
2021
2022 if (arg_arch_all) {
2023 log_info("Not changing EFI variables with --all-architectures.");
2024 return 0;
2025 }
2026
2027 char *path = strjoina("/EFI/systemd/systemd-boot", arch, ".efi");
2028 return install_variables(arg_esp_path, part, pstart, psize, uuid, path, install);
2029 }
2030
2031 static int verb_remove(int argc, char *argv[], void *userdata) {
2032 sd_id128_t uuid = SD_ID128_NULL;
2033 int r, q;
2034
2035 r = acquire_esp(/* unprivileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, &uuid, NULL);
2036 if (r < 0)
2037 return r;
2038
2039 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
2040 if (r < 0)
2041 return r;
2042
2043 r = settle_make_entry_directory();
2044 if (r < 0)
2045 return r;
2046
2047 r = remove_binaries(arg_esp_path);
2048
2049 q = remove_file(arg_esp_path, "/loader/loader.conf");
2050 if (q < 0 && r >= 0)
2051 r = q;
2052
2053 q = remove_file(arg_esp_path, "/loader/random-seed");
2054 if (q < 0 && r >= 0)
2055 r = q;
2056
2057 q = remove_file(arg_esp_path, "/loader/entries.srel");
2058 if (q < 0 && r >= 0)
2059 r = q;
2060
2061 q = remove_subdirs(arg_esp_path, esp_subdirs);
2062 if (q < 0 && r >= 0)
2063 r = q;
2064
2065 q = remove_subdirs(arg_esp_path, dollar_boot_subdirs);
2066 if (q < 0 && r >= 0)
2067 r = q;
2068
2069 q = remove_entry_directory(arg_esp_path);
2070 if (q < 0 && r >= 0)
2071 r = q;
2072
2073 if (arg_xbootldr_path) {
2074 /* Remove a subset of these also from the XBOOTLDR partition if it exists */
2075
2076 q = remove_file(arg_xbootldr_path, "/loader/entries.srel");
2077 if (q < 0 && r >= 0)
2078 r = q;
2079
2080 q = remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs);
2081 if (q < 0 && r >= 0)
2082 r = q;
2083
2084 q = remove_entry_directory(arg_xbootldr_path);
2085 if (q < 0 && r >= 0)
2086 r = q;
2087 }
2088
2089 (void) sync_everything();
2090
2091 if (!arg_touch_variables)
2092 return r;
2093
2094 if (arg_arch_all) {
2095 log_info("Not changing EFI variables with --all-architectures.");
2096 return r;
2097 }
2098
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)
2102 r = q;
2103
2104 q = remove_loader_variables();
2105 if (q < 0 && r >= 0)
2106 r = q;
2107
2108 return r;
2109 }
2110
2111 static int verb_is_installed(int argc, char *argv[], void *userdata) {
2112 int r;
2113
2114 r = acquire_esp(/* privileged_mode= */ false,
2115 /* graceful= */ arg_graceful,
2116 NULL, NULL, NULL, NULL, NULL);
2117 if (r < 0)
2118 return r;
2119
2120 r = are_we_installed(arg_esp_path);
2121 if (r < 0)
2122 return r;
2123
2124 if (r > 0) {
2125 if (!arg_quiet)
2126 puts("yes");
2127 return EXIT_SUCCESS;
2128 } else {
2129 if (!arg_quiet)
2130 puts("no");
2131 return EXIT_FAILURE;
2132 }
2133 }
2134
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)];
2137 char16_t *encoded;
2138 usec_t timeout;
2139 int r;
2140
2141 assert(arg1);
2142 assert(ret_timeout);
2143 assert(ret_timeout_size);
2144
2145 if (streq(arg1, "menu-force"))
2146 timeout = USEC_INFINITY;
2147 else if (streq(arg1, "menu-hidden"))
2148 timeout = 0;
2149 else {
2150 r = parse_time(arg1, &timeout, USEC_PER_SEC);
2151 if (r < 0)
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.");
2155 }
2156
2157 xsprintf(utf8, USEC_FMT, MIN(timeout / USEC_PER_SEC, UINT32_MAX));
2158
2159 encoded = utf8_to_utf16(utf8, strlen(utf8));
2160 if (!encoded)
2161 return log_oom();
2162
2163 *ret_timeout = encoded;
2164 *ret_timeout_size = char16_strlen(encoded) * 2 + 2;
2165 return 0;
2166 }
2167
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;
2170 int r;
2171
2172 assert(arg1);
2173 assert(ret_target);
2174 assert(ret_target_size);
2175
2176 if (streq(arg1, "@current")) {
2177 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntrySelected), NULL, (void *) ret_target, ret_target_size);
2178 if (r < 0)
2179 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntrySelected': %m");
2180
2181 } else if (streq(arg1, "@oneshot")) {
2182 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryOneShot), NULL, (void *) ret_target, ret_target_size);
2183 if (r < 0)
2184 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryOneShot': %m");
2185
2186 } else if (streq(arg1, "@default")) {
2187 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryDefault), NULL, (void *) ret_target, ret_target_size);
2188 if (r < 0)
2189 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryDefault': %m");
2190
2191 } else if (arg1[0] == '@' && !streq(arg1, "@saved"))
2192 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unsupported special entry identifier: %s", arg1);
2193 else {
2194 encoded = utf8_to_utf16(arg1, strlen(arg1));
2195 if (!encoded)
2196 return log_oom();
2197
2198 *ret_target = encoded;
2199 *ret_target_size = char16_strlen(encoded) * 2 + 2;
2200 }
2201
2202 return 0;
2203 }
2204
2205 static int verb_set_efivar(int argc, char *argv[], void *userdata) {
2206 int r;
2207
2208 if (!is_efi_boot())
2209 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2210 "Not booted with UEFI.");
2211
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.");
2215 return -EOPNOTSUPP;
2216 }
2217
2218 return log_error_errno(errno, "Failed to detect whether boot loader supports '%s' operation: %m", argv[0]);
2219 }
2220
2221 if (detect_container() > 0)
2222 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2223 "'%s' operation not supported in a container.",
2224 argv[0]);
2225
2226 if (!arg_touch_variables)
2227 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2228 "'%s' operation cannot be combined with --no-variables.",
2229 argv[0]);
2230
2231 const char *variable;
2232 int (* arg_parser)(const char *, char16_t **, size_t *);
2233
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;
2246 } else
2247 assert_not_reached();
2248
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);
2253 } else {
2254 _cleanup_free_ char16_t *value = NULL;
2255 size_t value_size = 0;
2256
2257 r = arg_parser(argv[1], &value, &value_size);
2258 if (r < 0)
2259 return r;
2260 r = efi_set_variable(variable, value, value_size);
2261 if (r < 0)
2262 return log_error_errno(r, "Failed to update EFI variable '%s': %m", variable);
2263 }
2264
2265 return 0;
2266 }
2267
2268 static int verb_random_seed(int argc, char *argv[], void *userdata) {
2269 int r;
2270
2271 r = find_esp_and_warn(arg_esp_path, false, &arg_esp_path, NULL, NULL, NULL, NULL, NULL);
2272 if (r == -ENOKEY) {
2273 /* find_esp_and_warn() doesn't warn about ENOKEY, so let's do that on our own */
2274 if (!arg_graceful)
2275 return log_error_errno(r, "Unable to find ESP.");
2276
2277 log_notice("No ESP found, not initializing random seed.");
2278 return 0;
2279 }
2280 if (r < 0)
2281 return r;
2282
2283 r = install_random_seed(arg_esp_path);
2284 if (r < 0)
2285 return r;
2286
2287 (void) sync_everything();
2288 return 0;
2289 }
2290
2291 static int verb_systemd_efi_options(int argc, char *argv[], void *userdata) {
2292 int r;
2293
2294 if (argc == 1) {
2295 _cleanup_free_ char *line = NULL, *new = NULL;
2296
2297 r = systemd_efi_options_variable(&line);
2298 if (r == -ENODATA)
2299 log_debug("No SystemdOptions EFI variable present in cache.");
2300 else if (r < 0)
2301 return log_error_errno(r, "Failed to read SystemdOptions EFI variable from cache: %m");
2302 else
2303 puts(line);
2304
2305 r = systemd_efi_options_efivarfs_if_newer(&new);
2306 if (r == -ENODATA) {
2307 if (line)
2308 log_notice("Note: SystemdOptions EFI variable has been removed since boot.");
2309 } else if (r < 0)
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",
2313 new);
2314 } else {
2315 r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE(SystemdOptions), argv[1]);
2316 if (r < 0)
2317 return log_error_errno(r, "Failed to set SystemdOptions EFI variable: %m");
2318 }
2319
2320 return 0;
2321 }
2322
2323 static int verb_reboot_to_firmware(int argc, char *argv[], void *userdata) {
2324 int r;
2325
2326 if (argc < 2) {
2327 r = efi_get_reboot_to_firmware();
2328 if (r > 0) {
2329 puts("active");
2330 return EXIT_SUCCESS; /* success */
2331 }
2332 if (r == 0) {
2333 puts("supported");
2334 return 1; /* recognizable error #1 */
2335 }
2336 if (r == -EOPNOTSUPP) {
2337 puts("not supported");
2338 return 2; /* recognizable error #2 */
2339 }
2340
2341 log_error_errno(r, "Failed to query reboot-to-firmware state: %m");
2342 return 3; /* other kind of error */
2343 } else {
2344 r = parse_boolean(argv[1]);
2345 if (r < 0)
2346 return log_error_errno(r, "Failed to parse argument: %s", argv[1]);
2347
2348 r = efi_set_reboot_to_firmware(r);
2349 if (r < 0)
2350 return log_error_errno(r, "Failed to set reboot-to-firmware option: %m");
2351
2352 return 0;
2353 }
2354 }
2355
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 },
2372 {}
2373 };
2374
2375 return dispatch_verb(argc, argv, verbs, NULL);
2376 }
2377
2378 static int run(int argc, char *argv[]) {
2379 int r;
2380
2381 log_parse_environment();
2382 log_open();
2383
2384 /* If we run in a container, automatically turn off EFI file system access */
2385 if (detect_container() > 0)
2386 arg_touch_variables = false;
2387
2388 r = parse_argv(argc, argv);
2389 if (r <= 0)
2390 return r;
2391
2392 return bootctl_main(argc, argv);
2393 }
2394
2395 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);