• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 20495933613

24 Dec 2025 06:25PM UTC coverage: 72.64% (-0.06%) from 72.701%
20495933613

push

github

YHNdnzj
man: document version for BindNetworkInterface instead of using ignore list

The ignore list is for older stuff, all new interfaces must be documented
with a version.

Follow-up for c1c787651

309829 of 426528 relevant lines covered (72.64%)

1135837.86 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.06
/src/bootctl/bootctl-install.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdlib.h>
4
#include <unistd.h>
5

6
#include "alloc-util.h"
7
#include "boot-entry.h"
8
#include "bootctl.h"
9
#include "bootctl-install.h"
10
#include "bootctl-random-seed.h"
11
#include "bootctl-util.h"
12
#include "chase.h"
13
#include "copy.h"
14
#include "dirent-util.h"
15
#include "efi-api.h"
16
#include "efi-fundamental.h"
17
#include "efivars.h"
18
#include "env-file.h"
19
#include "env-util.h"
20
#include "fd-util.h"
21
#include "fileio.h"
22
#include "fs-util.h"
23
#include "glyph-util.h"
24
#include "id128-util.h"
25
#include "io-util.h"
26
#include "kernel-config.h"
27
#include "log.h"
28
#include "openssl-util.h"
29
#include "parse-argument.h"
30
#include "path-util.h"
31
#include "pe-binary.h"
32
#include "rm-rf.h"
33
#include "stat-util.h"
34
#include "string-util.h"
35
#include "strv.h"
36
#include "sync-util.h"
37
#include "time-util.h"
38
#include "tmpfile-util.h"
39
#include "umask-util.h"
40
#include "utf8.h"
41

42
static int load_etc_machine_id(void) {
150✔
43
        int r;
150✔
44

45
        r = sd_id128_get_machine(&arg_machine_id);
150✔
46
        if (ERRNO_IS_NEG_MACHINE_ID_UNSET(r)) /* Not set or empty */
150✔
47
                return 0;
48
        if (r < 0)
150✔
49
                return log_error_errno(r, "Failed to get machine-id: %m");
×
50

51
        log_debug("Loaded machine ID %s from /etc/machine-id.", SD_ID128_TO_STRING(arg_machine_id));
150✔
52
        return 0;
150✔
53
}
54

55
static int load_etc_machine_info(void) {
150✔
56
        /* systemd v250 added support to store the kernel-install layout setting and the machine ID to use
57
         * for setting up the ESP in /etc/machine-info. The newer /etc/kernel/entry-token file, as well as
58
         * the $layout field in /etc/kernel/install.conf are better replacements for this though, hence this
59
         * has been deprecated and is only returned for compatibility. */
60
        _cleanup_free_ char *p = NULL, *s = NULL, *layout = NULL;
150✔
61
        int r;
150✔
62

63
        p = path_join(arg_root, "/etc/machine-info");
150✔
64
        if (!p)
150✔
65
                return log_oom();
×
66

67
        r = parse_env_file(NULL, p,
150✔
68
                           "KERNEL_INSTALL_LAYOUT", &layout,
69
                           "KERNEL_INSTALL_MACHINE_ID", &s);
70
        if (r == -ENOENT)
150✔
71
                return 0;
72
        if (r < 0)
×
73
                return log_error_errno(r, "Failed to parse /etc/machine-info: %m");
×
74

75
        if (!isempty(s)) {
×
76
                if (!arg_quiet)
×
77
                        log_notice("Read $KERNEL_INSTALL_MACHINE_ID from /etc/machine-info. "
×
78
                                   "Please move it to /etc/kernel/entry-token.");
79

80
                r = sd_id128_from_string(s, &arg_machine_id);
×
81
                if (r < 0)
×
82
                        return log_error_errno(r, "Failed to parse KERNEL_INSTALL_MACHINE_ID=%s in /etc/machine-info: %m", s);
×
83

84
                log_debug("Loaded KERNEL_INSTALL_MACHINE_ID=%s from /etc/machine-info.",
×
85
                          SD_ID128_TO_STRING(arg_machine_id));
86
        }
87

88
        if (!isempty(layout)) {
150✔
89
                if (!arg_quiet)
×
90
                        log_notice("Read $KERNEL_INSTALL_LAYOUT from /etc/machine-info. "
×
91
                                   "Please move it to the layout= setting of /etc/kernel/install.conf.");
92

93
                log_debug("KERNEL_INSTALL_LAYOUT=%s is specified in /etc/machine-info.", layout);
×
94
                free_and_replace(arg_install_layout, layout);
×
95
        }
96

97
        return 0;
98
}
99

100
static int load_kernel_install_layout(void) {
150✔
101
        _cleanup_free_ char *layout = NULL;
150✔
102
        int r;
150✔
103

104
        r = load_kernel_install_conf(arg_root,
150✔
105
                                     secure_getenv("KERNEL_INSTALL_CONF_ROOT"),
150✔
106
                                     /* ret_machine_id= */ NULL,
107
                                     /* ret_boot_root= */ NULL,
108
                                     &layout,
109
                                     /* ret_initrd_generator= */ NULL,
110
                                     /* ret_uki_generator= */ NULL);
111
        if (r <= 0)
150✔
112
                return r;
113

114
        if (!isempty(layout)) {
150✔
115
                log_debug("layout=%s is specified in config.", layout);
×
116
                free_and_replace(arg_install_layout, layout);
×
117
        }
118

119
        return 0;
120
}
121

122
static bool use_boot_loader_spec_type1(void) {
150✔
123
        /* If the layout is not specified, or if it is set explicitly to "bls" we assume Boot Loader
124
         * Specification Type #1 is the chosen format for our boot loader entries */
125
        return !arg_install_layout || streq(arg_install_layout, "bls");
150✔
126
}
127

128
static int settle_make_entry_directory(void) {
150✔
129
        int r;
150✔
130

131
        r = load_etc_machine_id();
150✔
132
        if (r < 0)
150✔
133
                return r;
134

135
        r = load_etc_machine_info();
150✔
136
        if (r < 0)
150✔
137
                return r;
138

139
        r = load_kernel_install_layout();
150✔
140
        if (r < 0)
150✔
141
                return r;
142

143
        r = settle_entry_token();
150✔
144
        if (r < 0)
150✔
145
                return r;
146

147
        bool layout_type1 = use_boot_loader_spec_type1();
150✔
148
        if (arg_make_entry_directory < 0) { /* Automatic mode */
150✔
149
                if (layout_type1) {
×
150
                        if (arg_entry_token_type == BOOT_ENTRY_TOKEN_MACHINE_ID) {
×
151
                                r = path_is_temporary_fs("/etc/machine-id");
×
152
                                if (r < 0)
×
153
                                        return log_debug_errno(r, "Couldn't determine whether /etc/machine-id is on a temporary file system: %m");
×
154

155
                                arg_make_entry_directory = r == 0;
×
156
                        } else
157
                                arg_make_entry_directory = true;
×
158
                } else
159
                        arg_make_entry_directory = false;
×
160
        }
161

162
        if (arg_make_entry_directory > 0 && !layout_type1)
150✔
163
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
164
                                       "KERNEL_INSTALL_LAYOUT=%s is configured, but Boot Loader Specification Type #1 entry directory creation was requested.",
165
                                       arg_install_layout);
166

