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