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