167
        return 0;
168
}
169

170
static int compare_product(const char *a, const char *b) {
248✔
171
        size_t x, y;
248✔
172

173
        assert(a);
248✔
174
        assert(b);
248✔
175

176
        x = strcspn(a, " ");
248✔
177
        y = strcspn(b, " ");
248✔
178
        if (x != y)
248✔
179
                return x < y ? -1 : x > y ? 1 : 0;
×
180

181
        return strncmp(a, b, x);
248✔
182
}
183

184
static int compare_version(const char *a, const char *b) {
248✔
185
        assert(a);
248✔
186
        assert(b);
248✔
187

188
        a += strcspn(a, " ");
248✔
189
        a += strspn(a, " ");
248✔
190
        b += strcspn(b, " ");
248✔
191
        b += strspn(b, " ");
248✔
192

193
        return strverscmp_improved(a, b);
248✔
194
}
195

196
static int version_check(int fd_from, const char *from, int fd_to, const char *to) {
248✔
197
        _cleanup_free_ char *a = NULL, *b = NULL;
248✔
198
        int r;
248✔
199

200
        assert(fd_from >= 0);
248✔
201
        assert(from);
248✔
202
        assert(fd_to >= 0);
248✔
203
        assert(to);
248✔
204

205
        r = get_file_version(fd_from, &a);
248✔
206
        if (r == -ESRCH)
248✔
207
                return log_notice_errno(r, "Source file \"%s\" does not carry version information!", from);
×
208
        if (r < 0)
248✔
209
                return r;
210

211
        r = get_file_version(fd_to, &b);
248✔
212
        if (r == -ESRCH)
248✔
213
                return log_info_errno(r, "Skipping \"%s\", it's owned by another boot loader (no version info found).", to);
×
214
        if (r < 0)
248✔
215
                return r;
216
        if (compare_product(a, b) != 0)
248✔
217
                return log_info_errno(SYNTHETIC_ERRNO(ESRCH),
×
218
                                      "Skipping \"%s\", it's owned by another boot loader.", to);
219

220
        r = compare_version(a, b);
248✔
221
        log_debug("Comparing versions: \"%s\" %s \"%s\"", a, comparison_operator(r), b);
484✔
222
        if (r < 0)
248✔
223
                return log_warning_errno(SYNTHETIC_ERRNO(ESTALE),
×
224
                                         "Skipping \"%s\", newer boot loader version in place already.", to);
225
        if (r == 0)
248✔
226
                return log_info_errno(SYNTHETIC_ERRNO(ESTALE),
248✔
227
                                      "Skipping \"%s\", same boot loader version in place already.", to);
228

229
        return 0;
230
}
231

232
static int copy_file_with_version_check(const char *from, const char *to, bool force) {
286✔
233
        _cleanup_close_ int fd_from = -EBADF, fd_to = -EBADF;
286✔
234
        _cleanup_free_ char *t = NULL;
286✔
235
        int r;
286✔
236

237
        fd_from = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
286✔
238
        if (fd_from < 0)
286✔
239
                return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", from);
×
240

241
        if (!force) {
286✔
242
                fd_to = open(to, O_RDONLY|O_CLOEXEC|O_NOCTTY);
248✔
243
                if (fd_to < 0) {
248✔
244
                        if (errno != ENOENT)
×
245
                                return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", to);
×
246
                } else {
247
                        r = version_check(fd_from, from, fd_to, to);
248✔
248
                        if (r < 0)
248✔
249
                                return r;
250

251
                        if (lseek(fd_from, 0, SEEK_SET) < 0)
×
252
                                return log_error_errno(errno, "Failed to seek in \"%s\": %m", from);
×
253

254
                        fd_to = safe_close(fd_to);
×
255
                }
256
        }
257

258
        r = tempfn_random(to, NULL, &t);
38✔
259
        if (r < 0)
38✔
260
                return log_oom();
×
261

262
        WITH_UMASK(0000) {
76✔
263
                fd_to = open(t, O_WRONLY|O_CREAT|O_CLOEXEC|O_EXCL|O_NOFOLLOW, 0644);
38✔
264
                if (fd_to < 0)
38✔
265
                        return log_error_errno(errno, "Failed to open \"%s\" for writing: %m", t);
×
266
        }
267

268
        r = copy_bytes(fd_from, fd_to, UINT64_MAX, COPY_REFLINK);
38✔
269
        if (r < 0) {
38✔
270
                (void) unlink(t);
×
271
                return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
×
272
        }
273

274
        (void) copy_times(fd_from, fd_to, 0);
38✔
275

276
        r = fsync_full(fd_to);
38✔
277
        if (r < 0) {
38✔
278
                (void) unlink(t);
×
279
                return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
×
280
        }
281

282
        r = RET_NERRNO(renameat(AT_FDCWD, t, AT_FDCWD, to));
38✔
283
        if (r < 0) {
×
284
                (void) unlink(t);
×
285
                return log_error_errno(r, "Failed to rename \"%s\" to \"%s\": %m", t, to);
×
286
        }
287

288
        log_info("Copied \"%s\" to \"%s\".", from, to);
38✔
289

290
        return 0;
291
}
292

293
static int mkdir_one(const char *prefix, const char *suffix) {
125✔
294
        _cleanup_free_ char *p = NULL;
125✔
295

296
        p = path_join(prefix, suffix);
125✔
297
        if (mkdir(p, 0700) < 0) {
125✔
298
                if (errno != EEXIST)
44✔
299
                        return log_error_errno(errno, "Failed to create \"%s\": %m", p);
×
300
        } else
301
                log_info("Created \"%s\".", p);
81✔
302

303
        return 0;
304
}
305

306
static const char *const esp_subdirs[] = {
307
        /* The directories to place in the ESP */
308
        "EFI",
309
        "EFI/systemd",
310
        "EFI/BOOT",
311
        "loader",
312
        "loader/keys",
313
        NULL
314
};
315

316
static const char *const dollar_boot_subdirs[] = {
317
        /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
318
        "loader",
319
        "loader/entries",  /* Type #1 entries */
320
        "EFI",
321
        "EFI/Linux",       /* Type #2 entries */
322
        NULL
323
};
324

325
static int create_subdirs(const char *root, const char * const *subdirs) {
26✔
326
        int r;
26✔
327

328
        STRV_FOREACH(i, subdirs) {
143✔
329
                r = mkdir_one(root, *i);
117✔
330
                if (r < 0)
117✔
331
                        return r;
332
        }
333

334
        return 0;
335
}
336

