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