]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/boot/bootctl.c
pretty-print: add helper for quickly outputting red/green cross/check marks
[thirdparty/systemd.git] / src / boot / bootctl.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
7b4d7cc0 2
0974a682 3#include <ctype.h>
3f6fd1ba 4#include <errno.h>
3f6fd1ba
LP
5#include <getopt.h>
6#include <limits.h>
5fa6c13c 7#include <linux/magic.h>
0974a682 8#include <stdbool.h>
3f6fd1ba 9#include <stdlib.h>
3f6fd1ba 10#include <sys/mman.h>
3f6fd1ba 11#include <unistd.h>
7b4d7cc0 12
dccca82b
LP
13#include "sd-id128.h"
14
b5efdb8a 15#include "alloc-util.h"
3f6fd1ba 16#include "blkid-util.h"
7e87c7d9 17#include "bootspec.h"
175d308c 18#include "copy.h"
e41256dc 19#include "dirent-util.h"
0bb2f0f1 20#include "efi-loader.h"
0974a682 21#include "efivars.h"
e44c3229 22#include "env-util.h"
9dae4c8a 23#include "escape.h"
3ffd4af2 24#include "fd-util.h"
0d39fa9c 25#include "fileio.h"
175d308c 26#include "fs-util.h"
d8e32c47 27#include "glyph-util.h"
608f8ec9 28#include "main-func.h"
a4a55e9a 29#include "mkdir.h"
57db6f18 30#include "pager.h"
6a3fff75 31#include "parse-argument.h"
2f2c539c 32#include "parse-util.h"
294bf0c3 33#include "pretty-print.h"
e44c3229 34#include "random-util.h"
c6878637 35#include "rm-rf.h"
175d308c 36#include "stat-util.h"
341890de 37#include "stdio-util.h"
07630cea 38#include "string-util.h"
2f2c539c 39#include "strv.h"
bf819d3a 40#include "sync-util.h"
7e87c7d9 41#include "terminal-util.h"
e4de7287 42#include "tmpfile-util.h"
2f2c539c 43#include "umask-util.h"
d88c96ff 44#include "utf8.h"
3f6fd1ba 45#include "util.h"
2f2c539c
LP
46#include "verbs.h"
47#include "virt.h"
7b4d7cc0 48
fbf45d22
LP
49static char *arg_esp_path = NULL;
50static char *arg_xbootldr_path = NULL;
51static bool arg_print_esp_path = false;
52static bool arg_print_dollar_boot_path = false;
25579a43 53static bool arg_touch_variables = true;
0221d68a 54static PagerFlags arg_pager_flags = 0;
351de38e 55static bool arg_graceful = false;
6a3fff75 56static int arg_make_machine_id_directory = -1;
25579a43 57
fbf45d22
LP
58STATIC_DESTRUCTOR_REGISTER(arg_esp_path, freep);
59STATIC_DESTRUCTOR_REGISTER(arg_xbootldr_path, freep);
60
61static const char *arg_dollar_boot_path(void) {
62 /* $BOOT shall be the XBOOTLDR partition if it exists, and otherwise the ESP */
63 return arg_xbootldr_path ?: arg_esp_path;
64}
608f8ec9 65
5caa3167
LP
66static int acquire_esp(
67 bool unprivileged_mode,
e5a8b4b5 68 bool graceful,
5caa3167
LP
69 uint32_t *ret_part,
70 uint64_t *ret_pstart,
71 uint64_t *ret_psize,
72 sd_id128_t *ret_uuid) {
73
74 char *np;
2f2c539c
LP
75 int r;
76
fbf45d22
LP
77 /* Find the ESP, and log about errors. Note that find_esp_and_warn() will log in all error cases on
78 * its own, except for ENOKEY (which is good, we want to show our own message in that case,
79 * suggesting use of --esp-path=) and EACCESS (only when we request unprivileged mode; in this case
80 * we simply eat up the error here, so that --list and --status work too, without noise about
81 * this). */
5caa3167 82
fbf45d22 83 r = find_esp_and_warn(arg_esp_path, unprivileged_mode, &np, ret_part, ret_pstart, ret_psize, ret_uuid);
e5a8b4b5
LP
84 if (r == -ENOKEY) {
85 if (graceful)
86 return log_info_errno(r, "Couldn't find EFI system partition, skipping.");
87
af918182 88 return log_error_errno(r,
5caa3167 89 "Couldn't find EFI system partition. It is recommended to mount it to /boot or /efi.\n"
fbf45d22 90 "Alternatively, use --esp-path= to specify path to mount point.");
e5a8b4b5 91 }
5caa3167
LP
92 if (r < 0)
93 return r;
94
fbf45d22
LP
95 free_and_replace(arg_esp_path, np);
96 log_debug("Using EFI System Partition at %s.", arg_esp_path);
97
98 return 1;
99}
0974a682 100
fbf45d22
LP
101static int acquire_xbootldr(bool unprivileged_mode, sd_id128_t *ret_uuid) {
102 char *np;
103 int r;
5caa3167 104
fbf45d22
LP
105 r = find_xbootldr_and_warn(arg_xbootldr_path, unprivileged_mode, &np, ret_uuid);
106 if (r == -ENOKEY) {
107 log_debug_errno(r, "Didn't find an XBOOTLDR partition, using the ESP as $BOOT.");
108 if (ret_uuid)
109 *ret_uuid = SD_ID128_NULL;
a2ae0d49 110 arg_xbootldr_path = mfree(arg_xbootldr_path);
fbf45d22
LP
111 return 0;
112 }
113 if (r < 0)
114 return r;
115
116 free_and_replace(arg_xbootldr_path, np);
117 log_debug("Using XBOOTLDR partition at %s as $BOOT.", arg_xbootldr_path);
118
119 return 1;
7b4d7cc0
KS
120}
121
6a3fff75 122static void settle_make_machine_id_directory(void) {
123 int r;
124
125 if (arg_make_machine_id_directory >= 0)
126 return;
127
128 r = path_is_temporary_fs("/etc/machine-id");
129 if (r < 0)
130 log_debug_errno(r, "Couldn't determine whether /etc/machine-id is on a temporary file system, assuming so.");
131
132 arg_make_machine_id_directory = r == 0;
133}
134
e7dd673d 135/* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */
d3226d77 136static int get_file_version(int fd, char **v) {
0974a682
KS
137 struct stat st;
138 char *buf;
139 const char *s, *e;
140 char *x = NULL;
c53aafb7 141 int r;
7b4d7cc0 142
d3226d77 143 assert(fd >= 0);
0974a682 144 assert(v);
7b4d7cc0 145
d3226d77 146 if (fstat(fd, &st) < 0)
db6d9fae 147 return log_error_errno(errno, "Failed to stat EFI binary: %m");
7b4d7cc0 148
c4ba5b51
LP
149 r = stat_verify_regular(&st);
150 if (r < 0)
d90f2add 151 return log_error_errno(r, "EFI binary is not a regular file: %m");
c4ba5b51 152
db6d9fae
LP
153 if (st.st_size < 27) {
154 *v = NULL;
0974a682 155 return 0;
db6d9fae 156 }
eb9da376 157
d3226d77 158 buf = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
0974a682 159 if (buf == MAP_FAILED)
db6d9fae 160 return log_error_errno(errno, "Failed to memory map EFI binary: %m");
7b4d7cc0 161
d8782cc5 162 s = mempmem_safe(buf, st.st_size - 8, "#### LoaderInfo: ", 17);
0974a682
KS
163 if (!s)
164 goto finish;
7b4d7cc0 165
e8b08edc 166 e = memmem_safe(s, st.st_size - (s - buf), " ####", 5);
0974a682 167 if (!e || e - s < 3) {
78d5d4ed 168 r = log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Malformed version string.");
0974a682
KS
169 goto finish;
170 }
7b4d7cc0 171
0974a682
KS
172 x = strndup(s, e - s);
173 if (!x) {
d3226d77 174 r = log_oom();
0974a682
KS
175 goto finish;
176 }
177 r = 1;
7b4d7cc0 178
0974a682 179finish:
db6d9fae 180 (void) munmap(buf, st.st_size);
0974a682
KS
181 *v = x;
182 return r;
183}
7b4d7cc0 184
0974a682 185static int enumerate_binaries(const char *esp_path, const char *path, const char *prefix) {
d3226d77 186 _cleanup_closedir_ DIR *d = NULL;
0974a682 187 struct dirent *de;
270384b2 188 const char *p;
fbf45d22 189 int c = 0, r;
fbf45d22
LP
190
191 assert(esp_path);
192 assert(path);
0974a682 193
270384b2 194 p = prefix_roota(esp_path, path);
0974a682
KS
195 d = opendir(p);
196 if (!d) {
d3226d77
ZJS
197 if (errno == ENOENT)
198 return 0;
7b4d7cc0 199
d3226d77 200 return log_error_errno(errno, "Failed to read \"%s\": %m", p);
0974a682
KS
201 }
202
e41256dc 203 FOREACH_DIRENT(de, d, break) {
d3226d77 204 _cleanup_free_ char *v = NULL;
fbf45d22 205 _cleanup_close_ int fd = -1;
0974a682 206
d3226d77 207 if (!endswith_no_case(de->d_name, ".efi"))
0974a682
KS
208 continue;
209
d3226d77 210 if (prefix && !startswith_no_case(de->d_name, prefix))
0974a682
KS
211 continue;
212
d3226d77
ZJS
213 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
214 if (fd < 0)
215 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
0974a682 216
d3226d77 217 r = get_file_version(fd, &v);
0974a682 218 if (r < 0)
d3226d77 219 return r;
0974a682 220 if (r > 0)
9a6f746f 221 printf(" File: %s/%s/%s (%s%s%s)\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path, de->d_name, ansi_highlight(), v, ansi_normal());
0974a682 222 else
9a6f746f 223 printf(" File: %s/%s/%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path, de->d_name);
fbf45d22 224
0974a682 225 c++;
0974a682
KS
226 }
227
d3226d77 228 return c;
7b4d7cc0
KS
229}
230
0974a682
KS
231static int status_binaries(const char *esp_path, sd_id128_t partition) {
232 int r;
233
7fd66f3c 234 printf("Available Boot Loaders on ESP:\n");
0974a682 235
cd2d4c7f
YW
236 if (!esp_path) {
237 printf(" ESP: Cannot find or access mount point of ESP.\n\n");
238 return -ENOENT;
239 }
240
241 printf(" ESP: %s", esp_path);
242 if (!sd_id128_is_null(partition))
bd44566c 243 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR ")", SD_ID128_FORMAT_VAL(partition));
cd2d4c7f 244 printf("\n");
0974a682
KS
245
246 r = enumerate_binaries(esp_path, "EFI/systemd", NULL);
fbf45d22 247 if (r < 0)
882b3bd6 248 goto finish;
0974a682 249 if (r == 0)
48184e43 250 log_info("systemd-boot not installed in ESP.");
0974a682 251
00f69504 252 r = enumerate_binaries(esp_path, "EFI/BOOT", "boot");
fbf45d22 253 if (r < 0)
882b3bd6 254 goto finish;
0974a682 255 if (r == 0)
48184e43 256 log_info("No default/fallback boot loader installed in ESP.");
0974a682 257
882b3bd6 258 r = 0;
c11ae0ba 259
882b3bd6
LP
260finish:
261 printf("\n");
262 return r;
0974a682
KS
263}
264
265static int print_efi_option(uint16_t id, bool in_order) {
7cb0f263
TA
266 _cleanup_free_ char *title = NULL;
267 _cleanup_free_ char *path = NULL;
0974a682
KS
268 sd_id128_t partition;
269 bool active;
c53aafb7 270 int r;
0974a682
KS
271
272 r = efi_get_boot_option(id, &title, &partition, &path, &active);
273 if (r < 0)
7cb0f263 274 return r;
7b4d7cc0 275
0974a682 276 /* print only configured entries with partition information */
3bbaff3e 277 if (!path || sd_id128_is_null(partition))
0974a682
KS
278 return 0;
279
280 efi_tilt_backslashes(path);
281
ba857253 282 printf(" Title: %s%s%s\n", ansi_highlight(), strna(title), ansi_normal());
0974a682
KS
283 printf(" ID: 0x%04X\n", id);
284 printf(" Status: %sactive%s\n", active ? "" : "in", in_order ? ", boot-order" : "");
bd44566c
ZJS
285 printf(" Partition: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR "\n",
286 SD_ID128_FORMAT_VAL(partition));
9a6f746f 287 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), path);
0974a682
KS
288 printf("\n");
289
7cb0f263 290 return 0;
0974a682
KS
291}
292
293static int status_variables(void) {
d3226d77 294 _cleanup_free_ uint16_t *options = NULL, *order = NULL;
c67bd42b 295 int n_options, n_order;
0974a682 296
0974a682 297 n_options = efi_get_boot_options(&options);
d3226d77 298 if (n_options == -ENOENT)
f939cff7
LP
299 return log_error_errno(n_options,
300 "Failed to access EFI variables, efivarfs"
d3226d77 301 " needs to be available at /sys/firmware/efi/efivars/.");
f939cff7 302 if (n_options < 0)
d3226d77 303 return log_error_errno(n_options, "Failed to read EFI boot entries: %m");
0974a682 304
0974a682 305 n_order = efi_get_boot_order(&order);
d3226d77 306 if (n_order == -ENOENT)
0974a682 307 n_order = 0;
d3226d77 308 else if (n_order < 0)
7709ef3a 309 return log_error_errno(n_order, "Failed to read EFI boot order: %m");
0974a682
KS
310
311 /* print entries in BootOrder first */
7fd66f3c 312 printf("Boot Loaders Listed in EFI Variables:\n");
c67bd42b 313 for (int i = 0; i < n_order; i++)
0974a682
KS
314 print_efi_option(order[i], true);
315
316 /* print remaining entries */
c67bd42b
ZJS
317 for (int i = 0; i < n_options; i++) {
318 for (int j = 0; j < n_order; j++)
d3226d77 319 if (options[i] == order[j])
a908cf0a 320 goto next_option;
0974a682
KS
321
322 print_efi_option(options[i], false);
a908cf0a
MM
323
324 next_option:
325 continue;
0974a682
KS
326 }
327
d3226d77 328 return 0;
0974a682
KS
329}
330
44e6a5ef 331static int boot_entry_file_check(const char *root, const char *p) {
c2b2df60 332 _cleanup_free_ char *path = NULL;
44e6a5ef
ZJS
333
334 path = path_join(root, p);
335 if (!path)
336 return log_oom();
337
7c248223 338 return RET_NERRNO(access(path, F_OK));
44e6a5ef
ZJS
339}
340
d3eb6072 341static void boot_entry_file_list(const char *field, const char *root, const char *p, int *ret_status) {
44e6a5ef
ZJS
342 int status = boot_entry_file_check(root, p);
343
405b104d 344 printf("%13s%s ", strempty(field), field ? ":" : " ");
44e6a5ef
ZJS
345 if (status < 0) {
346 errno = -status;
347 printf("%s%s%s (%m)\n", ansi_highlight_red(), p, ansi_normal());
348 } else
349 printf("%s\n", p);
d3eb6072
ZJS
350
351 if (*ret_status == 0 && status < 0)
352 *ret_status = status;
44e6a5ef
ZJS
353}
354
20a28174 355static int boot_entry_show(const BootEntry *e, bool show_as_default) {
d3eb6072
ZJS
356 int status = 0;
357
358 /* Returns 0 on success, negative on processing error, and positive if something is wrong with the
359 boot entry itself. */
360
20a28174
LP
361 assert(e);
362
ce4c4f81
ZJS
363 printf(" title: %s%s%s" "%s%s%s\n",
364 ansi_highlight(), boot_entry_title(e), ansi_normal(),
365 ansi_highlight_green(), show_as_default ? " (default)" : "", ansi_normal());
20a28174
LP
366
367 if (e->id)
368 printf(" id: %s\n", e->id);
cce9457c
ZJS
369 if (e->path) {
370 _cleanup_free_ char *link = NULL;
371
372 /* Let's urlify the link to make it easy to view in an editor, but only if it is a text
373 * file. Unified images are binary ELFs, and EFI variables are not pure text either. */
374 if (e->type == BOOT_ENTRY_CONF)
375 (void) terminal_urlify_path(e->path, NULL, &link);
376
377 printf(" source: %s\n", link ?: e->path);
378 }
20a28174
LP
379 if (e->version)
380 printf(" version: %s\n", e->version);
381 if (e->machine_id)
382 printf(" machine-id: %s\n", e->machine_id);
383 if (e->architecture)
384 printf(" architecture: %s\n", e->architecture);
385 if (e->kernel)
d3eb6072 386 boot_entry_file_list("linux", e->root, e->kernel, &status);
20a28174 387
44e6a5ef
ZJS
388 char **s;
389 STRV_FOREACH(s, e->initrd)
390 boot_entry_file_list(s == e->initrd ? "initrd" : NULL,
391 e->root,
d3eb6072
ZJS
392 *s,
393 &status);
20a28174 394 if (!strv_isempty(e->options)) {
9dae4c8a
ZJS
395 _cleanup_free_ char *t = NULL, *t2 = NULL;
396 _cleanup_strv_free_ char **ts = NULL;
20a28174
LP
397
398 t = strv_join(e->options, " ");
399 if (!t)
400 return log_oom();
401
9dae4c8a
ZJS
402 ts = strv_split_newlines(t);
403 if (!ts)
404 return log_oom();
405
406 t2 = strv_join(ts, "\n ");
407 if (!t2)
408 return log_oom();
409
9dae4c8a 410 printf(" options: %s\n", t2);
20a28174
LP
411 }
412 if (e->device_tree)
d3eb6072 413 boot_entry_file_list("devicetree", e->root, e->device_tree, &status);
20a28174 414
d3eb6072 415 return -status;
20a28174
LP
416}
417
81fed855
LP
418static int status_entries(
419 const char *esp_path,
420 sd_id128_t esp_partition_uuid,
421 const char *xbootldr_path,
422 sd_id128_t xbootldr_partition_uuid) {
423
7e87c7d9 424 _cleanup_(boot_config_free) BootConfig config = {};
81fed855
LP
425 sd_id128_t dollar_boot_partition_uuid;
426 const char *dollar_boot_path;
a099e035 427 int r;
7e87c7d9 428
81fed855
LP
429 assert(esp_path || xbootldr_path);
430
431 if (xbootldr_path) {
432 dollar_boot_path = xbootldr_path;
433 dollar_boot_partition_uuid = xbootldr_partition_uuid;
434 } else {
435 dollar_boot_path = esp_path;
436 dollar_boot_partition_uuid = esp_partition_uuid;
437 }
438
439 printf("Boot Loader Entries:\n"
440 " $BOOT: %s", dollar_boot_path);
441 if (!sd_id128_is_null(dollar_boot_partition_uuid))
bd44566c
ZJS
442 printf(" (/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR ")",
443 SD_ID128_FORMAT_VAL(dollar_boot_partition_uuid));
81fed855
LP
444 printf("\n\n");
445
fbf45d22 446 r = boot_entries_load_config(esp_path, xbootldr_path, &config);
7e87c7d9 447 if (r < 0)
21f7a622 448 return r;
7e87c7d9
ZJS
449
450 if (config.default_entry < 0)
a099e035 451 printf("%zu entries, no entry could be determined as default.\n", config.n_entries);
7e87c7d9 452 else {
7fd66f3c 453 printf("Default Boot Loader Entry:\n");
a099e035 454
d3eb6072
ZJS
455 r = boot_entry_show(config.entries + config.default_entry, false);
456 if (r > 0)
457 /* < 0 is already logged by the function itself, let's just emit an extra warning if
458 the default entry is broken */
459 printf("\nWARNING: default boot entry is broken\n");
7e87c7d9
ZJS
460 }
461
462 return 0;
463}
464
0974a682
KS
465static int compare_product(const char *a, const char *b) {
466 size_t x, y;
467
468 assert(a);
469 assert(b);
470
471 x = strcspn(a, " ");
472 y = strcspn(b, " ");
473 if (x != y)
474 return x < y ? -1 : x > y ? 1 : 0;
475
476 return strncmp(a, b, x);
477}
478
479static int compare_version(const char *a, const char *b) {
480 assert(a);
481 assert(b);
482
483 a += strcspn(a, " ");
484 a += strspn(a, " ");
485 b += strcspn(b, " ");
486 b += strspn(b, " ");
487
8087644a 488 return strverscmp_improved(a, b);
0974a682
KS
489}
490
175d308c 491static int version_check(int fd_from, const char *from, int fd_to, const char *to) {
d3226d77 492 _cleanup_free_ char *a = NULL, *b = NULL;
0974a682
KS
493 int r;
494
175d308c 495 assert(fd_from >= 0);
0974a682 496 assert(from);
175d308c 497 assert(fd_to >= 0);
0974a682
KS
498 assert(to);
499
175d308c 500 r = get_file_version(fd_from, &a);
0974a682 501 if (r < 0)
d3226d77 502 return r;
baaa35ad 503 if (r == 0)
e5a8b4b5 504 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE),
baaa35ad
ZJS
505 "Source file \"%s\" does not carry version information!",
506 from);
0974a682 507
175d308c 508 r = get_file_version(fd_to, &b);
0974a682 509 if (r < 0)
d3226d77 510 return r;
baaa35ad 511 if (r == 0 || compare_product(a, b) != 0)
e5a8b4b5 512 return log_notice_errno(SYNTHETIC_ERRNO(EREMOTE),
baaa35ad
ZJS
513 "Skipping \"%s\", since it's owned by another boot loader.",
514 to);
0974a682 515
e5a8b4b5
LP
516 r = compare_version(a, b);
517 if (r < 0)
518 return log_warning_errno(SYNTHETIC_ERRNO(ESTALE), "Skipping \"%s\", since newer boot loader version in place already.", to);
519 else if (r == 0)
520 return log_info_errno(SYNTHETIC_ERRNO(ESTALE), "Skipping \"%s\", since same boot loader version in place already.", to);
0974a682 521
d3226d77 522 return 0;
0974a682
KS
523}
524
175d308c
LP
525static int copy_file_with_version_check(const char *from, const char *to, bool force) {
526 _cleanup_close_ int fd_from = -1, fd_to = -1;
527 _cleanup_free_ char *t = NULL;
0974a682 528 int r;
0974a682 529
175d308c
LP
530 fd_from = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
531 if (fd_from < 0)
d3226d77 532 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", from);
0974a682
KS
533
534 if (!force) {
175d308c
LP
535 fd_to = open(to, O_RDONLY|O_CLOEXEC|O_NOCTTY);
536 if (fd_to < 0) {
6b8664cb 537 if (errno != ENOENT)
175d308c
LP
538 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", to);
539 } else {
540 r = version_check(fd_from, from, fd_to, to);
541 if (r < 0)
542 return r;
543
544 if (lseek(fd_from, 0, SEEK_SET) == (off_t) -1)
6719ca72 545 return log_error_errno(errno, "Failed to seek in \"%s\": %m", from);
175d308c
LP
546
547 fd_to = safe_close(fd_to);
0974a682 548 }
175d308c 549 }
d3226d77 550
175d308c
LP
551 r = tempfn_random(to, NULL, &t);
552 if (r < 0)
553 return log_oom();
0974a682 554
175d308c
LP
555 RUN_WITH_UMASK(0000) {
556 fd_to = open(t, O_WRONLY|O_CREAT|O_CLOEXEC|O_EXCL|O_NOFOLLOW, 0644);
557 if (fd_to < 0)
558 return log_error_errno(errno, "Failed to open \"%s\" for writing: %m", t);
0974a682
KS
559 }
560
f5fbe71d 561 r = copy_bytes(fd_from, fd_to, UINT64_MAX, COPY_REFLINK);
0974a682 562 if (r < 0) {
0675e94a
AJ
563 (void) unlink(t);
564 return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
0974a682
KS
565 }
566
adc6f43b 567 (void) copy_times(fd_from, fd_to, 0);
0974a682 568
bf819d3a
LP
569 r = fsync_full(fd_to);
570 if (r < 0) {
0675e94a 571 (void) unlink_noerrno(t);
bf819d3a 572 return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
0675e94a
AJ
573 }
574
b1c05b98 575 if (renameat(AT_FDCWD, t, AT_FDCWD, to) < 0) {
175d308c
LP
576 (void) unlink_noerrno(t);
577 return log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", t, to);
0974a682
KS
578 }
579
d3226d77 580 log_info("Copied \"%s\" to \"%s\".", from, to);
0974a682 581
175d308c 582 return 0;
0974a682
KS
583}
584
0974a682 585static int mkdir_one(const char *prefix, const char *suffix) {
e2600fd5 586 _cleanup_free_ char *p = NULL;
0974a682 587
e2600fd5 588 p = path_join(prefix, suffix);
0974a682 589 if (mkdir(p, 0700) < 0) {
d3226d77
ZJS
590 if (errno != EEXIST)
591 return log_error_errno(errno, "Failed to create \"%s\": %m", p);
0974a682 592 } else
d3226d77 593 log_info("Created \"%s\".", p);
7b4d7cc0 594
0974a682
KS
595 return 0;
596}
597
fbf45d22 598static const char *const esp_subdirs[] = {
e44c3229 599 /* The directories to place in the ESP */
d3226d77
ZJS
600 "EFI",
601 "EFI/systemd",
00f69504 602 "EFI/BOOT",
d3226d77 603 "loader",
9ee051b9 604 NULL
d3226d77
ZJS
605};
606
e44c3229
LP
607static const char *const dollar_boot_subdirs[] = {
608 /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
609 "loader",
610 "loader/entries", /* Type #1 entries */
611 "EFI",
612 "EFI/Linux", /* Type #2 entries */
613 NULL
614};
615
616static int create_subdirs(const char *root, const char * const *subdirs) {
fbf45d22 617 const char *const *i;
0974a682
KS
618 int r;
619
e44c3229
LP
620 STRV_FOREACH(i, subdirs) {
621 r = mkdir_one(root, *i);
d3226d77
ZJS
622 if (r < 0)
623 return r;
624 }
7b4d7cc0 625
7b4d7cc0 626 return 0;
7b4d7cc0
KS
627}
628
0974a682 629static int copy_one_file(const char *esp_path, const char *name, bool force) {
5509f912 630 const char *e;
d3226d77 631 char *p, *q;
0974a682
KS
632 int r;
633
d3226d77
ZJS
634 p = strjoina(BOOTLIBDIR "/", name);
635 q = strjoina(esp_path, "/EFI/systemd/", name);
175d308c 636 r = copy_file_with_version_check(p, q, force);
0974a682 637
5509f912
LP
638 e = startswith(name, "systemd-boot");
639 if (e) {
0974a682 640 int k;
d3226d77 641 char *v;
0974a682
KS
642
643 /* Create the EFI default boot loader name (specified for removable devices) */
5509f912 644 v = strjoina(esp_path, "/EFI/BOOT/BOOT", e);
846b8fc3 645 ascii_strupper(strrchr(v, '/') + 1);
0974a682 646
175d308c 647 k = copy_file_with_version_check(p, v, force);
0974a682 648 if (k < 0 && r == 0)
d3226d77 649 r = k;
0974a682
KS
650 }
651
652 return r;
7b4d7cc0
KS
653}
654
0974a682
KS
655static int install_binaries(const char *esp_path, bool force) {
656 struct dirent *de;
d3226d77 657 _cleanup_closedir_ DIR *d = NULL;
0974a682
KS
658 int r = 0;
659
e7dd673d 660 d = opendir(BOOTLIBDIR);
d3226d77
ZJS
661 if (!d)
662 return log_error_errno(errno, "Failed to open \""BOOTLIBDIR"\": %m");
0974a682 663
0d73a816 664 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read \""BOOTLIBDIR"\": %m")) {
0974a682
KS
665 int k;
666
d3226d77 667 if (!endswith_no_case(de->d_name, ".efi"))
0974a682
KS
668 continue;
669
670 k = copy_one_file(esp_path, de->d_name, force);
e5a8b4b5
LP
671 /* Don't propagate an error code if no update necessary, installed version already equal or
672 * newer version, or other boot loader in place. */
673 if (arg_graceful && IN_SET(k, -ESTALE, -EREMOTE))
674 continue;
0974a682
KS
675 if (k < 0 && r == 0)
676 r = k;
677 }
678
0974a682 679 return r;
7b4d7cc0
KS
680}
681
b461576d 682static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
d3226d77 683 _cleanup_free_ char *opath = NULL;
0974a682 684 sd_id128_t ouuid;
d3226d77 685 int r;
7b4d7cc0 686
d3226d77
ZJS
687 r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
688 if (r < 0)
0974a682
KS
689 return false;
690 if (!sd_id128_equal(uuid, ouuid))
d3226d77 691 return false;
5c2e5957 692
693 /* Some motherboards convert the path to uppercase under certain circumstances
694 * (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
695 * so use case-insensitive checking */
696 if (!strcaseeq_ptr(path, opath))
d3226d77 697 return false;
0974a682 698
d3226d77 699 return true;
0974a682
KS
700}
701
702static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
d3226d77
ZJS
703 _cleanup_free_ uint16_t *options = NULL;
704 int n, i;
0974a682 705
d3226d77
ZJS
706 n = efi_get_boot_options(&options);
707 if (n < 0)
708 return n;
0974a682 709
e7dd673d 710 /* find already existing systemd-boot entry */
d3226d77 711 for (i = 0; i < n; i++)
0974a682 712 if (same_entry(options[i], uuid, path)) {
d3226d77
ZJS
713 *id = options[i];
714 return 1;
0974a682
KS
715 }
716
717 /* find free slot in the sorted BootXXXX variable list */
d3226d77 718 for (i = 0; i < n; i++)
0974a682 719 if (i != options[i]) {
d3226d77 720 *id = i;
26d54e12 721 return 0;
0974a682
KS
722 }
723
724 /* use the next one */
725 if (i == 0xffff)
726 return -ENOSPC;
d3226d77
ZJS
727 *id = i;
728 return 0;
0974a682
KS
729}
730
731static int insert_into_order(uint16_t slot, bool first) {
d3226d77
ZJS
732 _cleanup_free_ uint16_t *order = NULL;
733 uint16_t *t;
c67bd42b 734 int n;
0974a682 735
d3226d77
ZJS
736 n = efi_get_boot_order(&order);
737 if (n <= 0)
0974a682 738 /* no entry, add us */
d3226d77 739 return efi_set_boot_order(&slot, 1);
0974a682
KS
740
741 /* are we the first and only one? */
d3226d77
ZJS
742 if (n == 1 && order[0] == slot)
743 return 0;
0974a682
KS
744
745 /* are we already in the boot order? */
c67bd42b 746 for (int i = 0; i < n; i++) {
0974a682
KS
747 if (order[i] != slot)
748 continue;
749
750 /* we do not require to be the first one, all is fine */
751 if (!first)
d3226d77 752 return 0;
0974a682
KS
753
754 /* move us to the first slot */
d3226d77 755 memmove(order + 1, order, i * sizeof(uint16_t));
0974a682 756 order[0] = slot;
d3226d77 757 return efi_set_boot_order(order, n);
0974a682
KS
758 }
759
760 /* extend array */
a7798cd8 761 t = reallocarray(order, n + 1, sizeof(uint16_t));
d3226d77
ZJS
762 if (!t)
763 return -ENOMEM;
764 order = t;
0974a682
KS
765
766 /* add us to the top or end of the list */
767 if (first) {
d3226d77 768 memmove(order + 1, order, n * sizeof(uint16_t));
0974a682
KS
769 order[0] = slot;
770 } else
d3226d77 771 order[n] = slot;
0974a682 772
d3226d77 773 return efi_set_boot_order(order, n + 1);
0974a682
KS
774}
775
776static int remove_from_order(uint16_t slot) {
7cb0f263 777 _cleanup_free_ uint16_t *order = NULL;
c67bd42b 778 int n;
0974a682 779
d3226d77
ZJS
780 n = efi_get_boot_order(&order);
781 if (n <= 0)
782 return n;
0974a682 783
c67bd42b 784 for (int i = 0; i < n; i++) {
0974a682
KS
785 if (order[i] != slot)
786 continue;
787
d3226d77
ZJS
788 if (i + 1 < n)
789 memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
790 return efi_set_boot_order(order, n - 1);
0974a682
KS
791 }
792
d3226d77 793 return 0;
0974a682
KS
794}
795
796static int install_variables(const char *esp_path,
797 uint32_t part, uint64_t pstart, uint64_t psize,
798 sd_id128_t uuid, const char *path,
799 bool first) {
270384b2 800 const char *p;
0974a682
KS
801 uint16_t slot;
802 int r;
803
804 if (!is_efi_boot()) {
d3226d77 805 log_warning("Not booted with EFI, skipping EFI variable setup.");
0974a682
KS
806 return 0;
807 }
808
270384b2 809 p = prefix_roota(esp_path, path);
0974a682
KS
810 if (access(p, F_OK) < 0) {
811 if (errno == ENOENT)
d3226d77 812 return 0;
f939cff7
LP
813
814 return log_error_errno(errno, "Cannot access \"%s\": %m", p);
0974a682 815 }
7b4d7cc0 816
0974a682 817 r = find_slot(uuid, path, &slot);
d3226d77
ZJS
818 if (r < 0)
819 return log_error_errno(r,
820 r == -ENOENT ?
821 "Failed to access EFI variables. Is the \"efivarfs\" filesystem mounted?" :
822 "Failed to determine current boot order: %m");
7b4d7cc0 823
181ccb43 824 if (first || r == 0) {
0974a682
KS
825 r = efi_add_boot_option(slot, "Linux Boot Manager",
826 part, pstart, psize,
827 uuid, path);
d3226d77
ZJS
828 if (r < 0)
829 return log_error_errno(r, "Failed to create EFI Boot variable entry: %m");
0974a682 830
d3226d77
ZJS
831 log_info("Created EFI boot entry \"Linux Boot Manager\".");
832 }
0974a682 833
d3226d77 834 return insert_into_order(slot, first);
0974a682
KS
835}
836
837static int remove_boot_efi(const char *esp_path) {
d3226d77 838 _cleanup_closedir_ DIR *d = NULL;
0974a682 839 struct dirent *de;
270384b2 840 const char *p;
d3226d77 841 int r, c = 0;
0974a682 842
270384b2 843 p = prefix_roota(esp_path, "/EFI/BOOT");
0974a682
KS
844 d = opendir(p);
845 if (!d) {
d3226d77
ZJS
846 if (errno == ENOENT)
847 return 0;
0974a682 848
d3226d77 849 return log_error_errno(errno, "Failed to open directory \"%s\": %m", p);
0974a682
KS
850 }
851
e41256dc 852 FOREACH_DIRENT(de, d, break) {
d3226d77
ZJS
853 _cleanup_close_ int fd = -1;
854 _cleanup_free_ char *v = NULL;
0974a682 855
d3226d77 856 if (!endswith_no_case(de->d_name, ".efi"))
0974a682
KS
857 continue;
858
b7536c45 859 if (!startswith_no_case(de->d_name, "boot"))
0974a682
KS
860 continue;
861
d3226d77 862 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
dd114e11 863 if (fd < 0)
d3226d77 864 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
0974a682 865
d3226d77 866 r = get_file_version(fd, &v);
0974a682 867 if (r < 0)
d3226d77
ZJS
868 return r;
869 if (r > 0 && startswith(v, "systemd-boot ")) {
870 r = unlinkat(dirfd(d), de->d_name, 0);
871 if (r < 0)
872 return log_error_errno(errno, "Failed to remove \"%s/%s\": %m", p, de->d_name);
873
a592ab6a 874 log_info("Removed \"%s/%s\".", p, de->d_name);
0974a682
KS
875 }
876
877 c++;
0974a682
KS
878 }
879
d3226d77 880 return c;
0974a682
KS
881}
882
883static int rmdir_one(const char *prefix, const char *suffix) {
270384b2 884 const char *p;
7b4d7cc0 885
270384b2 886 p = prefix_roota(prefix, suffix);
0974a682 887 if (rmdir(p) < 0) {
fbf45d22
LP
888 bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
889
890 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
891 "Failed to remove directory \"%s\": %m", p);
892 if (!ignore)
893 return -errno;
7b4d7cc0 894 } else
d3226d77 895 log_info("Removed \"%s\".", p);
7b4d7cc0 896
0974a682 897 return 0;
7b4d7cc0
KS
898}
899
e44c3229
LP
900static int remove_subdirs(const char *root, const char *const *subdirs) {
901 int r, q;
fbf45d22 902
e44c3229
LP
903 /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
904 * short the array is. */
fbf45d22 905
e44c3229
LP
906 if (!subdirs[0]) /* A the end of the list */
907 return 0;
fbf45d22 908
e44c3229
LP
909 r = remove_subdirs(root, subdirs + 1);
910 q = rmdir_one(root, subdirs[0]);
911
912 return r < 0 ? r : q;
913}
914
6a3fff75 915static int remove_machine_id_directory(const char *root) {
916 sd_id128_t machine_id;
6a3fff75 917 int r;
918
919 assert(root);
920 assert(arg_make_machine_id_directory >= 0);
921
922 if (!arg_make_machine_id_directory)
923 return 0;
924
925 r = sd_id128_get_machine(&machine_id);
926 if (r < 0)
927 return log_error_errno(r, "Failed to get machine id: %m");
928
85b55869 929 return rmdir_one(root, SD_ID128_TO_STRING(machine_id));
6a3fff75 930}
931
0974a682 932static int remove_binaries(const char *esp_path) {
270384b2 933 const char *p;
0974a682
KS
934 int r, q;
935
270384b2 936 p = prefix_roota(esp_path, "/EFI/systemd");
c6878637 937 r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
0974a682
KS
938
939 q = remove_boot_efi(esp_path);
940 if (q < 0 && r == 0)
941 r = q;
942
0974a682
KS
943 return r;
944}
945
e44c3229 946static int remove_file(const char *root, const char *file) {
fbf45d22
LP
947 const char *p;
948
e44c3229
LP
949 assert(root);
950 assert(file);
fbf45d22 951
e44c3229 952 p = prefix_roota(root, file);
fbf45d22 953 if (unlink(p) < 0) {
e44c3229
LP
954 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
955 "Failed to unlink file \"%s\": %m", p);
fbf45d22 956
e44c3229
LP
957 return errno == ENOENT ? 0 : -errno;
958 }
fbf45d22 959
e44c3229
LP
960 log_info("Removed \"%s\".", p);
961 return 1;
fbf45d22
LP
962}
963
0974a682
KS
964static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
965 uint16_t slot;
966 int r;
967
968 if (!is_efi_boot())
969 return 0;
970
971 r = find_slot(uuid, path, &slot);
972 if (r != 1)
973 return 0;
974
975 r = efi_remove_boot_option(slot);
976 if (r < 0)
977 return r;
978
979 if (in_order)
d3226d77 980 return remove_from_order(slot);
f939cff7
LP
981
982 return 0;
0974a682
KS
983}
984
e44c3229 985static int remove_loader_variables(void) {
e6f055cb 986 const char *variable;
e44c3229
LP
987 int r = 0;
988
989 /* Remove all persistent loader variables we define */
990
e6f055cb
ZJS
991 FOREACH_STRING(variable,
992 EFI_LOADER_VARIABLE(LoaderConfigTimeout),
993 EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot),
994 EFI_LOADER_VARIABLE(LoaderEntryDefault),
995 EFI_LOADER_VARIABLE(LoaderEntryOneShot),
996 EFI_LOADER_VARIABLE(LoaderSystemToken)){
e44c3229
LP
997
998 int q;
999
e6f055cb 1000 q = efi_set_variable(variable, NULL, 0);
e44c3229
LP
1001 if (q == -ENOENT)
1002 continue;
1003 if (q < 0) {
e6f055cb 1004 log_warning_errno(q, "Failed to remove EFI variable %s: %m", variable);
e44c3229
LP
1005 if (r >= 0)
1006 r = q;
1007 } else
e6f055cb 1008 log_info("Removed EFI variable %s.", variable);
e44c3229
LP
1009 }
1010
1011 return r;
1012}
1013
31e57550 1014static int install_loader_config(const char *esp_path) {
f5b84de2
LP
1015 _cleanup_(unlink_and_freep) char *t = NULL;
1016 _cleanup_fclose_ FILE *f = NULL;
b46c3e49 1017 _cleanup_close_ int fd = -1;
d5ff6d6d 1018 const char *p;
b46c3e49 1019 int r;
0974a682 1020
6a3fff75 1021 assert(arg_make_machine_id_directory >= 0);
1022
270384b2 1023 p = prefix_roota(esp_path, "/loader/loader.conf");
f5b84de2
LP
1024 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
1025 return 0;
1026
1027 fd = open_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t);
1028 if (fd < 0)
1029 return log_error_errno(fd, "Failed to open \"%s\" for writing: %m", p);
1030
b46c3e49
VC
1031 f = take_fdopen(&fd, "w");
1032 if (!f)
f5b84de2 1033 return log_oom();
0974a682 1034
a36b411e 1035 fprintf(f, "#timeout 3\n"
31e57550 1036 "#console-mode keep\n");
85b55869 1037
6a3fff75 1038 if (arg_make_machine_id_directory) {
85b55869
LP
1039 sd_id128_t machine_id;
1040
6a3fff75 1041 r = sd_id128_get_machine(&machine_id);
1042 if (r < 0)
1043 return log_error_errno(r, "Failed to get machine id: %m");
1044
85b55869 1045 fprintf(f, "default %s-*\n", SD_ID128_TO_STRING(machine_id));
6a3fff75 1046 }
0974a682 1047
0675e94a 1048 r = fflush_sync_and_check(f);
d5ff6d6d
LP
1049 if (r < 0)
1050 return log_error_errno(r, "Failed to write \"%s\": %m", p);
0974a682 1051
c46db6c0 1052 r = link_tmpfile(fileno(f), t, p);
f5b84de2
LP
1053 if (r == -EEXIST)
1054 return 0; /* Silently skip creation if the file exists now (recheck) */
1055 if (r < 0)
1056 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
1057
1058 t = mfree(t);
f5b84de2 1059 return 1;
0974a682
KS
1060}
1061
6a3fff75 1062static int install_machine_id_directory(const char *root) {
1063 sd_id128_t machine_id;
6a3fff75 1064 int r;
1065
1066 assert(root);
1067 assert(arg_make_machine_id_directory >= 0);
1068
1069 if (!arg_make_machine_id_directory)
1070 return 0;
1071
1072 r = sd_id128_get_machine(&machine_id);
1073 if (r < 0)
1074 return log_error_errno(r, "Failed to get machine id: %m");
1075
85b55869 1076 return mkdir_one(root, SD_ID128_TO_STRING(machine_id));
6a3fff75 1077}
1078
2f2c539c 1079static int help(int argc, char *argv[], void *userdata) {
37ec0fdd
LP
1080 _cleanup_free_ char *link = NULL;
1081 int r;
1082
1083 r = terminal_urlify_man("bootctl", "1", &link);
1084 if (r < 0)
1085 return log_oom();
2f2c539c 1086
64a7fcc5
LP
1087 printf("%1$s [OPTIONS...] COMMAND ...\n"
1088 "\n%5$sControl EFI firmware boot settings and manage boot loader.%6$s\n"
1089 "\n%3$sGeneric EFI Firmware/Boot Loader Commands:%4$s\n"
1090 " status Show status of installed boot loader and EFI variables\n"
002914e6
LP
1091 " reboot-to-firmware [BOOL]\n"
1092 " Query or set reboot-to-firmware EFI flag\n"
64a7fcc5
LP
1093 " systemd-efi-options [STRING]\n"
1094 " Query or set system options string in EFI variable\n"
1095 "\n%3$sBoot Loader Specification Commands:%4$s\n"
2536752d
ZJS
1096 " list List boot loader entries\n"
1097 " set-default ID Set default boot loader entry\n"
1098 " set-oneshot ID Set default boot loader entry, for next boot only\n"
39ddc32a
JJ
1099 " set-timeout SECONDS Set the menu timeout\n"
1100 " set-timeout-oneshot SECONDS\n"
1101 " Set the menu timeout for the next boot only\n"
64a7fcc5
LP
1102 "\n%3$ssystemd-boot Commands:%4$s\n"
1103 " install Install systemd-boot to the ESP and EFI variables\n"
1104 " update Update systemd-boot in the ESP and EFI variables\n"
1105 " remove Remove systemd-boot from the ESP and EFI variables\n"
1106 " is-installed Test whether systemd-boot is installed in the ESP\n"
1107 " random-seed Initialize random seed in ESP and EFI variables\n"
1108 "\n%3$sOptions:%4$s\n"
e1fac8a6
ZJS
1109 " -h --help Show this help\n"
1110 " --version Print version\n"
1111 " --esp-path=PATH Path to the EFI System Partition (ESP)\n"
1112 " --boot-path=PATH Path to the $BOOT partition\n"
1113 " -p --print-esp-path Print path to the EFI System Partition\n"
1114 " -x --print-boot-path Print path to the $BOOT partition\n"
1115 " --no-variables Don't touch EFI variables\n"
1116 " --no-pager Do not pipe output into a pager\n"
351de38e
LP
1117 " --graceful Don't fail when the ESP cannot be found or EFI\n"
1118 " variables cannot be written\n"
6a3fff75 1119 " --make-machine-id-directory=yes|no|auto\n"
1120 " Create $BOOT/$MACHINE_ID\n"
bc556335
DDM
1121 "\nSee the %2$s for details.\n",
1122 program_invocation_short_name,
1123 link,
1124 ansi_underline(),
1125 ansi_normal(),
1126 ansi_highlight(),
1127 ansi_normal());
0974a682
KS
1128
1129 return 0;
1130}
1131
0974a682
KS
1132static int parse_argv(int argc, char *argv[]) {
1133 enum {
fbf45d22
LP
1134 ARG_ESP_PATH = 0x100,
1135 ARG_BOOT_PATH,
0974a682
KS
1136 ARG_VERSION,
1137 ARG_NO_VARIABLES,
57db6f18 1138 ARG_NO_PAGER,
351de38e 1139 ARG_GRACEFUL,
6a3fff75 1140 ARG_MAKE_MACHINE_ID_DIRECTORY,
7b4d7cc0
KS
1141 };
1142
0974a682 1143 static const struct option options[] = {
6a3fff75 1144 { "help", no_argument, NULL, 'h' },
1145 { "version", no_argument, NULL, ARG_VERSION },
1146 { "esp-path", required_argument, NULL, ARG_ESP_PATH },
1147 { "path", required_argument, NULL, ARG_ESP_PATH }, /* Compatibility alias */
1148 { "boot-path", required_argument, NULL, ARG_BOOT_PATH },
1149 { "print-esp-path", no_argument, NULL, 'p' },
1150 { "print-path", no_argument, NULL, 'p' }, /* Compatibility alias */
1151 { "print-boot-path", no_argument, NULL, 'x' },
1152 { "no-variables", no_argument, NULL, ARG_NO_VARIABLES },
1153 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1154 { "graceful", no_argument, NULL, ARG_GRACEFUL },
1155 { "make-machine-id-directory", required_argument, NULL, ARG_MAKE_MACHINE_ID_DIRECTORY },
a36b411e 1156 {}
0974a682
KS
1157 };
1158
2f2c539c 1159 int c, r;
6a3fff75 1160 bool b;
7b4d7cc0
KS
1161
1162 assert(argc >= 0);
1163 assert(argv);
1164
fba4e945 1165 while ((c = getopt_long(argc, argv, "hpx", options, NULL)) >= 0)
0974a682 1166 switch (c) {
7b4d7cc0 1167
0974a682 1168 case 'h':
2f2c539c 1169 help(0, NULL, NULL);
7b4d7cc0 1170 return 0;
7b4d7cc0 1171
0974a682 1172 case ARG_VERSION:
3f6fd1ba 1173 return version();
7b4d7cc0 1174
fbf45d22
LP
1175 case ARG_ESP_PATH:
1176 r = free_and_strdup(&arg_esp_path, optarg);
1177 if (r < 0)
1178 return log_oom();
1179 break;
1180
1181 case ARG_BOOT_PATH:
1182 r = free_and_strdup(&arg_xbootldr_path, optarg);
2f2c539c
LP
1183 if (r < 0)
1184 return log_oom();
0974a682
KS
1185 break;
1186
30b50477 1187 case 'p':
aa467bca
ZJS
1188 if (arg_print_dollar_boot_path)
1189 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1190 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
fbf45d22
LP
1191 arg_print_esp_path = true;
1192 break;
1193
fba4e945 1194 case 'x':
aa467bca
ZJS
1195 if (arg_print_esp_path)
1196 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1197 "--print-boot-path/-x cannot be combined with --print-esp-path/-p");
fbf45d22 1198 arg_print_dollar_boot_path = true;
30b50477
ZJS
1199 break;
1200
0974a682
KS
1201 case ARG_NO_VARIABLES:
1202 arg_touch_variables = false;
1203 break;
1204
57db6f18 1205 case ARG_NO_PAGER:
0221d68a 1206 arg_pager_flags |= PAGER_DISABLE;
57db6f18
LP
1207 break;
1208
351de38e
LP
1209 case ARG_GRACEFUL:
1210 arg_graceful = true;
1211 break;
1212
6a3fff75 1213 case ARG_MAKE_MACHINE_ID_DIRECTORY:
1214 if (streq(optarg, "auto"))
1215 arg_make_machine_id_directory = -1; /* default */
1216 else {
1217 r = parse_boolean_argument("--make-machine-id-directory=", optarg, &b);
1218 if (r < 0)
1219 return r;
1220 arg_make_machine_id_directory = b;
1221 }
1222 break;
1223
0974a682
KS
1224 case '?':
1225 return -EINVAL;
1226
1227 default:
04499a70 1228 assert_not_reached();
7b4d7cc0 1229 }
7b4d7cc0 1230
0974a682
KS
1231 return 1;
1232}
7b4d7cc0 1233
e6f055cb 1234static void read_efi_var(const char *variable, char **ret) {
551710cf
ZJS
1235 int r;
1236
e6f055cb 1237 r = efi_get_variable_string(variable, ret);
551710cf 1238 if (r < 0 && r != -ENOENT)
e6f055cb 1239 log_warning_errno(r, "Failed to read EFI variable %s: %m", variable);
551710cf
ZJS
1240}
1241
607ebf2b
ZJS
1242static void print_yes_no_line(bool first, bool good, const char *name) {
1243 printf("%s%s%s%s %s\n",
1244 first ? " Features: " : " ",
312dff17
LP
1245 ansi_highlight_green_red(good),
1246 special_glyph_check_mark(good),
607ebf2b
ZJS
1247 ansi_normal(),
1248 name);
1249}
1250
2f2c539c 1251static int verb_status(int argc, char *argv[], void *userdata) {
fbf45d22 1252 sd_id128_t esp_uuid = SD_ID128_NULL, xbootldr_uuid = SD_ID128_NULL;
46fb255b 1253 int r, k;
0974a682 1254
e5a8b4b5 1255 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, &esp_uuid);
fbf45d22 1256 if (arg_print_esp_path) {
5caa3167
LP
1257 if (r == -EACCES) /* If we couldn't acquire the ESP path, log about access errors (which is the only
1258 * error the find_esp_and_warn() won't log on its own) */
fbf45d22 1259 return log_error_errno(r, "Failed to determine ESP location: %m");
30b50477
ZJS
1260 if (r < 0)
1261 return r;
1262
fbf45d22
LP
1263 puts(arg_esp_path);
1264 }
1265
e5a8b4b5 1266 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, &xbootldr_uuid);
fbf45d22
LP
1267 if (arg_print_dollar_boot_path) {
1268 if (r == -EACCES)
1269 return log_error_errno(r, "Failed to determine XBOOTLDR location: %m");
1270 if (r < 0)
1271 return r;
1272
f8a2b09a
YW
1273 const char *path = arg_dollar_boot_path();
1274 if (!path)
1275 return log_error_errno(SYNTHETIC_ERRNO(EACCES), "Failed to determine XBOOTLDR location: %m");
1276
1277 puts(path);
30b50477 1278 }
551710cf 1279
fbf45d22
LP
1280 if (arg_print_esp_path || arg_print_dollar_boot_path)
1281 return 0;
1282
5caa3167
LP
1283 r = 0; /* If we couldn't determine the path, then don't consider that a problem from here on, just show what we
1284 * can show */
1285
384c2c32 1286 pager_open(arg_pager_flags);
57db6f18 1287
2f2c539c 1288 if (is_efi_boot()) {
80641a81
LP
1289 static const struct {
1290 uint64_t flag;
1291 const char *name;
1292 } flags[] = {
22c5ff51
LP
1293 { EFI_LOADER_FEATURE_BOOT_COUNTING, "Boot counting" },
1294 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT, "Menu timeout control" },
1295 { EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT, "One-shot menu timeout control" },
1296 { EFI_LOADER_FEATURE_ENTRY_DEFAULT, "Default entry control" },
1297 { EFI_LOADER_FEATURE_ENTRY_ONESHOT, "One-shot entry control" },
1298 { EFI_LOADER_FEATURE_XBOOTLDR, "Support for XBOOTLDR partition" },
1299 { EFI_LOADER_FEATURE_RANDOM_SEED, "Support for passing random seed to OS" },
2553a548 1300 { EFI_LOADER_FEATURE_LOAD_DRIVER, "Load drop-in drivers" },
80641a81
LP
1301 };
1302
81375b9b 1303 _cleanup_free_ char *fw_type = NULL, *fw_info = NULL, *loader = NULL, *loader_path = NULL, *stub = NULL;
25579a43 1304 sd_id128_t loader_part_uuid = SD_ID128_NULL;
80641a81 1305 uint64_t loader_features = 0;
e6f055cb 1306 int have;
0974a682 1307
e6f055cb
ZJS
1308 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareType), &fw_type);
1309 read_efi_var(EFI_LOADER_VARIABLE(LoaderFirmwareInfo), &fw_info);
1310 read_efi_var(EFI_LOADER_VARIABLE(LoaderInfo), &loader);
1311 read_efi_var(EFI_LOADER_VARIABLE(StubInfo), &stub);
1312 read_efi_var(EFI_LOADER_VARIABLE(LoaderImageIdentifier), &loader_path);
80641a81 1313 (void) efi_loader_get_features(&loader_features);
551710cf 1314
2f2c539c
LP
1315 if (loader_path)
1316 efi_tilt_backslashes(loader_path);
1317
46fb255b
ZJS
1318 k = efi_loader_get_device_part_uuid(&loader_part_uuid);
1319 if (k < 0 && k != -ENOENT)
1320 r = log_warning_errno(k, "Failed to read EFI variable LoaderDevicePartUUID: %m");
2f2c539c 1321
c4964512 1322 SecureBootMode secure = efi_get_secure_boot_mode();
2f2c539c 1323 printf("System:\n");
ba857253 1324 printf(" Firmware: %s%s (%s)%s\n", ansi_highlight(), strna(fw_type), strna(fw_info), ansi_normal());
c4964512
JJ
1325 printf(" Secure Boot: %sd (%s)\n",
1326 enable_disable(IN_SET(secure, SECURE_BOOT_USER, SECURE_BOOT_DEPLOYED)),
1327 secure_boot_mode_to_string(secure));
b2a22049 1328 printf(" TPM2 Support: %s\n", yes_no(efi_has_tpm2()));
8a96369e 1329
c1b9708c
LP
1330 k = efi_get_reboot_to_firmware();
1331 if (k > 0)
8a96369e 1332 printf(" Boot into FW: %sactive%s\n", ansi_highlight_yellow(), ansi_normal());
c1b9708c 1333 else if (k == 0)
8a96369e 1334 printf(" Boot into FW: supported\n");
c1b9708c 1335 else if (k == -EOPNOTSUPP)
8a96369e
LP
1336 printf(" Boot into FW: not supported\n");
1337 else {
c1b9708c 1338 errno = -k;
8a96369e
LP
1339 printf(" Boot into FW: %sfailed%s (%m)\n", ansi_highlight_red(), ansi_normal());
1340 }
2f2c539c
LP
1341 printf("\n");
1342
7fd66f3c 1343 printf("Current Boot Loader:\n");
ba857253 1344 printf(" Product: %s%s%s\n", ansi_highlight(), strna(loader), ansi_normal());
80641a81 1345
c67bd42b 1346 for (size_t i = 0; i < ELEMENTSOF(flags); i++)
607ebf2b 1347 print_yes_no_line(i == 0, FLAGS_SET(loader_features, flags[i].flag), flags[i].name);
80641a81 1348
607ebf2b
ZJS
1349 sd_id128_t bootloader_esp_uuid;
1350 bool have_bootloader_esp_uuid = efi_loader_get_device_part_uuid(&bootloader_esp_uuid) >= 0;
80641a81 1351
250db1bf 1352 print_yes_no_line(false, have_bootloader_esp_uuid, "Boot loader sets ESP information");
607ebf2b 1353 if (have_bootloader_esp_uuid && !sd_id128_equal(esp_uuid, bootloader_esp_uuid))
9e516e4c 1354 printf("WARNING: The boot loader reports a different ESP UUID than detected!\n");
80641a81 1355
81375b9b
ДГ
1356 if (stub)
1357 printf(" Stub: %s\n", stub);
e28973ee 1358 if (!sd_id128_is_null(loader_part_uuid))
bd44566c 1359 printf(" ESP: /dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR "\n",
2f2c539c
LP
1360 SD_ID128_FORMAT_VAL(loader_part_uuid));
1361 else
cd2d4c7f 1362 printf(" ESP: n/a\n");
9a6f746f 1363 printf(" File: %s%s\n", special_glyph(SPECIAL_GLYPH_TREE_RIGHT), strna(loader_path));
2f2c539c 1364 printf("\n");
d6e9a347
LP
1365
1366 printf("Random Seed:\n");
e6f055cb
ZJS
1367 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderRandomSeed)), F_OK) >= 0;
1368 printf(" Passed to OS: %s\n", yes_no(have));
1369 have = access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderSystemToken)), F_OK) >= 0;
1370 printf(" System Token: %s\n", have ? "set" : "not set");
d6e9a347
LP
1371
1372 if (arg_esp_path) {
1373 _cleanup_free_ char *p = NULL;
1374
1375 p = path_join(arg_esp_path, "/loader/random-seed");
1376 if (!p)
1377 return log_oom();
1378
e6f055cb
ZJS
1379 have = access(p, F_OK) >= 0;
1380 printf(" Exists: %s\n", yes_no(have));
d6e9a347
LP
1381 }
1382
1383 printf("\n");
2f2c539c 1384 } else
cd2d4c7f 1385 printf("System:\n Not booted with EFI\n\n");
7b4d7cc0 1386
fbf45d22
LP
1387 if (arg_esp_path) {
1388 k = status_binaries(arg_esp_path, esp_uuid);
ecec2a5d
LP
1389 if (k < 0)
1390 r = k;
1391 }
2f2c539c 1392
cd2d4c7f 1393 if (is_efi_boot()) {
46fb255b
ZJS
1394 k = status_variables();
1395 if (k < 0)
1396 r = k;
cd2d4c7f 1397 }
0974a682 1398
fbf45d22 1399 if (arg_esp_path || arg_xbootldr_path) {
81fed855 1400 k = status_entries(arg_esp_path, esp_uuid, arg_xbootldr_path, xbootldr_uuid);
ecec2a5d
LP
1401 if (k < 0)
1402 r = k;
1403 }
7e87c7d9 1404
46fb255b 1405 return r;
2f2c539c 1406}
7b4d7cc0 1407
7e87c7d9 1408static int verb_list(int argc, char *argv[], void *userdata) {
5caa3167 1409 _cleanup_(boot_config_free) BootConfig config = {};
d4bd786d 1410 _cleanup_strv_free_ char **efi_entries = NULL;
5caa3167 1411 int r;
7e87c7d9 1412
5caa3167
LP
1413 /* If we lack privileges we invoke find_esp_and_warn() in "unprivileged mode" here, which does two things: turn
1414 * off logging about access errors and turn off potentially privileged device probing. Here we're interested in
1415 * the latter but not the former, hence request the mode, and log about EACCES. */
7e87c7d9 1416
e5a8b4b5 1417 r = acquire_esp(/* unprivileged_mode= */ geteuid() != 0, /* graceful= */ false, NULL, NULL, NULL, NULL);
5caa3167
LP
1418 if (r == -EACCES) /* We really need the ESP path for this call, hence also log about access errors */
1419 return log_error_errno(r, "Failed to determine ESP: %m");
7e87c7d9
ZJS
1420 if (r < 0)
1421 return r;
1422
e5a8b4b5 1423 r = acquire_xbootldr(/* unprivileged_mode= */ geteuid() != 0, NULL);
fbf45d22
LP
1424 if (r == -EACCES)
1425 return log_error_errno(r, "Failed to determine XBOOTLDR partition: %m");
1426 if (r < 0)
1427 return r;
1428
1429 r = boot_entries_load_config(arg_esp_path, arg_xbootldr_path, &config);
7e87c7d9 1430 if (r < 0)
21f7a622 1431 return r;
7e87c7d9 1432
d4bd786d
LP
1433 r = efi_loader_get_entries(&efi_entries);
1434 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
1435 log_debug_errno(r, "Boot loader reported no entries.");
1436 else if (r < 0)
1437 log_warning_errno(r, "Failed to determine entries reported by boot loader, ignoring: %m");
1438 else
1439 (void) boot_entries_augment_from_loader(&config, efi_entries, false);
bd2865ca 1440
20a28174
LP
1441 if (config.n_entries == 0)
1442 log_info("No boot loader entries found.");
1443 else {
384c2c32 1444 pager_open(arg_pager_flags);
57db6f18 1445
20a28174 1446 printf("Boot Loader Entries:\n");
7e87c7d9 1447
c67bd42b 1448 for (size_t n = 0; n < config.n_entries; n++) {
20a28174
LP
1449 r = boot_entry_show(config.entries + n, n == (size_t) config.default_entry);
1450 if (r < 0)
1451 return r;
7e87c7d9 1452
4629499e
LP
1453 if (n+1 < config.n_entries)
1454 putchar('\n');
7e87c7d9 1455 }
cd2d4c7f 1456 }
0974a682 1457
7e87c7d9 1458 return 0;
2f2c539c 1459}
7b4d7cc0 1460
e44c3229
LP
1461static int install_random_seed(const char *esp) {
1462 _cleanup_(unlink_and_freep) char *tmp = NULL;
1463 _cleanup_free_ void *buffer = NULL;
1464 _cleanup_free_ char *path = NULL;
1465 _cleanup_close_ int fd = -1;
1466 size_t sz, token_size;
1467 ssize_t n;
1468 int r;
1469
1470 assert(esp);
1471
1472 path = path_join(esp, "/loader/random-seed");
1473 if (!path)
1474 return log_oom();
1475
1476 sz = random_pool_size();
1477
1478 buffer = malloc(sz);
1479 if (!buffer)
1480 return log_oom();
1481
1482 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1483 if (r < 0)
a4d20801 1484 return log_error_errno(r, "Failed to acquire random seed: %m");
e44c3229 1485
a4a55e9a
LP
1486 /* Normally create_subdirs() should already have created everything we need, but in case "bootctl
1487 * random-seed" is called we want to just create the minimum we need for it, and not the full
1488 * list. */
1489 r = mkdir_parents(path, 0755);
1490 if (r < 0)
1491 return log_error_errno(r, "Failed to create parent directory for %s: %m", path);
1492
e44c3229
LP
1493 r = tempfn_random(path, "bootctl", &tmp);
1494 if (r < 0)
1495 return log_oom();
1496
1497 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|O_WRONLY|O_CLOEXEC, 0600);
1498 if (fd < 0) {
1499 tmp = mfree(tmp);
1500 return log_error_errno(fd, "Failed to open random seed file for writing: %m");
1501 }
1502
1503 n = write(fd, buffer, sz);
1504 if (n < 0)
1505 return log_error_errno(errno, "Failed to write random seed file: %m");
1506 if ((size_t) n != sz)
1507 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while writing random seed file.");
1508
1509 if (rename(tmp, path) < 0)
1510 return log_error_errno(r, "Failed to move random seed file into place: %m");
1511
1512 tmp = mfree(tmp);
1513
a4d20801 1514 log_info("Random seed file %s successfully written (%zu bytes).", path, sz);
e44c3229
LP
1515
1516 if (!arg_touch_variables)
1517 return 0;
1518
1519 if (!is_efi_boot()) {
1520 log_notice("Not booted with EFI, skipping EFI variable setup.");
1521 return 0;
1522 }
1523
1524 r = getenv_bool("SYSTEMD_WRITE_SYSTEM_TOKEN");
1525 if (r < 0) {
1526 if (r != -ENXIO)
1527 log_warning_errno(r, "Failed to parse $SYSTEMD_WRITE_SYSTEM_TOKEN, ignoring.");
1528
1529 if (detect_vm() > 0) {
1530 /* Let's not write a system token if we detect we are running in a VM
1531 * environment. Why? Our default security model for the random seed uses the system
1532 * token as a mechanism to ensure we are not vulnerable to golden master sloppiness
1533 * issues, i.e. that people initialize the random seed file, then copy the image to
1534 * many systems and end up with the same random seed in each that is assumed to be
1535 * valid but in reality is the same for all machines. By storing a system token in
1536 * the EFI variable space we can make sure that even though the random seeds on disk
1537 * are all the same they will be different on each system under the assumption that
1538 * the EFI variable space is maintained separate from the random seed storage. That
162392b7 1539 * is generally the case on physical systems, as the ESP is stored on persistent
e44c3229
LP
1540 * storage, and the EFI variables in NVRAM. However in virtualized environments this
1541 * is generally not true: the EFI variable set is typically stored along with the
1542 * disk image itself. For example, using the OVMF EFI firmware the EFI variables are
1543 * stored in a file in the ESP itself. */
1544
1545 log_notice("Not installing system token, since we are running in a virtualized environment.");
1546 return 0;
1547 }
1548 } else if (r == 0) {
1549 log_notice("Not writing system token, because $SYSTEMD_WRITE_SYSTEM_TOKEN is set to false.");
1550 return 0;
1551 }
1552
e6f055cb 1553 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), NULL, NULL, &token_size);
ad0b610b
LP
1554 if (r == -ENODATA)
1555 log_debug_errno(r, "LoaderSystemToken EFI variable is invalid (too short?), replacing.");
1556 else if (r < 0) {
e44c3229
LP
1557 if (r != -ENOENT)
1558 return log_error_errno(r, "Failed to test system token validity: %m");
1559 } else {
1560 if (token_size >= sz) {
1561 /* Let's avoid writes if we can, and initialize this only once. */
1562 log_debug("System token already written, not updating.");
1563 return 0;
1564 }
1565
1566 log_debug("Existing system token size (%zu) does not match our expectations (%zu), replacing.", token_size, sz);
1567 }
1568
1569 r = genuine_random_bytes(buffer, sz, RANDOM_BLOCK);
1570 if (r < 0)
1571 return log_error_errno(r, "Failed to acquire random seed: %m");
1572
1573 /* Let's write this variable with an umask in effect, so that unprivileged users can't see the token
1574 * and possibly get identification information or too much insight into the kernel's entropy pool
1575 * state. */
1576 RUN_WITH_UMASK(0077) {
e6f055cb 1577 r = efi_set_variable(EFI_LOADER_VARIABLE(LoaderSystemToken), buffer, sz);
351de38e
LP
1578 if (r < 0) {
1579 if (!arg_graceful)
1580 return log_error_errno(r, "Failed to write 'LoaderSystemToken' EFI variable: %m");
1581
1582 if (r == -EINVAL)
1583 log_warning_errno(r, "Unable to write 'LoaderSystemToken' EFI variable (firmware problem?), ignoring: %m");
1584 else
1585 log_warning_errno(r, "Unable to write 'LoaderSystemToken' EFI variable, ignoring: %m");
1586 } else
1587 log_info("Successfully initialized system token in EFI variable with %zu bytes.", sz);
e44c3229
LP
1588 }
1589
e44c3229
LP
1590 return 0;
1591}
1592
fbf45d22
LP
1593static int sync_everything(void) {
1594 int ret = 0, k;
e0e8d177 1595
fbf45d22
LP
1596 if (arg_esp_path) {
1597 k = syncfs_path(AT_FDCWD, arg_esp_path);
1598 if (k < 0)
1599 ret = log_error_errno(k, "Failed to synchronize the ESP '%s': %m", arg_esp_path);
1600 }
e0e8d177 1601
fbf45d22
LP
1602 if (arg_xbootldr_path) {
1603 k = syncfs_path(AT_FDCWD, arg_xbootldr_path);
1604 if (k < 0)
1605 ret = log_error_errno(k, "Failed to synchronize $BOOT '%s': %m", arg_xbootldr_path);
1606 }
e0e8d177 1607
fbf45d22 1608 return ret;
e0e8d177
LP
1609}
1610
2f2c539c 1611static int verb_install(int argc, char *argv[], void *userdata) {
2f2c539c
LP
1612 sd_id128_t uuid = SD_ID128_NULL;
1613 uint64_t pstart = 0, psize = 0;
1614 uint32_t part = 0;
e5a8b4b5 1615 bool install, graceful;
2f2c539c
LP
1616 int r;
1617
e5a8b4b5
LP
1618 install = streq(argv[0], "install");
1619 graceful = !install && arg_graceful; /* support graceful mode for updates */
1620
1621 r = acquire_esp(/* unprivileged_mode= */ false, graceful, &part, &pstart, &psize, &uuid);
1622 if (graceful && r == -ENOKEY)
1623 return 0; /* If --graceful is specified and we can't find an ESP, handle this cleanly */
2f2c539c
LP
1624 if (r < 0)
1625 return r;
1626
e5a8b4b5 1627 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL);
fbf45d22
LP
1628 if (r < 0)
1629 return r;
1630
6a3fff75 1631 settle_make_machine_id_directory();
1632
2f2c539c 1633 RUN_WITH_UMASK(0002) {
fbf45d22
LP
1634 if (install) {
1635 /* Don't create any of these directories when we are just updating. When we update
1636 * we'll drop-in our files (unless there are newer ones already), but we won't create
1637 * the directories for them in the first place. */
e44c3229
LP
1638 r = create_subdirs(arg_esp_path, esp_subdirs);
1639 if (r < 0)
1640 return r;
1641
1642 r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
fbf45d22
LP
1643 if (r < 0)
1644 return r;
1645 }
1646
1647 r = install_binaries(arg_esp_path, install);
0974a682 1648 if (r < 0)
d3226d77 1649 return r;
0974a682 1650
2f2c539c 1651 if (install) {
31e57550 1652 r = install_loader_config(arg_esp_path);
e44c3229
LP
1653 if (r < 0)
1654 return r;
1655
6a3fff75 1656 r = install_machine_id_directory(arg_dollar_boot_path());
1657 if (r < 0)
1658 return r;
1659
e44c3229 1660 r = install_random_seed(arg_esp_path);
d3226d77
ZJS
1661 if (r < 0)
1662 return r;
1663 }
2f2c539c 1664 }
0974a682 1665
fbf45d22 1666 (void) sync_everything();
e0e8d177 1667
2f2c539c 1668 if (arg_touch_variables)
fbf45d22 1669 r = install_variables(arg_esp_path,
2f2c539c
LP
1670 part, pstart, psize, uuid,
1671 "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi",
1672 install);
7b4d7cc0 1673
2f2c539c
LP
1674 return r;
1675}
0974a682 1676
2f2c539c 1677static int verb_remove(int argc, char *argv[], void *userdata) {
31e57550 1678 sd_id128_t uuid = SD_ID128_NULL;
fbf45d22 1679 int r, q;
0974a682 1680
e5a8b4b5 1681 r = acquire_esp(/* unprivileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, &uuid);
2f2c539c
LP
1682 if (r < 0)
1683 return r;
1684
e5a8b4b5 1685 r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL);
fbf45d22
LP
1686 if (r < 0)
1687 return r;
2f2c539c 1688
6a3fff75 1689 settle_make_machine_id_directory();
1690
fbf45d22 1691 r = remove_binaries(arg_esp_path);
e0e8d177 1692
e44c3229 1693 q = remove_file(arg_esp_path, "/loader/loader.conf");
fbf45d22
LP
1694 if (q < 0 && r >= 0)
1695 r = q;
1696
e44c3229 1697 q = remove_file(arg_esp_path, "/loader/random-seed");
fbf45d22
LP
1698 if (q < 0 && r >= 0)
1699 r = q;
2f2c539c 1700
e44c3229 1701 q = remove_subdirs(arg_esp_path, esp_subdirs);
fbf45d22
LP
1702 if (q < 0 && r >= 0)
1703 r = q;
1704
e44c3229
LP
1705 q = remove_subdirs(arg_esp_path, dollar_boot_subdirs);
1706 if (q < 0 && r >= 0)
1707 r = q;
fbf45d22 1708
6a3fff75 1709 q = remove_machine_id_directory(arg_esp_path);
1710 if (q < 0 && r >= 0)
1711 r = 1;
1712
e44c3229
LP
1713 if (arg_xbootldr_path) {
1714 /* Remove the latter two also in the XBOOTLDR partition if it exists */
1715 q = remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs);
1716 if (q < 0 && r >= 0)
1717 r = q;
6a3fff75 1718
1719 q = remove_machine_id_directory(arg_xbootldr_path);
1720 if (q < 0 && r >= 0)
1721 r = q;
7b4d7cc0
KS
1722 }
1723
e44c3229
LP
1724 (void) sync_everything();
1725
1726 if (!arg_touch_variables)
1727 return r;
1728
1729 q = remove_variables(uuid, "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi", true);
1730 if (q < 0 && r >= 0)
1731 r = q;
1732
1733 q = remove_loader_variables();
1734 if (q < 0 && r >= 0)
1735 r = q;
1736
d3226d77 1737 return r;
7b4d7cc0
KS
1738}
1739
a2aa605d
LP
1740static int verb_is_installed(int argc, char *argv[], void *userdata) {
1741 _cleanup_free_ char *p = NULL;
1742 int r;
1743
e5a8b4b5 1744 r = acquire_esp(/* privileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, NULL);
a2aa605d
LP
1745 if (r < 0)
1746 return r;
1747
1748 /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
1749 * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
1750 * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
1751 * should be a suitable and very minimal check for a number of reasons:
1752 *
1753 * → The check is architecture independent (i.e. we check if any systemd-boot loader is installed, not a
1754 * specific one.)
1755 *
1756 * → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
1757 * /EFI/BOOT/BOOT*.EFI fallback binary.
1758 *
1759 * → It specifically checks for systemd-boot, not for other boot loaders (which a check for
1760 * /boot/loader/entries would do). */
1761
1762 p = path_join(arg_esp_path, "/EFI/systemd/");
1763 if (!p)
1764 return log_oom();
1765
1766 r = dir_is_empty(p);
1767 if (r > 0 || r == -ENOENT) {
1768 puts("no");
1769 return EXIT_FAILURE;
1770 }
1771 if (r < 0)
1772 return log_error_errno(r, "Failed to detect whether systemd-boot is installed: %m");
1773
1774 puts("yes");
1775 return EXIT_SUCCESS;
1776}
1777
39ddc32a
JJ
1778static int parse_timeout(const char *arg1, char16_t **ret_timeout, size_t *ret_timeout_size) {
1779 char utf8[DECIMAL_STR_MAX(usec_t)];
1780 char16_t *encoded;
1781 usec_t timeout;
1782 int r;
1783
1784 assert(arg1);
1785 assert(ret_timeout);
1786 assert(ret_timeout_size);
1787
1788 if (streq(arg1, "menu-force"))
1789 timeout = USEC_INFINITY;
1790 else if (streq(arg1, "menu-hidden"))
1791 timeout = 0;
1792 else {
1793 r = parse_time(arg1, &timeout, USEC_PER_SEC);
1794 if (r < 0)
1795 return log_error_errno(r, "Failed to parse timeout '%s': %m", arg1);
1796 if (timeout != USEC_INFINITY && timeout > UINT32_MAX * USEC_PER_SEC)
1797 log_warning("Timeout is too long and will be treated as 'menu-force' instead.");
1798 }
1799
1800 xsprintf(utf8, USEC_FMT, MIN(timeout / USEC_PER_SEC, UINT32_MAX));
6663b509 1801
39ddc32a
JJ
1802 encoded = utf8_to_utf16(utf8, strlen(utf8));
1803 if (!encoded)
1804 return log_oom();
6663b509 1805
39ddc32a
JJ
1806 *ret_timeout = encoded;
1807 *ret_timeout_size = char16_strlen(encoded) * 2 + 2;
1808 return 0;
1809}
1810
c4b84347 1811static int parse_loader_entry_target_arg(const char *arg1, char16_t **ret_target, size_t *ret_target_size) {
6663b509 1812 char16_t *encoded = NULL;
c4b84347 1813 int r;
6663b509
LP
1814
1815 assert(arg1);
1816 assert(ret_target);
1817 assert(ret_target_size);
1818
c4b84347 1819 if (streq(arg1, "@current")) {
e6f055cb 1820 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntrySelected), NULL, (void *) ret_target, ret_target_size);
c4b84347
ДГ
1821 if (r < 0)
1822 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntrySelected': %m");
6663b509 1823
c4b84347 1824 } else if (streq(arg1, "@oneshot")) {
e6f055cb 1825 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryOneShot), NULL, (void *) ret_target, ret_target_size);
c4b84347
ДГ
1826 if (r < 0)
1827 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryOneShot': %m");
6663b509 1828
c4b84347 1829 } else if (streq(arg1, "@default")) {
e6f055cb 1830 r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryDefault), NULL, (void *) ret_target, ret_target_size);
c4b84347
ДГ
1831 if (r < 0)
1832 return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryDefault': %m");
6663b509 1833
ee4fd9cb 1834 } else if (arg1[0] == '@' && !streq(arg1, "@saved"))
6663b509
LP
1835 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unsupported special entry identifier: %s", arg1);
1836 else {
c4b84347
ДГ
1837 encoded = utf8_to_utf16(arg1, strlen(arg1));
1838 if (!encoded)
1839 return log_oom();
6663b509 1840
c4b84347
ДГ
1841 *ret_target = encoded;
1842 *ret_target_size = char16_strlen(encoded) * 2 + 2;
1843 }
6663b509 1844
c4b84347
ДГ
1845 return 0;
1846}
1847
39ddc32a 1848static int verb_set_efivar(int argc, char *argv[], void *userdata) {
d88c96ff
LP
1849 int r;
1850
baaa35ad
ZJS
1851 if (!is_efi_boot())
1852 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1853 "Not booted with UEFI.");
d88c96ff 1854
e6f055cb 1855 if (access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderInfo)), F_OK) < 0) {
d88c96ff
LP
1856 if (errno == ENOENT) {
1857 log_error_errno(errno, "Not booted with a supported boot loader.");
1858 return -EOPNOTSUPP;
1859 }
1860
1861 return log_error_errno(errno, "Failed to detect whether boot loader supports '%s' operation: %m", argv[0]);
1862 }
1863
baaa35ad
ZJS
1864 if (detect_container() > 0)
1865 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1866 "'%s' operation not supported in a container.",
1867 argv[0]);
d88c96ff 1868
baaa35ad
ZJS
1869 if (!arg_touch_variables)
1870 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
39ddc32a 1871 "'%s' operation cannot be combined with --no-variables.",
baaa35ad 1872 argv[0]);
d88c96ff 1873
39ddc32a
JJ
1874 const char *variable;
1875 int (* arg_parser)(const char *, char16_t **, size_t *);
1876
1877 if (streq(argv[0], "set-default")) {
1878 variable = EFI_LOADER_VARIABLE(LoaderEntryDefault);
1879 arg_parser = parse_loader_entry_target_arg;
1880 } else if (streq(argv[0], "set-oneshot")) {
1881 variable = EFI_LOADER_VARIABLE(LoaderEntryOneShot);
1882 arg_parser = parse_loader_entry_target_arg;
1883 } else if (streq(argv[0], "set-timeout")) {
1884 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeout);
1885 arg_parser = parse_timeout;
1886 } else if (streq(argv[0], "set-timeout-oneshot")) {
1887 variable = EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot);
1888 arg_parser = parse_timeout;
1889 } else
1890 assert_not_reached();
d88c96ff
LP
1891
1892 if (isempty(argv[1])) {
e6f055cb 1893 r = efi_set_variable(variable, NULL, 0);
d88c96ff 1894 if (r < 0 && r != -ENOENT)
e6f055cb 1895 return log_error_errno(r, "Failed to remove EFI variable '%s': %m", variable);
d88c96ff 1896 } else {
39ddc32a
JJ
1897 _cleanup_free_ char16_t *value = NULL;
1898 size_t value_size = 0;
d88c96ff 1899
39ddc32a 1900 r = arg_parser(argv[1], &value, &value_size);
c4b84347
ДГ
1901 if (r < 0)
1902 return r;
39ddc32a 1903 r = efi_set_variable(variable, value, value_size);
d88c96ff 1904 if (r < 0)
e6f055cb 1905 return log_error_errno(r, "Failed to update EFI variable '%s': %m", variable);
d88c96ff
LP
1906 }
1907
1908 return 0;
1909}
1910
e44c3229
LP
1911static int verb_random_seed(int argc, char *argv[], void *userdata) {
1912 int r;
1913
351de38e
LP
1914 r = find_esp_and_warn(arg_esp_path, false, &arg_esp_path, NULL, NULL, NULL, NULL);
1915 if (r == -ENOKEY) {
1916 /* find_esp_and_warn() doesn't warn about ENOKEY, so let's do that on our own */
1917 if (!arg_graceful)
1918 return log_error_errno(r, "Unable to find ESP.");
1919
1920 log_notice("No ESP found, not initializing random seed.");
1921 return 0;
1922 }
e44c3229
LP
1923 if (r < 0)
1924 return r;
1925
1926 r = install_random_seed(arg_esp_path);
1927 if (r < 0)
1928 return r;
1929
1930 (void) sync_everything();
1931 return 0;
1932}
1933
2536752d 1934static int verb_systemd_efi_options(int argc, char *argv[], void *userdata) {
4e5aa791
ZJS
1935 int r;
1936
1937 if (argc == 1) {
ad2d6880 1938 _cleanup_free_ char *line = NULL, *new = NULL;
4e5aa791 1939
2536752d 1940 r = systemd_efi_options_variable(&line);
ad2d6880
ZJS
1941 if (r == -ENODATA)
1942 log_debug("No SystemdOptions EFI variable present in cache.");
1943 else if (r < 0)
1944 return log_error_errno(r, "Failed to read SystemdOptions EFI variable from cache: %m");
1945 else
1946 puts(line);
1947
1948 r = systemd_efi_options_efivarfs_if_newer(&new);
1949 if (r == -ENODATA) {
1950 if (line)
1951 log_notice("Note: SystemdOptions EFI variable has been removed since boot.");
1952 } else if (r < 0)
1953 log_warning_errno(r, "Failed to check SystemdOptions EFI variable in efivarfs, ignoring: %m");
1954 else if (new && !streq_ptr(line, new))
1955 log_notice("Note: SystemdOptions EFI variable has been modified since boot. New value: %s",
1956 new);
4e5aa791 1957 } else {
e6f055cb 1958 r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE(SystemdOptions), argv[1]);
4e5aa791
ZJS
1959 if (r < 0)
1960 return log_error_errno(r, "Failed to set SystemdOptions EFI variable: %m");
1961 }
1962
1963 return 0;
1964}
1965
002914e6
LP
1966static int verb_reboot_to_firmware(int argc, char *argv[], void *userdata) {
1967 int r;
1968
1969 if (argc < 2) {
1970 r = efi_get_reboot_to_firmware();
1971 if (r > 0) {
1972 puts("active");
1973 return EXIT_SUCCESS; /* success */
1974 }
1975 if (r == 0) {
1976 puts("supported");
1977 return 1; /* recognizable error #1 */
1978 }
1979 if (r == -EOPNOTSUPP) {
1980 puts("not supported");
1981 return 2; /* recognizable error #2 */
1982 }
1983
1984 log_error_errno(r, "Failed to query reboot-to-firmware state: %m");
1985 return 3; /* other kind of error */
1986 } else {
1987 r = parse_boolean(argv[1]);
1988 if (r < 0)
1989 return log_error_errno(r, "Failed to parse argument: %s", argv[1]);
1990
1991 r = efi_set_reboot_to_firmware(r);
1992 if (r < 0)
1993 return log_error_errno(r, "Failed to set reboot-to-firmware option: %m");
1994
1995 return 0;
1996 }
1997}
1998
2f2c539c 1999static int bootctl_main(int argc, char *argv[]) {
2f2c539c 2000 static const Verb verbs[] = {
2536752d
ZJS
2001 { "help", VERB_ANY, VERB_ANY, 0, help },
2002 { "status", VERB_ANY, 1, VERB_DEFAULT, verb_status },
2003 { "install", VERB_ANY, 1, 0, verb_install },
2004 { "update", VERB_ANY, 1, 0, verb_install },
2005 { "remove", VERB_ANY, 1, 0, verb_remove },
2006 { "is-installed", VERB_ANY, 1, 0, verb_is_installed },
2007 { "list", VERB_ANY, 1, 0, verb_list },
39ddc32a
JJ
2008 { "set-default", 2, 2, 0, verb_set_efivar },
2009 { "set-oneshot", 2, 2, 0, verb_set_efivar },
2010 { "set-timeout", 2, 2, 0, verb_set_efivar },
2011 { "set-timeout-oneshot", 2, 2, 0, verb_set_efivar },
2536752d
ZJS
2012 { "random-seed", VERB_ANY, 1, 0, verb_random_seed },
2013 { "systemd-efi-options", VERB_ANY, 2, 0, verb_systemd_efi_options },
002914e6 2014 { "reboot-to-firmware", VERB_ANY, 2, 0, verb_reboot_to_firmware },
2f2c539c
LP
2015 {}
2016 };
2017
2018 return dispatch_verb(argc, argv, verbs, NULL);
2019}
2020
608f8ec9 2021static int run(int argc, char *argv[]) {
601185b4 2022 int r;
7b4d7cc0
KS
2023
2024 log_parse_environment();
2025 log_open();
2026
341890de 2027 /* If we run in a container, automatically turn off EFI file system access */
2f2c539c
LP
2028 if (detect_container() > 0)
2029 arg_touch_variables = false;
2030
7b4d7cc0 2031 r = parse_argv(argc, argv);
601185b4 2032 if (r <= 0)
608f8ec9 2033 return r;
57db6f18 2034
608f8ec9 2035 return bootctl_main(argc, argv);
7b4d7cc0 2036}
608f8ec9 2037
002914e6 2038DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);