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