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