]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/boot/bootctl.c
tree-wide: drop license boilerplate
[thirdparty/systemd.git] / src / boot / bootctl.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2013-2015 Kay Sievers
6 Copyright 2013 Lennart Poettering
7 ***/
8
9 #include <blkid.h>
10 #include <ctype.h>
11 #include <dirent.h>
12 #include <errno.h>
13 #include <ftw.h>
14 #include <getopt.h>
15 #include <limits.h>
16 #include <linux/magic.h>
17 #include <stdbool.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <sys/mman.h>
22 #include <sys/stat.h>
23 #include <sys/statfs.h>
24 #include <unistd.h>
25
26 #include "sd-id128.h"
27
28 #include "alloc-util.h"
29 #include "blkid-util.h"
30 #include "bootspec.h"
31 #include "copy.h"
32 #include "dirent-util.h"
33 #include "efivars.h"
34 #include "fd-util.h"
35 #include "fileio.h"
36 #include "fs-util.h"
37 #include "locale-util.h"
38 #include "parse-util.h"
39 #include "rm-rf.h"
40 #include "stat-util.h"
41 #include "string-util.h"
42 #include "strv.h"
43 #include "terminal-util.h"
44 #include "umask-util.h"
45 #include "util.h"
46 #include "verbs.h"
47 #include "virt.h"
48
49 static char *arg_path = NULL;
50 static bool arg_print_path = false;
51 static bool arg_touch_variables = true;
52
53 static int acquire_esp(
54 bool unprivileged_mode,
55 uint32_t *ret_part,
56 uint64_t *ret_pstart,
57 uint64_t *ret_psize,
58 sd_id128_t *ret_uuid) {
59
60 char *np;
61 int r;
62
63 /* Find the ESP, and log about errors. Note that find_esp_and_warn() will log in all error cases on its own,
64 * except for ENOKEY (which is good, we want to show our own message in that case, suggesting use of --path=)
65 * and EACCESS (only when we request unprivileged mode; in this case we simply eat up the error here, so that
66 * --list and --status work too, without noise about this). */
67
68 r = find_esp_and_warn(arg_path, unprivileged_mode, &np, ret_part, ret_pstart, ret_psize, ret_uuid);
69 if (r == -ENOKEY)
70 return log_error_errno(r,
71 "Couldn't find EFI system partition. It is recommended to mount it to /boot or /efi.\n"
72 "Alternatively, use --path= to specify path to mount point.");
73 if (r < 0)
74 return r;
75
76 free_and_replace(arg_path, np);
77
78 log_debug("Using EFI System Partition at %s.", arg_path);
79
80 return 0;
81 }
82
83 /* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */
84 static int get_file_version(int fd, char **v) {
85 struct stat st;
86 char *buf;
87 const char *s, *e;
88 char *x = NULL;
89 int r = 0;
90
91 assert(fd >= 0);
92 assert(v);
93
94 if (fstat(fd, &st) < 0)
95 return log_error_errno(errno, "Failed to stat EFI binary: %m");
96
97 if (st.st_size < 27) {
98 *v = NULL;
99 return 0;
100 }
101
102 buf = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
103 if (buf == MAP_FAILED)
104 return log_error_errno(errno, "Failed to memory map EFI binary: %m");
105
106 s = memmem(buf, st.st_size - 8, "#### LoaderInfo: ", 17);
107 if (!s)
108 goto finish;
109 s += 17;
110
111 e = memmem(s, st.st_size - (s - buf), " ####", 5);
112 if (!e || e - s < 3) {
113 log_error("Malformed version string.");
114 r = -EINVAL;
115 goto finish;
116 }
117
118 x = strndup(s, e - s);
119 if (!x) {
120 r = log_oom();
121 goto finish;
122 }
123 r = 1;
124
125 finish:
126 (void) munmap(buf, st.st_size);
127 *v = x;
128 return r;
129 }
130
131 static int enumerate_binaries(const char *esp_path, const char *path, const char *prefix) {
132 char *p;
133 _cleanup_closedir_ DIR *d = NULL;
134 struct dirent *de;
135 int r = 0, c = 0;
136
137 p = strjoina(esp_path, "/", path);
138 d = opendir(p);
139 if (!d) {
140 if (errno == ENOENT)
141 return 0;
142
143 return log_error_errno(errno, "Failed to read \"%s\": %m", p);
144 }
145
146 FOREACH_DIRENT(de, d, break) {
147 _cleanup_close_ int fd = -1;
148 _cleanup_free_ char *v = NULL;
149
150 if (!endswith_no_case(de->d_name, ".efi"))
151 continue;
152
153 if (prefix && !startswith_no_case(de->d_name, prefix))
154 continue;
155
156 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
157 if (fd < 0)
158 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
159
160 r = get_file_version(fd, &v);
161 if (r < 0)
162 return r;
163 if (r > 0)
164 printf(" File: %s/%s/%s (%s)\n", special_glyph(TREE_RIGHT), path, de->d_name, v);
165 else
166 printf(" File: %s/%s/%s\n", special_glyph(TREE_RIGHT), path, de->d_name);
167 c++;
168 }
169
170 return c;
171 }
172
173 static int status_binaries(const char *esp_path, sd_id128_t partition) {
174 int r;
175
176 printf("Boot Loader Binaries:\n");
177
178 if (!esp_path) {
179 printf(" ESP: Cannot find or access mount point of ESP.\n\n");
180 return -ENOENT;
181 }
182
183 printf(" ESP: %s", esp_path);
184 if (!sd_id128_is_null(partition))
185 printf(" (/dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x)", SD_ID128_FORMAT_VAL(partition));
186 printf("\n");
187
188 r = enumerate_binaries(esp_path, "EFI/systemd", NULL);
189 if (r == 0)
190 log_error("systemd-boot not installed in ESP.");
191 else if (r < 0)
192 return r;
193
194 r = enumerate_binaries(esp_path, "EFI/BOOT", "boot");
195 if (r == 0)
196 log_error("No default/fallback boot loader installed in ESP.");
197 else if (r < 0)
198 return r;
199
200 printf("\n");
201
202 return 0;
203 }
204
205 static int print_efi_option(uint16_t id, bool in_order) {
206 _cleanup_free_ char *title = NULL;
207 _cleanup_free_ char *path = NULL;
208 sd_id128_t partition;
209 bool active;
210 int r = 0;
211
212 r = efi_get_boot_option(id, &title, &partition, &path, &active);
213 if (r < 0)
214 return r;
215
216 /* print only configured entries with partition information */
217 if (!path || sd_id128_is_null(partition))
218 return 0;
219
220 efi_tilt_backslashes(path);
221
222 printf(" Title: %s\n", strna(title));
223 printf(" ID: 0x%04X\n", id);
224 printf(" Status: %sactive%s\n", active ? "" : "in", in_order ? ", boot-order" : "");
225 printf(" Partition: /dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", SD_ID128_FORMAT_VAL(partition));
226 printf(" File: %s%s\n", special_glyph(TREE_RIGHT), path);
227 printf("\n");
228
229 return 0;
230 }
231
232 static int status_variables(void) {
233 int n_options, n_order;
234 _cleanup_free_ uint16_t *options = NULL, *order = NULL;
235 int i;
236
237 n_options = efi_get_boot_options(&options);
238 if (n_options == -ENOENT)
239 return log_error_errno(n_options,
240 "Failed to access EFI variables, efivarfs"
241 " needs to be available at /sys/firmware/efi/efivars/.");
242 if (n_options < 0)
243 return log_error_errno(n_options, "Failed to read EFI boot entries: %m");
244
245 n_order = efi_get_boot_order(&order);
246 if (n_order == -ENOENT)
247 n_order = 0;
248 else if (n_order < 0)
249 return log_error_errno(n_order, "Failed to read EFI boot order.");
250
251 /* print entries in BootOrder first */
252 printf("Boot Loader Entries in EFI Variables:\n");
253 for (i = 0; i < n_order; i++)
254 print_efi_option(order[i], true);
255
256 /* print remaining entries */
257 for (i = 0; i < n_options; i++) {
258 int j;
259
260 for (j = 0; j < n_order; j++)
261 if (options[i] == order[j])
262 goto next_option;
263
264 print_efi_option(options[i], false);
265
266 next_option:
267 continue;
268 }
269
270 return 0;
271 }
272
273 static int status_entries(const char *esp_path, sd_id128_t partition) {
274 int r;
275
276 _cleanup_(boot_config_free) BootConfig config = {};
277
278 printf("Default Boot Entry:\n");
279
280 r = boot_entries_load_config(esp_path, &config);
281 if (r < 0)
282 return log_error_errno(r, "Failed to load bootspec config from \"%s/loader\": %m",
283 esp_path);
284
285 if (config.default_entry < 0)
286 printf("%zu entries, no entry suitable as default\n", config.n_entries);
287 else {
288 const BootEntry *e = &config.entries[config.default_entry];
289
290 printf(" title: %s\n", boot_entry_title(e));
291 if (e->version)
292 printf(" version: %s\n", e->version);
293 if (e->kernel)
294 printf(" linux: %s\n", e->kernel);
295 if (!strv_isempty(e->initrd)) {
296 _cleanup_free_ char *t;
297
298 t = strv_join(e->initrd, " ");
299 if (!t)
300 return log_oom();
301
302 printf(" initrd: %s\n", t);
303 }
304 if (!strv_isempty(e->options)) {
305 _cleanup_free_ char *t;
306
307 t = strv_join(e->options, " ");
308 if (!t)
309 return log_oom();
310
311 printf(" options: %s\n", t);
312 }
313 if (e->device_tree)
314 printf(" devicetree: %s\n", e->device_tree);
315 puts("");
316 }
317
318 return 0;
319 }
320
321 static int compare_product(const char *a, const char *b) {
322 size_t x, y;
323
324 assert(a);
325 assert(b);
326
327 x = strcspn(a, " ");
328 y = strcspn(b, " ");
329 if (x != y)
330 return x < y ? -1 : x > y ? 1 : 0;
331
332 return strncmp(a, b, x);
333 }
334
335 static int compare_version(const char *a, const char *b) {
336 assert(a);
337 assert(b);
338
339 a += strcspn(a, " ");
340 a += strspn(a, " ");
341 b += strcspn(b, " ");
342 b += strspn(b, " ");
343
344 return strverscmp(a, b);
345 }
346
347 static int version_check(int fd_from, const char *from, int fd_to, const char *to) {
348 _cleanup_free_ char *a = NULL, *b = NULL;
349 int r;
350
351 assert(fd_from >= 0);
352 assert(from);
353 assert(fd_to >= 0);
354 assert(to);
355
356 r = get_file_version(fd_from, &a);
357 if (r < 0)
358 return r;
359 if (r == 0) {
360 log_error("Source file \"%s\" does not carry version information!", from);
361 return -EINVAL;
362 }
363
364 r = get_file_version(fd_to, &b);
365 if (r < 0)
366 return r;
367 if (r == 0 || compare_product(a, b) != 0) {
368 log_notice("Skipping \"%s\", since it's owned by another boot loader.", to);
369 return -EEXIST;
370 }
371
372 if (compare_version(a, b) < 0) {
373 log_warning("Skipping \"%s\", since a newer boot loader version exists already.", to);
374 return -ESTALE;
375 }
376
377 return 0;
378 }
379
380 static int copy_file_with_version_check(const char *from, const char *to, bool force) {
381 _cleanup_close_ int fd_from = -1, fd_to = -1;
382 _cleanup_free_ char *t = NULL;
383 int r;
384
385 fd_from = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
386 if (fd_from < 0)
387 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", from);
388
389 if (!force) {
390 fd_to = open(to, O_RDONLY|O_CLOEXEC|O_NOCTTY);
391 if (fd_to < 0) {
392 if (errno != -ENOENT)
393 return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", to);
394 } else {
395 r = version_check(fd_from, from, fd_to, to);
396 if (r < 0)
397 return r;
398
399 if (lseek(fd_from, 0, SEEK_SET) == (off_t) -1)
400 return log_error_errno(errno, "Failed to seek in \"%s\": %m", from);
401
402 fd_to = safe_close(fd_to);
403 }
404 }
405
406 r = tempfn_random(to, NULL, &t);
407 if (r < 0)
408 return log_oom();
409
410 RUN_WITH_UMASK(0000) {
411 fd_to = open(t, O_WRONLY|O_CREAT|O_CLOEXEC|O_EXCL|O_NOFOLLOW, 0644);
412 if (fd_to < 0)
413 return log_error_errno(errno, "Failed to open \"%s\" for writing: %m", t);
414 }
415
416 r = copy_bytes(fd_from, fd_to, (uint64_t) -1, COPY_REFLINK);
417 if (r < 0) {
418 (void) unlink(t);
419 return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
420 }
421
422 (void) copy_times(fd_from, fd_to);
423
424 if (fsync(fd_to) < 0) {
425 (void) unlink_noerrno(t);
426 return log_error_errno(errno, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
427 }
428
429 (void) fsync_directory_of_file(fd_to);
430
431 r = renameat(AT_FDCWD, t, AT_FDCWD, to);
432 if (r < 0) {
433 (void) unlink_noerrno(t);
434 return log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", t, to);
435 }
436
437 log_info("Copied \"%s\" to \"%s\".", from, to);
438
439 return 0;
440 }
441
442 static int mkdir_one(const char *prefix, const char *suffix) {
443 char *p;
444
445 p = strjoina(prefix, "/", suffix);
446 if (mkdir(p, 0700) < 0) {
447 if (errno != EEXIST)
448 return log_error_errno(errno, "Failed to create \"%s\": %m", p);
449 } else
450 log_info("Created \"%s\".", p);
451
452 return 0;
453 }
454
455 static const char *efi_subdirs[] = {
456 "EFI",
457 "EFI/systemd",
458 "EFI/BOOT",
459 "loader",
460 "loader/entries",
461 NULL
462 };
463
464 static int create_dirs(const char *esp_path) {
465 const char **i;
466 int r;
467
468 STRV_FOREACH(i, efi_subdirs) {
469 r = mkdir_one(esp_path, *i);
470 if (r < 0)
471 return r;
472 }
473
474 return 0;
475 }
476
477 static int copy_one_file(const char *esp_path, const char *name, bool force) {
478 char *p, *q;
479 int r;
480
481 p = strjoina(BOOTLIBDIR "/", name);
482 q = strjoina(esp_path, "/EFI/systemd/", name);
483 r = copy_file_with_version_check(p, q, force);
484
485 if (startswith(name, "systemd-boot")) {
486 int k;
487 char *v;
488
489 /* Create the EFI default boot loader name (specified for removable devices) */
490 v = strjoina(esp_path, "/EFI/BOOT/BOOT",
491 name + STRLEN("systemd-boot"));
492 ascii_strupper(strrchr(v, '/') + 1);
493
494 k = copy_file_with_version_check(p, v, force);
495 if (k < 0 && r == 0)
496 r = k;
497 }
498
499 return r;
500 }
501
502 static int install_binaries(const char *esp_path, bool force) {
503 struct dirent *de;
504 _cleanup_closedir_ DIR *d = NULL;
505 int r = 0;
506
507 if (force) {
508 /* Don't create any of these directories when we are
509 * just updating. When we update we'll drop-in our
510 * files (unless there are newer ones already), but we
511 * won't create the directories for them in the first
512 * place. */
513 r = create_dirs(esp_path);
514 if (r < 0)
515 return r;
516 }
517
518 d = opendir(BOOTLIBDIR);
519 if (!d)
520 return log_error_errno(errno, "Failed to open \""BOOTLIBDIR"\": %m");
521
522 FOREACH_DIRENT(de, d, break) {
523 int k;
524
525 if (!endswith_no_case(de->d_name, ".efi"))
526 continue;
527
528 k = copy_one_file(esp_path, de->d_name, force);
529 if (k < 0 && r == 0)
530 r = k;
531 }
532
533 return r;
534 }
535
536 static bool same_entry(uint16_t id, const sd_id128_t uuid, const char *path) {
537 _cleanup_free_ char *opath = NULL;
538 sd_id128_t ouuid;
539 int r;
540
541 r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
542 if (r < 0)
543 return false;
544 if (!sd_id128_equal(uuid, ouuid))
545 return false;
546 if (!streq_ptr(path, opath))
547 return false;
548
549 return true;
550 }
551
552 static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
553 _cleanup_free_ uint16_t *options = NULL;
554 int n, i;
555
556 n = efi_get_boot_options(&options);
557 if (n < 0)
558 return n;
559
560 /* find already existing systemd-boot entry */
561 for (i = 0; i < n; i++)
562 if (same_entry(options[i], uuid, path)) {
563 *id = options[i];
564 return 1;
565 }
566
567 /* find free slot in the sorted BootXXXX variable list */
568 for (i = 0; i < n; i++)
569 if (i != options[i]) {
570 *id = i;
571 return 1;
572 }
573
574 /* use the next one */
575 if (i == 0xffff)
576 return -ENOSPC;
577 *id = i;
578 return 0;
579 }
580
581 static int insert_into_order(uint16_t slot, bool first) {
582 _cleanup_free_ uint16_t *order = NULL;
583 uint16_t *t;
584 int n, i;
585
586 n = efi_get_boot_order(&order);
587 if (n <= 0)
588 /* no entry, add us */
589 return efi_set_boot_order(&slot, 1);
590
591 /* are we the first and only one? */
592 if (n == 1 && order[0] == slot)
593 return 0;
594
595 /* are we already in the boot order? */
596 for (i = 0; i < n; i++) {
597 if (order[i] != slot)
598 continue;
599
600 /* we do not require to be the first one, all is fine */
601 if (!first)
602 return 0;
603
604 /* move us to the first slot */
605 memmove(order + 1, order, i * sizeof(uint16_t));
606 order[0] = slot;
607 return efi_set_boot_order(order, n);
608 }
609
610 /* extend array */
611 t = realloc(order, (n + 1) * sizeof(uint16_t));
612 if (!t)
613 return -ENOMEM;
614 order = t;
615
616 /* add us to the top or end of the list */
617 if (first) {
618 memmove(order + 1, order, n * sizeof(uint16_t));
619 order[0] = slot;
620 } else
621 order[n] = slot;
622
623 return efi_set_boot_order(order, n + 1);
624 }
625
626 static int remove_from_order(uint16_t slot) {
627 _cleanup_free_ uint16_t *order = NULL;
628 int n, i;
629
630 n = efi_get_boot_order(&order);
631 if (n <= 0)
632 return n;
633
634 for (i = 0; i < n; i++) {
635 if (order[i] != slot)
636 continue;
637
638 if (i + 1 < n)
639 memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
640 return efi_set_boot_order(order, n - 1);
641 }
642
643 return 0;
644 }
645
646 static int install_variables(const char *esp_path,
647 uint32_t part, uint64_t pstart, uint64_t psize,
648 sd_id128_t uuid, const char *path,
649 bool first) {
650 char *p;
651 uint16_t slot;
652 int r;
653
654 if (!is_efi_boot()) {
655 log_warning("Not booted with EFI, skipping EFI variable setup.");
656 return 0;
657 }
658
659 p = strjoina(esp_path, path);
660 if (access(p, F_OK) < 0) {
661 if (errno == ENOENT)
662 return 0;
663
664 return log_error_errno(errno, "Cannot access \"%s\": %m", p);
665 }
666
667 r = find_slot(uuid, path, &slot);
668 if (r < 0)
669 return log_error_errno(r,
670 r == -ENOENT ?
671 "Failed to access EFI variables. Is the \"efivarfs\" filesystem mounted?" :
672 "Failed to determine current boot order: %m");
673
674 if (first || r == 0) {
675 r = efi_add_boot_option(slot, "Linux Boot Manager",
676 part, pstart, psize,
677 uuid, path);
678 if (r < 0)
679 return log_error_errno(r, "Failed to create EFI Boot variable entry: %m");
680
681 log_info("Created EFI boot entry \"Linux Boot Manager\".");
682 }
683
684 return insert_into_order(slot, first);
685 }
686
687 static int remove_boot_efi(const char *esp_path) {
688 char *p;
689 _cleanup_closedir_ DIR *d = NULL;
690 struct dirent *de;
691 int r, c = 0;
692
693 p = strjoina(esp_path, "/EFI/BOOT");
694 d = opendir(p);
695 if (!d) {
696 if (errno == ENOENT)
697 return 0;
698
699 return log_error_errno(errno, "Failed to open directory \"%s\": %m", p);
700 }
701
702 FOREACH_DIRENT(de, d, break) {
703 _cleanup_close_ int fd = -1;
704 _cleanup_free_ char *v = NULL;
705
706 if (!endswith_no_case(de->d_name, ".efi"))
707 continue;
708
709 if (!startswith_no_case(de->d_name, "boot"))
710 continue;
711
712 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC);
713 if (fd < 0)
714 return log_error_errno(errno, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
715
716 r = get_file_version(fd, &v);
717 if (r < 0)
718 return r;
719 if (r > 0 && startswith(v, "systemd-boot ")) {
720 r = unlinkat(dirfd(d), de->d_name, 0);
721 if (r < 0)
722 return log_error_errno(errno, "Failed to remove \"%s/%s\": %m", p, de->d_name);
723
724 log_info("Removed \"%s/%s\".", p, de->d_name);
725 }
726
727 c++;
728 }
729
730 return c;
731 }
732
733 static int rmdir_one(const char *prefix, const char *suffix) {
734 char *p;
735
736 p = strjoina(prefix, "/", suffix);
737 if (rmdir(p) < 0) {
738 if (!IN_SET(errno, ENOENT, ENOTEMPTY))
739 return log_error_errno(errno, "Failed to remove \"%s\": %m", p);
740 } else
741 log_info("Removed \"%s\".", p);
742
743 return 0;
744 }
745
746 static int remove_binaries(const char *esp_path) {
747 char *p;
748 int r, q;
749 unsigned i;
750
751 p = strjoina(esp_path, "/EFI/systemd");
752 r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
753
754 q = remove_boot_efi(esp_path);
755 if (q < 0 && r == 0)
756 r = q;
757
758 for (i = ELEMENTSOF(efi_subdirs)-1; i > 0; i--) {
759 q = rmdir_one(esp_path, efi_subdirs[i-1]);
760 if (q < 0 && r == 0)
761 r = q;
762 }
763
764 return r;
765 }
766
767 static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
768 uint16_t slot;
769 int r;
770
771 if (!is_efi_boot())
772 return 0;
773
774 r = find_slot(uuid, path, &slot);
775 if (r != 1)
776 return 0;
777
778 r = efi_remove_boot_option(slot);
779 if (r < 0)
780 return r;
781
782 if (in_order)
783 return remove_from_order(slot);
784
785 return 0;
786 }
787
788 static int install_loader_config(const char *esp_path) {
789
790 char machine_string[SD_ID128_STRING_MAX];
791 _cleanup_(unlink_and_freep) char *t = NULL;
792 _cleanup_fclose_ FILE *f = NULL;
793 sd_id128_t machine_id;
794 const char *p;
795 int r, fd;
796
797 r = sd_id128_get_machine(&machine_id);
798 if (r < 0)
799 return log_error_errno(r, "Failed to get machine id: %m");
800
801 p = strjoina(esp_path, "/loader/loader.conf");
802
803 if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
804 return 0;
805
806 fd = open_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t);
807 if (fd < 0)
808 return log_error_errno(fd, "Failed to open \"%s\" for writing: %m", p);
809
810 f = fdopen(fd, "we");
811 if (!f) {
812 safe_close(fd);
813 return log_oom();
814 }
815
816 fprintf(f, "#timeout 3\n");
817 fprintf(f, "#console-mode keep\n");
818 fprintf(f, "default %s-*\n", sd_id128_to_string(machine_id, machine_string));
819
820 r = fflush_sync_and_check(f);
821 if (r < 0)
822 return log_error_errno(r, "Failed to write \"%s\": %m", p);
823
824 r = link_tmpfile(fd, t, p);
825 if (r == -EEXIST)
826 return 0; /* Silently skip creation if the file exists now (recheck) */
827 if (r < 0)
828 return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
829
830 t = mfree(t);
831
832 return 1;
833 }
834
835 static int help(int argc, char *argv[], void *userdata) {
836
837 printf("%s [COMMAND] [OPTIONS...]\n"
838 "\n"
839 "Install, update or remove the systemd-boot EFI boot manager.\n\n"
840 " -h --help Show this help\n"
841 " --version Print version\n"
842 " --path=PATH Path to the EFI System Partition (ESP)\n"
843 " -p --print-path Print path to the EFI partition\n"
844 " --no-variables Don't touch EFI variables\n"
845 "\n"
846 "Commands:\n"
847 " status Show status of installed systemd-boot and EFI variables\n"
848 " list List boot entries\n"
849 " install Install systemd-boot to the ESP and EFI variables\n"
850 " update Update systemd-boot in the ESP and EFI variables\n"
851 " remove Remove systemd-boot from the ESP and EFI variables\n",
852 program_invocation_short_name);
853
854 return 0;
855 }
856
857 static int parse_argv(int argc, char *argv[]) {
858 enum {
859 ARG_PATH = 0x100,
860 ARG_VERSION,
861 ARG_NO_VARIABLES,
862 };
863
864 static const struct option options[] = {
865 { "help", no_argument, NULL, 'h' },
866 { "version", no_argument, NULL, ARG_VERSION },
867 { "path", required_argument, NULL, ARG_PATH },
868 { "print-path", no_argument, NULL, 'p' },
869 { "no-variables", no_argument, NULL, ARG_NO_VARIABLES },
870 { NULL, 0, NULL, 0 }
871 };
872
873 int c, r;
874
875 assert(argc >= 0);
876 assert(argv);
877
878 while ((c = getopt_long(argc, argv, "hp", options, NULL)) >= 0)
879 switch (c) {
880
881 case 'h':
882 help(0, NULL, NULL);
883 return 0;
884
885 case ARG_VERSION:
886 return version();
887
888 case ARG_PATH:
889 r = free_and_strdup(&arg_path, optarg);
890 if (r < 0)
891 return log_oom();
892 break;
893
894 case 'p':
895 arg_print_path = true;
896 break;
897
898 case ARG_NO_VARIABLES:
899 arg_touch_variables = false;
900 break;
901
902 case '?':
903 return -EINVAL;
904
905 default:
906 assert_not_reached("Unknown option");
907 }
908
909 return 1;
910 }
911
912 static void read_loader_efi_var(const char *name, char **var) {
913 int r;
914
915 r = efi_get_variable_string(EFI_VENDOR_LOADER, name, var);
916 if (r < 0 && r != -ENOENT)
917 log_warning_errno(r, "Failed to read EFI variable %s: %m", name);
918 }
919
920 static int verb_status(int argc, char *argv[], void *userdata) {
921
922 sd_id128_t uuid = SD_ID128_NULL;
923 int r, k;
924
925 r = acquire_esp(geteuid() != 0, NULL, NULL, NULL, &uuid);
926
927 if (arg_print_path) {
928 if (r == -EACCES) /* If we couldn't acquire the ESP path, log about access errors (which is the only
929 * error the find_esp_and_warn() won't log on its own) */
930 return log_error_errno(r, "Failed to determine ESP: %m");
931 if (r < 0)
932 return r;
933
934 puts(arg_path);
935 return 0;
936 }
937
938 r = 0; /* If we couldn't determine the path, then don't consider that a problem from here on, just show what we
939 * can show */
940
941 if (is_efi_boot()) {
942 _cleanup_free_ char *fw_type = NULL, *fw_info = NULL, *loader = NULL, *loader_path = NULL, *stub = NULL;
943 sd_id128_t loader_part_uuid = SD_ID128_NULL;
944
945 read_loader_efi_var("LoaderFirmwareType", &fw_type);
946 read_loader_efi_var("LoaderFirmwareInfo", &fw_info);
947 read_loader_efi_var("LoaderInfo", &loader);
948 read_loader_efi_var("StubInfo", &stub);
949 read_loader_efi_var("LoaderImageIdentifier", &loader_path);
950
951 if (loader_path)
952 efi_tilt_backslashes(loader_path);
953
954 k = efi_loader_get_device_part_uuid(&loader_part_uuid);
955 if (k < 0 && k != -ENOENT)
956 r = log_warning_errno(k, "Failed to read EFI variable LoaderDevicePartUUID: %m");
957
958 printf("System:\n");
959 printf(" Firmware: %s (%s)\n", strna(fw_type), strna(fw_info));
960
961 k = is_efi_secure_boot();
962 if (k < 0)
963 r = log_warning_errno(k, "Failed to query secure boot status: %m");
964 else
965 printf(" Secure Boot: %sd\n", enable_disable(k));
966
967 k = is_efi_secure_boot_setup_mode();
968 if (k < 0)
969 r = log_warning_errno(k, "Failed to query secure boot mode: %m");
970 else
971 printf(" Setup Mode: %s\n", k ? "setup" : "user");
972 printf("\n");
973
974 printf("Current Loader:\n");
975 printf(" Product: %s\n", strna(loader));
976 if (stub)
977 printf(" Stub: %s\n", stub);
978 if (!sd_id128_is_null(loader_part_uuid))
979 printf(" ESP: /dev/disk/by-partuuid/%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
980 SD_ID128_FORMAT_VAL(loader_part_uuid));
981 else
982 printf(" ESP: n/a\n");
983 printf(" File: %s%s\n", special_glyph(TREE_RIGHT), strna(loader_path));
984 printf("\n");
985 } else
986 printf("System:\n Not booted with EFI\n\n");
987
988 if (arg_path) {
989 k = status_binaries(arg_path, uuid);
990 if (k < 0)
991 r = k;
992 }
993
994 if (is_efi_boot()) {
995 k = status_variables();
996 if (k < 0)
997 r = k;
998 }
999
1000 if (arg_path) {
1001 k = status_entries(arg_path, uuid);
1002 if (k < 0)
1003 r = k;
1004 }
1005
1006 return r;
1007 }
1008
1009 static int verb_list(int argc, char *argv[], void *userdata) {
1010 _cleanup_(boot_config_free) BootConfig config = {};
1011 sd_id128_t uuid = SD_ID128_NULL;
1012 unsigned n;
1013 int r;
1014
1015 /* If we lack privileges we invoke find_esp_and_warn() in "unprivileged mode" here, which does two things: turn
1016 * off logging about access errors and turn off potentially privileged device probing. Here we're interested in
1017 * the latter but not the former, hence request the mode, and log about EACCES. */
1018
1019 r = acquire_esp(geteuid() != 0, NULL, NULL, NULL, &uuid);
1020 if (r == -EACCES) /* We really need the ESP path for this call, hence also log about access errors */
1021 return log_error_errno(r, "Failed to determine ESP: %m");
1022 if (r < 0)
1023 return r;
1024
1025 r = boot_entries_load_config(arg_path, &config);
1026 if (r < 0)
1027 return log_error_errno(r, "Failed to load bootspec config from \"%s/loader\": %m",
1028 arg_path);
1029
1030 printf("Available boot entries:\n");
1031
1032 for (n = 0; n < config.n_entries; n++) {
1033 const BootEntry *e = &config.entries[n];
1034
1035 printf(" title: %s%s%s%s%s%s\n",
1036 ansi_highlight(),
1037 boot_entry_title(e),
1038 ansi_normal(),
1039 ansi_highlight_green(),
1040 n == (unsigned) config.default_entry ? " (default)" : "",
1041 ansi_normal());
1042 if (e->version)
1043 printf(" version: %s\n", e->version);
1044 if (e->machine_id)
1045 printf(" machine-id: %s\n", e->machine_id);
1046 if (e->architecture)
1047 printf(" architecture: %s\n", e->architecture);
1048 if (e->kernel)
1049 printf(" linux: %s\n", e->kernel);
1050 if (!strv_isempty(e->initrd)) {
1051 _cleanup_free_ char *t;
1052
1053 t = strv_join(e->initrd, " ");
1054 if (!t)
1055 return log_oom();
1056
1057 printf(" initrd: %s\n", t);
1058 }
1059 if (!strv_isempty(e->options)) {
1060 _cleanup_free_ char *t;
1061
1062 t = strv_join(e->options, " ");
1063 if (!t)
1064 return log_oom();
1065
1066 printf(" options: %s\n", t);
1067 }
1068 if (e->device_tree)
1069 printf(" devicetree: %s\n", e->device_tree);
1070
1071 puts("");
1072 }
1073
1074 return 0;
1075 }
1076
1077 static int verb_install(int argc, char *argv[], void *userdata) {
1078
1079 sd_id128_t uuid = SD_ID128_NULL;
1080 uint64_t pstart = 0, psize = 0;
1081 uint32_t part = 0;
1082 bool install;
1083 int r;
1084
1085 r = acquire_esp(false, &part, &pstart, &psize, &uuid);
1086 if (r < 0)
1087 return r;
1088
1089 install = streq(argv[0], "install");
1090
1091 RUN_WITH_UMASK(0002) {
1092 r = install_binaries(arg_path, install);
1093 if (r < 0)
1094 return r;
1095
1096 if (install) {
1097 r = install_loader_config(arg_path);
1098 if (r < 0)
1099 return r;
1100 }
1101 }
1102
1103 if (arg_touch_variables)
1104 r = install_variables(arg_path,
1105 part, pstart, psize, uuid,
1106 "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi",
1107 install);
1108
1109 return r;
1110 }
1111
1112 static int verb_remove(int argc, char *argv[], void *userdata) {
1113 sd_id128_t uuid = SD_ID128_NULL;
1114 int r;
1115
1116 r = acquire_esp(false, NULL, NULL, NULL, &uuid);
1117 if (r < 0)
1118 return r;
1119
1120 r = remove_binaries(arg_path);
1121
1122 if (arg_touch_variables) {
1123 int q;
1124
1125 q = remove_variables(uuid, "/EFI/systemd/systemd-boot" EFI_MACHINE_TYPE_NAME ".efi", true);
1126 if (q < 0 && r == 0)
1127 r = q;
1128 }
1129
1130 return r;
1131 }
1132
1133 static int bootctl_main(int argc, char *argv[]) {
1134
1135 static const Verb verbs[] = {
1136 { "help", VERB_ANY, VERB_ANY, 0, help },
1137 { "status", VERB_ANY, 1, VERB_DEFAULT, verb_status },
1138 { "list", VERB_ANY, 1, 0, verb_list },
1139 { "install", VERB_ANY, 1, VERB_MUST_BE_ROOT, verb_install },
1140 { "update", VERB_ANY, 1, VERB_MUST_BE_ROOT, verb_install },
1141 { "remove", VERB_ANY, 1, VERB_MUST_BE_ROOT, verb_remove },
1142 {}
1143 };
1144
1145 return dispatch_verb(argc, argv, verbs, NULL);
1146 }
1147
1148 int main(int argc, char *argv[]) {
1149 int r;
1150
1151 log_parse_environment();
1152 log_open();
1153
1154 /* If we run in a container, automatically turn of EFI file system access */
1155 if (detect_container() > 0)
1156 arg_touch_variables = false;
1157
1158 r = parse_argv(argc, argv);
1159 if (r <= 0)
1160 goto finish;
1161
1162 r = bootctl_main(argc, argv);
1163
1164 finish:
1165 free(arg_path);
1166 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1167 }