337
static int update_efi_boot_binaries(
124✔
338
                const char *esp_path,
339
                const char *source_path,
340
                const char *ignore_filename) {
341

342
        _cleanup_closedir_ DIR *d = NULL;
124✔
343
        _cleanup_free_ char *p = NULL;
124✔
344
        int r, ret = 0;
124✔
345

346
        assert(esp_path);
124✔
347
        assert(source_path);
124✔
348

349
        r = chase_and_opendir("/EFI/BOOT", esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, &p, &d);
124✔
350
        if (r == -ENOENT)
124✔
351
                return 0;
352
        if (r < 0)
124✔
353
                return log_error_errno(r, "Failed to open directory \"%s/EFI/BOOT\": %m", esp_path);
×
354

355
        FOREACH_DIRENT(de, d, break) {
620✔
356
                _cleanup_close_ int fd = -EBADF;
620✔
357

358
                if (!endswith_no_case(de->d_name, ".efi"))
248✔
359
                        continue;
×
360

361
                if (strcaseeq_ptr(ignore_filename, de->d_name))
248✔
362
                        continue;
124✔
363

364
                fd = xopenat_full(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW, XO_REGULAR, /* mode= */ 0);
124✔
365
                if (fd < 0)
124✔
366
                        return log_error_errno(fd, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
×
367

368
                r = pe_is_native_fd(fd);
124✔
369
                if (r < 0) {
124✔
370
                        log_warning_errno(r, "Failed to detect if \"%s/%s\" is native architecture, ignoring: %m", p, de->d_name);
×
371
                        continue;
×
372
                }
373
                if (r == 0)
124✔
374
                        continue;
124✔
375

376
                _cleanup_free_ char *dest_path = path_join(p, de->d_name);
×
377
                if (!dest_path)
×
378
                        return log_oom();
×
379

380
                r = copy_file_with_version_check(source_path, dest_path, /* force= */ false);
×
381
                if (IN_SET(r, -ESTALE, -ESRCH))
×
382
                        continue;
×
383
                RET_GATHER(ret, r);
×
384
        }
385

386
        return ret;
387
}
388

389
static int copy_one_file(const char *esp_path, const char *name, bool force) {
143✔
390
        char *root = IN_SET(arg_install_source, INSTALL_SOURCE_AUTO, INSTALL_SOURCE_IMAGE) ? arg_root : NULL;
143✔
391
        _cleanup_free_ char *source_path = NULL, *dest_path = NULL, *p = NULL, *q = NULL;
143✔
392
        const char *e;
143✔
393
        char *dest_name, *s;
143✔
394
        int r, ret;
143✔
395

396
        dest_name = strdupa_safe(name);
143✔
397
        s = endswith_no_case(dest_name, ".signed");
143✔
398
        if (s)
143✔
399
                *s = 0;
143✔
400

401
        p = path_join(BOOTLIBDIR, name);
143✔
402
        if (!p)
143✔
403
                return log_oom();
×
404

405
        r = chase(p, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, &source_path, NULL);
143✔
406
        /* If we had a root directory to try, we didn't find it and we are in auto mode, retry on the host */
407
        if (r == -ENOENT && root && arg_install_source == INSTALL_SOURCE_AUTO)
143✔
408
                r = chase(p, NULL, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, &source_path, NULL);
16✔
409
        if (r < 0)
143✔
410
                return log_error_errno(r,
×
411
                                       "Failed to resolve path %s%s%s: %m",
412
                                       p,
413
                                       root ? " under directory " : "",
414
                                       strempty(root));
415

416
        q = path_join("/EFI/systemd/", dest_name);
143✔
417
        if (!q)
143✔
418
                return log_oom();
×
419

420
        r = chase(q, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_NONEXISTENT|CHASE_TRIGGER_AUTOFS, &dest_path, NULL);
143✔
421
        if (r < 0)
143✔
422
                return log_error_errno(r, "Failed to resolve path %s under directory %s: %m", q, esp_path);
×
423

424
        /* Note that if this fails we do the second copy anyway, but return this error code,
425
         * so we stash it away in a separate variable. */
426
        ret = copy_file_with_version_check(source_path, dest_path, force);
143✔
427

428
        e = startswith(dest_name, "systemd-boot");
143✔
429
        if (e) {
143✔
430
                _cleanup_free_ char *default_dest_path = NULL;
143✔
431
                char *v;
143✔
432

433
                /* Create the EFI default boot loader name (specified for removable devices) */
434
                v = strjoina("/EFI/BOOT/BOOT", e);
715✔
435
                const char *boot_dot_efi = ascii_strupper(strrchr(v, '/') + 1);
143✔
436

437
                r = chase(v, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_NONEXISTENT|CHASE_TRIGGER_AUTOFS, &default_dest_path, NULL);
143✔
438
                if (r < 0)
143✔
439
                        return log_error_errno(r, "Failed to resolve path %s under directory %s: %m", v, esp_path);
×
440

441
                RET_GATHER(ret, copy_file_with_version_check(source_path, default_dest_path, force));
143✔
442

443
                /* If we were installed under any other name in /EFI/BOOT/, make sure we update those binaries
444
                 * as well. */
445
                if (!force)
143✔
446
                        RET_GATHER(ret, update_efi_boot_binaries(esp_path, source_path, boot_dot_efi));
124✔
447
        }
448

449
        return ret;
450
}
451

452
static int install_binaries(const char *esp_path, const char *arch, bool force) {
137✔
453
        char *root = IN_SET(arg_install_source, INSTALL_SOURCE_AUTO, INSTALL_SOURCE_IMAGE) ? arg_root : NULL;
137✔
454
        _cleanup_closedir_ DIR *d = NULL;
137✔
455
        _cleanup_free_ char *path = NULL;
137✔
456
        int r;
137✔
457

458
        r = chase_and_opendir(BOOTLIBDIR, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, &path, &d);
137✔
459
        /* If we had a root directory to try, we didn't find it and we are in auto mode, retry on the host */
460
        if (r == -ENOENT && root && arg_install_source == INSTALL_SOURCE_AUTO)
137✔
461
                r = chase_and_opendir(BOOTLIBDIR, NULL, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, &path, &d);
12✔
462
        if (r == -ENOENT && arg_graceful() != ARG_GRACEFUL_NO) {
137✔
463
                log_debug("Source directory does not exist, ignoring.");
×
464
                return 0;
×
465
        }
466
        if (r < 0)
137✔
467
                return log_error_errno(r, "Failed to open boot loader directory %s%s: %m", strempty(root), BOOTLIBDIR);
×
468

469
        const char *suffix = strjoina(arch, ".efi");
685✔
470
        const char *suffix_signed = strjoina(arch, ".efi.signed");
685✔
471

472
        FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read \"%s\": %m", path)) {
1,507✔
473
                int k;
1,096✔
474

475
                if (!endswith_no_case(de->d_name, suffix) && !endswith_no_case(de->d_name, suffix_signed))
1,096✔
476
                        continue;
810✔
477

478
                /* skip the .efi file, if there's a .signed version of it */
479
                if (endswith_no_case(de->d_name, ".efi")) {
286✔
480
                        _cleanup_free_ const char *s = strjoin(de->d_name, ".signed");
286✔
481
                        if (!s)
143✔
482
                                return log_oom();
×
483
                        if (faccessat(dirfd(d), s, F_OK, 0) >= 0)
143✔
484
                                continue;
143✔
485
                }
486

487
                k = copy_one_file(esp_path, de->d_name, force);
143✔
488
                /* Don't propagate an error code if no update necessary, installed version already equal or
489
                 * newer version, or other boot loader in place. */
490
                if (arg_graceful() != ARG_GRACEFUL_NO && IN_SET(k, -ESTALE, -ESRCH))
143✔
491
                        continue;
121✔
492
                RET_GATHER(r, k);
22✔
493
        }
494

495
        return r;
496
}
497

