]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/bootspec.c
tree-wide: use typesafe_qsort()
[thirdparty/systemd.git] / src / shared / bootspec.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <stdio.h>
4 #include <linux/magic.h>
5
6 #include "sd-id128.h"
7
8 #include "alloc-util.h"
9 #include "blkid-util.h"
10 #include "bootspec.h"
11 #include "conf-files.h"
12 #include "def.h"
13 #include "device-nodes.h"
14 #include "efivars.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "parse-util.h"
18 #include "stat-util.h"
19 #include "string-util.h"
20 #include "strv.h"
21 #include "virt.h"
22
23 void boot_entry_free(BootEntry *entry) {
24 assert(entry);
25
26 free(entry->filename);
27 free(entry->title);
28 free(entry->show_title);
29 free(entry->version);
30 free(entry->machine_id);
31 free(entry->architecture);
32 strv_free(entry->options);
33 free(entry->kernel);
34 free(entry->efi);
35 strv_free(entry->initrd);
36 free(entry->device_tree);
37 }
38
39 int boot_entry_load(const char *path, BootEntry *entry) {
40 _cleanup_(boot_entry_free) BootEntry tmp = {};
41 _cleanup_fclose_ FILE *f = NULL;
42 unsigned line = 1;
43 char *b, *c;
44 int r;
45
46 assert(path);
47 assert(entry);
48
49 c = endswith_no_case(path, ".conf");
50 if (!c) {
51 log_error("Invalid loader entry filename: %s", path);
52 return -EINVAL;
53 }
54
55 b = basename(path);
56 tmp.filename = strndup(b, c - b);
57 if (!tmp.filename)
58 return log_oom();
59
60 f = fopen(path, "re");
61 if (!f)
62 return log_error_errno(errno, "Failed to open \"%s\": %m", path);
63
64 for (;;) {
65 _cleanup_free_ char *buf = NULL, *field = NULL;
66 const char *p;
67
68 r = read_line(f, LONG_LINE_MAX, &buf);
69 if (r == 0)
70 break;
71 if (r == -ENOBUFS)
72 return log_error_errno(r, "%s:%u: Line too long", path, line);
73 if (r < 0)
74 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
75
76 line++;
77
78 if (IN_SET(*strstrip(buf), '#', '\0'))
79 continue;
80
81 p = buf;
82 r = extract_first_word(&p, &field, " \t", 0);
83 if (r < 0) {
84 log_error_errno(r, "Failed to parse config file %s line %u: %m", path, line);
85 continue;
86 }
87 if (r == 0) {
88 log_warning("%s:%u: Bad syntax", path, line);
89 continue;
90 }
91
92 if (streq(field, "title"))
93 r = free_and_strdup(&tmp.title, p);
94 else if (streq(field, "version"))
95 r = free_and_strdup(&tmp.version, p);
96 else if (streq(field, "machine-id"))
97 r = free_and_strdup(&tmp.machine_id, p);
98 else if (streq(field, "architecture"))
99 r = free_and_strdup(&tmp.architecture, p);
100 else if (streq(field, "options"))
101 r = strv_extend(&tmp.options, p);
102 else if (streq(field, "linux"))
103 r = free_and_strdup(&tmp.kernel, p);
104 else if (streq(field, "efi"))
105 r = free_and_strdup(&tmp.efi, p);
106 else if (streq(field, "initrd"))
107 r = strv_extend(&tmp.initrd, p);
108 else if (streq(field, "devicetree"))
109 r = free_and_strdup(&tmp.device_tree, p);
110 else {
111 log_notice("%s:%u: Unknown line \"%s\"", path, line, field);
112 continue;
113 }
114 if (r < 0)
115 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
116 }
117
118 *entry = tmp;
119 tmp = (BootEntry) {};
120 return 0;
121 }
122
123 void boot_config_free(BootConfig *config) {
124 size_t i;
125
126 assert(config);
127
128 free(config->default_pattern);
129 free(config->timeout);
130 free(config->editor);
131 free(config->auto_entries);
132 free(config->auto_firmware);
133
134 free(config->entry_oneshot);
135 free(config->entry_default);
136
137 for (i = 0; i < config->n_entries; i++)
138 boot_entry_free(config->entries + i);
139 free(config->entries);
140 }
141
142 int boot_loader_read_conf(const char *path, BootConfig *config) {
143 _cleanup_fclose_ FILE *f = NULL;
144 unsigned line = 1;
145 int r;
146
147 assert(path);
148 assert(config);
149
150 f = fopen(path, "re");
151 if (!f)
152 return log_error_errno(errno, "Failed to open \"%s\": %m", path);
153
154 for (;;) {
155 _cleanup_free_ char *buf = NULL, *field = NULL;
156 const char *p;
157
158 r = read_line(f, LONG_LINE_MAX, &buf);
159 if (r == 0)
160 break;
161 if (r == -ENOBUFS)
162 return log_error_errno(r, "%s:%u: Line too long", path, line);
163 if (r < 0)
164 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
165
166 line++;
167
168 if (IN_SET(*strstrip(buf), '#', '\0'))
169 continue;
170
171 p = buf;
172 r = extract_first_word(&p, &field, " \t", 0);
173 if (r < 0) {
174 log_error_errno(r, "Failed to parse config file %s line %u: %m", path, line);
175 continue;
176 }
177 if (r == 0) {
178 log_warning("%s:%u: Bad syntax", path, line);
179 continue;
180 }
181
182 if (streq(field, "default"))
183 r = free_and_strdup(&config->default_pattern, p);
184 else if (streq(field, "timeout"))
185 r = free_and_strdup(&config->timeout, p);
186 else if (streq(field, "editor"))
187 r = free_and_strdup(&config->editor, p);
188 else if (streq(field, "auto-entries"))
189 r = free_and_strdup(&config->auto_entries, p);
190 else if (streq(field, "auto-firmware"))
191 r = free_and_strdup(&config->auto_firmware, p);
192 else if (streq(field, "console-mode"))
193 r = free_and_strdup(&config->console_mode, p);
194 else {
195 log_notice("%s:%u: Unknown line \"%s\"", path, line, field);
196 continue;
197 }
198 if (r < 0)
199 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
200 }
201
202 return 0;
203 }
204
205 static int boot_entry_compare(const BootEntry *a, const BootEntry *b) {
206 return str_verscmp(a->filename, b->filename);
207 }
208
209 int boot_entries_find(const char *dir, BootEntry **ret_entries, size_t *ret_n_entries) {
210 _cleanup_strv_free_ char **files = NULL;
211 char **f;
212 int r;
213 BootEntry *array = NULL;
214 size_t n_allocated = 0, n = 0;
215
216 assert(dir);
217 assert(ret_entries);
218 assert(ret_n_entries);
219
220 r = conf_files_list(&files, ".conf", NULL, 0, dir, NULL);
221 if (r < 0)
222 return log_error_errno(r, "Failed to list files in \"%s\": %m", dir);
223
224 STRV_FOREACH(f, files) {
225 if (!GREEDY_REALLOC0(array, n_allocated, n + 1))
226 return log_oom();
227
228 r = boot_entry_load(*f, array + n);
229 if (r < 0)
230 continue;
231
232 n++;
233 }
234
235 typesafe_qsort(array, n, boot_entry_compare);
236
237 *ret_entries = array;
238 *ret_n_entries = n;
239
240 return 0;
241 }
242
243 static bool find_nonunique(BootEntry *entries, size_t n_entries, bool *arr) {
244 size_t i, j;
245 bool non_unique = false;
246
247 assert(entries || n_entries == 0);
248 assert(arr || n_entries == 0);
249
250 for (i = 0; i < n_entries; i++)
251 arr[i] = false;
252
253 for (i = 0; i < n_entries; i++)
254 for (j = 0; j < n_entries; j++)
255 if (i != j && streq(boot_entry_title(entries + i),
256 boot_entry_title(entries + j)))
257 non_unique = arr[i] = arr[j] = true;
258
259 return non_unique;
260 }
261
262 static int boot_entries_uniquify(BootEntry *entries, size_t n_entries) {
263 char *s;
264 size_t i;
265 int r;
266 bool arr[n_entries];
267
268 assert(entries || n_entries == 0);
269
270 /* Find _all_ non-unique titles */
271 if (!find_nonunique(entries, n_entries, arr))
272 return 0;
273
274 /* Add version to non-unique titles */
275 for (i = 0; i < n_entries; i++)
276 if (arr[i] && entries[i].version) {
277 r = asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].version);
278 if (r < 0)
279 return -ENOMEM;
280
281 free_and_replace(entries[i].show_title, s);
282 }
283
284 if (!find_nonunique(entries, n_entries, arr))
285 return 0;
286
287 /* Add machine-id to non-unique titles */
288 for (i = 0; i < n_entries; i++)
289 if (arr[i] && entries[i].machine_id) {
290 r = asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].machine_id);
291 if (r < 0)
292 return -ENOMEM;
293
294 free_and_replace(entries[i].show_title, s);
295 }
296
297 if (!find_nonunique(entries, n_entries, arr))
298 return 0;
299
300 /* Add file name to non-unique titles */
301 for (i = 0; i < n_entries; i++)
302 if (arr[i]) {
303 r = asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].filename);
304 if (r < 0)
305 return -ENOMEM;
306
307 free_and_replace(entries[i].show_title, s);
308 }
309
310 return 0;
311 }
312
313 static int boot_entries_select_default(const BootConfig *config) {
314 int i;
315
316 assert(config);
317
318 if (config->entry_oneshot)
319 for (i = config->n_entries - 1; i >= 0; i--)
320 if (streq(config->entry_oneshot, config->entries[i].filename)) {
321 log_debug("Found default: filename \"%s\" is matched by LoaderEntryOneShot",
322 config->entries[i].filename);
323 return i;
324 }
325
326 if (config->entry_default)
327 for (i = config->n_entries - 1; i >= 0; i--)
328 if (streq(config->entry_default, config->entries[i].filename)) {
329 log_debug("Found default: filename \"%s\" is matched by LoaderEntryDefault",
330 config->entries[i].filename);
331 return i;
332 }
333
334 if (config->default_pattern)
335 for (i = config->n_entries - 1; i >= 0; i--)
336 if (fnmatch(config->default_pattern, config->entries[i].filename, FNM_CASEFOLD) == 0) {
337 log_debug("Found default: filename \"%s\" is matched by pattern \"%s\"",
338 config->entries[i].filename, config->default_pattern);
339 return i;
340 }
341
342 if (config->n_entries > 0)
343 log_debug("Found default: last entry \"%s\"", config->entries[config->n_entries - 1].filename);
344 else
345 log_debug("Found no default boot entry :(");
346
347 return config->n_entries - 1; /* -1 means "no default" */
348 }
349
350 int boot_entries_load_config(const char *esp_path, BootConfig *config) {
351 const char *p;
352 int r;
353
354 assert(esp_path);
355 assert(config);
356
357 p = strjoina(esp_path, "/loader/loader.conf");
358 r = boot_loader_read_conf(p, config);
359 if (r < 0)
360 return log_error_errno(r, "Failed to read boot config from \"%s\": %m", p);
361
362 p = strjoina(esp_path, "/loader/entries");
363 r = boot_entries_find(p, &config->entries, &config->n_entries);
364 if (r < 0)
365 return log_error_errno(r, "Failed to read boot entries from \"%s\": %m", p);
366
367 r = boot_entries_uniquify(config->entries, config->n_entries);
368 if (r < 0)
369 return log_error_errno(r, "Failed to uniquify boot entries: %m");
370
371 r = efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderEntryOneShot", &config->entry_oneshot);
372 if (r < 0 && r != -ENOENT)
373 return log_error_errno(r, "Failed to read EFI var \"LoaderEntryOneShot\": %m");
374
375 r = efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderEntryDefault", &config->entry_default);
376 if (r < 0 && r != -ENOENT)
377 return log_error_errno(r, "Failed to read EFI var \"LoaderEntryDefault\": %m");
378
379 config->default_entry = boot_entries_select_default(config);
380 return 0;
381 }
382
383 /********************************************************************************/
384
385 static int verify_esp(
386 const char *p,
387 bool searching,
388 bool unprivileged_mode,
389 uint32_t *ret_part,
390 uint64_t *ret_pstart,
391 uint64_t *ret_psize,
392 sd_id128_t *ret_uuid) {
393 #if HAVE_BLKID
394 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
395 char t[DEV_NUM_PATH_MAX];
396 const char *v;
397 #endif
398 uint64_t pstart = 0, psize = 0;
399 struct stat st, st2;
400 const char *t2;
401 struct statfs sfs;
402 sd_id128_t uuid = SD_ID128_NULL;
403 uint32_t part = 0;
404 int r;
405
406 assert(p);
407
408 /* Non-root user can only check the status, so if an error occured in the following, it does not cause any
409 * issues. Let's also, silence the error messages. */
410
411 if (statfs(p, &sfs) < 0) {
412 /* If we are searching for the mount point, don't generate a log message if we can't find the path */
413 if (errno == ENOENT && searching)
414 return -ENOENT;
415
416 return log_full_errno(unprivileged_mode && errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
417 "Failed to check file system type of \"%s\": %m", p);
418 }
419
420 if (!F_TYPE_EQUAL(sfs.f_type, MSDOS_SUPER_MAGIC)) {
421 if (searching)
422 return -EADDRNOTAVAIL;
423
424 log_error("File system \"%s\" is not a FAT EFI System Partition (ESP) file system.", p);
425 return -ENODEV;
426 }
427
428 if (stat(p, &st) < 0)
429 return log_full_errno(unprivileged_mode && errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
430 "Failed to determine block device node of \"%s\": %m", p);
431
432 if (major(st.st_dev) == 0) {
433 log_error("Block device node of %p is invalid.", p);
434 return -ENODEV;
435 }
436
437 t2 = strjoina(p, "/..");
438 r = stat(t2, &st2);
439 if (r < 0)
440 return log_full_errno(unprivileged_mode && errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
441 "Failed to determine block device node of parent of \"%s\": %m", p);
442
443 if (st.st_dev == st2.st_dev) {
444 log_error("Directory \"%s\" is not the root of the EFI System Partition (ESP) file system.", p);
445 return -ENODEV;
446 }
447
448 /* In a container we don't have access to block devices, skip this part of the verification, we trust the
449 * container manager set everything up correctly on its own. Also skip the following verification for non-root user. */
450 if (detect_container() > 0 || unprivileged_mode)
451 goto finish;
452
453 #if HAVE_BLKID
454 xsprintf_dev_num_path(t, "block", st.st_dev);
455 errno = 0;
456 b = blkid_new_probe_from_filename(t);
457 if (!b)
458 return log_error_errno(errno ?: ENOMEM, "Failed to open file system \"%s\": %m", p);
459
460 blkid_probe_enable_superblocks(b, 1);
461 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
462 blkid_probe_enable_partitions(b, 1);
463 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
464
465 errno = 0;
466 r = blkid_do_safeprobe(b);
467 if (r == -2) {
468 log_error("File system \"%s\" is ambiguous.", p);
469 return -ENODEV;
470 } else if (r == 1) {
471 log_error("File system \"%s\" does not contain a label.", p);
472 return -ENODEV;
473 } else if (r != 0)
474 return log_error_errno(errno ?: EIO, "Failed to probe file system \"%s\": %m", p);
475
476 errno = 0;
477 r = blkid_probe_lookup_value(b, "TYPE", &v, NULL);
478 if (r != 0)
479 return log_error_errno(errno ?: EIO, "Failed to probe file system type \"%s\": %m", p);
480 if (!streq(v, "vfat")) {
481 log_error("File system \"%s\" is not FAT.", p);
482 return -ENODEV;
483 }
484
485 errno = 0;
486 r = blkid_probe_lookup_value(b, "PART_ENTRY_SCHEME", &v, NULL);
487 if (r != 0)
488 return log_error_errno(errno ?: EIO, "Failed to probe partition scheme \"%s\": %m", p);
489 if (!streq(v, "gpt")) {
490 log_error("File system \"%s\" is not on a GPT partition table.", p);
491 return -ENODEV;
492 }
493
494 errno = 0;
495 r = blkid_probe_lookup_value(b, "PART_ENTRY_TYPE", &v, NULL);
496 if (r != 0)
497 return log_error_errno(errno ?: EIO, "Failed to probe partition type UUID \"%s\": %m", p);
498 if (!streq(v, "c12a7328-f81f-11d2-ba4b-00a0c93ec93b")) {
499 log_error("File system \"%s\" has wrong type for an EFI System Partition (ESP).", p);
500 return -ENODEV;
501 }
502
503 errno = 0;
504 r = blkid_probe_lookup_value(b, "PART_ENTRY_UUID", &v, NULL);
505 if (r != 0)
506 return log_error_errno(errno ?: EIO, "Failed to probe partition entry UUID \"%s\": %m", p);
507 r = sd_id128_from_string(v, &uuid);
508 if (r < 0) {
509 log_error("Partition \"%s\" has invalid UUID \"%s\".", p, v);
510 return -EIO;
511 }
512
513 errno = 0;
514 r = blkid_probe_lookup_value(b, "PART_ENTRY_NUMBER", &v, NULL);
515 if (r != 0)
516 return log_error_errno(errno ?: EIO, "Failed to probe partition number \"%s\": m", p);
517 r = safe_atou32(v, &part);
518 if (r < 0)
519 return log_error_errno(r, "Failed to parse PART_ENTRY_NUMBER field.");
520
521 errno = 0;
522 r = blkid_probe_lookup_value(b, "PART_ENTRY_OFFSET", &v, NULL);
523 if (r != 0)
524 return log_error_errno(errno ?: EIO, "Failed to probe partition offset \"%s\": %m", p);
525 r = safe_atou64(v, &pstart);
526 if (r < 0)
527 return log_error_errno(r, "Failed to parse PART_ENTRY_OFFSET field.");
528
529 errno = 0;
530 r = blkid_probe_lookup_value(b, "PART_ENTRY_SIZE", &v, NULL);
531 if (r != 0)
532 return log_error_errno(errno ?: EIO, "Failed to probe partition size \"%s\": %m", p);
533 r = safe_atou64(v, &psize);
534 if (r < 0)
535 return log_error_errno(r, "Failed to parse PART_ENTRY_SIZE field.");
536 #endif
537
538 finish:
539 if (ret_part)
540 *ret_part = part;
541 if (ret_pstart)
542 *ret_pstart = pstart;
543 if (ret_psize)
544 *ret_psize = psize;
545 if (ret_uuid)
546 *ret_uuid = uuid;
547
548 return 0;
549 }
550
551 int find_esp_and_warn(
552 const char *path,
553 bool unprivileged_mode,
554 char **ret_path,
555 uint32_t *ret_part,
556 uint64_t *ret_pstart,
557 uint64_t *ret_psize,
558 sd_id128_t *ret_uuid) {
559
560 int r;
561
562 /* This logs about all errors except:
563 *
564 * -ENOKEY → when we can't find the partition
565 * -EACCESS → when unprivileged_mode is true, and we can't access something
566 */
567
568 if (path) {
569 r = verify_esp(path, false, unprivileged_mode, ret_part, ret_pstart, ret_psize, ret_uuid);
570 if (r < 0)
571 return r;
572
573 goto found;
574 }
575
576 FOREACH_STRING(path, "/efi", "/boot", "/boot/efi") {
577
578 r = verify_esp(path, true, unprivileged_mode, ret_part, ret_pstart, ret_psize, ret_uuid);
579 if (r >= 0)
580 goto found;
581 if (!IN_SET(r, -ENOENT, -EADDRNOTAVAIL)) /* This one is not it */
582 return r;
583 }
584
585 /* No logging here */
586 return -ENOKEY;
587
588 found:
589 if (ret_path) {
590 char *c;
591
592 c = strdup(path);
593 if (!c)
594 return log_oom();
595
596 *ret_path = c;
597 }
598
599 return 0;
600 }