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