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

systemd / systemd / 19020191358

02 Nov 2025 05:04PM UTC coverage: 72.222% (-0.02%) from 72.241%
19020191358

push

github

web-flow
Enhance docs for ukify and direct kernel boots (#39516)

305246 of 422650 relevant lines covered (72.22%)

1085243.28 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) {
151✔
43
        int r;
151✔
44

45
        r = sd_id128_get_machine(&arg_machine_id);
151✔
46
        if (ERRNO_IS_NEG_MACHINE_ID_UNSET(r)) /* Not set or empty */
151✔
47
                return 0;
48
        if (r < 0)
151✔
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));
151✔
52
        return 0;
151✔
53
}
54

55
static int load_etc_machine_info(void) {
151✔
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;
151✔
61
        int r;
151✔
62

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

67
        r = parse_env_file(NULL, p,
151✔
68
                           "KERNEL_INSTALL_LAYOUT", &layout,
69
                           "KERNEL_INSTALL_MACHINE_ID", &s);
70
        if (r == -ENOENT)
151✔
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)) {
151✔
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) {
151✔
101
        _cleanup_free_ char *layout = NULL;
151✔
102
        int r;
151✔
103

104
        r = load_kernel_install_conf(arg_root,
151✔
105
                                     secure_getenv("KERNEL_INSTALL_CONF_ROOT"),
151✔
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)
151✔
112
                return r;
113

114
        if (!isempty(layout)) {
151✔
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) {
151✔
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");
151✔
126
}
127

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

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

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

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

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

147
        bool layout_type1 = use_boot_loader_spec_type1();
151✔
148
        if (arg_make_entry_directory < 0) { /* Automatic mode */
151✔
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)
151✔
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) {
250✔
171
        size_t x, y;
250✔
172

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

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

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

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

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

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

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

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

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

211
        r = get_file_version(fd_to, &b);
250✔
212
        if (r == -ESRCH)
250✔
213
                return log_info_errno(r, "Skipping \"%s\", it's owned by another boot loader (no version info found).", to);
×
214
        if (r < 0)
250✔
215
                return r;
216
        if (compare_product(a, b) != 0)
250✔
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);
250✔
221
        log_debug("Comparing versions: \"%s\" %s \"%s\"", a, comparison_operator(r), b);
488✔
222
        if (r < 0)
250✔
223
                return log_warning_errno(SYNTHETIC_ERRNO(ESTALE),
×
224
                                         "Skipping \"%s\", newer boot loader version in place already.", to);
225
        if (r == 0)
250✔
226
                return log_info_errno(SYNTHETIC_ERRNO(ESTALE),
250✔
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) {
288✔
233
        _cleanup_close_ int fd_from = -EBADF, fd_to = -EBADF;
288✔
234
        _cleanup_free_ char *t = NULL;
288✔
235
        int r;
288✔
236

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

241
        if (!force) {
288✔
242
                fd_to = open(to, O_RDONLY|O_CLOEXEC|O_NOCTTY);
250✔
243
                if (fd_to < 0) {
250✔
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);
250✔
248
                        if (r < 0)
250✔
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(
125✔
338
                const char *esp_path,
339
                const char *source_path,
340
                const char *ignore_filename) {
341

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

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

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

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

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

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

364
                fd = xopenat_full(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW, XO_REGULAR, /* mode= */ 0);
125✔
365
                if (fd < 0)
125✔
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);
125✔
369
                if (r < 0) {
125✔
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)
125✔
374
                        continue;
125✔
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) {
144✔
390
        char *root = IN_SET(arg_install_source, INSTALL_SOURCE_AUTO, INSTALL_SOURCE_IMAGE) ? arg_root : NULL;
144✔
391
        _cleanup_free_ char *source_path = NULL, *dest_path = NULL, *p = NULL, *q = NULL;
144✔
392
        const char *e;
144✔
393
        char *dest_name, *s;
144✔
394
        int r, ret;
144✔
395

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

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

405
        r = chase(p, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, &source_path, NULL);
144✔
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)
144✔
408
                r = chase(p, NULL, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, &source_path, NULL);
16✔
409
        if (r < 0)
144✔
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);
144✔
417
        if (!q)
144✔
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);
144✔
421
        if (r < 0)
144✔
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);
144✔
427

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

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

437
                r = chase(v, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_NONEXISTENT|CHASE_TRIGGER_AUTOFS, &default_dest_path, NULL);
144✔
438
                if (r < 0)
144✔
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));
144✔
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)
144✔
446
                        RET_GATHER(ret, update_efi_boot_binaries(esp_path, source_path, boot_dot_efi));
125✔
447
        }
448

449
        return ret;
450
}
451

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

458
        r = chase_and_opendir(BOOTLIBDIR, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_TRIGGER_AUTOFS, &path, &d);
138✔
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)
138✔
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) {
138✔
463
                log_debug("Source directory does not exist, ignoring.");
×
464
                return 0;
×
465
        }
466
        if (r < 0)
138✔
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");
690✔
470
        const char *suffix_signed = strjoina(arch, ".efi.signed");
690✔
471

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

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

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

487
                k = copy_one_file(esp_path, de->d_name, force);
144✔
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))
144✔
491
                        continue;
122✔
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) {
135✔
535
        _cleanup_(unlink_and_freep) char *t = NULL;
×
536
        _cleanup_fclose_ FILE *f = NULL;
135✔
537
        _cleanup_free_ char *p = NULL;
135✔
538
        int r;
135✔
539

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

544
        if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
135✔
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) {
137✔
937
        int r;
137✔
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/");
274✔
954
        if (!p)
137✔
955
                return log_oom();
×
956

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

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

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

970
        int r;
138✔
971

972
        assert(ret_certificate);
138✔
973
        assert(ret_private_key);
138✔
974

975
        if (!arg_secure_boot_auto_enroll) {
138✔
976
                *ret_certificate = NULL;
137✔
977
                *ret_private_key = NULL;
137✔
978
                return 0;
137✔
979
        }
980

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

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

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

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

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

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

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

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

1036
        install = streq(argv[0], "install");
138✔
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);
138✔
1040

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

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

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

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

1070
        r = settle_make_entry_directory();
138✔
1071
        if (r < 0)
138✔
1072
                return r;
1073

1074
        const char *arch = arg_arch_all ? "" : get_efi_arch();
138✔
1075

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

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

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

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

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

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

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

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

1118
                r = install_loader_specification(arg_dollar_boot_path());
205✔
1119
                if (r < 0)
135✔
1120
                        return r;
1121
        }
1122

1123
        (void) sync_everything();
135✔
1124

1125
        if (!touch_variables())
135✔
1126
                return 0;
1127

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

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

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

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

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

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

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

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

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

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

1179
                c++;
13✔
1180
        }
1181

1182
        return c;
1183
}
1184

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

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

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

1200
        return 0;
1201
}
1202

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1271
        return 0;
1272
}
1273

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

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

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

1289
                int q;
24✔
1290

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

1300
        return r;
3✔
1301
}
1302

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

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

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

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

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

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

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

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

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

1344
        (void) sync_everything();
13✔
1345

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

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

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

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

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

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

1372
        if (r > 0) {
12✔
1373
                if (!arg_quiet)
6✔
1374
                        puts("yes");
6✔
1375
                return EXIT_SUCCESS;
6✔
1376
        } else {
1377
                if (!arg_quiet)
6✔
1378
                        puts("no");
6✔
1379
                return EXIT_FAILURE;
6✔
1380
        }
1381
}
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