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