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