]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/boot/bootctl.c
Merge pull request #22519 from poettering/boot-order-title-revert
[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 "dirent-util.h"
20 #include "efi-loader.h"
21 #include "efivars.h"
22 #include "env-file.h"
23 #include "env-util.h"
24 #include "escape.h"
25 #include "fd-util.h"
26 #include "fileio.h"
27 #include "find-esp.h"
28 #include "fs-util.h"
29 #include "glyph-util.h"
30 #include "main-func.h"
31 #include "mkdir.h"
32 #include "os-util.h"
33 #include "pager.h"
34 #include "parse-argument.h"
35 #include "parse-util.h"
36 #include "pretty-print.h"
37 #include "random-util.h"
38 #include "rm-rf.h"
39 #include "stat-util.h"
40 #include "stdio-util.h"
41 #include "string-table.h"
42 #include "string-util.h"
43 #include "strv.h"
44 #include "sync-util.h"
45 #include "terminal-util.h"
46 #include "tmpfile-util.h"
47 #include "tmpfile-util-label.h"
48 #include "umask-util.h"
49 #include "utf8.h"
50 #include "util.h"
51 #include "verbs.h"
52 #include "virt.h"
53
54 static char *arg_esp_path = NULL;
55 static char *arg_xbootldr_path = NULL;
56 static bool arg_print_esp_path = false;
57 static bool arg_print_dollar_boot_path = false;
58 static bool arg_touch_variables = true;
59 static PagerFlags arg_pager_flags = 0;
60 static bool arg_graceful = false;
61 static int arg_make_entry_directory = false; /* tri-state: < 0 for automatic logic */
62 static sd_id128_t arg_machine_id = SD_ID128_NULL;
63 static char *arg_install_layout = NULL;
64 static enum {
65 ARG_ENTRY_TOKEN_MACHINE_ID,
66 ARG_ENTRY_TOKEN_OS_IMAGE_ID,
67 ARG_ENTRY_TOKEN_OS_ID,
68 ARG_ENTRY_TOKEN_LITERAL,
69 ARG_ENTRY_TOKEN_AUTO,
70 } arg_entry_token_type = ARG_ENTRY_TOKEN_AUTO;
71 static char *arg_entry_token = NULL;
72
73 STATIC_DESTRUCTOR_REGISTER(arg_esp_path, freep);
74 STATIC_DESTRUCTOR_REGISTER(arg_xbootldr_path, freep);
75 STATIC_DESTRUCTOR_REGISTER(arg_install_layout, freep);
76 STATIC_DESTRUCTOR_REGISTER(arg_entry_token, freep);
77
78 static const char *arg_dollar_boot_path(void) {
79 /* $BOOT shall be the XBOOTLDR partition if it exists, and otherwise the ESP */
80 return arg_xbootldr_path ?: arg_esp_path;
81 }
82
83 static int acquire_esp(
84 bool unprivileged_mode,
85 bool graceful,
86 uint32_t *ret_part,
87 uint64_t *ret_pstart,
88 uint64_t *ret_psize,
89 sd_id128_t *ret_uuid,
90 dev_t *ret_devid) {
91
92 char *np;
93 int r;
94
95 /* Find the ESP, and log about errors. Note that find_esp_and_warn() will log in all error cases on
96 * its own, except for ENOKEY (which is good, we want to show our own message in that case,
97 * suggesting use of --esp-path=) and EACCESS (only when we request unprivileged mode; in this case
98 * we simply eat up the error here, so that --list and --status work too, without noise about
99 * this). */
100
101 r = find_esp_and_warn(arg_esp_path, unprivileged_mode, &np, ret_part, ret_pstart, ret_psize, ret_uuid, ret_devid);
102 if (r == -ENOKEY) {
103 if (graceful)
104 return log_info_errno(r, "Couldn't find EFI system partition, skipping.");
105
106 return log_error_errno(r,
107 "Couldn't find EFI system partition. It is recommended to mount it to /boot or /efi.\n"
108 "Alternatively, use --esp-path= to specify path to mount point.");
109 }
110 if (r < 0)
111 return r;
112
113 free_and_replace(arg_esp_path, np);
114 log_debug("Using EFI System Partition at %s.", arg_esp_path);
115
116 return 1;
117 }
118
119 static int acquire_xbootldr(
120 bool unprivileged_mode,
121 sd_id128_t *ret_uuid,
122 dev_t *ret_devid) {
123
124 char *np;
125 int r;
126
127 r = find_xbootldr_and_warn(arg_xbootldr_path, unprivileged_mode, &np, ret_uuid, ret_devid);
128 if (r == -ENOKEY) {
129 log_debug_errno(r, "Didn't find an XBOOTLDR partition, using the ESP as $BOOT.");
130 arg_xbootldr_path = mfree(arg_xbootldr_path);
131
132 if (ret_uuid)
133 *ret_uuid = SD_ID128_NULL;
134 if (ret_devid)
135 *ret_devid = 0;
136 return 0;
137 }
138 if (r < 0)
139 return r;
140
141 free_and_replace(arg_xbootldr_path, np);
142 log_debug("Using XBOOTLDR partition at %s as $BOOT.", arg_xbootldr_path);
143
144 return 1;
145 }
146
147 static int load_install_machine_id_and_layout(void) {
148 /* Figure out the right machine-id for operations. If KERNEL_INSTALL_MACHINE_ID is configured in
149 * /etc/machine-info, let's use that. Otherwise, just use the real machine-id.
150 *
151 * Also load KERNEL_INSTALL_LAYOUT.
152 */
153 _cleanup_free_ char *s = NULL, *layout = NULL;
154 int r;
155
156 r = parse_env_file(NULL, "/etc/machine-info",
157 "KERNEL_INSTALL_LAYOUT", &layout,
158 "KERNEL_INSTALL_MACHINE_ID", &s);
159 if (r < 0 && r != -ENOENT)
160 return log_error_errno(r, "Failed to parse /etc/machine-info: %m");
161
162 if (isempty(s)) {
163 r = sd_id128_get_machine(&arg_machine_id);
164 if (r < 0 && !IN_SET(r, -ENOENT, -ENOMEDIUM))
165 return log_error_errno(r, "Failed to get machine-id: %m");
166 } else {
167 r = sd_id128_from_string(s, &arg_machine_id);
168 if (r < 0)
169 return log_error_errno(r, "Failed to parse KERNEL_INSTALL_MACHINE_ID=%s in /etc/machine-info: %m", s);
170
171 }
172 log_debug("Using KERNEL_INSTALL_MACHINE_ID=%s from %s.",
173 SD_ID128_TO_STRING(arg_machine_id),
174 isempty(s) ? "/etc/machine_id" : "KERNEL_INSTALL_MACHINE_ID in /etc/machine-info");
175
176 if (!isempty(layout)) {
177 log_debug("KERNEL_INSTALL_LAYOUT=%s is specified in /etc/machine-info.", layout);
178 arg_install_layout = TAKE_PTR(layout);
179 }
180
181 return 0;
182 }
183
184 static int settle_entry_token(void) {
185 int r;
186
187 switch (arg_entry_token_type) {
188
189 case ARG_ENTRY_TOKEN_AUTO: {
190 _cleanup_free_ char *buf = NULL;
191 r = read_one_line_file("/etc/kernel/entry-token", &buf);
192 if (r < 0 && r != -ENOENT)
193 return log_error_errno(r, "Failed to read /etc/kernel/entry-token: %m");
194
195 if (!isempty(buf)) {
196 free_and_replace(arg_entry_token, buf);
197 arg_entry_token_type = ARG_ENTRY_TOKEN_LITERAL;
198 } else if (sd_id128_is_null(arg_machine_id)) {
199 _cleanup_free_ char *id = NULL, *image_id = NULL;
200
201 r = parse_os_release(NULL,
202 "IMAGE_ID", &image_id,
203 "ID", &id);
204 if (r < 0)
205 return log_error_errno(r, "Failed to load /etc/os-release: %m");
206
207 if (!isempty(image_id)) {
208 free_and_replace(arg_entry_token, image_id);
209 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_IMAGE_ID;
210 } else if (!isempty(id)) {
211 free_and_replace(arg_entry_token, id);
212 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_ID;
213 } else
214 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No machine ID set, and /etc/os-release carries no ID=/IMAGE_ID= fields.");
215 } else {
216 r = free_and_strdup_warn(&arg_entry_token, SD_ID128_TO_STRING(arg_machine_id));
217 if (r < 0)
218 return r;
219
220 arg_entry_token_type = ARG_ENTRY_TOKEN_MACHINE_ID;
221 }
222
223 break;
224 }
225
226 case ARG_ENTRY_TOKEN_MACHINE_ID:
227 if (sd_id128_is_null(arg_machine_id))
228 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No machine ID set.");
229
230 r = free_and_strdup_warn(&arg_entry_token, SD_ID128_TO_STRING(arg_machine_id));
231 if (r < 0)
232 return r;
233
234 break;
235
236 case ARG_ENTRY_TOKEN_OS_IMAGE_ID: {
237 _cleanup_free_ char *buf = NULL;
238
239 r = parse_os_release(NULL, "IMAGE_ID", &buf);
240 if (r < 0)
241 return log_error_errno(r, "Failed to load /etc/os-release: %m");
242
243 if (isempty(buf))
244 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "IMAGE_ID= field not set in /etc/os-release.");
245
246 free_and_replace(arg_entry_token, buf);
247 break;
248 }
249
250 case ARG_ENTRY_TOKEN_OS_ID: {
251 _cleanup_free_ char *buf = NULL;
252
253 r = parse_os_release(NULL, "ID", &buf);
254 if (r < 0)
255 return log_error_errno(r, "Failed to load /etc/os-release: %m");
256
257 if (isempty(buf))
258 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "ID= field not set in /etc/os-release.");
259
260 free_and_replace(arg_entry_token, buf);
261 break;
262 }
263
264 case ARG_ENTRY_TOKEN_LITERAL:
265 assert(!isempty(arg_entry_token)); /* already filled in by command line parser */
266 break;
267 }
268
269 if (isempty(arg_entry_token) || !string_is_safe(arg_entry_token))
270 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Selected entry token not valid: %s", arg_entry_token);
271
272 log_debug("Using entry token: %s", arg_entry_token);
273 return 0;
274 }
275
276 static bool use_boot_loader_spec_type1(void) {
277 /* If the layout is not specified, or if it is set explicitly to "bls" we assume Boot Loader
278 * Specification Type #1 is the chosen format for our boot loader entries */
279 return !arg_install_layout || streq(arg_install_layout, "bls");
280 }
281
282 static int settle_make_entry_directory(void) {
283 int r;
284
285 r = load_install_machine_id_and_layout();
286 if (r < 0)
287 return r;
288
289 r = settle_entry_token();
290 if (r < 0)
291 return r;
292
293 bool layout_type1 = use_boot_loader_spec_type1();
294 if (arg_make_entry_directory < 0) { /* Automatic mode */
295 if (layout_type1) {
296 if (arg_entry_token == ARG_ENTRY_TOKEN_MACHINE_ID) {
297 r = path_is_temporary_fs("/etc/machine-id");
298 if (r < 0)
299 return log_debug_errno(r, "Couldn't determine whether /etc/machine-id is on a temporary file system: %m");
300
301 arg_make_entry_directory = r == 0;
302 } else
303 arg_make_entry_directory = true;
304 } else
305 arg_make_entry_directory = false;
306 }
307
308 if (arg_make_entry_directory > 0 && !layout_type1)
309 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
310 "KERNEL_INSTALL_LAYOUT=%s is configured, but Boot Loader Specification Type #1 entry directory creation was requested.",
311 arg_install_layout);
312
313 return 0;
314 }
315
316 /* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */
317 static int get_file_version(int fd, char **v) {
318 struct stat st;
319 char *buf;
320 const char *s, *e;
321 char *x = NULL;
322 int r;
323
324 assert(fd >= 0);
325 assert(v);
326
327 if (fstat(fd, &st) < 0)
328 return log_error_errno(errno, "Failed to stat EFI binary: %m");
329
330 r = stat_verify_regular(&st);
331 if (r < 0)
332 return log_error_errno(r, "EFI binary is not a regular file: %m");
333
334 if (st.st_size < 27 || file_offset_beyond_memory_size(st.st_size)) {
335 *v = NULL;
336 return 0;
337 }
338
339 buf = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
340 if (buf == MAP_FAILED)
341 return log_error_errno(errno, "Failed to memory map EFI binary: %m");
342
343 s = mempmem_safe(buf, st.st_size - 8, "#### LoaderInfo: ", 17);
344 if (!s)
345 goto finish;
346
347 e = memmem_safe(s, st.st_size - (s - buf), " ####", 5);
348 if (!e || e - s < 3) {
349 r = log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Malformed version string.");
350 goto finish;
351 }
352
353 x = strndup(s, e - s);
354 if (!x) {
355 r = log_oom();
356 goto finish;
357 }
358 r = 1;
359
360 finish:
361 (void) munmap(buf, st.st_size);
362 *v = x;
363 return r;
364 }
365
366 static int enumerate_binaries(const char *esp_path, const char *path, const char *prefix) {
367 _cleanup_closedir_ DIR *d = NULL;
368 const char *p;
369 int c = 0, r;
370
371 assert(esp_path);
372 assert(path);
373
374 p = prefix_roota(esp_path, path);
375 d = opendir(p);
376 if (!d) {
377 if (errno == ENOENT)
378 return 0;
379
380 return log_error_errno(errno, "Failed to read \"%s\": %m", p);
381 }
382
383 FOREACH_DIRENT(de, d, break) {
384 _cleanup_free_ char *v = NULL;
385 _cleanup_close_ int fd = -1;
386
387 if (!endswith_no_case(de->d_name, ".efi"))
388 continue;
389
390 if (prefix && !startswith_no_case(de->d_name, prefix))
391 continue;
392
393 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
394 if (fd < 0)
395 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
396
397 r = get_file_version(fd, &v);
398 if (r < 0)
399 return r;
400 if (r > 0)
401 printf(" File: %s/%s/%s (%s%s%s)\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path, de->d_name, ansi_highlight(), v, ansi_normal());
402 else
403 printf(" File: %s/%s/%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path, de->d_name);
404
405 c++;
406 }
407
408 return c;
409 }
410
411 static int status_binaries(const char *esp_path, sd_id128_t partition) {
412 int r;
413
414 printf("Available Boot Loaders on ESP:\n");
415
416 if (!esp_path) {
417 printf(" ESP: Cannot find or access mount point of ESP.\n\n");
418 return -ENOENT;
419 }
420
421 printf(" ESP: %s", esp_path);
422 if (!sd_id128_is_null(partition))
423 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR ")", SD_ID128_FORMAT_VAL(partition));
424 printf("\n");
425
426 r = enumerate_binaries(esp_path, "EFI/systemd", NULL);
427 if (r < 0)
428 goto finish;
429 if (r == 0)
430 log_info("systemd-boot not installed in ESP.");
431
432 r = enumerate_binaries(esp_path, "EFI/BOOT", "boot");
433 if (r < 0)
434 goto finish;
435 if (r == 0)
436 log_info("No default/fallback boot loader installed in ESP.");
437
438 r = 0;
439
440 finish:
441 printf("\n");
442 return r;
443 }
444
445 static int print_efi_option(uint16_t id, bool in_order) {
446 _cleanup_free_ char *title = NULL;
447 _cleanup_free_ char *path = NULL;
448 sd_id128_t partition;
449 bool active;
450 int r;
451
452 r = efi_get_boot_option(id, &title, &partition, &path, &active);
453 if (r < 0)
454 return r;
455
456 /* print only configured entries with partition information */
457 if (!path || sd_id128_is_null(partition))
458 return 0;
459
460 efi_tilt_backslashes(path);
461
462 printf(" Title: %s%s%s\n", ansi_highlight(), strna(title), ansi_normal());
463 printf(" ID: 0x%04X\n", id);
464 printf(" Status: %sactive%s\n", active ? "" : "in", in_order ? ", boot-order" : "");
465 printf(" Partition: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR "\n",
466 SD_ID128_FORMAT_VAL(partition));
467 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path);
468 printf("\n");
469
470 return 0;
471 }
472
473 static int status_variables(void) {
474 _cleanup_free_ uint16_t *options = NULL, *order = NULL;
475 int n_options, n_order;
476
477 n_options = efi_get_boot_options(&options);
478 if (n_options == -ENOENT)
479 return log_error_errno(n_options,
480 "Failed to access EFI variables, efivarfs"
481 " needs to be available at /sys/firmware/efi/efivars/.");
482 if (n_options < 0)
483 return log_error_errno(n_options, "Failed to read EFI boot entries: %m");
484
485 n_order = efi_get_boot_order(&order);
486 if (n_order == -ENOENT)
487 n_order = 0;
488 else if (n_order < 0)
489 return log_error_errno(n_order, "Failed to read EFI boot order: %m");
490
491 /* print entries in BootOrder first */
492 printf("Boot Loaders Listed in EFI Variables:\n");
493 for (int i = 0; i < n_order; i++)
494 print_efi_option(order[i], true);
495
496 /* print remaining entries */
497 for (int i = 0; i < n_options; i++) {
498 for (int j = 0; j < n_order; j++)
499 if (options[i] == order[j])
500 goto next_option;
501
502 print_efi_option(options[i], false);
503
504 next_option:
505 continue;
506 }
507
508 return 0;
509 }
510
511 static int boot_entry_file_check(const char *root, const char *p) {
512 _cleanup_free_ char *path = NULL;
513
514 path = path_join(root, p);
515 if (!path)
516 return log_oom();
517
518 return RET_NERRNO(access(path, F_OK));
519 }
520
521 static void boot_entry_file_list(const char *field, const char *root, const char *p, int *ret_status) {
522 int status = boot_entry_file_check(root, p);
523
524 printf("%13s%s ", strempty(field), field ? ":" : " ");
525 if (status < 0) {
526 errno = -status;
527 printf("%s%s%s (%m)\n", ansi_highlight_red(), p, ansi_normal());
528 } else
529 printf("%s\n", p);
530
531 if (*ret_status == 0 && status < 0)
532 *ret_status = status;
533 }
534
535 static const char* const boot_entry_type_table[_BOOT_ENTRY_TYPE_MAX] = {
536 [BOOT_ENTRY_CONF] = "Boot Loader Specification Type #1 (.conf)",
537 [BOOT_ENTRY_UNIFIED] = "Boot Loader Specification Type #2 (.efi)",
538 [BOOT_ENTRY_LOADER] = "Reported by Boot Loader",
539 [BOOT_ENTRY_LOADER_AUTO] = "Automatic",
540 };
541
542 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(boot_entry_type, BootEntryType);
543
544 static int boot_entry_show(
545 const BootEntry *e,
546 bool show_as_default,
547 bool show_as_selected,
548 bool show_reported) {
549
550 int status = 0;
551
552 /* Returns 0 on success, negative on processing error, and positive if something is wrong with the
553 boot entry itself. */
554
555 assert(e);
556
557 printf(" type: %s\n",
558 boot_entry_type_to_string(e->type));
559
560 printf(" title: %s%s%s",
561 ansi_highlight(), boot_entry_title(e), ansi_normal());
562
563 if (show_as_default)
564 printf(" %s(default)%s",
565 ansi_highlight_green(), ansi_normal());
566
567 if (show_as_selected)
568 printf(" %s(selected)%s",
569 ansi_highlight_magenta(), ansi_normal());
570
571 if (show_reported) {
572 if (e->type == BOOT_ENTRY_LOADER)
573 printf(" %s(reported/absent)%s",
574 ansi_highlight_red(), ansi_normal());
575 else if (!e->reported_by_loader && e->type != BOOT_ENTRY_LOADER_AUTO)
576 printf(" %s(not reported/new)%s",
577 ansi_highlight_green(), ansi_normal());
578 }
579
580 putchar('\n');
581
582 if (e->id)
583 printf(" id: %s\n", e->id);
584 if (e->path) {
585 _cleanup_free_ char *link = NULL;
586
587 /* Let's urlify the link to make it easy to view in an editor, but only if it is a text
588 * file. Unified images are binary ELFs, and EFI variables are not pure text either. */
589 if (e->type == BOOT_ENTRY_CONF)
590 (void) terminal_urlify_path(e->path, NULL, &link);
591
592 printf(" source: %s\n", link ?: e->path);
593 }
594 if (e->sort_key)
595 printf(" sort-key: %s\n", e->sort_key);
596 if (e->version)
597 printf(" version: %s\n", e->version);
598 if (e->machine_id)
599 printf(" machine-id: %s\n", e->machine_id);
600 if (e->architecture)
601 printf(" architecture: %s\n", e->architecture);
602 if (e->kernel)
603 boot_entry_file_list("linux", e->root, e->kernel, &status);
604
605 char **s;
606 STRV_FOREACH(s, e->initrd)
607 boot_entry_file_list(s == e->initrd ? "initrd" : NULL,
608 e->root,
609 *s,
610 &status);
611
612 if (!strv_isempty(e->options)) {
613 _cleanup_free_ char *t = NULL, *t2 = NULL;
614 _cleanup_strv_free_ char **ts = NULL;
615
616 t = strv_join(e->options, " ");
617 if (!t)
618 return log_oom();
619
620 ts = strv_split_newlines(t);
621 if (!ts)
622 return log_oom();
623
624 t2 = strv_join(ts, "\n ");
625 if (!t2)
626 return log_oom();
627
628 printf(" options: %s\n", t2);
629 }
630
631 if (e->device_tree)
632 boot_entry_file_list("devicetree", e->root, e->device_tree, &status);
633
634 STRV_FOREACH(s, e->device_tree_overlay)
635 boot_entry_file_list(s == e->device_tree_overlay ? "devicetree-overlay" : NULL,
636 e->root,
637 *s,
638 &status);
639
640 return -status;
641 }
642
643 static int status_entries(
644 const char *esp_path,
645 sd_id128_t esp_partition_uuid,
646 const char *xbootldr_path,
647 sd_id128_t xbootldr_partition_uuid) {
648
649 _cleanup_(boot_config_free) BootConfig config = {};
650 sd_id128_t dollar_boot_partition_uuid;
651 const char *dollar_boot_path;
652 int r;
653
654 assert(esp_path || xbootldr_path);
655
656 if (xbootldr_path) {
657 dollar_boot_path = xbootldr_path;
658 dollar_boot_partition_uuid = xbootldr_partition_uuid;
659 } else {
660 dollar_boot_path = esp_path;
661 dollar_boot_partition_uuid = esp_partition_uuid;
662 }
663
664 printf("Boot Loader Entries:\n"
665 " $BOOT: %s", dollar_boot_path);
666 if (!sd_id128_is_null(dollar_boot_partition_uuid))
667 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR ")",
668 SD_ID128_FORMAT_VAL(dollar_boot_partition_uuid));
669 printf("\n\n");
670
671 r = boot_entries_load_config(esp_path, xbootldr_path, &config);
672 if (r < 0)
673 return r;
674
675 if (config.default_entry < 0)
676 printf("%zu entries, no entry could be determined as default.\n", config.n_entries);
677 else {
678 printf("Default Boot Loader Entry:\n");
679
680 r = boot_entry_show(
681 config.entries + config.default_entry,
682 /* show_as_default= */ false,
683 /* show_as_selected= */ false,
684 /* show_discovered= */ false);
685 if (r > 0)
686 /* < 0 is already logged by the function itself, let's just emit an extra warning if
687 the default entry is broken */
688 printf("\nWARNING: default boot entry is broken\n");
689 }
690
691 return 0;
692 }
693
694 static int compare_product(const char *a, const char *b) {
695 size_t x, y;
696
697 assert(a);
698 assert(b);
699
700 x = strcspn(a, " ");
701 y = strcspn(b, " ");
702 if (x != y)
703 return x < y ? -1 : x > y ? 1 : 0;
704
705 return strncmp(a, b, x);
706 }
707
708 static int compare_version(const char *a, const char *b) {
709 assert(a);
710 assert(b);
711
712 a += strcspn(a, " ");
713 a += strspn(a, " ");
714 b += strcspn(b, " ");
715 b += strspn(b, " ");
716
717 return strverscmp_improved(a, b);
718 }
719
720 static int version_check(int fd_from, const char *from, int fd_to, const char *to) {
721 _cleanup_free_ char *a = NULL, *b = NULL;
722 int r;
723
724 assert(fd_from >= 0);
725 assert(from);
726 assert(fd_to >= 0);
727 assert(to);
728
729 r = get_file_version(fd_from, &a);
730 if (r < 0)
731 return r;
732 if (r == 0)
733 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE),
734 "Source file \"%s\" does not carry version information!",
735 from);
736
737 r = get_file_version(fd_to, &b);
738 if (r < 0)
739 return r;
740 if (r == 0 || compare_product(a, b) != 0)
741 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE),
742 "Skipping \"%s\", since it's owned by another boot loader.",
743 to);
744
745 r = compare_version(a, b);
746 if (r < 0)
747 return log_warning_errno(SYNTHETIC_ERRNO(ESTALE), "Skipping \"%s\", since newer boot loader version in place already.", to);
748 else if (r == 0)
749 return log_info_errno(SYNTHETIC_ERRNO(ESTALE), "Skipping \"%s\", since same boot loader version in place already.", to);
750
751 return 0;
752 }
753
754 static int copy_file_with_version_check(const char *from, const char *to, bool force) {
755 _cleanup_close_ int fd_from = -1, fd_to = -1;
756 _cleanup_free_ char *t = NULL;
757 int r;
758
759 fd_from = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
760 if (fd_from < 0)
761 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", from);
762
763 if (!force) {
764 fd_to = open(to, O_RDONLY|O_CLOEXEC|O_NOCTTY);
765 if (fd_to < 0) {
766 if (errno != ENOENT)
767 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", to);
768 } else {
769 r = version_check(fd_from, from, fd_to, to);
770 if (r < 0)
771 return r;
772
773 if (lseek(fd_from, 0, SEEK_SET) == (off_t) -1)
774 return log_error_errno(errno, "Failed to seek in \"%s\": %m", from);
775
776 fd_to = safe_close(fd_to);
777 }
778 }
779
780 r = tempfn_random(to, NULL, &t);
781 if (r < 0)
782 return log_oom();
783
784 RUN_WITH_UMASK(0000) {
785 fd_to = open(t, O_WRONLY|O_CREAT|O_CLOEXEC|O_EXCL|O_NOFOLLOW, 0644);
786 if (fd_to < 0)
787 return log_error_errno(errno, "Failed to open \"%s\" for writing: %m", t);
788 }
789
790 r = copy_bytes(fd_from, fd_to, UINT64_MAX, COPY_REFLINK);
791 if (r < 0) {
792 (void) unlink(t);
793 return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
794 }
795
796 (void) copy_times(fd_from, fd_to, 0);
797
798 r = fsync_full(fd_to);
799 if (r < 0) {
800 (void) unlink_noerrno(t);
801 return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
802 }
803
804 if (renameat(AT_FDCWD, t, AT_FDCWD, to) < 0) {
805 (void) unlink_noerrno(t);
806 return log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", t, to);
807 }
808
809 log_info("Copied \"%s\" to \"%s\".", from, to);
810
811 return 0;
812 }
813
814 static int mkdir_one(const char *prefix, const char *suffix) {
815 _cleanup_free_ char *p = NULL;
816
817 p = path_join(prefix, suffix);
818 if (mkdir(p, 0700) < 0) {
819 if (errno != EEXIST)
820 return log_error_errno(errno, "Failed to create \"%s\": %m", p);
821 } else
822 log_info("Created \"%s\".", p);
823
824 return 0;
825 }
826
827 static const char *const esp_subdirs[] = {
828 /* The directories to place in the ESP */
829 "EFI",
830 "EFI/systemd",
831 "EFI/BOOT",
832 "loader",
833 NULL
834 };
835
836 static const char *const dollar_boot_subdirs[] = {
837 /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
838 "loader",
839 "loader/entries", /* Type #1 entries */
840 "EFI",
841 "EFI/Linux", /* Type #2 entries */
842 NULL
843 };
844
845 static int create_subdirs(const char *root, const char * const *subdirs) {
846 const char *const *i;
847 int r;
848
849 STRV_FOREACH(i, subdirs) {
850 r = mkdir_one(root, *i);
851 if (r < 0)
852 return r;
853 }
854
855 return 0;
856 }
857
858 static int copy_one_file(const char *esp_path, const char *name, bool force) {
859 const char *e;
860 char *p, *q, *dest_name, *s;
861 int r;
862
863 dest_name = strdupa_safe(name);
864 s = endswith_no_case(dest_name, ".signed");
865 if (s)
866 *s = 0;
867
868 p = strjoina(BOOTLIBDIR "/", name);
869 q = strjoina(esp_path, "/EFI/systemd/", dest_name);
870 r = copy_file_with_version_check(p, q, force);
871
872 e = startswith(dest_name, "systemd-boot");
873 if (e) {
874 int k;
875 char *v;
876
877 /* Create the EFI default boot loader name (specified for removable devices) */
878 v = strjoina(esp_path, "/EFI/BOOT/BOOT", e);
879 ascii_strupper(strrchr(v, '/') + 1);
880
881 k = copy_file_with_version_check(p, v, force);
882 if (k < 0 && r == 0)
883 r = k;
884 }
885
886 return r;
887 }
888
889 static int install_binaries(const char *esp_path, bool force) {
890 _cleanup_closedir_ DIR *d = NULL;
891 int r = 0;
892
893 d = opendir(BOOTLIBDIR);
894 if (!d)
895 return log_error_errno(errno, "Failed to open \""BOOTLIBDIR"\": %m");
896
897 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read \""BOOTLIBDIR"\": %m")) {
898 int k;
899
900 if (!endswith_no_case(de->d_name, ".efi") && !endswith_no_case(de->d_name, ".efi.signed"))
901 continue;
902
903 /* skip the .efi file, if there's a .signed version of it */
904 if (endswith_no_case(de->d_name, ".efi")) {
905 _cleanup_free_ const char *s = strjoin(de->d_name, ".signed");
906 if (!s)
907 return log_oom();
908 if (faccessat(dirfd(d), s, F_OK, 0) >= 0)
909 continue;
910 }
911
912 k = copy_one_file(esp_path, de->d_name, force);
913 /* Don't propagate an error code if no update necessary, installed version already equal or
914 * newer version, or other boot loader in place. */
915 if (arg_graceful && IN_SET(k, -ESTALE, -EREMOTE))
916 continue;
917 if (k < 0 && r == 0)
918 r = k;
919 }
920
921 return r;
922 }
923
924 static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
925 _cleanup_free_ char *opath = NULL;
926 sd_id128_t ouuid;
927 int r;
928
929 r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
930 if (r < 0)
931 return false;
932 if (!sd_id128_equal(uuid, ouuid))
933 return false;
934
935 /* Some motherboards convert the path to uppercase under certain circumstances
936 * (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
937 * so use case-insensitive checking */
938 if (!strcaseeq_ptr(path, opath))
939 return false;
940
941 return true;
942 }
943
944 static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
945 _cleanup_free_ uint16_t *options = NULL;
946 int n, i;
947
948 n = efi_get_boot_options(&options);
949 if (n < 0)
950 return n;
951
952 /* find already existing systemd-boot entry */
953 for (i = 0; i < n; i++)
954 if (same_entry(options[i], uuid, path)) {
955 *id = options[i];
956 return 1;
957 }
958
959 /* find free slot in the sorted BootXXXX variable list */
960 for (i = 0; i < n; i++)
961 if (i != options[i]) {
962 *id = i;
963 return 0;
964 }
965
966 /* use the next one */
967 if (i == 0xffff)
968 return -ENOSPC;
969 *id = i;
970 return 0;
971 }
972
973 static int insert_into_order(uint16_t slot, bool first) {
974 _cleanup_free_ uint16_t *order = NULL;
975 uint16_t *t;
976 int n;
977
978 n = efi_get_boot_order(&order);
979 if (n <= 0)
980 /* no entry, add us */
981 return efi_set_boot_order(&slot, 1);
982
983 /* are we the first and only one? */
984 if (n == 1 && order[0] == slot)
985 return 0;
986
987 /* are we already in the boot order? */
988 for (int i = 0; i < n; i++) {
989 if (order[i] != slot)
990 continue;
991
992 /* we do not require to be the first one, all is fine */
993 if (!first)
994 return 0;
995
996 /* move us to the first slot */
997 memmove(order + 1, order, i * sizeof(uint16_t));
998 order[0] = slot;
999 return efi_set_boot_order(order, n);
1000 }
1001
1002 /* extend array */
1003 t = reallocarray(order, n + 1, sizeof(uint16_t));
1004 if (!t)
1005 return -ENOMEM;
1006 order = t;
1007
1008 /* add us to the top or end of the list */
1009 if (first) {
1010 memmove(order + 1, order, n * sizeof(uint16_t));
1011 order[0] = slot;
1012 } else
1013 order[n] = slot;
1014
1015 return efi_set_boot_order(order, n + 1);
1016 }
1017
1018 static int remove_from_order(uint16_t slot) {
1019 _cleanup_free_ uint16_t *order = NULL;
1020 int n;
1021
1022 n = efi_get_boot_order(&order);
1023 if (n <= 0)
1024 return n;
1025
1026 for (int i = 0; i < n; i++) {
1027 if (order[i] != slot)
1028 continue;
1029
1030 if (i + 1 < n)
1031 memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
1032 return efi_set_boot_order(order, n - 1);
1033 }
1034
1035 return 0;
1036 }
1037
1038 static int install_variables(const char *esp_path,
1039 uint32_t part, uint64_t pstart, uint64_t psize,
1040 sd_id128_t uuid, const char *path,
1041 bool first) {
1042 const char *p;
1043 uint16_t slot;
1044 int r;
1045
1046 if (!is_efi_boot()) {
1047 log_warning("Not booted with EFI, skipping EFI variable setup.");
1048 return 0;
1049 }
1050
1051 p = prefix_roota(esp_path, path);
1052 if (access(p, F_OK) < 0) {
1053 if (errno == ENOENT)
1054 return 0;
1055
1056 return log_error_errno(errno, "Cannot access \"%s\": %m", p);
1057 }
1058
1059 r = find_slot(uuid, path, &slot);
1060 if (r < 0)
1061 return log_error_errno(r,
1062 r == -ENOENT ?
1063 "Failed to access EFI variables. Is the \"efivarfs\" filesystem mounted?" :
1064 "Failed to determine current boot order: %m");
1065
1066 if (first || r == 0) {
1067 r = efi_add_boot_option(slot, "Linux Boot Manager",
1068 part, pstart, psize,
1069 uuid, path);
1070 if (r < 0)
1071 return log_error_errno(r, "Failed to create EFI Boot variable entry: %m");
1072
1073 log_info("Created EFI boot entry \"Linux Boot Manager\".");
1074 }
1075
1076 return insert_into_order(slot, first);
1077 }
1078
1079 static int remove_boot_efi(const char *esp_path) {
1080 _cleanup_closedir_ DIR *d = NULL;
1081 const char *p;
1082 int r, c = 0;
1083
1084 p = prefix_roota(esp_path, "/EFI/BOOT");
1085 d = opendir(p);
1086 if (!d) {
1087 if (errno == ENOENT)
1088 return 0;
1089
1090 return log_error_errno(errno, "Failed to open directory \"%s\": %m", p);
1091 }
1092
1093 FOREACH_DIRENT(de, d, break) {
1094 _cleanup_close_ int fd = -1;
1095 _cleanup_free_ char *v = NULL;
1096
1097 if (!endswith_no_case(de->d_name, ".efi"))
1098 continue;
1099
1100 if (!startswith_no_case(de->d_name, "boot"))
1101 continue;
1102
1103 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
1104 if (fd < 0)
1105 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
1106
1107 r = get_file_version(fd, &v);
1108 if (r < 0)
1109 return r;
1110 if (r > 0 && startswith(v, "systemd-boot ")) {
1111 r = unlinkat(dirfd(d), de->d_name, 0);
1112 if (r < 0)
1113 return log_error_errno(errno, "Failed to remove \"%s/%s\": %m", p, de->d_name);
1114
1115 log_info("Removed \"%s/%s\".", p, de->d_name);
1116 }
1117
1118 c++;
1119 }
1120
1121 return c;
1122 }
1123
1124 static int rmdir_one(const char *prefix, const char *suffix) {
1125 const char *p;
1126
1127 p = prefix_roota(prefix, suffix);
1128 if (rmdir(p) < 0) {
1129 bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
1130
1131 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
1132 "Failed to remove directory \"%s\": %m", p);
1133 if (!ignore)
1134 return -errno;
1135 } else
1136 log_info("Removed \"%s\".", p);
1137
1138 return 0;
1139 }
1140
1141 static int remove_subdirs(const char *root, const char *const *subdirs) {
1142 int r, q;
1143
1144 /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
1145 * short the array is. */
1146
1147 if (!subdirs[0]) /* A the end of the list */
1148 return 0;
1149
1150 r = remove_subdirs(root, subdirs + 1);
1151 q = rmdir_one(root, subdirs[0]);
1152
1153 return r < 0 ? r : q;
1154 }
1155
1156 static int remove_entry_directory(const char *root) {
1157 assert(root);
1158 assert(arg_make_entry_directory >= 0);
1159
1160 if (!arg_make_entry_directory || !arg_entry_token)
1161 return 0;
1162
1163 return rmdir_one(root, arg_entry_token);
1164 }
1165
1166 static int remove_binaries(const char *esp_path) {
1167 const char *p;
1168 int r, q;
1169
1170 p = prefix_roota(esp_path, "/EFI/systemd");
1171 r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
1172
1173 q = remove_boot_efi(esp_path);
1174 if (q < 0 && r == 0)
1175 r = q;
1176
1177 return r;
1178 }
1179
1180 static int remove_file(const char *root, const char *file) {
1181 const char *p;
1182
1183 assert(root);
1184 assert(file);
1185
1186 p = prefix_roota(root, file);
1187 if (unlink(p) < 0) {
1188 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
1189 "Failed to unlink file \"%s\": %m", p);
1190
1191 return errno == ENOENT ? 0 : -errno;
1192 }
1193
1194 log_info("Removed \"%s\".", p);
1195 return 1;
1196 }
1197
1198 static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
1199 uint16_t slot;
1200 int r;
1201
1202 if (!is_efi_boot())
1203 return 0;
1204
1205 r = find_slot(uuid, path, &slot);
1206 if (r != 1)
1207 return 0;
1208
1209 r = efi_remove_boot_option(slot);
1210 if (r < 0)
1211 return r;
1212
1213 if (in_order)
1214 return remove_from_order(slot);
1215
1216 return 0;
1217 }
1218
1219 static int remove_loader_variables(void) {
1220 const char *variable;
1221 int r = 0;
1222
1223 /* Remove all persistent loader variables we define */
1224
1225 FOREACH_STRING(variable,
1226 EFI_LOADER_VARIABLE(LoaderConfigTimeout),
1227 EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot),
1228 EFI_LOADER_VARIABLE(LoaderEntryDefault),
1229 EFI_LOADER_VARIABLE(LoaderEntryOneShot),
1230 EFI_LOADER_VARIABLE(LoaderSystemToken)){
1231
1232 int q;
1233
1234 q = efi_set_variable(variable, NULL, 0);
1235 if (q == -ENOENT)
1236 continue;
1237 if (q < 0) {
1238 log_warning_errno(q, "Failed to remove EFI variable %s: %m", variable);
1239 if (r >= 0)
1240 r = q;
1241 } else
1242 log_info("Removed EFI variable %s.", variable);
1243 }
1244
1245 return r;
1246 }
1247
1248 static int install_loader_config(const char *esp_path) {
1249 _cleanup_(unlink_and_freep) char *t = NULL;
1250 _cleanup_fclose_ FILE *f = NULL;
1251 _cleanup_close_ int fd = -1;
1252 const char *p;
1253 int r;
1254
1255 assert(arg_make_entry_directory >= 0);
1256
1257 p = prefix_roota(esp_path, "/loader/loader.conf");
1258 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
1259 return 0;
1260
1261 fd = open_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t);
1262 if (fd < 0)
1263 return log_error_errno(fd, "Failed to open \"%s\" for writing: %m", p);
1264
1265 f = take_fdopen(&fd, "w");
1266 if (!f)
1267 return log_oom();
1268
1269 fprintf(f, "#timeout 3\n"
1270 "#console-mode keep\n");
1271
1272 if (arg_make_entry_directory) {
1273 assert(arg_entry_token);
1274 fprintf(f, "default %s-*\n", arg_entry_token);
1275 }
1276
1277 r = fflush_sync_and_check(f);
1278 if (r < 0)
1279 return log_error_errno(r, "Failed to write \"%s\": %m", p);
1280
1281 r = link_tmpfile(fileno(f), t, p);
1282 if (r == -EEXIST)
1283 return 0; /* Silently skip creation if the file exists now (recheck) */
1284 if (r < 0)
1285 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1286
1287 t = mfree(t);
1288 return 1;
1289 }
1290
1291 static int install_entry_directory(const char *root) {
1292 assert(root);
1293 assert(arg_make_entry_directory >= 0);
1294
1295 if (!arg_make_entry_directory)
1296 return 0;
1297
1298 assert(arg_entry_token);
1299 return mkdir_one(root, arg_entry_token);
1300 }
1301
1302 static int install_entry_token(void) {
1303 int r;
1304
1305 assert(arg_make_entry_directory >= 0);
1306 assert(arg_entry_token);
1307
1308 /* Let's save the used entry token in /etc/kernel/entry-token if we used it to create the entry
1309 * directory, or if anything else but the machine ID */
1310
1311 if (!arg_make_entry_directory && arg_entry_token_type == ARG_ENTRY_TOKEN_MACHINE_ID)
1312 return 0;
1313
1314 r = write_string_file("/etc/kernel/entry-token", arg_entry_token, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755);
1315 if (r < 0)
1316 return log_error_errno(r, "Failed to write entry token '%s' to /etc/kernel/entry-token", arg_entry_token);
1317
1318 return 0;
1319 }
1320
1321 static int help(int argc, char *argv[], void *userdata) {
1322 _cleanup_free_ char *link = NULL;
1323 int r;
1324
1325 r = terminal_urlify_man("bootctl", "1", &link);
1326 if (r < 0)
1327 return log_oom();
1328
1329 printf("%1$s [OPTIONS...] COMMAND ...\n"
1330 "\n%5$sControl EFI firmware boot settings and manage boot loader.%6$s\n"
1331 "\n%3$sGeneric EFI Firmware/Boot Loader Commands:%4$s\n"
1332 " status Show status of installed boot loader and EFI variables\n"
1333 " reboot-to-firmware [BOOL]\n"
1334 " Query or set reboot-to-firmware EFI flag\n"
1335 " systemd-efi-options [STRING]\n"
1336 " Query or set system options string in EFI variable\n"
1337 "\n%3$sBoot Loader Specification Commands:%4$s\n"
1338 " list List boot loader entries\n"
1339 " set-default ID Set default boot loader entry\n"
1340 " set-oneshot ID Set default boot loader entry, for next boot only\n"
1341 " set-timeout SECONDS Set the menu timeout\n"
1342 " set-timeout-oneshot SECONDS\n"
1343 " Set the menu timeout for the next boot only\n"
1344 "\n%3$ssystemd-boot Commands:%4$s\n"
1345 " install Install systemd-boot to the ESP and EFI variables\n"
1346 " update Update systemd-boot in the ESP and EFI variables\n"
1347 " remove Remove systemd-boot from the ESP and EFI variables\n"
1348 " is-installed Test whether systemd-boot is installed in the ESP\n"
1349 " random-seed Initialize random seed in ESP and EFI variables\n"
1350 "\n%3$sOptions:%4$s\n"
1351 " -h --help Show this help\n"
1352 " --version Print version\n"
1353 " --esp-path=PATH Path to the EFI System Partition (ESP)\n"
1354 " --boot-path=PATH Path to the $BOOT partition\n"
1355 " -p --print-esp-path Print path to the EFI System Partition\n"
1356 " -x --print-boot-path Print path to the $BOOT partition\n"
1357 " --no-variables Don't touch EFI variables\n"
1358 " --no-pager Do not pipe output into a pager\n"
1359 " --graceful Don't fail when the ESP cannot be found or EFI\n"
1360 " variables cannot be written\n"
1361 " --make-entry-directory=yes|no|auto\n"
1362 " Create $BOOT/ENTRY-TOKEN/ directory\n"
1363 " --entry-token=machine-id|os-id|os-image-id|auto|literal:…\n"
1364 " Entry token to use for this installation\n"
1365 "\nSee the %2$s for details.\n",
1366 program_invocation_short_name,
1367 link,
1368 ansi_underline(),
1369 ansi_normal(),
1370 ansi_highlight(),
1371 ansi_normal());
1372
1373 return 0;
1374 }
1375
1376 static int parse_argv(int argc, char *argv[]) {
1377 enum {
1378 ARG_ESP_PATH = 0x100,
1379 ARG_BOOT_PATH,
1380 ARG_VERSION,
1381 ARG_NO_VARIABLES,
1382 ARG_NO_PAGER,
1383 ARG_GRACEFUL,
1384 ARG_MAKE_ENTRY_DIRECTORY,
1385 ARG_ENTRY_TOKEN,
1386 };
1387
1388 static const struct option options[] = {
1389 { "help", no_argument, NULL, 'h' },
1390 { "version", no_argument, NULL, ARG_VERSION },
1391 { "esp-path", required_argument, NULL, ARG_ESP_PATH },
1392 { "path", required_argument, NULL, ARG_ESP_PATH }, /* Compatibility alias */
1393 { "boot-path", required_argument, NULL, ARG_BOOT_PATH },
1394 { "print-esp-path", no_argument, NULL, 'p' },
1395 { "print-path", no_argument, NULL, 'p' }, /* Compatibility alias */
1396 { "print-boot-path", no_argument, NULL, 'x' },
1397 { "no-variables", no_argument, NULL, ARG_NO_VARIABLES },
1398 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1399 { "graceful", no_argument, NULL, ARG_GRACEFUL },
1400 { "make-entry-directory", required_argument, NULL, ARG_MAKE_ENTRY_DIRECTORY },
1401 { "make-machine-id-directory", required_argument, NULL, ARG_MAKE_ENTRY_DIRECTORY }, /* Compatibility alias */
1402 { "entry-token", required_argument, NULL, ARG_ENTRY_TOKEN },
1403 {}
1404 };
1405
1406 int c, r;
1407 bool b;
1408
1409 assert(argc >= 0);
1410 assert(argv);
1411
1412 while ((c = getopt_long(argc, argv, "hpx", options, NULL)) >= 0)
1413 switch (c) {
1414
1415 case 'h':
1416 help(0, NULL, NULL);
1417 return 0;
1418
1419 case ARG_VERSION:
1420 return version();
1421
1422 case ARG_ESP_PATH:
1423 r = free_and_strdup(&arg_esp_path, optarg);
1424 if (r < 0)
1425 return log_oom();
1426 break;
1427
1428 case ARG_BOOT_PATH:
1429 r = free_and_strdup(&arg_xbootldr_path, optarg);
1430 if (r < 0)
1431 return log_oom();
1432 break;
1433
1434 case 'p':
1435 if (arg_print_dollar_boot_path)
1436 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1437 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1438 arg_print_esp_path = true;
1439 break;
1440
1441 case 'x':
1442 if (arg_print_esp_path)
1443 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1444 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
1445 arg_print_dollar_boot_path = true;
1446 break;
1447
1448 case ARG_NO_VARIABLES:
1449 arg_touch_variables = false;
1450 break;
1451
1452 case ARG_NO_PAGER:
1453 arg_pager_flags |= PAGER_DISABLE;
1454 break;
1455
1456 case ARG_GRACEFUL:
1457 arg_graceful = true;
1458 break;
1459
1460 case ARG_ENTRY_TOKEN: {
1461 const char *e;
1462
1463 if (streq(optarg, "machine-id")) {
1464 arg_entry_token_type = ARG_ENTRY_TOKEN_MACHINE_ID;
1465 arg_entry_token = mfree(arg_entry_token);
1466 } else if (streq(optarg, "os-image-id")) {
1467 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_IMAGE_ID;
1468 arg_entry_token = mfree(arg_entry_token);
1469 } else if (streq(optarg, "os-id")) {
1470 arg_entry_token_type = ARG_ENTRY_TOKEN_OS_ID;
1471 arg_entry_token = mfree(arg_entry_token);
1472 } else if ((e = startswith(optarg, "literal:"))) {
1473 arg_entry_token_type = ARG_ENTRY_TOKEN_LITERAL;
1474
1475 r = free_and_strdup_warn(&arg_entry_token, e);
1476 if (r < 0)
1477 return r;
1478 } else
1479 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1480 "Unexpected parameter for --entry-token=: %s", optarg);
1481
1482 break;
1483 }
1484
1485 case ARG_MAKE_ENTRY_DIRECTORY:
1486 if (streq(optarg, "auto")) /* retained for backwards compatibility */
1487 arg_make_entry_directory = -1; /* yes if machine-id is permanent */
1488 else {
1489 r = parse_boolean_argument("--make-entry-directory=", optarg, &b);
1490 if (r < 0)
1491 return r;
1492
1493 arg_make_entry_directory = b;
1494 }
1495 break;
1496
1497 case '?':
1498 return -EINVAL;
1499
1500 default:
1501 assert_not_reached();
1502 }
1503
1504 return 1;
1505 }
1506
1507 static void read_efi_var(const char *variable, char **ret) {
1508 int r;
1509
1510 r = efi_get_variable_string(variable, ret);
1511 if (r < 0 && r != -ENOENT)
1512 log_warning_errno(r, "Failed to read EFI variable %s: %m", variable);
1513 }
1514
1515 static void print_yes_no_line(bool first, bool good, const char *name) {
1516 printf("%s%s %s\n",
1517 first ? " Features: " : " ",
1518 COLOR_MARK_BOOL(good),
1519 name);
1520 }
1521
1522 static int are_we_installed(void) {
1523 int r;
1524
1525 r = acquire_esp(/* privileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, NULL, NULL);
1526 if (r < 0)
1527 return r;
1528
1529 /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
1530 * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
1531 * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
1532 * should be a suitable and very minimal check for a number of reasons:
1533 *
1534 * → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
1535 * not a specific one.)
1536 *
1537 * → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
1538 * /EFI/BOOT/BOOT*.EFI fallback binary.
1539 *
1540 * → It specifically checks for systemd-boot, not for other boot loaders (which a check for
1541 * /boot/loader/entries would do). */
1542
1543 _cleanup_free_ char *p = path_join(arg_esp_path, "/EFI/systemd/");
1544 if (!p)
1545 return log_oom();
1546
1547 log_debug("Checking whether %s contains any files…", p);
1548 r = dir_is_empty(p);
1549 if (r < 0 && r != -ENOENT)
1550 return log_error_errno(r, "Failed to check whether %s contains any files: %m", p);
1551
1552 return r == 0;
1553 }
1554
1555 static int verb_status(int argc, char *argv[], void *userdata) {
1556 sd_id128_t esp_uuid = SD_ID128_NULL, xbootldr_uuid = SD_ID128_NULL;
1557 dev_t esp_devid = 0, xbootldr_devid = 0;
1558 int r, k;
1559
1560 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, &esp_uuid, &esp_devid);
1561 if (arg_print_esp_path) {
1562 if (r == -EACCES) /* If we couldn't acquire the ESP path, log about access errors (which is the only
1563 * error the find_esp_and_warn() won't log on its own) */
1564 return log_error_errno(r, "Failed to determine ESP location: %m");
1565 if (r < 0)
1566 return r;
1567
1568 puts(arg_esp_path);
1569 }
1570
1571 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, &xbootldr_uuid, &xbootldr_devid);
1572 if (arg_print_dollar_boot_path) {
1573 if (r == -EACCES)
1574 return log_error_errno(r, "Failed to determine XBOOTLDR location: %m");
1575 if (r < 0)
1576 return r;
1577
1578 const char *path = arg_dollar_boot_path();
1579 if (!path)
1580 return log_error_errno(SYNTHETIC_ERRNO(EACCES), "Failed to determine XBOOTLDR location: %m");
1581
1582 puts(path);
1583 }
1584
1585 if (arg_print_esp_path || arg_print_dollar_boot_path)
1586 return 0;
1587
1588 r = 0; /* If we couldn't determine the path, then don't consider that a problem from here on, just show what we
1589 * can show */
1590
1591 pager_open(arg_pager_flags);
1592
1593 if (is_efi_boot()) {
1594 static const struct {
1595 uint64_t flag;
1596 const char *name;
1597 } flags[] = {
1598 { EFI_LOADER_FEATURE_BOOT_COUNTING, "Boot counting" },
1599 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT, "Menu timeout control" },
1600 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT, "One-shot menu timeout control" },
1601 { EFI_LOADER_FEATURE_ENTRY_DEFAULT, "Default entry control" },
1602 { EFI_LOADER_FEATURE_ENTRY_ONESHOT, "One-shot entry control" },
1603 { EFI_LOADER_FEATURE_XBOOTLDR, "Support for XBOOTLDR partition" },
1604 { EFI_LOADER_FEATURE_RANDOM_SEED, "Support for passing random seed to OS" },
1605 { EFI_LOADER_FEATURE_LOAD_DRIVER, "Load drop-in drivers" },
1606 };
1607
1608 _cleanup_free_ char *fw_type = NULL, *fw_info = NULL, *loader = NULL, *loader_path = NULL, *stub = NULL;
1609 sd_id128_t loader_part_uuid = SD_ID128_NULL;
1610 uint64_t loader_features = 0;
1611 int have;
1612
1613 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareType), &fw_type);
1614 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareInfo), &fw_info);
1615 read_efi_var(EFI_LOADER_VARIABLE(LoaderInfo), &loader);
1616 read_efi_var(EFI_LOADER_VARIABLE(StubInfo), &stub);
1617 read_efi_var(EFI_LOADER_VARIABLE(LoaderImageIdentifier), &loader_path);
1618 (void) efi_loader_get_features(&loader_features);
1619
1620 if (loader_path)
1621 efi_tilt_backslashes(loader_path);
1622
1623 k = efi_loader_get_device_part_uuid(&loader_part_uuid);
1624 if (k < 0 && k != -ENOENT)
1625 r = log_warning_errno(k, "Failed to read EFI variable LoaderDevicePartUUID: %m");
1626
1627 SecureBootMode secure = efi_get_secure_boot_mode();
1628 printf("System:\n");
1629 printf(" Firmware: %s%s (%s)%s\n", ansi_highlight(), strna(fw_type), strna(fw_info), ansi_normal());
1630 printf(" Secure Boot: %sd (%s)\n",
1631 enable_disable(IN_SET(secure, SECURE_BOOT_USER, SECURE_BOOT_DEPLOYED)),
1632 secure_boot_mode_to_string(secure));
1633 printf(" TPM2 Support: %s\n", yes_no(efi_has_tpm2()));
1634
1635 k = efi_get_reboot_to_firmware();
1636 if (k > 0)
1637 printf(" Boot into FW: %sactive%s\n", ansi_highlight_yellow(), ansi_normal());
1638 else if (k == 0)
1639 printf(" Boot into FW: supported\n");
1640 else if (k == -EOPNOTSUPP)
1641 printf(" Boot into FW: not supported\n");
1642 else {
1643 errno = -k;
1644 printf(" Boot into FW: %sfailed%s (%m)\n", ansi_highlight_red(), ansi_normal());
1645 }
1646 printf("\n");
1647
1648 printf("Current Boot Loader:\n");
1649 printf(" Product: %s%s%s\n", ansi_highlight(), strna(loader), ansi_normal());
1650
1651 for (size_t i = 0; i < ELEMENTSOF(flags); i++)
1652 print_yes_no_line(i == 0, FLAGS_SET(loader_features, flags[i].flag), flags[i].name);
1653
1654 sd_id128_t bootloader_esp_uuid;
1655 bool have_bootloader_esp_uuid = efi_loader_get_device_part_uuid(&bootloader_esp_uuid) >= 0;
1656
1657 print_yes_no_line(false, have_bootloader_esp_uuid, "Boot loader sets ESP information");
1658 if (have_bootloader_esp_uuid && !sd_id128_equal(esp_uuid, bootloader_esp_uuid))
1659 printf("WARNING: The boot loader reports a different ESP UUID than detected!\n");
1660
1661 if (stub)
1662 printf(" Stub: %s\n", stub);
1663 if (!sd_id128_is_null(loader_part_uuid))
1664 printf(" ESP: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR "\n",
1665 SD_ID128_FORMAT_VAL(loader_part_uuid));
1666 else
1667 printf(" ESP: n/a\n");
1668 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), strna(loader_path));
1669 printf("\n");
1670
1671 printf("Random Seed:\n");
1672 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderRandomSeed)), F_OK) >= 0;
1673 printf(" Passed to OS: %s\n", yes_no(have));
1674 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderSystemToken)), F_OK) >= 0;
1675 printf(" System Token: %s\n", have ? "set" : "not set");
1676
1677 if (arg_esp_path) {
1678 _cleanup_free_ char *p = NULL;
1679
1680 p = path_join(arg_esp_path, "/loader/random-seed");
1681 if (!p)
1682 return log_oom();
1683
1684 have = access(p, F_OK) >= 0;
1685 printf(" Exists: %s\n", yes_no(have));
1686 }
1687
1688 printf("\n");
1689 } else
1690 printf("System:\n Not booted with EFI\n\n");
1691
1692 if (arg_esp_path) {
1693 k = status_binaries(arg_esp_path, esp_uuid);
1694 if (k < 0)
1695 r = k;
1696 }
1697
1698 if (is_efi_boot()) {
1699 k = status_variables();
1700 if (k < 0)
1701 r = k;
1702 }
1703
1704 if (arg_esp_path || arg_xbootldr_path) {
1705 /* If XBOOTLDR and ESP actually refer to the same block device, suppress XBOOTLDR, since it would find the same entries twice */
1706 bool same = arg_esp_path && arg_xbootldr_path && devid_set_and_equal(esp_devid, xbootldr_devid);
1707
1708 k = status_entries(
1709 arg_esp_path,
1710 esp_uuid,
1711 same ? NULL : arg_xbootldr_path,
1712 same ? SD_ID128_NULL : xbootldr_uuid);
1713 if (k < 0)
1714 r = k;
1715 }
1716
1717 return r;
1718 }
1719
1720 static int verb_list(int argc, char *argv[], void *userdata) {
1721 _cleanup_(boot_config_free) BootConfig config = {};
1722 _cleanup_strv_free_ char **efi_entries = NULL;
1723 dev_t esp_devid = 0, xbootldr_devid = 0;
1724 int r;
1725
1726 /* If we lack privileges we invoke find_esp_and_warn() in "unprivileged mode" here, which does two things: turn
1727 * off logging about access errors and turn off potentially privileged device probing. Here we're interested in
1728 * the latter but not the former, hence request the mode, and log about EACCES. */
1729
1730 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, NULL, &esp_devid);
1731 if (r == -EACCES) /* We really need the ESP path for this call, hence also log about access errors */
1732 return log_error_errno(r, "Failed to determine ESP: %m");
1733 if (r < 0)
1734 return r;
1735
1736 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, NULL, &xbootldr_devid);
1737 if (r == -EACCES)
1738 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1739 if (r < 0)
1740 return r;
1741
1742 /* If XBOOTLDR and ESP actually refer to the same block device, suppress XBOOTLDR, since it would find the same entries twice */
1743 bool same = arg_esp_path && arg_xbootldr_path && devid_set_and_equal(esp_devid, xbootldr_devid);
1744
1745 r = boot_entries_load_config(arg_esp_path, same ? NULL : arg_xbootldr_path, &config);
1746 if (r < 0)
1747 return r;
1748
1749 r = efi_loader_get_entries(&efi_entries);
1750 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
1751 log_debug_errno(r, "Boot loader reported no entries.");
1752 else if (r < 0)
1753 log_warning_errno(r, "Failed to determine entries reported by boot loader, ignoring: %m");
1754 else
1755 (void) boot_entries_augment_from_loader(&config, efi_entries, /* only_auto= */ false);
1756
1757 if (config.n_entries == 0)
1758 log_info("No boot loader entries found.");
1759 else {
1760 pager_open(arg_pager_flags);
1761
1762 printf("Boot Loader Entries:\n");
1763
1764 for (size_t n = 0; n < config.n_entries; n++) {
1765 r = boot_entry_show(
1766 config.entries + n,
1767 /* show_as_default= */ n == (size_t) config.default_entry,
1768 /* show_as_selected= */ n == (size_t) config.selected_entry,
1769 /* show_discovered= */ true);
1770 if (r < 0)
1771 return r;
1772
1773 if (n+1 < config.n_entries)
1774 putchar('\n');
1775 }
1776 }
1777
1778 return 0;
1779 }
1780
1781 static int install_random_seed(const char *esp) {
1782 _cleanup_(unlink_and_freep) char *tmp = NULL;
1783 _cleanup_free_ void *buffer = NULL;
1784 _cleanup_free_ char *path = NULL;
1785 _cleanup_close_ int fd = -1;
1786 size_t sz, token_size;
1787 ssize_t n;
1788 int r;
1789
1790 assert(esp);
1791
1792 path = path_join(esp, "/loader/random-seed");
1793 if (!path)
1794 return log_oom();
1795
1796 sz = random_pool_size();
1797
1798 buffer = malloc(sz);
1799 if (!buffer)
1800 return log_oom();
1801
1802 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1803 if (r < 0)
1804 return log_error_errno(r, "Failed to acquire random seed: %m");
1805
1806 /* Normally create_subdirs() should already have created everything we need, but in case "bootctl
1807 * random-seed" is called we want to just create the minimum we need for it, and not the full
1808 * list. */
1809 r = mkdir_parents(path, 0755);
1810 if (r < 0)
1811 return log_error_errno(r, "Failed to create parent directory for %s: %m", path);
1812
1813 r = tempfn_random(path, "bootctl", &tmp);
1814 if (r < 0)
1815 return log_oom();
1816
1817 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|O_WRONLY|O_CLOEXEC, 0600);
1818 if (fd < 0) {
1819 tmp = mfree(tmp);
1820 return log_error_errno(fd, "Failed to open random seed file for writing: %m");
1821 }
1822
1823 n = write(fd, buffer, sz);
1824 if (n < 0)
1825 return log_error_errno(errno, "Failed to write random seed file: %m");
1826 if ((size_t) n != sz)
1827 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while writing random seed file.");
1828
1829 if (rename(tmp, path) < 0)
1830 return log_error_errno(r, "Failed to move random seed file into place: %m");
1831
1832 tmp = mfree(tmp);
1833
1834 log_info("Random seed file %s successfully written (%zu bytes).", path, sz);
1835
1836 if (!arg_touch_variables)
1837 return 0;
1838
1839 if (!is_efi_boot()) {
1840 log_notice("Not booted with EFI, skipping EFI variable setup.");
1841 return 0;
1842 }
1843
1844 r = getenv_bool("SYSTEMD_WRITE_SYSTEM_TOKEN");
1845 if (r < 0) {
1846 if (r != -ENXIO)
1847 log_warning_errno(r, "Failed to parse $SYSTEMD_WRITE_SYSTEM_TOKEN, ignoring.");
1848
1849 if (detect_vm() > 0) {
1850 /* Let's not write a system token if we detect we are running in a VM
1851 * environment. Why? Our default security model for the random seed uses the system
1852 * token as a mechanism to ensure we are not vulnerable to golden master sloppiness
1853 * issues, i.e. that people initialize the random seed file, then copy the image to
1854 * many systems and end up with the same random seed in each that is assumed to be
1855 * valid but in reality is the same for all machines. By storing a system token in
1856 * the EFI variable space we can make sure that even though the random seeds on disk
1857 * are all the same they will be different on each system under the assumption that
1858 * the EFI variable space is maintained separate from the random seed storage. That
1859 * is generally the case on physical systems, as the ESP is stored on persistent
1860 * storage, and the EFI variables in NVRAM. However in virtualized environments this
1861 * is generally not true: the EFI variable set is typically stored along with the
1862 * disk image itself. For example, using the OVMF EFI firmware the EFI variables are
1863 * stored in a file in the ESP itself. */
1864
1865 log_notice("Not installing system token, since we are running in a virtualized environment.");
1866 return 0;
1867 }
1868 } else if (r == 0) {
1869 log_notice("Not writing system token, because $SYSTEMD_WRITE_SYSTEM_TOKEN is set to false.");
1870 return 0;
1871 }
1872
1873 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), NULL, NULL, &token_size);
1874 if (r == -ENODATA)
1875 log_debug_errno(r, "LoaderSystemToken EFI variable is invalid (too short?), replacing.");
1876 else if (r < 0) {
1877 if (r != -ENOENT)
1878 return log_error_errno(r, "Failed to test system token validity: %m");
1879 } else {
1880 if (token_size >= sz) {
1881 /* Let's avoid writes if we can, and initialize this only once. */
1882 log_debug("System token already written, not updating.");
1883 return 0;
1884 }
1885
1886 log_debug("Existing system token size (%zu) does not match our expectations (%zu), replacing.", token_size, sz);
1887 }
1888
1889 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1890 if (r < 0)
1891 return log_error_errno(r, "Failed to acquire random seed: %m");
1892
1893 /* Let's write this variable with an umask in effect, so that unprivileged users can't see the token
1894 * and possibly get identification information or too much insight into the kernel's entropy pool
1895 * state. */
1896 RUN_WITH_UMASK(0077) {
1897 r = efi_set_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), buffer, sz);
1898 if (r < 0) {
1899 if (!arg_graceful)
1900 return log_error_errno(r, "Failed to write 'LoaderSystemToken' EFI variable: %m");
1901
1902 if (r == -EINVAL)
1903 log_warning_errno(r, "Unable to write 'LoaderSystemToken' EFI variable (firmware problem?), ignoring: %m");
1904 else
1905 log_warning_errno(r, "Unable to write 'LoaderSystemToken' EFI variable, ignoring: %m");
1906 } else
1907 log_info("Successfully initialized system token in EFI variable with %zu bytes.", sz);
1908 }
1909
1910 return 0;
1911 }
1912
1913 static int sync_everything(void) {
1914 int ret = 0, k;
1915
1916 if (arg_esp_path) {
1917 k = syncfs_path(AT_FDCWD, arg_esp_path);
1918 if (k < 0)
1919 ret = log_error_errno(k, "Failed to synchronize the ESP '%s': %m", arg_esp_path);
1920 }
1921
1922 if (arg_xbootldr_path) {
1923 k = syncfs_path(AT_FDCWD, arg_xbootldr_path);
1924 if (k < 0)
1925 ret = log_error_errno(k, "Failed to synchronize $BOOT '%s': %m", arg_xbootldr_path);
1926 }
1927
1928 return ret;
1929 }
1930
1931 static int verb_install(int argc, char *argv[], void *userdata) {
1932 sd_id128_t uuid = SD_ID128_NULL;
1933 uint64_t pstart = 0, psize = 0;
1934 uint32_t part = 0;
1935 bool install, graceful;
1936 int r;
1937
1938 /* Invoked for both "update" and "install" */
1939
1940 install = streq(argv[0], "install");
1941 graceful = !install && arg_graceful; /* support graceful mode for updates */
1942
1943 r = acquire_esp(/* unprivileged_mode= */ false, graceful, &part, &pstart, &psize, &uuid, NULL);
1944 if (graceful && r == -ENOKEY)
1945 return 0; /* If --graceful is specified and we can't find an ESP, handle this cleanly */
1946 if (r < 0)
1947 return r;
1948
1949 if (!install) {
1950 /* If we are updating, don't do anything if sd-boot wasn't actually installed. */
1951 r = are_we_installed();
1952 if (r < 0)
1953 return r;
1954 if (r == 0) {
1955 log_debug("Skipping update because sd-boot is not installed in the ESP.");
1956 return 0;
1957 }
1958 }
1959
1960 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
1961 if (r < 0)
1962 return r;
1963
1964 r = settle_make_entry_directory();
1965 if (r < 0)
1966 return r;
1967
1968 RUN_WITH_UMASK(0002) {
1969 if (install) {
1970 /* Don't create any of these directories when we are just updating. When we update
1971 * we'll drop-in our files (unless there are newer ones already), but we won't create
1972 * the directories for them in the first place. */
1973 r = create_subdirs(arg_esp_path, esp_subdirs);
1974 if (r < 0)
1975 return r;
1976
1977 r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
1978 if (r < 0)
1979 return r;
1980 }
1981
1982 r = install_binaries(arg_esp_path, install);
1983 if (r < 0)
1984 return r;
1985
1986 if (install) {
1987 r = install_loader_config(arg_esp_path);
1988 if (r < 0)
1989 return r;
1990
1991 r = install_entry_directory(arg_dollar_boot_path());
1992 if (r < 0)
1993 return r;
1994
1995 r = install_entry_token();
1996 if (r < 0)
1997 return r;
1998
1999 r = install_random_seed(arg_esp_path);
2000 if (r < 0)
2001 return r;
2002 }
2003 }
2004
2005 (void) sync_everything();
2006
2007 if (arg_touch_variables)
2008 r = install_variables(arg_esp_path,
2009 part, pstart, psize, uuid,
2010 "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi",
2011 install);
2012
2013 return r;
2014 }
2015
2016 static int verb_remove(int argc, char *argv[], void *userdata) {
2017 sd_id128_t uuid = SD_ID128_NULL;
2018 int r, q;
2019
2020 r = acquire_esp(/* unprivileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, &uuid, NULL);
2021 if (r < 0)
2022 return r;
2023
2024 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
2025 if (r < 0)
2026 return r;
2027
2028 r = settle_make_entry_directory();
2029 if (r < 0)
2030 return r;
2031
2032 r = remove_binaries(arg_esp_path);
2033
2034 q = remove_file(arg_esp_path, "/loader/loader.conf");
2035 if (q < 0 && r >= 0)
2036 r = q;
2037
2038 q = remove_file(arg_esp_path, "/loader/random-seed");
2039 if (q < 0 && r >= 0)
2040 r = q;
2041
2042 q = remove_subdirs(arg_esp_path, esp_subdirs);
2043 if (q < 0 && r >= 0)
2044 r = q;
2045
2046 q = remove_subdirs(arg_esp_path, dollar_boot_subdirs);
2047 if (q < 0 && r >= 0)
2048 r = q;
2049
2050 q = remove_entry_directory(arg_esp_path);
2051 if (q < 0 && r >= 0)
2052 r = q;
2053
2054 if (arg_xbootldr_path) {
2055 /* Remove the latter two also in the XBOOTLDR partition if it exists */
2056 q = remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs);
2057 if (q < 0 && r >= 0)
2058 r = q;
2059
2060 q = remove_entry_directory(arg_xbootldr_path);
2061 if (q < 0 && r >= 0)
2062 r = q;
2063 }
2064
2065 (void) sync_everything();
2066
2067 if (!arg_touch_variables)
2068 return r;
2069
2070 q = remove_variables(uuid, "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi", true);
2071 if (q < 0 && r >= 0)
2072 r = q;
2073
2074 q = remove_loader_variables();
2075 if (q < 0 && r >= 0)
2076 r = q;
2077
2078 return r;
2079 }
2080
2081 static int verb_is_installed(int argc, char *argv[], void *userdata) {
2082 int r;
2083
2084 r = are_we_installed();
2085 if (r < 0)
2086 return r;
2087
2088 if (r > 0) {
2089 puts("yes");
2090 return EXIT_SUCCESS;
2091 } else {
2092 puts("no");
2093 return EXIT_FAILURE;
2094 }
2095 }
2096
2097 static int parse_timeout(const char *arg1, char16_t **ret_timeout, size_t *ret_timeout_size) {
2098 char utf8[DECIMAL_STR_MAX(usec_t)];
2099 char16_t *encoded;
2100 usec_t timeout;
2101 int r;
2102
2103 assert(arg1);
2104 assert(ret_timeout);
2105 assert(ret_timeout_size);
2106
2107 if (streq(arg1, "menu-force"))
2108 timeout = USEC_INFINITY;
2109 else if (streq(arg1, "menu-hidden"))
2110 timeout = 0;
2111 else {
2112 r = parse_time(arg1, &timeout, USEC_PER_SEC);
2113 if (r < 0)
2114 return log_error_errno(r, "Failed to parse timeout '%s': %m", arg1);
2115 if (timeout != USEC_INFINITY && timeout > UINT32_MAX * USEC_PER_SEC)
2116 log_warning("Timeout is too long and will be treated as 'menu-force' instead.");
2117 }
2118
2119 xsprintf(utf8, USEC_FMT, MIN(timeout / USEC_PER_SEC, UINT32_MAX));
2120
2121 encoded = utf8_to_utf16(utf8, strlen(utf8));
2122 if (!encoded)
2123 return log_oom();
2124
2125 *ret_timeout = encoded;
2126 *ret_timeout_size = char16_strlen(encoded) * 2 + 2;
2127 return 0;
2128 }
2129
2130 static int parse_loader_entry_target_arg(const char *arg1, char16_t **ret_target, size_t *ret_target_size) {
2131 char16_t *encoded = NULL;
2132 int r;
2133
2134 assert(arg1);
2135 assert(ret_target);
2136 assert(ret_target_size);
2137
2138 if (streq(arg1, "@current")) {
2139 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntrySelected), NULL, (void *) ret_target, ret_target_size);
2140 if (r < 0)
2141 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntrySelected': %m");
2142
2143 } else if (streq(arg1, "@oneshot")) {
2144 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryOneShot), NULL, (void *) ret_target, ret_target_size);
2145 if (r < 0)
2146 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryOneShot': %m");
2147
2148 } else if (streq(arg1, "@default")) {
2149 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryDefault), NULL, (void *) ret_target, ret_target_size);
2150 if (r < 0)
2151 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryDefault': %m");
2152
2153 } else if (arg1[0] == '@' && !streq(arg1, "@saved"))
2154 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unsupported special entry identifier: %s", arg1);
2155 else {
2156 encoded = utf8_to_utf16(arg1, strlen(arg1));
2157 if (!encoded)
2158 return log_oom();
2159
2160 *ret_target = encoded;
2161 *ret_target_size = char16_strlen(encoded) * 2 + 2;
2162 }
2163
2164 return 0;
2165 }
2166
2167 static int verb_set_efivar(int argc, char *argv[], void *userdata) {
2168 int r;
2169
2170 if (!is_efi_boot())
2171 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2172 "Not booted with UEFI.");
2173
2174 if (access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderInfo)), F_OK) < 0) {
2175 if (errno == ENOENT) {
2176 log_error_errno(errno, "Not booted with a supported boot loader.");
2177 return -EOPNOTSUPP;
2178 }
2179
2180 return log_error_errno(errno, "Failed to detect whether boot loader supports '%s' operation: %m", argv[0]);
2181 }
2182
2183 if (detect_container() > 0)
2184 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2185 "'%s' operation not supported in a container.",
2186 argv[0]);
2187
2188 if (!arg_touch_variables)
2189 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2190 "'%s' operation cannot be combined with --no-variables.",
2191 argv[0]);
2192
2193 const char *variable;
2194 int (* arg_parser)(const char *, char16_t **, size_t *);
2195
2196 if (streq(argv[0], "set-default")) {
2197 variable = EFI_LOADER_VARIABLE(LoaderEntryDefault);
2198 arg_parser = parse_loader_entry_target_arg;
2199 } else if (streq(argv[0], "set-oneshot")) {
2200 variable = EFI_LOADER_VARIABLE(LoaderEntryOneShot);
2201 arg_parser = parse_loader_entry_target_arg;
2202 } else if (streq(argv[0], "set-timeout")) {
2203 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeout);
2204 arg_parser = parse_timeout;
2205 } else if (streq(argv[0], "set-timeout-oneshot")) {
2206 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot);
2207 arg_parser = parse_timeout;
2208 } else
2209 assert_not_reached();
2210
2211 if (isempty(argv[1])) {
2212 r = efi_set_variable(variable, NULL, 0);
2213 if (r < 0 && r != -ENOENT)
2214 return log_error_errno(r, "Failed to remove EFI variable '%s': %m", variable);
2215 } else {
2216 _cleanup_free_ char16_t *value = NULL;
2217 size_t value_size = 0;
2218
2219 r = arg_parser(argv[1], &value, &value_size);
2220 if (r < 0)
2221 return r;
2222 r = efi_set_variable(variable, value, value_size);
2223 if (r < 0)
2224 return log_error_errno(r, "Failed to update EFI variable '%s': %m", variable);
2225 }
2226
2227 return 0;
2228 }
2229
2230 static int verb_random_seed(int argc, char *argv[], void *userdata) {
2231 int r;
2232
2233 r = find_esp_and_warn(arg_esp_path, false, &arg_esp_path, NULL, NULL, NULL, NULL, NULL);
2234 if (r == -ENOKEY) {
2235 /* find_esp_and_warn() doesn't warn about ENOKEY, so let's do that on our own */
2236 if (!arg_graceful)
2237 return log_error_errno(r, "Unable to find ESP.");
2238
2239 log_notice("No ESP found, not initializing random seed.");
2240 return 0;
2241 }
2242 if (r < 0)
2243 return r;
2244
2245 r = install_random_seed(arg_esp_path);
2246 if (r < 0)
2247 return r;
2248
2249 (void) sync_everything();
2250 return 0;
2251 }
2252
2253 static int verb_systemd_efi_options(int argc, char *argv[], void *userdata) {
2254 int r;
2255
2256 if (argc == 1) {
2257 _cleanup_free_ char *line = NULL, *new = NULL;
2258
2259 r = systemd_efi_options_variable(&line);
2260 if (r == -ENODATA)
2261 log_debug("No SystemdOptions EFI variable present in cache.");
2262 else if (r < 0)
2263 return log_error_errno(r, "Failed to read SystemdOptions EFI variable from cache: %m");
2264 else
2265 puts(line);
2266
2267 r = systemd_efi_options_efivarfs_if_newer(&new);
2268 if (r == -ENODATA) {
2269 if (line)
2270 log_notice("Note: SystemdOptions EFI variable has been removed since boot.");
2271 } else if (r < 0)
2272 log_warning_errno(r, "Failed to check SystemdOptions EFI variable in efivarfs, ignoring: %m");
2273 else if (new && !streq_ptr(line, new))
2274 log_notice("Note: SystemdOptions EFI variable has been modified since boot. New value: %s",
2275 new);
2276 } else {
2277 r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE(SystemdOptions), argv[1]);
2278 if (r < 0)
2279 return log_error_errno(r, "Failed to set SystemdOptions EFI variable: %m");
2280 }
2281
2282 return 0;
2283 }
2284
2285 static int verb_reboot_to_firmware(int argc, char *argv[], void *userdata) {
2286 int r;
2287
2288 if (argc < 2) {
2289 r = efi_get_reboot_to_firmware();
2290 if (r > 0) {
2291 puts("active");
2292 return EXIT_SUCCESS; /* success */
2293 }
2294 if (r == 0) {
2295 puts("supported");
2296 return 1; /* recognizable error #1 */
2297 }
2298 if (r == -EOPNOTSUPP) {
2299 puts("not supported");
2300 return 2; /* recognizable error #2 */
2301 }
2302
2303 log_error_errno(r, "Failed to query reboot-to-firmware state: %m");
2304 return 3; /* other kind of error */
2305 } else {
2306 r = parse_boolean(argv[1]);
2307 if (r < 0)
2308 return log_error_errno(r, "Failed to parse argument: %s", argv[1]);
2309
2310 r = efi_set_reboot_to_firmware(r);
2311 if (r < 0)
2312 return log_error_errno(r, "Failed to set reboot-to-firmware option: %m");
2313
2314 return 0;
2315 }
2316 }
2317
2318 static int bootctl_main(int argc, char *argv[]) {
2319 static const Verb verbs[] = {
2320 { "help", VERB_ANY, VERB_ANY, 0, help },
2321 { "status", VERB_ANY, 1, VERB_DEFAULT, verb_status },
2322 { "install", VERB_ANY, 1, 0, verb_install },
2323 { "update", VERB_ANY, 1, 0, verb_install },
2324 { "remove", VERB_ANY, 1, 0, verb_remove },
2325 { "is-installed", VERB_ANY, 1, 0, verb_is_installed },
2326 { "list", VERB_ANY, 1, 0, verb_list },
2327 { "set-default", 2, 2, 0, verb_set_efivar },
2328 { "set-oneshot", 2, 2, 0, verb_set_efivar },
2329 { "set-timeout", 2, 2, 0, verb_set_efivar },
2330 { "set-timeout-oneshot", 2, 2, 0, verb_set_efivar },
2331 { "random-seed", VERB_ANY, 1, 0, verb_random_seed },
2332 { "systemd-efi-options", VERB_ANY, 2, 0, verb_systemd_efi_options },
2333 { "reboot-to-firmware", VERB_ANY, 2, 0, verb_reboot_to_firmware },
2334 {}
2335 };
2336
2337 return dispatch_verb(argc, argv, verbs, NULL);
2338 }
2339
2340 static int run(int argc, char *argv[]) {
2341 int r;
2342
2343 log_parse_environment();
2344 log_open();
2345
2346 /* If we run in a container, automatically turn off EFI file system access */
2347 if (detect_container() > 0)
2348 arg_touch_variables = false;
2349
2350 r = parse_argv(argc, argv);
2351 if (r <= 0)
2352 return r;
2353
2354 return bootctl_main(argc, argv);
2355 }
2356
2357 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);