498
static int install_loader_config(const char *esp_path) {
13✔
499
        _cleanup_(unlink_and_freep) char *t = NULL;
×
500
        _cleanup_fclose_ FILE *f = NULL;
13✔
501
        _cleanup_free_ char *p = NULL;
13✔
502
        int r;
13✔
503

504
        assert(arg_make_entry_directory >= 0);
13✔
505

506
        p = path_join(esp_path, "/loader/loader.conf");
13✔
507
        if (!p)
13✔
508
                return log_oom();
×
509
        if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
13✔
510
                return 0;
511

512
        r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
11✔
513
        if (r < 0)
11✔
514
                return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
×
515

516
        fprintf(f, "#timeout 3\n"
11✔
517
                   "#console-mode keep\n");
518

519
        if (arg_make_entry_directory) {
11✔
520
                assert(arg_entry_token);
5✔
521
                fprintf(f, "default %s-*\n", arg_entry_token);
5✔
522
        }
523

524
        r = flink_tmpfile(f, t, p, LINK_TMPFILE_SYNC);
11✔
525
        if (r == -EEXIST)
11✔
526
                return 0; /* Silently skip creation if the file exists now (recheck) */
527
        if (r < 0)
11✔
528
                return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
×
529

530
        t = mfree(t);
11✔
531
        return 1;
11✔
532
}
533

534
static int install_loader_specification(const char *root) {
134✔
535
        _cleanup_(unlink_and_freep) char *t = NULL;
×
536
        _cleanup_fclose_ FILE *f = NULL;
134✔
537
        _cleanup_free_ char *p = NULL;
134✔
538
        int r;
134✔
539

540
        p = path_join(root, "/loader/entries.srel");
134✔
541
        if (!p)
134✔
542
                return log_oom();
×
543

544
        if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
134✔
545
                return 0;
546

547
        r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
11✔
548
        if (r < 0)
11✔
549
                return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
×
550

551
        fprintf(f, "type1\n");
11✔
552

553
        r = flink_tmpfile(f, t, p, LINK_TMPFILE_SYNC);
11✔
554
        if (r == -EEXIST)
11✔
555
                return 0; /* Silently skip creation if the file exists now (recheck) */
556
        if (r < 0)
11✔
557
                return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
×
558

559
        t = mfree(t);
11✔
560
        return 1;
11✔
561
}
562

563
static int install_entry_directory(const char *root) {
13✔
564
        assert(root);
13✔
565
        assert(arg_make_entry_directory >= 0);
13✔
566

567
        if (!arg_make_entry_directory)
13✔
568
                return 0;
569

570
        assert(arg_entry_token);
7✔
571
        return mkdir_one(root, arg_entry_token);
7✔
572
}
573

574
static int install_entry_token(void) {
13✔
575
        _cleanup_free_ char* p = NULL;
13✔
576
        int r;
13✔
577

578
        assert(arg_make_entry_directory >= 0);
13✔
579
        assert(arg_entry_token);
13✔
580

581
        /* Let's save the used entry token in /etc/kernel/entry-token if we used it to create the entry
582
         * directory, or if anything else but the machine ID */
583

584
        if (!arg_make_entry_directory && arg_entry_token_type == BOOT_ENTRY_TOKEN_MACHINE_ID)
13✔
585
                return 0;
586

587
        p = path_join(arg_root, secure_getenv("KERNEL_INSTALL_CONF_ROOT") ?: "/etc/kernel/", "entry-token");
26✔
588
        if (!p)
13✔
589
                return log_oom();
×
590

591
        r = write_string_file(p, arg_entry_token, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755);
13✔
592
        if (r < 0)
13✔
593
                return log_error_errno(r, "Failed to write entry token '%s' to %s: %m", arg_entry_token, p);
×
594

595
        return 0;
596
}
597

598
#if HAVE_OPENSSL
599
static int efi_timestamp(EFI_TIME *ret) {
1✔
600
        uint64_t epoch = UINT64_MAX;
1✔
601
        struct tm tm = {};
1✔
602
        int r;
1✔
603

604
        assert(ret);
1✔
605

606
        r = secure_getenv_uint64("SOURCE_DATE_EPOCH", &epoch);
1✔
607
        if (r != -ENXIO)
1✔
608
                log_debug_errno(r, "Failed to parse $SOURCE_DATE_EPOCH, ignoring: %m");
×
609

610
        r = localtime_or_gmtime_usec(epoch != UINT64_MAX ? epoch : now(CLOCK_REALTIME), /* utc= */ true, &tm);
1✔
611
        if (r < 0)
1✔
612
                return log_error_errno(r, "Failed to convert timestamp to calendar time: %m");
×
613

614
        *ret = (EFI_TIME) {
1✔
615
                .Year = 1900 + tm.tm_year,
1✔
616
                /* tm_mon starts at 0, EFI_TIME months start at 1. */
617
                .Month = tm.tm_mon + 1,
1✔
618
                .Day = tm.tm_mday,
1✔
619
                .Hour = tm.tm_hour,
1✔
620
                .Minute = tm.tm_min,
1✔
621
                .Second = tm.tm_sec,
1✔
622
        };
623

624
        return 0;
1✔
625
}
626

627
static int install_secure_boot_auto_enroll(const char *esp, X509 *certificate, EVP_PKEY *private_key) {
13✔
628
        int r;
13✔
629

630
        if (!arg_secure_boot_auto_enroll)
13✔
631
                return 0;
13✔
632

633
        _cleanup_free_ uint8_t *dercert = NULL;
1✔
634
        int dercertsz;
1✔
635
        dercertsz = i2d_X509(certificate, &dercert);
1✔
636
        if (dercertsz < 0)
1✔
637
                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert X.509 certificate to DER: %s",
×
638
                                       ERR_error_string(ERR_get_error(), NULL));
639

640
        r = mkdir_one(esp, "loader/keys/auto");
1✔
641
        if (r < 0)
1✔
642
                return r;
643

644
        _cleanup_close_ int keys_fd = chase_and_open("loader/keys/auto", esp, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, O_DIRECTORY, NULL);
2✔
645
        if (keys_fd < 0)
1✔
646
                return log_error_errno(keys_fd, "Failed to chase loader/keys/auto in the ESP: %m");
×
647

648
        uint32_t siglistsz = offsetof(EFI_SIGNATURE_LIST, Signatures) + offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz;
1✔
649
        /* We use malloc0() to zero-initialize the SignatureOwner field of Signatures[0]. */
650
        _cleanup_free_ EFI_SIGNATURE_LIST *siglist = malloc0(siglistsz);
2✔
651
        if (!siglist)
1✔
652
                return log_oom();
×
653

654
        *siglist = (EFI_SIGNATURE_LIST) {
1✔
655
                .SignatureType = EFI_CERT_X509_GUID,
656
                .SignatureListSize = siglistsz,
657
                .SignatureSize = offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz,
1✔
658
        };
659

660
        memcpy(siglist->Signatures[0].SignatureData, dercert, dercertsz);
1✔
661

662
        EFI_TIME timestamp;
1✔
663
        r = efi_timestamp(&timestamp);
1✔
664
        if (r < 0)
1✔
665
                return r;
666

667
        uint32_t attrs =
1✔
668
                EFI_VARIABLE_NON_VOLATILE|
669
                EFI_VARIABLE_BOOTSERVICE_ACCESS|
670
                EFI_VARIABLE_RUNTIME_ACCESS|
671
                EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
672

