]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/bootspec.c
update TODO
[thirdparty/systemd.git] / src / shared / bootspec.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
7e87c7d9 2
ca78ad1d 3#include <unistd.h>
7e87c7d9 4
e94830c0 5#include "bootspec-fundamental.h"
432ce537 6#include "bootspec.h"
2683ae2d 7#include "chase-symlinks.h"
7e87c7d9 8#include "conf-files.h"
7176f06c 9#include "devnum-util.h"
5e146a75 10#include "dirent-util.h"
0bb2f0f1 11#include "efi-loader.h"
5e146a75 12#include "env-file.h"
432ce537 13#include "errno-util.h"
7e87c7d9
ZJS
14#include "fd-util.h"
15#include "fileio.h"
e94830c0 16#include "find-esp.h"
cc7a0bfa 17#include "path-util.h"
5e146a75 18#include "pe-header.h"
432ce537 19#include "pretty-print.h"
d04f0331 20#include "recurse-dir.h"
760877e9 21#include "sort-util.h"
ddfdf86f 22#include "stat-util.h"
432ce537 23#include "string-table.h"
7e87c7d9 24#include "strv.h"
432ce537 25#include "terminal-util.h"
5e146a75 26#include "unaligned.h"
7e87c7d9 27
432ce537
ZJS
28static const char* const boot_entry_type_table[_BOOT_ENTRY_TYPE_MAX] = {
29 [BOOT_ENTRY_CONF] = "Boot Loader Specification Type #1 (.conf)",
30 [BOOT_ENTRY_UNIFIED] = "Boot Loader Specification Type #2 (.efi)",
31 [BOOT_ENTRY_LOADER] = "Reported by Boot Loader",
32 [BOOT_ENTRY_LOADER_AUTO] = "Automatic",
33};
34
35DEFINE_STRING_TABLE_LOOKUP_TO_STRING(boot_entry_type, BootEntryType);
36
0de2e1fd 37static void boot_entry_free(BootEntry *entry) {
4fe2ba0e 38 assert(entry);
7e87c7d9 39
12580bc3 40 free(entry->id);
15b82eec 41 free(entry->id_old);
2d3bfb69 42 free(entry->path);
43b736a8 43 free(entry->root);
7e87c7d9 44 free(entry->title);
64f05708 45 free(entry->show_title);
20ec8f53 46 free(entry->sort_key);
7e87c7d9
ZJS
47 free(entry->version);
48 free(entry->machine_id);
49 free(entry->architecture);
50 strv_free(entry->options);
51 free(entry->kernel);
52 free(entry->efi);
53 strv_free(entry->initrd);
54 free(entry->device_tree);
fdc5c042 55 strv_free(entry->device_tree_overlay);
7e87c7d9
ZJS
56}
57
d68c6bea
LP
58static int mangle_path(
59 const char *fname,
60 unsigned line,
61 const char *field,
62 const char *p,
63 char **ret) {
64
bb9133bb
LP
65 _cleanup_free_ char *c = NULL;
66
67 assert(field);
68 assert(p);
69 assert(ret);
70
71 /* Spec leaves open if prefixed with "/" or not, let's normalize that */
72 if (path_is_absolute(p))
73 c = strdup(p);
74 else
75 c = strjoin("/", p);
76 if (!c)
77 return -ENOMEM;
78
79 /* We only reference files, never directories */
80 if (endswith(c, "/")) {
d68c6bea 81 log_syntax(NULL, LOG_WARNING, fname, line, 0, "Path in field '%s' has trailing slash, ignoring: %s", field, c);
bb9133bb
LP
82 *ret = NULL;
83 return 0;
84 }
85
86 /* Remove duplicate "/" */
87 path_simplify(c);
88
89 /* No ".." or "." or so */
90 if (!path_is_normalized(c)) {
d68c6bea 91 log_syntax(NULL, LOG_WARNING, fname, line, 0, "Path in field '%s' is not normalized, ignoring: %s", field, c);
bb9133bb
LP
92 *ret = NULL;
93 return 0;
94 }
95
96 *ret = TAKE_PTR(c);
97 return 1;
98}
99
d68c6bea
LP
100static int parse_path_one(
101 const char *fname,
102 unsigned line,
103 const char *field,
104 char **s,
105 const char *p) {
106
bb9133bb
LP
107 _cleanup_free_ char *c = NULL;
108 int r;
109
110 assert(field);
111 assert(s);
112 assert(p);
113
d68c6bea 114 r = mangle_path(fname, line, field, p, &c);
bb9133bb
LP
115 if (r <= 0)
116 return r;
117
28340719 118 return free_and_replace(*s, c);
bb9133bb
LP
119}
120
d68c6bea
LP
121static int parse_path_strv(
122 const char *fname,
123 unsigned line,
124 const char *field,
125 char ***s,
126 const char *p) {
127
bb9133bb
LP
128 char *c;
129 int r;
130
131 assert(field);
132 assert(s);
133 assert(p);
134
d68c6bea 135 r = mangle_path(fname, line, field, p, &c);
bb9133bb
LP
136 if (r <= 0)
137 return r;
138
139 return strv_consume(s, c);
140}
141
d68c6bea
LP
142static int parse_path_many(
143 const char *fname,
144 unsigned line,
145 const char *field,
146 char ***s,
147 const char *p) {
148
bb9133bb
LP
149 _cleanup_strv_free_ char **l = NULL, **f = NULL;
150 int r;
151
152 l = strv_split(p, NULL);
153 if (!l)
154 return -ENOMEM;
155
156 STRV_FOREACH(i, l) {
157 char *c;
158
d68c6bea 159 r = mangle_path(fname, line, field, *i, &c);
bb9133bb
LP
160 if (r < 0)
161 return r;
162 if (r == 0)
163 continue;
164
165 r = strv_consume(&f, c);
166 if (r < 0)
167 return r;
168 }
169
170 return strv_extend_strv(s, f, /* filter_duplicates= */ false);
171}
172
7f5780ed
LP
173static int parse_tries(const char *fname, const char **p, unsigned *ret) {
174 _cleanup_free_ char *d = NULL;
175 unsigned tries;
176 size_t n;
177 int r;
178
179 assert(fname);
180 assert(p);
181 assert(*p);
182 assert(ret);
183
184 n = strspn(*p, DIGITS);
185 if (n == 0) {
186 *ret = UINT_MAX;
187 return 0;
188 }
189
190 d = strndup(*p, n);
191 if (!d)
192 return log_oom();
193
194 r = safe_atou_full(d, 10, &tries);
195 if (r >= 0 && tries > INT_MAX) /* sd-boot allows INT_MAX, let's use the same limit */
196 r = -ERANGE;
197 if (r < 0)
198 return log_error_errno(r, "Failed to parse tries counter of filename '%s': %m", fname);
199
200 *p = *p + n;
201 *ret = tries;
202 return 1;
203}
204
205int boot_filename_extract_tries(
206 const char *fname,
207 char **ret_stripped,
208 unsigned *ret_tries_left,
209 unsigned *ret_tries_done) {
210
211 unsigned tries_left = UINT_MAX, tries_done = UINT_MAX;
212 _cleanup_free_ char *stripped = NULL;
213 const char *p, *suffix, *m;
214 int r;
215
216 assert(fname);
217 assert(ret_stripped);
218 assert(ret_tries_left);
219 assert(ret_tries_done);
220
221 /* Be liberal with suffix, only insist on a dot. After all we want to cover any capitalization here
222 * (vfat is case insensitive after all), and at least .efi and .conf as suffix. */
223 suffix = strrchr(fname, '.');
224 if (!suffix)
225 goto nothing;
226
227 p = m = memrchr(fname, '+', suffix - fname);
228 if (!p)
229 goto nothing;
230 p++;
231
232 r = parse_tries(fname, &p, &tries_left);
233 if (r < 0)
234 return r;
235 if (r == 0)
236 goto nothing;
237
238 if (*p == '-') {
239 p++;
240
241 r = parse_tries(fname, &p, &tries_done);
242 if (r < 0)
243 return r;
244 if (r == 0)
245 goto nothing;
246 }
247
248 if (p != suffix)
249 goto nothing;
250
251 stripped = strndup(fname, m - fname);
252 if (!stripped)
253 return log_oom();
254
255 if (!strextend(&stripped, suffix))
256 return log_oom();
257
258 *ret_stripped = TAKE_PTR(stripped);
259 *ret_tries_left = tries_left;
260 *ret_tries_done = tries_done;
261
262 return 0;
263
264nothing:
265 stripped = strdup(fname);
266 if (!stripped)
267 return log_oom();
268
269 *ret_stripped = TAKE_PTR(stripped);
270 *ret_tries_left = *ret_tries_done = UINT_MAX;
271 return 0;
272}
273
85e17916 274static int boot_entry_load_type1(
d04f0331 275 FILE *f,
43b736a8 276 const char *root,
d04f0331 277 const char *dir,
f70de82f 278 const char *fname,
43b736a8
LP
279 BootEntry *entry) {
280
7f5780ed 281 _cleanup_(boot_entry_free) BootEntry tmp = BOOT_ENTRY_INIT(BOOT_ENTRY_CONF);
7e87c7d9 282 unsigned line = 1;
736783d4 283 char *c;
7e87c7d9
ZJS
284 int r;
285
d04f0331 286 assert(f);
43b736a8 287 assert(root);
d04f0331 288 assert(dir);
f70de82f 289 assert(fname);
4fe2ba0e
LP
290 assert(entry);
291
d04f0331 292 /* Loads a Type #1 boot menu entry from the specified FILE* object */
7e87c7d9 293
7f5780ed
LP
294 r = boot_filename_extract_tries(fname, &tmp.id, &tmp.tries_left, &tmp.tries_done);
295 if (r < 0)
296 return r;
297
298 if (!efi_loader_entry_name_valid(tmp.id))
f70de82f 299 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid loader entry name: %s", fname);
d04f0331 300
7f5780ed 301 c = endswith_no_case(tmp.id, ".conf");
736783d4 302 if (!c)
f70de82f 303 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid loader entry file suffix: %s", fname);
7e87c7d9 304
7f5780ed 305 tmp.id_old = strndup(tmp.id, c - tmp.id); /* Without .conf suffix */
736783d4
LP
306 if (!tmp.id_old)
307 return log_oom();
308
f70de82f 309 tmp.path = path_join(dir, fname);
2d3bfb69
ZJS
310 if (!tmp.path)
311 return log_oom();
312
43b736a8
LP
313 tmp.root = strdup(root);
314 if (!tmp.root)
315 return log_oom();
316
7e87c7d9 317 for (;;) {
f99fdc3e
YW
318 _cleanup_free_ char *buf = NULL, *field = NULL;
319 const char *p;
7e87c7d9
ZJS
320
321 r = read_line(f, LONG_LINE_MAX, &buf);
322 if (r == 0)
323 break;
324 if (r == -ENOBUFS)
d68c6bea 325 return log_syntax(NULL, LOG_ERR, tmp.path, line, r, "Line too long.");
7e87c7d9 326 if (r < 0)
d68c6bea 327 return log_syntax(NULL, LOG_ERR, tmp.path, line, r, "Error while reading: %m");
7e87c7d9
ZJS
328
329 line++;
330
da8f277c
LP
331 p = strstrip(buf);
332 if (IN_SET(p[0], '#', '\0'))
7e87c7d9
ZJS
333 continue;
334
da8f277c 335 r = extract_first_word(&p, &field, NULL, 0);
f99fdc3e 336 if (r < 0) {
d68c6bea 337 log_syntax(NULL, LOG_WARNING, tmp.path, line, r, "Failed to parse, ignoring line: %m");
f99fdc3e
YW
338 continue;
339 }
340 if (r == 0) {
d68c6bea 341 log_syntax(NULL, LOG_WARNING, tmp.path, line, 0, "Bad syntax, ignoring line.");
7e87c7d9
ZJS
342 continue;
343 }
7e87c7d9 344
b6bd2562
ZJS
345 if (isempty(p)) {
346 /* Some fields can reasonably have an empty value. In other cases warn. */
347 if (!STR_IN_SET(field, "options", "devicetree-overlay"))
d68c6bea
LP
348 log_syntax(NULL, LOG_WARNING, tmp.path, line, 0, "Field '%s' without value, ignoring line.", field);
349
b6bd2562
ZJS
350 continue;
351 }
352
f99fdc3e 353 if (streq(field, "title"))
7e87c7d9 354 r = free_and_strdup(&tmp.title, p);
20ec8f53
LP
355 else if (streq(field, "sort-key"))
356 r = free_and_strdup(&tmp.sort_key, p);
f99fdc3e 357 else if (streq(field, "version"))
7e87c7d9 358 r = free_and_strdup(&tmp.version, p);
f99fdc3e 359 else if (streq(field, "machine-id"))
7e87c7d9 360 r = free_and_strdup(&tmp.machine_id, p);
f99fdc3e 361 else if (streq(field, "architecture"))
7e87c7d9 362 r = free_and_strdup(&tmp.architecture, p);
f99fdc3e 363 else if (streq(field, "options"))
7e87c7d9 364 r = strv_extend(&tmp.options, p);
f99fdc3e 365 else if (streq(field, "linux"))
d68c6bea 366 r = parse_path_one(tmp.path, line, field, &tmp.kernel, p);
f99fdc3e 367 else if (streq(field, "efi"))
d68c6bea 368 r = parse_path_one(tmp.path, line, field, &tmp.efi, p);
f99fdc3e 369 else if (streq(field, "initrd"))
d68c6bea 370 r = parse_path_strv(tmp.path, line, field, &tmp.initrd, p);
f99fdc3e 371 else if (streq(field, "devicetree"))
d68c6bea 372 r = parse_path_one(tmp.path, line, field, &tmp.device_tree, p);
bb9133bb 373 else if (streq(field, "devicetree-overlay"))
d68c6bea 374 r = parse_path_many(tmp.path, line, field, &tmp.device_tree_overlay, p);
bb9133bb 375 else {
d68c6bea 376 log_syntax(NULL, LOG_WARNING, tmp.path, line, 0, "Unknown line '%s', ignoring.", field);
7e87c7d9
ZJS
377 continue;
378 }
379 if (r < 0)
d68c6bea 380 return log_syntax(NULL, LOG_ERR, tmp.path, line, r, "Error while parsing: %m");
7e87c7d9
ZJS
381 }
382
383 *entry = tmp;
384 tmp = (BootEntry) {};
385 return 0;
386}
387
a847b539
ZJS
388int boot_config_load_type1(
389 BootConfig *config,
390 FILE *f,
391 const char *root,
392 const char *dir,
f70de82f 393 const char *fname) {
a847b539
ZJS
394 int r;
395
396 assert(config);
397 assert(f);
398 assert(root);
399 assert(dir);
f70de82f 400 assert(fname);
a847b539
ZJS
401
402 if (!GREEDY_REALLOC0(config->entries, config->n_entries + 1))
403 return log_oom();
404
f70de82f 405 r = boot_entry_load_type1(f, root, dir, fname, config->entries + config->n_entries);
a847b539
ZJS
406 if (r < 0)
407 return r;
408
409 config->n_entries++;
410 return 0;
411}
412
7e87c7d9 413void boot_config_free(BootConfig *config) {
4fe2ba0e
LP
414 assert(config);
415
7e87c7d9
ZJS
416 free(config->default_pattern);
417 free(config->timeout);
418 free(config->editor);
c1d4e298
JJ
419 free(config->auto_entries);
420 free(config->auto_firmware);
72263375 421 free(config->console_mode);
d403d8f0 422 free(config->beep);
7e87c7d9
ZJS
423
424 free(config->entry_oneshot);
425 free(config->entry_default);
a78e472d 426 free(config->entry_selected);
7e87c7d9 427
9817b7db 428 for (size_t i = 0; i < config->n_entries; i++)
7e87c7d9
ZJS
429 boot_entry_free(config->entries + i);
430 free(config->entries);
d486a0ea
LP
431
432 set_free(config->inodes_seen);
7e87c7d9
ZJS
433}
434
5ba1550f 435int boot_loader_read_conf(BootConfig *config, FILE *file, const char *path) {
7e87c7d9
ZJS
436 unsigned line = 1;
437 int r;
438
4fe2ba0e 439 assert(config);
5ba1550f
ZJS
440 assert(file);
441 assert(path);
7e87c7d9
ZJS
442
443 for (;;) {
f99fdc3e
YW
444 _cleanup_free_ char *buf = NULL, *field = NULL;
445 const char *p;
7e87c7d9 446
5ba1550f 447 r = read_line(file, LONG_LINE_MAX, &buf);
7e87c7d9
ZJS
448 if (r == 0)
449 break;
450 if (r == -ENOBUFS)
d68c6bea 451 return log_syntax(NULL, LOG_ERR, path, line, r, "Line too long.");
7e87c7d9 452 if (r < 0)
d68c6bea 453 return log_syntax(NULL, LOG_ERR, path, line, r, "Error while reading: %m");
7e87c7d9
ZJS
454
455 line++;
456
da8f277c
LP
457 p = strstrip(buf);
458 if (IN_SET(p[0], '#', '\0'))
7e87c7d9
ZJS
459 continue;
460
da8f277c 461 r = extract_first_word(&p, &field, NULL, 0);
f99fdc3e 462 if (r < 0) {
d68c6bea 463 log_syntax(NULL, LOG_WARNING, path, line, r, "Failed to parse, ignoring line: %m");
f99fdc3e
YW
464 continue;
465 }
466 if (r == 0) {
d68c6bea 467 log_syntax(NULL, LOG_WARNING, path, line, 0, "Bad syntax, ignoring line.");
7e87c7d9
ZJS
468 continue;
469 }
9ac2a89a
LP
470 if (isempty(p)) {
471 log_syntax(NULL, LOG_WARNING, path, line, 0, "Field '%s' without value, ignoring line.", field);
472 continue;
473 }
7e87c7d9 474
f99fdc3e 475 if (streq(field, "default"))
7e87c7d9 476 r = free_and_strdup(&config->default_pattern, p);
f99fdc3e 477 else if (streq(field, "timeout"))
7e87c7d9 478 r = free_and_strdup(&config->timeout, p);
f99fdc3e 479 else if (streq(field, "editor"))
7e87c7d9 480 r = free_and_strdup(&config->editor, p);
790f84eb 481 else if (streq(field, "auto-entries"))
c1d4e298 482 r = free_and_strdup(&config->auto_entries, p);
790f84eb 483 else if (streq(field, "auto-firmware"))
c1d4e298 484 r = free_and_strdup(&config->auto_firmware, p);
790f84eb 485 else if (streq(field, "console-mode"))
d37b0737 486 r = free_and_strdup(&config->console_mode, p);
fe5a698f 487 else if (streq(field, "random-seed-mode"))
47b3e966 488 log_syntax(NULL, LOG_WARNING, path, line, 0, "'random-seed-mode' has been deprecated, ignoring.");
d403d8f0
LP
489 else if (streq(field, "beep"))
490 r = free_and_strdup(&config->beep, p);
7e87c7d9 491 else {
d68c6bea 492 log_syntax(NULL, LOG_WARNING, path, line, 0, "Unknown line '%s', ignoring.", field);
7e87c7d9
ZJS
493 continue;
494 }
495 if (r < 0)
d68c6bea 496 return log_syntax(NULL, LOG_ERR, path, line, r, "Error while parsing: %m");
7e87c7d9
ZJS
497 }
498
f91ed3dc 499 return 1;
7e87c7d9
ZJS
500}
501
2683ae2d
LP
502static int boot_loader_read_conf_path(BootConfig *config, const char *root, const char *path) {
503 _cleanup_free_ char *full = NULL;
5ba1550f 504 _cleanup_fclose_ FILE *f = NULL;
2683ae2d 505 int r;
5ba1550f
ZJS
506
507 assert(config);
508 assert(path);
509
b353d5ee 510 r = chase_symlinks_and_fopen_unlocked(path, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, "re", &full, &f);
2683ae2d
LP
511 if (r == -ENOENT)
512 return 0;
513 if (r < 0)
514 return log_error_errno(r, "Failed to open '%s/%s': %m", root, path);
5ba1550f 515
2683ae2d 516 return boot_loader_read_conf(config, f, full);
5ba1550f
ZJS
517}
518
93bab288 519static int boot_entry_compare(const BootEntry *a, const BootEntry *b) {
20ec8f53
LP
520 int r;
521
522 assert(a);
523 assert(b);
524
525 r = CMP(!a->sort_key, !b->sort_key);
526 if (r != 0)
527 return r;
62a4b584 528
20ec8f53
LP
529 if (a->sort_key && b->sort_key) {
530 r = strcmp(a->sort_key, b->sort_key);
531 if (r != 0)
532 return r;
533
534 r = strcmp_ptr(a->machine_id, b->machine_id);
535 if (r != 0)
536 return r;
537
538 r = -strverscmp_improved(a->version, b->version);
539 if (r != 0)
540 return r;
541 }
542
62a4b584 543 return -strverscmp_improved(a->id, b->id);
7e87c7d9
ZJS
544}
545
d486a0ea
LP
546static int config_check_inode_relevant_and_unseen(BootConfig *config, int fd, const char *fname) {
547 _cleanup_free_ char *d = NULL;
548 struct stat st;
549
550 assert(config);
551 assert(fd >= 0);
552 assert(fname);
553
554 /* So, here's the thing: because of the mess around /efi/ vs. /boot/ vs. /boot/efi/ it might be that
555 * people have these dirs, or subdirs of them symlinked or bind mounted, and we might end up
556 * iterating though some dirs multiple times. Let's thus rather be safe than sorry, and track the
557 * inodes we already processed: let's ignore inodes we have seen already. This should be robust
558 * against any form of symlinking or bind mounting, and effectively suppress any such duplicates. */
559
560 if (fstat(fd, &st) < 0)
561 return log_error_errno(errno, "Failed to stat('%s'): %m", fname);
562 if (!S_ISREG(st.st_mode)) {
563 log_debug("File '%s' is not a reguar file, ignoring.", fname);
564 return false;
565 }
566
567 if (set_contains(config->inodes_seen, &st)) {
568 log_debug("Inode '%s' already seen before, ignoring.", fname);
569 return false;
570 }
571 d = memdup(&st, sizeof(st));
572 if (!d)
573 return log_oom();
574 if (set_ensure_put(&config->inodes_seen, &inode_hash_ops, d) < 0)
575 return log_oom();
576
577 TAKE_PTR(d);
578 return true;
579}
580
85e17916 581static int boot_entries_find_type1(
85f4ae2f 582 BootConfig *config,
43b736a8 583 const char *root,
85f4ae2f 584 const char *dir) {
43b736a8 585
d04f0331 586 _cleanup_free_ DirectoryEntries *dentries = NULL;
2683ae2d 587 _cleanup_free_ char *full = NULL;
d04f0331 588 _cleanup_close_ int dir_fd = -1;
7e87c7d9 589 int r;
7e87c7d9 590
85f4ae2f 591 assert(config);
43b736a8 592 assert(root);
4fe2ba0e 593 assert(dir);
4fe2ba0e 594
b353d5ee 595 dir_fd = chase_symlinks_and_open(dir, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, O_DIRECTORY|O_CLOEXEC, &full);
2683ae2d
LP
596 if (dir_fd == -ENOENT)
597 return 0;
598 if (dir_fd < 0)
599 return log_error_errno(dir_fd, "Failed to open '%s/%s': %m", root, dir);
d04f0331
LP
600
601 r = readdir_all(dir_fd, RECURSE_DIR_IGNORE_DOT, &dentries);
7e87c7d9 602 if (r < 0)
2683ae2d 603 return log_error_errno(r, "Failed to read directory '%s': %m", full);
d04f0331
LP
604
605 for (size_t i = 0; i < dentries->n_entries; i++) {
606 const struct dirent *de = dentries->entries[i];
607 _cleanup_fclose_ FILE *f = NULL;
608
609 if (!dirent_is_file(de))
610 continue;
611
612 if (!endswith_no_case(de->d_name, ".conf"))
613 continue;
7e87c7d9 614
f2c51304 615 r = xfopenat(dir_fd, de->d_name, "re", O_NOFOLLOW|O_NOCTTY, &f);
d04f0331 616 if (r < 0) {
2683ae2d 617 log_warning_errno(r, "Failed to open %s/%s, ignoring: %m", full, de->d_name);
d04f0331
LP
618 continue;
619 }
620
d486a0ea
LP
621 r = config_check_inode_relevant_and_unseen(config, fileno(f), de->d_name);
622 if (r < 0)
623 return r;
624 if (r == 0) /* inode already seen or otherwise not relevant */
d04f0331 625 continue;
d486a0ea 626
2683ae2d 627 r = boot_config_load_type1(config, f, root, full, de->d_name);
293e2240 628 if (r == -ENOMEM) /* ignore all other errors */
a847b539 629 return r;
7e87c7d9
ZJS
630 }
631
7e87c7d9
ZJS
632 return 0;
633}
634
5e146a75
LP
635static int boot_entry_load_unified(
636 const char *root,
637 const char *path,
638 const char *osrelease,
639 const char *cmdline,
640 BootEntry *ret) {
641
7f5780ed 642 _cleanup_free_ char *fname = NULL, *os_pretty_name = NULL, *os_image_id = NULL, *os_name = NULL, *os_id = NULL,
c2caeb5d 643 *os_image_version = NULL, *os_version = NULL, *os_version_id = NULL, *os_build_id = NULL;
7f5780ed 644 _cleanup_(boot_entry_free) BootEntry tmp = BOOT_ENTRY_INIT(BOOT_ENTRY_UNIFIED);
20ec8f53 645 const char *k, *good_name, *good_version, *good_sort_key;
5e146a75 646 _cleanup_fclose_ FILE *f = NULL;
5e146a75
LP
647 int r;
648
649 assert(root);
650 assert(path);
651 assert(osrelease);
652
653 k = path_startswith(path, root);
654 if (!k)
655 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not below root: %s", path);
656
673a1e6f 657 f = fmemopen_unlocked((void*) osrelease, strlen(osrelease), "r");
5e146a75
LP
658 if (!f)
659 return log_error_errno(errno, "Failed to open os-release buffer: %m");
660
15b82eec
SM
661 r = parse_env_file(f, "os-release",
662 "PRETTY_NAME", &os_pretty_name,
c2caeb5d
LP
663 "IMAGE_ID", &os_image_id,
664 "NAME", &os_name,
15b82eec 665 "ID", &os_id,
c2caeb5d
LP
666 "IMAGE_VERSION", &os_image_version,
667 "VERSION", &os_version,
668 "VERSION_ID", &os_version_id,
669 "BUILD_ID", &os_build_id);
5e146a75
LP
670 if (r < 0)
671 return log_error_errno(r, "Failed to parse os-release data from unified kernel image %s: %m", path);
672
20ec8f53 673 if (!bootspec_pick_name_version_sort_key(
c2caeb5d
LP
674 os_pretty_name,
675 os_image_id,
676 os_name,
677 os_id,
678 os_image_version,
679 os_version,
680 os_version_id,
681 os_build_id,
682 &good_name,
20ec8f53
LP
683 &good_version,
684 &good_sort_key))
5e146a75
LP
685 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Missing fields in os-release data from unified kernel image %s, refusing.", path);
686
7f5780ed 687 r = path_extract_filename(path, &fname);
c2caeb5d
LP
688 if (r < 0)
689 return log_error_errno(r, "Failed to extract file name from '%s': %m", path);
5e146a75 690
7f5780ed
LP
691 r = boot_filename_extract_tries(fname, &tmp.id, &tmp.tries_left, &tmp.tries_done);
692 if (r < 0)
693 return r;
694
eed7210a 695 if (!efi_loader_entry_name_valid(tmp.id))
dfc22cb4 696 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid loader entry name: %s", tmp.id);
eed7210a 697
c2caeb5d
LP
698 if (os_id && os_version_id) {
699 tmp.id_old = strjoin(os_id, "-", os_version_id);
700 if (!tmp.id_old)
701 return log_oom();
702 }
703
5e146a75
LP
704 tmp.path = strdup(path);
705 if (!tmp.path)
706 return log_oom();
707
708 tmp.root = strdup(root);
709 if (!tmp.root)
710 return log_oom();
711
78517322 712 tmp.kernel = path_make_absolute(k, "/");
5e146a75
LP
713 if (!tmp.kernel)
714 return log_oom();
715
716 tmp.options = strv_new(skip_leading_chars(cmdline, WHITESPACE));
717 if (!tmp.options)
718 return log_oom();
719
720 delete_trailing_chars(tmp.options[0], WHITESPACE);
721
c2caeb5d
LP
722 tmp.title = strdup(good_name);
723 if (!tmp.title)
724 return log_oom();
725
20ec8f53
LP
726 tmp.sort_key = strdup(good_sort_key);
727 if (!tmp.sort_key)
728 return log_oom();
729
87c77795
VW
730 if (good_version) {
731 tmp.version = strdup(good_version);
732 if (!tmp.version)
733 return log_oom();
734 }
5e146a75
LP
735
736 *ret = tmp;
737 tmp = (BootEntry) {};
738 return 0;
739}
740
741/* Maximum PE section we are willing to load (Note that sections we are not interested in may be larger, but
742 * the ones we do care about and we are willing to load into memory have this size limit.) */
743#define PE_SECTION_SIZE_MAX (4U*1024U*1024U)
744
745static int find_sections(
746 int fd,
35148e8f 747 const char *path,
5e146a75
LP
748 char **ret_osrelease,
749 char **ret_cmdline) {
750
751 _cleanup_free_ struct PeSectionHeader *sections = NULL;
752 _cleanup_free_ char *osrelease = NULL, *cmdline = NULL;
5e146a75
LP
753 ssize_t n;
754
9817b7db 755 struct DosFileHeader dos;
5e146a75
LP
756 n = pread(fd, &dos, sizeof(dos), 0);
757 if (n < 0)
35148e8f 758 return log_warning_errno(errno, "%s: Failed to read DOS header, ignoring: %m", path);
5e146a75 759 if (n != sizeof(dos))
35148e8f 760 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "%s: Short read while reading DOS header, ignoring.", path);
5e146a75
LP
761
762 if (dos.Magic[0] != 'M' || dos.Magic[1] != 'Z')
35148e8f 763 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: DOS executable magic missing, ignoring.", path);
5e146a75 764
9817b7db
ZJS
765 uint64_t start = unaligned_read_le32(&dos.ExeHeader);
766
767 struct PeHeader pe;
5e146a75
LP
768 n = pread(fd, &pe, sizeof(pe), start);
769 if (n < 0)
35148e8f 770 return log_warning_errno(errno, "%s: Failed to read PE header, ignoring: %m", path);
5e146a75 771 if (n != sizeof(pe))
35148e8f 772 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "%s: Short read while reading PE header, ignoring.", path);
5e146a75
LP
773
774 if (pe.Magic[0] != 'P' || pe.Magic[1] != 'E' || pe.Magic[2] != 0 || pe.Magic[3] != 0)
35148e8f 775 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: PE executable magic missing, ignoring.", path);
5e146a75 776
9817b7db 777 size_t n_sections = unaligned_read_le16(&pe.FileHeader.NumberOfSections);
5e146a75 778 if (n_sections > 96)
35148e8f 779 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: PE header has too many sections, ignoring.", path);
5e146a75
LP
780
781 sections = new(struct PeSectionHeader, n_sections);
782 if (!sections)
783 return log_oom();
784
785 n = pread(fd, sections,
786 n_sections * sizeof(struct PeSectionHeader),
787 start + sizeof(pe) + unaligned_read_le16(&pe.FileHeader.SizeOfOptionalHeader));
788 if (n < 0)
35148e8f 789 return log_warning_errno(errno, "%s: Failed to read section data, ignoring: %m", path);
5e146a75 790 if ((size_t) n != n_sections * sizeof(struct PeSectionHeader))
35148e8f 791 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "%s: Short read while reading sections, ignoring.", path);
5e146a75 792
9817b7db 793 for (size_t i = 0; i < n_sections; i++) {
5e146a75
LP
794 _cleanup_free_ char *k = NULL;
795 uint32_t offset, size;
796 char **b;
797
798 if (strneq((char*) sections[i].Name, ".osrel", sizeof(sections[i].Name)))
799 b = &osrelease;
800 else if (strneq((char*) sections[i].Name, ".cmdline", sizeof(sections[i].Name)))
801 b = &cmdline;
802 else
803 continue;
804
805 if (*b)
35148e8f 806 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: Duplicate section %s, ignoring.", path, sections[i].Name);
5e146a75
LP
807
808 offset = unaligned_read_le32(&sections[i].PointerToRawData);
809 size = unaligned_read_le32(&sections[i].VirtualSize);
810
811 if (size > PE_SECTION_SIZE_MAX)
35148e8f 812 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: Section %s too large, ignoring.", path, sections[i].Name);
5e146a75
LP
813
814 k = new(char, size+1);
815 if (!k)
816 return log_oom();
817
818 n = pread(fd, k, size, offset);
819 if (n < 0)
35148e8f 820 return log_warning_errno(errno, "%s: Failed to read section payload, ignoring: %m", path);
a75fcef8 821 if ((size_t) n != size)
35148e8f 822 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "%s: Short read while reading section payload, ignoring:", path);
5e146a75
LP
823
824 /* Allow one trailing NUL byte, but nothing more. */
825 if (size > 0 && memchr(k, 0, size - 1))
35148e8f 826 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: Section contains embedded NUL byte, ignoring.", path);
5e146a75
LP
827
828 k[size] = 0;
829 *b = TAKE_PTR(k);
830 }
831
832 if (!osrelease)
35148e8f 833 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: Image lacks .osrel section, ignoring.", path);
5e146a75
LP
834
835 if (ret_osrelease)
836 *ret_osrelease = TAKE_PTR(osrelease);
837 if (ret_cmdline)
838 *ret_cmdline = TAKE_PTR(cmdline);
839
840 return 0;
841}
842
843static int boot_entries_find_unified(
85f4ae2f 844 BootConfig *config,
5e146a75 845 const char *root,
85f4ae2f 846 const char *dir) {
5e146a75
LP
847
848 _cleanup_(closedirp) DIR *d = NULL;
2683ae2d 849 _cleanup_free_ char *full = NULL;
5e146a75
LP
850 int r;
851
85f4ae2f 852 assert(config);
5e146a75 853 assert(dir);
5e146a75 854
b353d5ee 855 r = chase_symlinks_and_opendir(dir, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &full, &d);
2683ae2d
LP
856 if (r == -ENOENT)
857 return 0;
858 if (r < 0)
859 return log_error_errno(r, "Failed to open '%s/%s': %m", root, dir);
5e146a75 860
2683ae2d 861 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read %s: %m", full)) {
5e146a75
LP
862 _cleanup_free_ char *j = NULL, *osrelease = NULL, *cmdline = NULL;
863 _cleanup_close_ int fd = -1;
864
865 if (!dirent_is_file(de))
866 continue;
867
868 if (!endswith_no_case(de->d_name, ".efi"))
869 continue;
870
85f4ae2f 871 if (!GREEDY_REALLOC0(config->entries, config->n_entries + 1))
5e146a75
LP
872 return log_oom();
873
f2c51304 874 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOFOLLOW|O_NOCTTY);
5e146a75 875 if (fd < 0) {
2683ae2d 876 log_warning_errno(errno, "Failed to open %s/%s, ignoring: %m", full, de->d_name);
5e146a75
LP
877 continue;
878 }
879
d486a0ea
LP
880 r = config_check_inode_relevant_and_unseen(config, fd, de->d_name);
881 if (r < 0)
882 return r;
883 if (r == 0) /* inode already seen or otherwise not relevant */
5e146a75 884 continue;
5e146a75 885
2683ae2d 886 j = path_join(full, de->d_name);
5e146a75
LP
887 if (!j)
888 return log_oom();
889
35148e8f
JJ
890 if (find_sections(fd, j, &osrelease, &cmdline) < 0)
891 continue;
892
85f4ae2f 893 r = boot_entry_load_unified(root, j, osrelease, cmdline, config->entries + config->n_entries);
5e146a75
LP
894 if (r < 0)
895 continue;
896
85f4ae2f 897 config->n_entries++;
5e146a75
LP
898 }
899
5e146a75
LP
900 return 0;
901}
902
bb682057 903static bool find_nonunique(const BootEntry *entries, size_t n_entries, bool arr[]) {
64f05708
ZJS
904 bool non_unique = false;
905
4fe2ba0e
LP
906 assert(entries || n_entries == 0);
907 assert(arr || n_entries == 0);
908
d5ac1d4e 909 for (size_t i = 0; i < n_entries; i++)
64f05708
ZJS
910 arr[i] = false;
911
d5ac1d4e
LP
912 for (size_t i = 0; i < n_entries; i++)
913 for (size_t j = 0; j < n_entries; j++)
64f05708
ZJS
914 if (i != j && streq(boot_entry_title(entries + i),
915 boot_entry_title(entries + j)))
916 non_unique = arr[i] = arr[j] = true;
917
918 return non_unique;
919}
920
921static int boot_entries_uniquify(BootEntry *entries, size_t n_entries) {
d5ac1d4e 922 _cleanup_free_ bool *arr = NULL;
64f05708 923 char *s;
64f05708 924
4fe2ba0e
LP
925 assert(entries || n_entries == 0);
926
d5ac1d4e
LP
927 if (n_entries == 0)
928 return 0;
929
930 arr = new(bool, n_entries);
931 if (!arr)
932 return -ENOMEM;
933
64f05708
ZJS
934 /* Find _all_ non-unique titles */
935 if (!find_nonunique(entries, n_entries, arr))
936 return 0;
937
938 /* Add version to non-unique titles */
d5ac1d4e 939 for (size_t i = 0; i < n_entries; i++)
64f05708 940 if (arr[i] && entries[i].version) {
d5ac1d4e 941 if (asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].version) < 0)
64f05708
ZJS
942 return -ENOMEM;
943
944 free_and_replace(entries[i].show_title, s);
945 }
946
947 if (!find_nonunique(entries, n_entries, arr))
948 return 0;
949
950 /* Add machine-id to non-unique titles */
d5ac1d4e 951 for (size_t i = 0; i < n_entries; i++)
64f05708 952 if (arr[i] && entries[i].machine_id) {
d5ac1d4e 953 if (asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].machine_id) < 0)
64f05708
ZJS
954 return -ENOMEM;
955
956 free_and_replace(entries[i].show_title, s);
957 }
958
959 if (!find_nonunique(entries, n_entries, arr))
960 return 0;
961
962 /* Add file name to non-unique titles */
d5ac1d4e 963 for (size_t i = 0; i < n_entries; i++)
64f05708 964 if (arr[i]) {
d5ac1d4e 965 if (asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].id) < 0)
64f05708
ZJS
966 return -ENOMEM;
967
968 free_and_replace(entries[i].show_title, s);
969 }
970
971 return 0;
972}
973
20ec8f53
LP
974static int boot_config_find(const BootConfig *config, const char *id) {
975 assert(config);
976
977 if (!id)
978 return -1;
979
7941f11a
JJ
980 if (id[0] == '@') {
981 if (!strcaseeq(id, "@saved"))
982 return -1;
983 id = config->entry_selected;
984 }
985
20ec8f53
LP
986 for (size_t i = 0; i < config->n_entries; i++)
987 if (fnmatch(id, config->entries[i].id, FNM_CASEFOLD) == 0)
988 return i;
989
990 return -1;
991}
992
ad1afd60 993static int boot_entries_select_default(const BootConfig *config) {
7e87c7d9
ZJS
994 int i;
995
4fe2ba0e 996 assert(config);
388d2993
ZJS
997 assert(config->entries || config->n_entries == 0);
998
999 if (config->n_entries == 0) {
1000 log_debug("Found no default boot entry :(");
1001 return -1; /* -1 means "no default" */
1002 }
4fe2ba0e 1003
20ec8f53
LP
1004 if (config->entry_oneshot) {
1005 i = boot_config_find(config, config->entry_oneshot);
1006 if (i >= 0) {
1007 log_debug("Found default: id \"%s\" is matched by LoaderEntryOneShot",
1008 config->entries[i].id);
1009 return i;
1010 }
1011 }
1012
1013 if (config->entry_default) {
1014 i = boot_config_find(config, config->entry_default);
1015 if (i >= 0) {
1016 log_debug("Found default: id \"%s\" is matched by LoaderEntryDefault",
1017 config->entries[i].id);
1018 return i;
1019 }
1020 }
1021
1022 if (config->default_pattern) {
1023 i = boot_config_find(config, config->default_pattern);
1024 if (i >= 0) {
1025 log_debug("Found default: id \"%s\" is matched by pattern \"%s\"",
1026 config->entries[i].id, config->default_pattern);
1027 return i;
1028 }
1029 }
1030
1031 log_debug("Found default: first entry \"%s\"", config->entries[0].id);
1032 return 0;
7e87c7d9
ZJS
1033}
1034
a78e472d 1035static int boot_entries_select_selected(const BootConfig *config) {
a78e472d
LP
1036 assert(config);
1037 assert(config->entries || config->n_entries == 0);
1038
1039 if (!config->entry_selected || config->n_entries == 0)
1040 return -1;
1041
20ec8f53 1042 return boot_config_find(config, config->entry_selected);
a78e472d
LP
1043}
1044
80a2381d 1045static int boot_load_efi_entry_pointers(BootConfig *config, bool skip_efivars) {
a78e472d
LP
1046 int r;
1047
1048 assert(config);
1049
80a2381d 1050 if (skip_efivars || !is_efi_boot())
a78e472d
LP
1051 return 0;
1052
1053 /* Loads the three "pointers" to boot loader entries from their EFI variables */
1054
1055 r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderEntryOneShot), &config->entry_oneshot);
92067ab6
LP
1056 if (r == -ENOMEM)
1057 return log_oom();
1058 if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
1059 log_warning_errno(r, "Failed to read EFI variable \"LoaderEntryOneShot\", ignoring: %m");
a78e472d
LP
1060
1061 r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderEntryDefault), &config->entry_default);
92067ab6
LP
1062 if (r == -ENOMEM)
1063 return log_oom();
1064 if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
1065 log_warning_errno(r, "Failed to read EFI variable \"LoaderEntryDefault\", ignoring: %m");
a78e472d
LP
1066
1067 r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderEntrySelected), &config->entry_selected);
92067ab6
LP
1068 if (r == -ENOMEM)
1069 return log_oom();
1070 if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
1071 log_warning_errno(r, "Failed to read EFI variable \"LoaderEntrySelected\", ignoring: %m");
a78e472d
LP
1072
1073 return 1;
1074}
1075
80a2381d 1076int boot_config_select_special_entries(BootConfig *config, bool skip_efivars) {
f7a7a5e2
LP
1077 int r;
1078
1079 assert(config);
1080
80a2381d 1081 r = boot_load_efi_entry_pointers(config, skip_efivars);
f7a7a5e2
LP
1082 if (r < 0)
1083 return r;
1084
1085 config->default_entry = boot_entries_select_default(config);
1086 config->selected_entry = boot_entries_select_selected(config);
1087
1088 return 0;
1089}
1090
5ba1550f
ZJS
1091int boot_config_finalize(BootConfig *config) {
1092 int r;
1093
1094 typesafe_qsort(config->entries, config->n_entries, boot_entry_compare);
1095
1096 r = boot_entries_uniquify(config->entries, config->n_entries);
1097 if (r < 0)
1098 return log_error_errno(r, "Failed to uniquify boot entries: %m");
1099
1100 return 0;
1101}
1102
af9ae750
LP
1103int boot_config_load(
1104 BootConfig *config,
a2f8664e 1105 const char *esp_path,
af9ae750 1106 const char *xbootldr_path) {
a2f8664e 1107
7e87c7d9
ZJS
1108 int r;
1109
4fe2ba0e
LP
1110 assert(config);
1111
a2f8664e 1112 if (esp_path) {
2683ae2d 1113 r = boot_loader_read_conf_path(config, esp_path, "/loader/loader.conf");
a2f8664e
LP
1114 if (r < 0)
1115 return r;
7e87c7d9 1116
2683ae2d 1117 r = boot_entries_find_type1(config, esp_path, "/loader/entries");
a2f8664e
LP
1118 if (r < 0)
1119 return r;
5e146a75 1120
2683ae2d 1121 r = boot_entries_find_unified(config, esp_path, "/EFI/Linux/");
5e146a75
LP
1122 if (r < 0)
1123 return r;
a2f8664e
LP
1124 }
1125
1126 if (xbootldr_path) {
2683ae2d 1127 r = boot_entries_find_type1(config, xbootldr_path, "/loader/entries");
a2f8664e
LP
1128 if (r < 0)
1129 return r;
5e146a75 1130
2683ae2d 1131 r = boot_entries_find_unified(config, xbootldr_path, "/EFI/Linux/");
5e146a75
LP
1132 if (r < 0)
1133 return r;
a2f8664e 1134 }
7e87c7d9 1135
5ba1550f 1136 return boot_config_finalize(config);
7e87c7d9 1137}
af918182 1138
af9ae750
LP
1139int boot_config_load_auto(
1140 BootConfig *config,
eea4ce1e 1141 const char *override_esp_path,
af9ae750 1142 const char *override_xbootldr_path) {
eea4ce1e
LP
1143
1144 _cleanup_free_ char *esp_where = NULL, *xbootldr_where = NULL;
f63b5ad9 1145 dev_t esp_devid = 0, xbootldr_devid = 0;
eea4ce1e
LP
1146 int r;
1147
1148 assert(config);
1149
1150 /* This function is similar to boot_entries_load_config(), however we automatically search for the
1151 * ESP and the XBOOTLDR partition unless it is explicitly specified. Also, if the user did not pass
1152 * an ESP or XBOOTLDR path directly, let's see if /run/boot-loader-entries/ exists. If so, let's
1153 * read data from there, as if it was an ESP (i.e. loading both entries and loader.conf data from
1154 * it). This allows other boot loaders to pass boot loader entry information to our tools if they
1155 * want to. */
1156
1157 if (!override_esp_path && !override_xbootldr_path) {
f40999f8 1158 if (access("/run/boot-loader-entries/", F_OK) >= 0)
af9ae750 1159 return boot_config_load(config, "/run/boot-loader-entries/", NULL);
eea4ce1e 1160
f40999f8
ZJS
1161 if (errno != ENOENT)
1162 return log_error_errno(errno,
1163 "Failed to determine whether /run/boot-loader-entries/ exists: %m");
eea4ce1e
LP
1164 }
1165
80a2381d 1166 r = find_esp_and_warn(NULL, override_esp_path, /* unprivileged_mode= */ false, &esp_where, NULL, NULL, NULL, NULL, &esp_devid);
cc5957dc 1167 if (r < 0) /* we don't log about ENOKEY here, but propagate it, leaving it to the caller to log */
eea4ce1e
LP
1168 return r;
1169
80a2381d 1170 r = find_xbootldr_and_warn(NULL, override_xbootldr_path, /* unprivileged_mode= */ false, &xbootldr_where, NULL, &xbootldr_devid);
eea4ce1e
LP
1171 if (r < 0 && r != -ENOKEY)
1172 return r; /* It's fine if the XBOOTLDR partition doesn't exist, hence we ignore ENOKEY here */
1173
f63b5ad9 1174 /* If both paths actually refer to the same inode, suppress the xbootldr path */
7176f06c 1175 if (esp_where && xbootldr_where && devnum_set_and_equal(esp_devid, xbootldr_devid))
f63b5ad9
LP
1176 xbootldr_where = mfree(xbootldr_where);
1177
af9ae750 1178 return boot_config_load(config, esp_where, xbootldr_where);
eea4ce1e
LP
1179}
1180
af9ae750 1181int boot_config_augment_from_loader(
d4bd786d 1182 BootConfig *config,
9951736b
LP
1183 char **found_by_loader,
1184 bool only_auto) {
d4bd786d
LP
1185
1186 static const char *const title_table[] = {
93f14ce2
LP
1187 /* Pretty names for a few well-known automatically discovered entries. */
1188 "auto-osx", "macOS",
1189 "auto-windows", "Windows Boot Manager",
1190 "auto-efi-shell", "EFI Shell",
1191 "auto-efi-default", "EFI Default Loader",
1192 "auto-reboot-to-firmware-setup", "Reboot Into Firmware Interface",
d4f72d10 1193 NULL,
93f14ce2
LP
1194 };
1195
93f14ce2
LP
1196 assert(config);
1197
1198 /* Let's add the entries discovered by the boot loader to the end of our list, unless they are
1199 * already included there. */
1200
93f14ce2 1201 STRV_FOREACH(i, found_by_loader) {
bb682057 1202 BootEntry *existing;
ce4c4f81 1203 _cleanup_free_ char *c = NULL, *t = NULL, *p = NULL;
93f14ce2 1204
bb682057
LP
1205 existing = boot_config_find_entry(config, *i);
1206 if (existing) {
1207 existing->reported_by_loader = true;
93f14ce2 1208 continue;
bb682057 1209 }
93f14ce2 1210
9951736b 1211 if (only_auto && !startswith(*i, "auto-"))
93f14ce2
LP
1212 continue;
1213
1214 c = strdup(*i);
1215 if (!c)
1216 return log_oom();
1217
2034c8b8 1218 STRV_FOREACH_PAIR(a, b, title_table)
93f14ce2
LP
1219 if (streq(*a, *i)) {
1220 t = strdup(*b);
1221 if (!t)
1222 return log_oom();
1223 break;
1224 }
1225
e6f055cb 1226 p = strdup(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderEntries)));
ce4c4f81
ZJS
1227 if (!p)
1228 return log_oom();
1229
319a4f4b 1230 if (!GREEDY_REALLOC0(config->entries, config->n_entries + 1))
93f14ce2
LP
1231 return log_oom();
1232
1233 config->entries[config->n_entries++] = (BootEntry) {
bb682057 1234 .type = startswith(*i, "auto-") ? BOOT_ENTRY_LOADER_AUTO : BOOT_ENTRY_LOADER,
93f14ce2
LP
1235 .id = TAKE_PTR(c),
1236 .title = TAKE_PTR(t),
ce4c4f81 1237 .path = TAKE_PTR(p),
bb682057 1238 .reported_by_loader = true,
7f5780ed
LP
1239 .tries_left = UINT_MAX,
1240 .tries_done = UINT_MAX,
93f14ce2
LP
1241 };
1242 }
1243
1244 return 0;
1245}
3f8e42c0
LP
1246
1247BootEntry* boot_config_find_entry(BootConfig *config, const char *id) {
1248 assert(config);
1249 assert(id);
1250
1251 for (size_t j = 0; j < config->n_entries; j++)
1252 if (streq_ptr(config->entries[j].id, id) ||
1253 streq_ptr(config->entries[j].id_old, id))
1254 return config->entries + j;
1255
1256 return NULL;
1257}
432ce537 1258
2683ae2d
LP
1259static void boot_entry_file_list(
1260 const char *field,
1261 const char *root,
1262 const char *p,
1263 int *ret_status) {
1264
1265 assert(p);
1266 assert(ret_status);
1267
b353d5ee 1268 int status = chase_symlinks_and_access(p, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, F_OK, NULL, NULL);
432ce537 1269
78517322
JJ
1270 /* Note that this shows two '/' between the root and the file. This is intentional to highlight (in
1271 * the abscence of color support) to the user that the boot loader is only interested in the second
1272 * part of the file. */
1273 printf("%13s%s %s%s/%s", strempty(field), field ? ":" : " ", ansi_grey(), root, ansi_normal());
1274
432ce537
ZJS
1275 if (status < 0) {
1276 errno = -status;
1277 printf("%s%s%s (%m)\n", ansi_highlight_red(), p, ansi_normal());
1278 } else
1279 printf("%s\n", p);
1280
1281 if (*ret_status == 0 && status < 0)
1282 *ret_status = status;
1283}
1284
1285int show_boot_entry(
1286 const BootEntry *e,
1287 bool show_as_default,
1288 bool show_as_selected,
1289 bool show_reported) {
1290
1291 int status = 0;
1292
1293 /* Returns 0 on success, negative on processing error, and positive if something is wrong with the
1294 boot entry itself. */
1295
1296 assert(e);
1297
1298 printf(" type: %s\n",
1299 boot_entry_type_to_string(e->type));
1300
1301 printf(" title: %s%s%s",
1302 ansi_highlight(), boot_entry_title(e), ansi_normal());
1303
1304 if (show_as_default)
1305 printf(" %s(default)%s",
1306 ansi_highlight_green(), ansi_normal());
1307
1308 if (show_as_selected)
1309 printf(" %s(selected)%s",
1310 ansi_highlight_magenta(), ansi_normal());
1311
1312 if (show_reported) {
1313 if (e->type == BOOT_ENTRY_LOADER)
1314 printf(" %s(reported/absent)%s",
1315 ansi_highlight_red(), ansi_normal());
1316 else if (!e->reported_by_loader && e->type != BOOT_ENTRY_LOADER_AUTO)
1317 printf(" %s(not reported/new)%s",
1318 ansi_highlight_green(), ansi_normal());
1319 }
1320
1321 putchar('\n');
1322
1323 if (e->id)
1324 printf(" id: %s\n", e->id);
1325 if (e->path) {
5a65d2e5
ZJS
1326 _cleanup_free_ char *text = NULL, *link = NULL;
1327
1328 const char *p = e->root ? path_startswith(e->path, e->root) : NULL;
1329 if (p) {
1330 text = strjoin(ansi_grey(), e->root, "/", ansi_normal(), "/", p);
1331 if (!text)
1332 return log_oom();
1333 }
432ce537
ZJS
1334
1335 /* Let's urlify the link to make it easy to view in an editor, but only if it is a text
1336 * file. Unified images are binary ELFs, and EFI variables are not pure text either. */
1337 if (e->type == BOOT_ENTRY_CONF)
5a65d2e5 1338 (void) terminal_urlify_path(e->path, text, &link);
432ce537 1339
5a65d2e5 1340 printf(" source: %s\n", link ?: text ?: e->path);
432ce537 1341 }
7f5780ed
LP
1342 if (e->tries_left != UINT_MAX) {
1343 printf(" tries: %u left", e->tries_left);
1344
1345 if (e->tries_done != UINT_MAX)
1346 printf("; %u done\n", e->tries_done);
1347 else
1348 printf("\n");
1349 }
1350
432ce537
ZJS
1351 if (e->sort_key)
1352 printf(" sort-key: %s\n", e->sort_key);
1353 if (e->version)
1354 printf(" version: %s\n", e->version);
1355 if (e->machine_id)
1356 printf(" machine-id: %s\n", e->machine_id);
1357 if (e->architecture)
1358 printf(" architecture: %s\n", e->architecture);
1359 if (e->kernel)
1360 boot_entry_file_list("linux", e->root, e->kernel, &status);
1361
1362 STRV_FOREACH(s, e->initrd)
1363 boot_entry_file_list(s == e->initrd ? "initrd" : NULL,
1364 e->root,
1365 *s,
1366 &status);
1367
1368 if (!strv_isempty(e->options)) {
1369 _cleanup_free_ char *t = NULL, *t2 = NULL;
1370 _cleanup_strv_free_ char **ts = NULL;
1371
1372 t = strv_join(e->options, " ");
1373 if (!t)
1374 return log_oom();
1375
1376 ts = strv_split_newlines(t);
1377 if (!ts)
1378 return log_oom();
1379
1380 t2 = strv_join(ts, "\n ");
1381 if (!t2)
1382 return log_oom();
1383
1384 printf(" options: %s\n", t2);
1385 }
1386
1387 if (e->device_tree)
1388 boot_entry_file_list("devicetree", e->root, e->device_tree, &status);
1389
1390 STRV_FOREACH(s, e->device_tree_overlay)
1391 boot_entry_file_list(s == e->device_tree_overlay ? "devicetree-overlay" : NULL,
1392 e->root,
1393 *s,
1394 &status);
1395
1396 return -status;
1397}
1398
1399int show_boot_entries(const BootConfig *config, JsonFormatFlags json_format) {
1400 int r;
1401
8c87f247
LP
1402 assert(config);
1403
432ce537
ZJS
1404 if (!FLAGS_SET(json_format, JSON_FORMAT_OFF)) {
1405 for (size_t i = 0; i < config->n_entries; i++) {
1406 _cleanup_free_ char *opts = NULL;
1407 const BootEntry *e = config->entries + i;
1408 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
1409
1410 if (!strv_isempty(e->options)) {
1411 opts = strv_join(e->options, " ");
1412 if (!opts)
1413 return log_oom();
1414 }
1415
4d49d19e 1416 r = json_append(&v, JSON_BUILD_OBJECT(
432ce537
ZJS
1417 JSON_BUILD_PAIR_CONDITION(e->id, "id", JSON_BUILD_STRING(e->id)),
1418 JSON_BUILD_PAIR_CONDITION(e->path, "path", JSON_BUILD_STRING(e->path)),
1419 JSON_BUILD_PAIR_CONDITION(e->root, "root", JSON_BUILD_STRING(e->root)),
1420 JSON_BUILD_PAIR_CONDITION(e->title, "title", JSON_BUILD_STRING(e->title)),
1421 JSON_BUILD_PAIR_CONDITION(boot_entry_title(e), "showTitle", JSON_BUILD_STRING(boot_entry_title(e))),
1422 JSON_BUILD_PAIR_CONDITION(e->sort_key, "sortKey", JSON_BUILD_STRING(e->sort_key)),
1423 JSON_BUILD_PAIR_CONDITION(e->version, "version", JSON_BUILD_STRING(e->version)),
1424 JSON_BUILD_PAIR_CONDITION(e->machine_id, "machineId", JSON_BUILD_STRING(e->machine_id)),
1425 JSON_BUILD_PAIR_CONDITION(e->architecture, "architecture", JSON_BUILD_STRING(e->architecture)),
1426 JSON_BUILD_PAIR_CONDITION(opts, "options", JSON_BUILD_STRING(opts)),
1427 JSON_BUILD_PAIR_CONDITION(e->kernel, "linux", JSON_BUILD_STRING(e->kernel)),
1428 JSON_BUILD_PAIR_CONDITION(e->efi, "efi", JSON_BUILD_STRING(e->efi)),
1429 JSON_BUILD_PAIR_CONDITION(!strv_isempty(e->initrd), "initrd", JSON_BUILD_STRV(e->initrd)),
1430 JSON_BUILD_PAIR_CONDITION(e->device_tree, "devicetree", JSON_BUILD_STRING(e->device_tree)),
4d49d19e
YW
1431 JSON_BUILD_PAIR_CONDITION(!strv_isempty(e->device_tree_overlay), "devicetreeOverlay", JSON_BUILD_STRV(e->device_tree_overlay))));
1432 if (r < 0)
1433 return log_oom();
1434
1435 /* Sanitizers (only memory sanitizer?) do not like function call with too many
1436 * arguments and trigger false positive warnings. Let's not add too many json objects
1437 * at once. */
1438 r = json_append(&v, JSON_BUILD_OBJECT(
7f5780ed
LP
1439 JSON_BUILD_PAIR_CONDITION(e->tries_left != UINT_MAX, "triesLeft", JSON_BUILD_UNSIGNED(e->tries_left)),
1440 JSON_BUILD_PAIR_CONDITION(e->tries_done != UINT_MAX, "triesDone", JSON_BUILD_UNSIGNED(e->tries_done))));
432ce537
ZJS
1441 if (r < 0)
1442 return log_oom();
1443
1444 json_variant_dump(v, json_format, stdout, NULL);
1445 }
1446
1447 } else {
432ce537
ZJS
1448 for (size_t n = 0; n < config->n_entries; n++) {
1449 r = show_boot_entry(
1450 config->entries + n,
1451 /* show_as_default= */ n == (size_t) config->default_entry,
1452 /* show_as_selected= */ n == (size_t) config->selected_entry,
1453 /* show_discovered= */ true);
1454 if (r < 0)
1455 return r;
1456
1457 if (n+1 < config->n_entries)
1458 putchar('\n');
1459 }
1460 }
1461
1462 return 0;
1463}