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