673
        FOREACH_STRING(db, "PK", "KEK", "db") {
4✔
674
                _cleanup_(BIO_freep) BIO *bio = NULL;
3✔
675

676
                bio = BIO_new(BIO_s_mem());
3✔
677
                if (!bio)
3✔
678
                        return log_oom();
×
679

680
                _cleanup_free_ char16_t *db16 = utf8_to_utf16(db, SIZE_MAX);
6✔
681
                if (!db16)
3✔
682
                        return log_oom();
×
683

684
                /* Don't count the trailing NUL terminator. */
685
                if (BIO_write(bio, db16, char16_strsize(db16) - sizeof(char16_t)) < 0)
3✔
686
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write variable name to bio");
×
687

688
                EFI_GUID *guid = STR_IN_SET(db, "PK", "KEK") ? &(EFI_GUID) EFI_GLOBAL_VARIABLE : &(EFI_GUID) EFI_IMAGE_SECURITY_DATABASE_GUID;
3✔
689

690
                if (BIO_write(bio, guid, sizeof(*guid)) < 0)
3✔
691
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write variable GUID to bio");
×
692

693
                if (BIO_write(bio, &attrs, sizeof(attrs)) < 0)
3✔
694
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write variable attributes to bio");
×
695

696
                if (BIO_write(bio, &timestamp, sizeof(timestamp)) < 0)
3✔
697
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write timestamp to bio");
×
698

699
                if (BIO_write(bio, siglist, siglistsz) < 0)
3✔
700
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write signature list to bio");
×
701

702
                _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
3✔
703
                p7 = PKCS7_sign(certificate, private_key, /* certs= */ NULL, bio, PKCS7_DETACHED|PKCS7_NOATTR|PKCS7_BINARY|PKCS7_NOSMIMECAP);
3✔
704
                if (!p7)
3✔
705
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to calculate PKCS7 signature: %s",
×
706
                                               ERR_error_string(ERR_get_error(), NULL));
707

708
                _cleanup_free_ uint8_t *sig = NULL;
×
709
                int sigsz = i2d_PKCS7(p7, &sig);
3✔
710
                if (sigsz < 0)
3✔
711
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert PKCS7 signature to DER: %s",
×
712
                                               ERR_error_string(ERR_get_error(), NULL));
713

714
                size_t authsz = offsetof(EFI_VARIABLE_AUTHENTICATION_2, AuthInfo.CertData) + sigsz;
3✔
715
                _cleanup_free_ EFI_VARIABLE_AUTHENTICATION_2 *auth = malloc(authsz);
×
716
                if (!auth)
3✔
717
                        return log_oom();
×
718

719
                *auth = (EFI_VARIABLE_AUTHENTICATION_2) {
3✔
720
                        .TimeStamp = timestamp,
721
                        .AuthInfo = {
722
                                .Hdr = {
723
                                        .dwLength = offsetof(WIN_CERTIFICATE_UEFI_GUID, CertData) + sigsz,
3✔
724
                                        .wRevision = 0x0200,
725
                                        .wCertificateType = 0x0EF1, /* WIN_CERT_TYPE_EFI_GUID */
726
                                },
727
                                .CertType = EFI_CERT_TYPE_PKCS7_GUID,
728
                        }
729
                };
730

731
                memcpy(auth->AuthInfo.CertData, sig, sigsz);
3✔
732

733
                _cleanup_free_ char *filename = strjoin(db, ".auth");
6✔
734
                if (!filename)
3✔
735
                        return log_oom();
×
736

737
                _cleanup_close_ int fd = openat(keys_fd, filename, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|O_WRONLY|O_CLOEXEC, 0600);
6✔
738
                if (fd < 0)
3✔
739
                        return log_error_errno(fd, "Failed to open secure boot auto-enrollment file for writing: %m");
×
740

741
                r = loop_write(fd, auth, authsz);
3✔
742
                if (r < 0)
3✔
743
                        return log_error_errno(r, "Failed to write authentication descriptor to secure boot auto-enrollment file: %m");
×
744

745
                r = loop_write(fd, siglist, siglistsz);
3✔
746
                if (r < 0)
3✔
747
                        return log_error_errno(r, "Failed to write signature list to secure boot auto-enrollment file: %m");
×
748

749
                if (fsync(fd) < 0 || fsync(keys_fd) < 0)
3✔
750
                        return log_error_errno(errno, "Failed to sync secure boot auto-enrollment file: %m");
×
751

752
                log_info("Secure boot auto-enrollment file %s/loader/keys/auto/%s successfully written.", esp, filename);
3✔
753
        }
754

755
        return 0;
1✔
756
}
757
#endif
758

759
static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
25✔
760
        _cleanup_free_ char *opath = NULL;
25✔
761
        sd_id128_t ouuid;
25✔
762
        int r;
25✔
763

764
        r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
25✔
765
        if (r < 0)
25✔
766
                return false;
767
        if (!sd_id128_equal(uuid, ouuid))
25✔
768
                return false;
21✔
769

770
        /* Some motherboards convert the path to uppercase under certain circumstances
771
         * (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
772
         * so use case-insensitive checking */
773
        if (!strcaseeq_ptr(path, opath))
4✔
774
                return false;
×
775

776
        return true;
777
}
778

779
static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
7✔
780
        _cleanup_free_ uint16_t *options = NULL;
7✔
781

782
        int n = efi_get_boot_options(&options);
7✔
783
        if (n < 0)
7✔
784
                return n;
785

786
        /* find already existing systemd-boot entry */
787
        for (int i = 0; i < n; i++)
28✔
788
                if (same_entry(options[i], uuid, path)) {
25✔
789
                        *id = options[i];
4✔
790
                        return 1;
4✔
791
                }
792

793
        /* find free slot in the sorted BootXXXX variable list */
794
        for (int i = 0; i < n; i++)
12✔
795
                if (i != options[i]) {
9✔
796
                        *id = i;
×
797
                        return 0;
×
798
                }
799

800
        /* use the next one */
801
        if (n == 0xffff)
3✔
802
                return -ENOSPC;
803
        *id = n;
3✔
804
        return 0;
3✔
805
}
806

807
static int insert_into_order(uint16_t slot, bool first) {
4✔
808
        _cleanup_free_ uint16_t *order = NULL;
4✔
809
        uint16_t *t;
4✔
810
        int n;
4✔
811

812
        n = efi_get_boot_order(&order);
4✔
813
        if (n <= 0)
4✔
814
                /* no entry, add us */
815
                return efi_set_boot_order(&slot, 1);
×
816

817
        /* are we the first and only one? */
818
        if (n == 1 && order[0] == slot)
4✔
819
                return 0;
820

821
        /* are we already in the boot order? */
822
        for (int i = 0; i < n; i++) {
13✔
823
                if (order[i] != slot)
10✔
824
                        continue;
9✔
825

826
                /* we do not require to be the first one, all is fine */
827
                if (!first)
1✔
828
                        return 0;
829

830
                /* move us to the first slot */
831
                memmove(order + 1, order, i * sizeof(uint16_t));
×
832
                order[0] = slot;
×
833
                return efi_set_boot_order(order, n);
×
834
        }
835

836
        /* extend array */
837
        t = reallocarray(order, n + 1, sizeof(uint16_t));
3✔
838
        if (!t)
3✔
839
                return -ENOMEM;
840
        order = t;
3✔
841

842
        /* add us to the top or end of the list */
843
        if (first) {
3✔
844
                memmove(order + 1, order, n * sizeof(uint16_t));
3✔
845
                order[0] = slot;
3✔
846
        } else
847
                order[n] = slot;
×
848

849
        return efi_set_boot_order(order, n + 1);
3✔
850
}
851

