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