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