852
static int remove_from_order(uint16_t slot) {
3✔
853
        _cleanup_free_ uint16_t *order = NULL;
3✔
854
        int n;
3✔
855

856
        n = efi_get_boot_order(&order);
3✔
857
        if (n <= 0)
3✔
858
                return n;
859

860
        for (int i = 0; i < n; i++) {
3✔
861
                if (order[i] != slot)
3✔
862
                        continue;
×
863

864
                if (i + 1 < n)
3✔
865
                        memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
3✔
866
                return efi_set_boot_order(order, n - 1);
3✔
867
        }
868

869
        return 0;
870
}
871

872
static const char *pick_efi_boot_option_description(void) {
6✔
873
        return arg_efi_boot_option_description ?: "Linux Boot Manager";
6✔
874
}
875

876
static int install_variables(
4✔
877
                const char *esp_path,
878
                uint32_t part,
879
                uint64_t pstart,
880
                uint64_t psize,
881
                sd_id128_t uuid,
882
                const char *path,
883
                bool first,
884
                bool graceful) {
885

886
        uint16_t slot;
4✔
887
        int r;
4✔
888

889
        r = chase_and_access(path, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, F_OK, NULL);
4✔
890
        if (r == -ENOENT)
4✔
891
                return 0;
4✔
892
        if (r < 0)
4✔
893
                return log_error_errno(r, "Cannot access \"%s/%s\": %m", esp_path, skip_leading_slash(path));
×
894

895
        r = find_slot(uuid, path, &slot);
4✔
896
        if (r < 0) {
4✔
897
                int level = graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
×
898
                const char *skip = graceful ? ", skipping" : "";
899

900
                log_full_errno(level, r,
×
901
                               r == -ENOENT ?
902
                               "Failed to access EFI variables%s. Is the \"efivarfs\" filesystem mounted?" :
903
                               "Failed to determine current boot order%s: %m", skip);
904

905
                return graceful ? 0 : r;
×
906
        }
907

908
        bool existing = r > 0;
4✔
909

910
        if (first || !existing) {
4✔
911
                r = efi_add_boot_option(
3✔
912
                                slot,
913
                                pick_efi_boot_option_description(),
914
                                part,
915
                                pstart,
916
                                psize,
917
                                uuid,
918
                                path);
919
                if (r < 0) {
3✔
920
                        int level = graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
×
921
                        const char *skip = graceful ? ", skipping" : "";
922

923
                        log_full_errno(level, r, "Failed to create EFI Boot variable entry%s: %m", skip);
×
924

925
                        return graceful ? 0 : r;
×
926
                }
927

928
                log_info("%s EFI boot entry \"%s\".",
6✔
929
                         existing ? "Updated" : "Created",
930
                         pick_efi_boot_option_description());
931
        }
932

933
        return insert_into_order(slot, first);
4✔
934
}
935

936
static int are_we_installed(const char *esp_path) {
136✔
937
        int r;
136✔
938

939
        /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
940
         * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
941
         * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
942
         * should be a suitable and very minimal check for a number of reasons:
943
         *
944
         *  → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
945
         *    not a specific one.)
946
         *
947
         *  → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
948
         *    /EFI/BOOT/BOOT*.EFI fallback binary.
949
         *
950
         *  → It specifically checks for systemd-boot, not for other boot loaders (which a check for
951
         *    /boot/loader/entries would do). */
952

953
        _cleanup_free_ char *p = path_join(esp_path, "/EFI/systemd/");
272✔
954
        if (!p)
136✔
955
                return log_oom();
×
956

957
        log_debug("Checking whether %s contains any files%s", p, glyph(GLYPH_ELLIPSIS));
254✔
958
        r = dir_is_empty(p, /* ignore_hidden_or_backup= */ false);
136✔
959
        if (r < 0 && r != -ENOENT)
136✔
960
                return log_error_errno(r, "Failed to check whether %s contains any files: %m", p);
×
961

962
        return r == 0;
136✔
963
}
964

965
#if HAVE_OPENSSL
966
static int load_secure_boot_auto_enroll(
137✔
967
                X509 **ret_certificate,
968
                EVP_PKEY **ret_private_key,
969
                OpenSSLAskPasswordUI **ret_ui) {
970

971
        int r;
137✔
972

973
        assert(ret_certificate);
137✔
974
        assert(ret_private_key);
137✔
975
        assert(ret_ui);
137✔
976

977
        if (!arg_secure_boot_auto_enroll) {
137✔
978
                *ret_certificate = NULL;
136✔
979
                *ret_private_key = NULL;
136✔
980
                return 0;
136✔
981
        }
982

983
        if (arg_certificate_source_type == OPENSSL_CERTIFICATE_SOURCE_FILE) {
1✔
984
                r = parse_path_argument(arg_certificate, /* suppress_root= */ false, &arg_certificate);
1✔
985
                if (r < 0)
1✔
986
                        return r;
987
        }
988

989
        _cleanup_(X509_freep) X509 *certificate = NULL;
137✔
990
        r = openssl_load_x509_certificate(
1✔
991
                        arg_certificate_source_type,
992
                        arg_certificate_source,
993
                        arg_certificate,
994
                        &certificate);
995
        if (r < 0)
1✔
996
                return log_error_errno(r, "Failed to load X.509 certificate from %s: %m", arg_certificate);
×
997

998
        if (arg_private_key_source_type == OPENSSL_KEY_SOURCE_FILE) {
1✔
999
                r = parse_path_argument(arg_private_key, /* suppress_root= */ false, &arg_private_key);
1✔
1000
                if (r < 0)
1✔
1001
                        return log_error_errno(r, "Failed to parse private key path %s: %m", arg_private_key);
×
1002
        }
1003

1004
        r = openssl_load_private_key(
2✔
1005
                        arg_private_key_source_type,
1006
                        arg_private_key_source,
1007
                        arg_private_key,
1008
                        &(AskPasswordRequest) {
1✔
1009
                                .tty_fd = -EBADF,
1010
                                .id = "bootctl-private-key-pin",
1011
                                .keyring = arg_private_key,
1012
                                .credential = "bootctl.private-key-pin",
1013
                                .until = USEC_INFINITY,
1014
                                .hup_fd = -EBADF,
1015
                        },
1016
                        ret_private_key,
1017
                        ret_ui);
1018
        if (r < 0)
1✔
1019
                return log_error_errno(r, "Failed to load private key from %s: %m", arg_private_key);
×
1020

1021
        *ret_certificate = TAKE_PTR(certificate);
1✔
1022

1023
        return 0;
1✔
1024
}
1025
#endif
1026

1027
int verb_install(int argc, char *argv[], void *userdata) {
137✔
1028
        sd_id128_t uuid = SD_ID128_NULL;
137✔
1029
        uint64_t pstart = 0, psize = 0;
137✔
1030
        uint32_t part = 0;
137✔
1031
        bool install, graceful;
137✔
1032
        int r;
137✔
1033

1034
        /* Invoked for both "update" and "install" */
1035

1036
        install = streq(argv[0], "install");
137✔
1037

1038
        /* Support graceful mode only for updates, unless forcibly enabled in chroot environments */
1039
        graceful = arg_graceful() == ARG_GRACEFUL_FORCE || (!install && arg_graceful() != ARG_GRACEFUL_NO);
137✔
1040

1041
#if HAVE_OPENSSL
1042
        _cleanup_(openssl_ask_password_ui_freep) OpenSSLAskPasswordUI *ui = NULL;
137✔
1043
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *private_key = NULL;
137✔
1044
        _cleanup_(X509_freep) X509 *certificate = NULL;
137✔
1045
        r = load_secure_boot_auto_enroll(&certificate, &private_key, &ui);
137✔
1046
        if (r < 0)
137✔
1047
                return r;
1048
#endif
1049

1050
        r = acquire_esp(/* unprivileged_mode= */ false, graceful, &part, &pstart, &psize, &uuid, NULL);
137✔
1051
        if (graceful && r == -ENOKEY)
137✔
1052
                return 0; /* If --graceful is specified and we can't find an ESP, handle this cleanly */
1053
        if (r < 0)
137✔
1054
                return r;
1055

1056
        if (!install) {
137✔
1057
                /* If we are updating, don't do anything if sd-boot wasn't actually installed. */
1058
                r = are_we_installed(arg_esp_path);
124✔
1059
                if (r < 0)
124✔
1060
                        return r;
1061
                if (r == 0) {
124✔
1062
                        log_debug("Skipping update because sd-boot is not installed in the ESP.");
×
1063
                        return 0;
×
1064
                }
1065
        }
1066

1067
        r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
137✔
1068
        if (r < 0)
137✔
1069
                return r;
1070

1071
        r = settle_make_entry_directory();
137✔
1072
        if (r < 0)
137✔
1073
                return r;
1074

1075
        const char *arch = arg_arch_all ? "" : get_efi_arch();
137✔
1076

1077
        WITH_UMASK(0002) {
274✔
1078
                if (install) {
137✔
1079
                        /* Don't create any of these directories when we are just updating. When we update
1080
                         * we'll drop-in our files (unless there are newer ones already), but we won't create
1081
                         * the directories for them in the first place. */
1082
                        r = create_subdirs(arg_esp_path, esp_subdirs);
13✔
1083
                        if (r < 0)
13✔
1084
                                return r;
1085

1086
                        r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
18✔
1087
                        if (r < 0)
13✔
1088
                                return r;
1089
                }
1090

1091
                r = install_binaries(arg_esp_path, arch, install);
137✔
1092
                if (r < 0)
137✔
1093
                        return r;
1094

1095
                if (install) {
134✔
1096
                        r = install_loader_config(arg_esp_path);
13✔
1097
                        if (r < 0)
13✔
1098
                                return r;
1099

1100
                        r = install_entry_directory(arg_dollar_boot_path());
18✔
1101
                        if (r < 0)
13✔
1102
                                return r;
1103

1104
                        r = install_entry_token();
13✔
1105
                        if (r < 0)
13✔
1106
                                return r;
1107

1108
                        r = install_random_seed(arg_esp_path);
13✔
1109
                        if (r < 0)
13✔
1110
                                return r;
1111

1112
#if HAVE_OPENSSL
1113
                        r = install_secure_boot_auto_enroll(arg_esp_path, certificate, private_key);
13✔
1114
                        if (r < 0)
13✔
1115
                                return r;
1116
#endif
1117
                }
1118

1119
                r = install_loader_specification(arg_dollar_boot_path());
203✔
1120
                if (r < 0)
134✔
1121
                        return r;
1122
        }
1123

1124
        (void) sync_everything();
134✔
1125

1126
        if (!touch_variables())
134✔
1127
                return 0;
1128

1129
        if (arg_arch_all) {
6✔
1130
                log_info("Not changing EFI variables with --all-architectures.");
2✔
1131
                return 0;
2✔
1132
        }
1133

1134
        char *path = strjoina("/EFI/systemd/systemd-boot", arch, ".efi");
28✔
1135
        return install_variables(arg_esp_path, part, pstart, psize, uuid, path, install, graceful);
4✔
1136
}
1137

1138
static int remove_boot_efi(const char *esp_path) {
13✔
1139
        _cleanup_closedir_ DIR *d = NULL;
13✔
1140
        _cleanup_free_ char *p = NULL;
13✔
1141
        int r, c = 0;
13✔
1142

1143
        r = chase_and_opendir("/EFI/BOOT", esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, &p, &d);
13✔
1144
        if (r == -ENOENT)
13✔
1145
                return 0;
1146
        if (r < 0)
13✔
1147
                return log_error_errno(r, "Failed to open directory \"%s/EFI/BOOT\": %m", esp_path);
×
1148

1149
        FOREACH_DIRENT(de, d, break) {
63✔
1150
                _cleanup_close_ int fd = -EBADF;
24✔
1151
                _cleanup_free_ char *v = NULL;
24✔
1152

1153
                if (!endswith_no_case(de->d_name, ".efi"))
24✔
1154
                        continue;
×
1155

1156
                fd = xopenat_full(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW, XO_REGULAR, /* mode= */ 0);
24✔
1157
                if (fd < 0)
24✔
1158
                        return log_error_errno(fd, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
×
1159

1160
                r = pe_is_native_fd(fd);
24✔
1161
                if (r < 0) {
24✔
1162
                        log_warning_errno(r, "Failed to detect if \"%s/%s\" is native architecture, ignoring: %m", p, de->d_name);
×
1163
                        continue;
×
1164
                }
1165
                if (r == 0)
24✔
1166
                        continue;
11✔
1167

1168
                r = get_file_version(fd, &v);
13✔
1169
                if (r == -ESRCH)
13✔
1170
                        continue;  /* No version information */
×
1171
                if (r < 0)
13✔
1172
                        return r;
1173
                if (startswith(v, "systemd-boot ")) {
13✔
1174
                        if (unlinkat(dirfd(d), de->d_name, 0) < 0)
13✔
1175
                                return log_error_errno(errno, "Failed to remove \"%s/%s\": %m", p, de->d_name);
×
1176

1177
                        log_info("Removed \"%s/%s\".", p, de->d_name);
13✔
1178
                }
1179

1180
                c++;
13✔
1181
        }
1182

1183
        return c;
1184
}
1185

1186
static int rmdir_one(const char *prefix, const char *suffix) {
172✔
1187
        _cleanup_free_ char *p = path_join(prefix, suffix);
344✔
1188
        if (!p)
172✔
1189
                return log_oom();
×
1190

1191
        if (rmdir(p) < 0) {
172✔
1192
                bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
102✔
1193

1194
                log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
102✔
1195
                               "Failed to remove directory \"%s\": %m", p);
1196
                if (!ignore)
102✔
1197
                        return -errno;
×
1198
        } else
1199
                log_info("Removed \"%s\".", p);
70✔
1200

1201
        return 0;
1202
}
1203

1204
static int remove_subdirs(const char *root, const char *const *subdirs) {
183✔
1205
        int r;
183✔
1206

1207
        /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
1208
         * short the array is. */
1209

1210
        if (!subdirs[0]) /* A the end of the list */
183✔
1211
                return 0;
183✔
1212

1213
        r = remove_subdirs(root, subdirs + 1);
149✔
1214
        return RET_GATHER(r, rmdir_one(root, subdirs[0]));
149✔
1215
}
1216

1217
static int remove_entry_directory(const char *root) {
21✔
1218
        assert(root);
21✔
1219
        assert(arg_make_entry_directory >= 0);
21✔
1220

1221
        if (!arg_make_entry_directory || !arg_entry_token)
21✔
1222
                return 0;
1223

1224
        return rmdir_one(root, arg_entry_token);
10✔
1225
}
1226

1227
static int remove_binaries(const char *esp_path) {
13✔
1228
        int r;
13✔
1229

1230
        _cleanup_free_ char *p = path_join(esp_path, "/EFI/systemd");
26✔
1231
        if (!p)
13✔
1232
                return log_oom();
×
1233

1234
        r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
13✔
1235
        return RET_GATHER(r, remove_boot_efi(esp_path));
13✔
1236
}
1237

1238
static int remove_file(const char *root, const char *file) {
86✔
1239
        assert(root);
86✔
1240
        assert(file);
86✔
1241

1242
        _cleanup_free_ char *p = path_join(root, file);
172✔
1243
        if (!p)
86✔
1244
                return log_oom();
×
1245

1246
        if (unlink(p) < 0) {
86✔
1247
                log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
41✔
1248
                               "Failed to unlink file \"%s\": %m", p);
1249

1250
                return errno == ENOENT ? 0 : -errno;
41✔
1251
        }
1252

1253
        log_info("Removed \"%s\".", p);
45✔
1254
        return 1;
1255
}
1256

1257
static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
3✔
1258
        uint16_t slot;
3✔
1259
        int r;
3✔
1260

1261
        r = find_slot(uuid, path, &slot);
3✔
1262
        if (r != 1)
3✔
1263
                return 0;
3✔
1264

1265
        r = efi_remove_boot_option(slot);
3✔
1266
        if (r < 0)
3✔
1267
                return r;
1268

1269
        if (in_order)
3✔
1270
                return remove_from_order(slot);
3✔
1271

1272
        return 0;
1273
}
1274

1275
static int remove_loader_variables(void) {
3✔
1276
        int r = 0;
3✔
1277

1278
        /* Remove all persistent loader variables we define */
1279

1280
        FOREACH_STRING(var,
27✔
1281
                       EFI_LOADER_VARIABLE_STR("LoaderConfigConsoleMode"),
1282
                       EFI_LOADER_VARIABLE_STR("LoaderConfigTimeout"),
1283
                       EFI_LOADER_VARIABLE_STR("LoaderConfigTimeoutOneShot"),
1284
                       EFI_LOADER_VARIABLE_STR("LoaderEntryDefault"),
1285
                       EFI_LOADER_VARIABLE_STR("LoaderEntrySysFail"),
1286
                       EFI_LOADER_VARIABLE_STR("LoaderEntryLastBooted"),
1287
                       EFI_LOADER_VARIABLE_STR("LoaderEntryOneShot"),
1288
                       EFI_LOADER_VARIABLE_STR("LoaderSystemToken")) {
1289

1290
                int q;
24✔
1291

1292
                q = efi_set_variable(var, NULL, 0);
24✔
1293
                if (q == -ENOENT)
24✔
1294
                        continue;
21✔
1295
                if (q < 0)
3✔
1296
                        RET_GATHER(r, log_warning_errno(q, "Failed to remove EFI variable %s: %m", var));
×
1297
                else
1298
                        log_info("Removed EFI variable %s.", var);
3✔
1299
        }
1300

1301
        return r;
3✔
1302
}
1303

1304
int verb_remove(int argc, char *argv[], void *userdata) {
13✔
1305
        sd_id128_t uuid = SD_ID128_NULL;
13✔
1306
        int r;
13✔
1307

1308
        r = acquire_esp(/* unprivileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, &uuid, NULL);
13✔
1309
        if (r < 0)
13✔
1310
                return r;
13✔
1311

1312
        r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
13✔
1313
        if (r < 0)
13✔
1314
                return r;
1315

1316
        r = settle_make_entry_directory();
13✔
1317
        if (r < 0)
13✔
1318
                return r;
1319

1320
        r = remove_binaries(arg_esp_path);
13✔
1321
        RET_GATHER(r, remove_file(arg_esp_path, "/loader/loader.conf"));
13✔
1322
        RET_GATHER(r, remove_file(arg_esp_path, "/loader/random-seed"));
13✔
1323
        RET_GATHER(r, remove_file(arg_esp_path, "/loader/entries.srel"));
13✔
1324

1325
        FOREACH_STRING(db, "PK.auth", "KEK.auth", "db.auth") {
52✔
1326
                _cleanup_free_ char *p = path_join("/loader/keys/auto", db);
78✔
1327
                if (!p)
39✔
1328
                        return log_oom();
×
1329

1330
                RET_GATHER(r, remove_file(arg_esp_path, p));
39✔
1331
        }
1332

1333
        RET_GATHER(r, rmdir_one(arg_esp_path, "/loader/keys/auto"));
13✔
1334
        RET_GATHER(r, remove_subdirs(arg_esp_path, esp_subdirs));
13✔
1335
        RET_GATHER(r, remove_subdirs(arg_esp_path, dollar_boot_subdirs));
13✔
1336
        RET_GATHER(r, remove_entry_directory(arg_esp_path));
13✔
1337

1338
        if (arg_xbootldr_path) {
13✔
1339
                /* Remove a subset of these also from the XBOOTLDR partition if it exists */
1340
                RET_GATHER(r, remove_file(arg_xbootldr_path, "/loader/entries.srel"));
8✔
1341
                RET_GATHER(r, remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs));
8✔
1342
                RET_GATHER(r, remove_entry_directory(arg_xbootldr_path));
8✔
1343
        }
1344

1345
        (void) sync_everything();
13✔
1346

1347
        if (!touch_variables())
13✔
1348
                return r;
1349

1350
        if (arg_arch_all) {
5✔
1351
                log_info("Not changing EFI variables with --all-architectures.");
2✔
1352
                return r;
2✔
1353
        }
1354

1355
        char *path = strjoina("/EFI/systemd/systemd-boot", get_efi_arch(), ".efi");
21✔
1356
        RET_GATHER(r, remove_variables(uuid, path, /* in_order= */ true));
3✔
1357
        return RET_GATHER(r, remove_loader_variables());
3✔
1358
}
1359

1360
int verb_is_installed(int argc, char *argv[], void *userdata) {
12✔
1361
        int r;
12✔
1362

1363
        r = acquire_esp(/* unprivileged_mode= */ false,
12✔
1364
                        /* graceful= */ arg_graceful() != ARG_GRACEFUL_NO,
12✔
1365
                        NULL, NULL, NULL, NULL, NULL);
1366
        if (r < 0)
12✔
1367
                return r;
1368

1369
        r = are_we_installed(arg_esp_path);
12✔
1370
        if (r < 0)
12✔
1371
                return r;
1372

1373
        if (r > 0) {
12✔
1374
                if (!arg_quiet)
6✔
1375
                        puts("yes");
6✔
1376
                return EXIT_SUCCESS;
6✔
1377
        } else {
1378
                if (!arg_quiet)
6✔
1379
                        puts("no");
6✔
1380
                return EXIT_FAILURE;
6✔
1381
        }
1382
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc