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

systemd / systemd / 16458254342

22 Jul 2025 11:49PM UTC coverage: 72.173% (+0.05%) from 72.121%
16458254342

push

github

yuwata
meson: prepend sys_root to bpf isystem

These sort of absolute include paths are generally unsafe when cross compiling.

302515 of 419153 relevant lines covered (72.17%)

734662.87 hits per line

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

65.98
/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) {
149✔
43
        int r;
149✔
44

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

230
        return 0;
231
}
232

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

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

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

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

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

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

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

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

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

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

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

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

291
        return 0;
292
}
293

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

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

304
        return 0;
305
}
306

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

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

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

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

335
        return 0;
336
}
337

338
static int update_efi_boot_binaries(const char *esp_path, const char *source_path) {
123✔
339
        _cleanup_closedir_ DIR *d = NULL;
123✔
340
        _cleanup_free_ char *p = NULL;
123✔
341
        int r, ret = 0;
123✔
342

343
        assert(esp_path);
123✔
344
        assert(source_path);
123✔
345

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

352
        FOREACH_DIRENT(de, d, break) {
615✔
353
                _cleanup_close_ int fd = -EBADF;
615✔
354

355
                if (!endswith_no_case(de->d_name, ".efi"))
246✔
356
                        continue;
×
357

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

362
                r = pe_is_native_fd(fd);
246✔
363
                if (r < 0) {
246✔
364
                        log_warning_errno(r, "Failed to detect if \"%s/%s\" is native architecture, ignoring: %m", p, de->d_name);
×
365
                        continue;
×
366
                }
367
                if (r == 0)
246✔
368
                        continue;
123✔
369

370
                _cleanup_free_ char *dest_path = path_join(p, de->d_name);
246✔
371
                if (!dest_path)
123✔
372
                        return log_oom();
×
373

374
                r = copy_file_with_version_check(source_path, dest_path, /* force = */ false);
123✔
375
                if (IN_SET(r, -ESTALE, -ESRCH))
123✔
376
                        continue;
123✔
377
                RET_GATHER(ret, r);
×
378
        }
379

380
        return ret;
381
}
382

383
static int copy_one_file(const char *esp_path, const char *name, bool force) {
142✔
384
        char *root = IN_SET(arg_install_source, ARG_INSTALL_SOURCE_AUTO, ARG_INSTALL_SOURCE_IMAGE) ? arg_root : NULL;
142✔
385
        _cleanup_free_ char *source_path = NULL, *dest_path = NULL, *p = NULL, *q = NULL;
142✔
386
        const char *e;
142✔
387
        char *dest_name, *s;
142✔
388
        int r, ret;
142✔
389

390
        dest_name = strdupa_safe(name);
142✔
391
        s = endswith_no_case(dest_name, ".signed");
142✔
392
        if (s)
142✔
393
                *s = 0;
×
394

395
        p = path_join(BOOTLIBDIR, name);
142✔
396
        if (!p)
142✔
397
                return log_oom();
×
398

399
        r = chase(p, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &source_path, NULL);
142✔
400
        /* If we had a root directory to try, we didn't find it and we are in auto mode, retry on the host */
401
        if (r == -ENOENT && root && arg_install_source == ARG_INSTALL_SOURCE_AUTO)
142✔
402
                r = chase(p, NULL, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &source_path, NULL);
16✔
403
        if (r < 0)
142✔
404
                return log_error_errno(r,
×
405
                                       "Failed to resolve path %s%s%s: %m",
406
                                       p,
407
                                       root ? " under directory " : "",
408
                                       strempty(root));
409

410
        q = path_join("/EFI/systemd/", dest_name);
142✔
411
        if (!q)
142✔
412
                return log_oom();
×
413

414
        r = chase(q, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_NONEXISTENT, &dest_path, NULL);
142✔
415
        if (r < 0)
142✔
416
                return log_error_errno(r, "Failed to resolve path %s under directory %s: %m", q, esp_path);
×
417

418
        /* Note that if this fails we do the second copy anyway, but return this error code,
419
         * so we stash it away in a separate variable. */
420
        ret = copy_file_with_version_check(source_path, dest_path, force);
142✔
421

422
        e = startswith(dest_name, "systemd-boot");
142✔
423
        if (e) {
142✔
424
                _cleanup_free_ char *default_dest_path = NULL;
142✔
425
                char *v;
142✔
426

427
                /* Create the EFI default boot loader name (specified for removable devices) */
428
                v = strjoina("/EFI/BOOT/BOOT", e);
710✔
429
                ascii_strupper(strrchr(v, '/') + 1);
142✔
430

431
                r = chase(v, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_NONEXISTENT, &default_dest_path, NULL);
142✔
432
                if (r < 0)
142✔
433
                        return log_error_errno(r, "Failed to resolve path %s under directory %s: %m", v, esp_path);
×
434

435
                RET_GATHER(ret, copy_file_with_version_check(source_path, default_dest_path, force));
142✔
436

437
                /* If we were installed under any other name in /EFI/BOOT, make sure we update those binaries
438
                 * as well. */
439
                if (!force)
142✔
440
                        RET_GATHER(ret, update_efi_boot_binaries(esp_path, source_path));
123✔
441
        }
442

443
        return ret;
444
}
445

446
static int install_binaries(const char *esp_path, const char *arch, bool force) {
136✔
447
        char *root = IN_SET(arg_install_source, ARG_INSTALL_SOURCE_AUTO, ARG_INSTALL_SOURCE_IMAGE) ? arg_root : NULL;
136✔
448
        _cleanup_closedir_ DIR *d = NULL;
136✔
449
        _cleanup_free_ char *path = NULL;
136✔
450
        int r;
136✔
451

452
        r = chase_and_opendir(BOOTLIBDIR, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &path, &d);
136✔
453
        /* If we had a root directory to try, we didn't find it and we are in auto mode, retry on the host */
454
        if (r == -ENOENT && root && arg_install_source == ARG_INSTALL_SOURCE_AUTO)
136✔
455
                r = chase_and_opendir(BOOTLIBDIR, NULL, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &path, &d);
12✔
456
        if (r == -ENOENT && arg_graceful) {
136✔
457
                log_debug("Source directory does not exist, ignoring.");
×
458
                return 0;
×
459
        }
460
        if (r < 0)
136✔
461
                return log_error_errno(r, "Failed to open boot loader directory %s%s: %m", strempty(root), BOOTLIBDIR);
×
462

463
        const char *suffix = strjoina(arch, ".efi");
680✔
464
        const char *suffix_signed = strjoina(arch, ".efi.signed");
680✔
465

466
        FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read \"%s\": %m", path)) {
1,224✔
467
                int k;
816✔
468

469
                if (!endswith_no_case(de->d_name, suffix) && !endswith_no_case(de->d_name, suffix_signed))
816✔
470
                        continue;
674✔
471

472
                /* skip the .efi file, if there's a .signed version of it */
473
                if (endswith_no_case(de->d_name, ".efi")) {
142✔
474
                        _cleanup_free_ const char *s = strjoin(de->d_name, ".signed");
284✔
475
                        if (!s)
142✔
476
                                return log_oom();
×
477
                        if (faccessat(dirfd(d), s, F_OK, 0) >= 0)
142✔
478
                                continue;
×
479
                }
480

481
                k = copy_one_file(esp_path, de->d_name, force);
142✔
482
                /* Don't propagate an error code if no update necessary, installed version already equal or
483
                 * newer version, or other boot loader in place. */
484
                if (arg_graceful && IN_SET(k, -ESTALE, -ESRCH))
142✔
485
                        continue;
120✔
486
                RET_GATHER(r, k);
22✔
487
        }
488

489
        return r;
490
}
491

492
static int install_loader_config(const char *esp_path) {
13✔
493
        _cleanup_(unlink_and_freep) char *t = NULL;
×
494
        _cleanup_fclose_ FILE *f = NULL;
13✔
495
        _cleanup_free_ char *p = NULL;
13✔
496
        int r;
13✔
497

498
        assert(arg_make_entry_directory >= 0);
13✔
499

500
        p = path_join(esp_path, "/loader/loader.conf");
13✔
501
        if (!p)
13✔
502
                return log_oom();
×
503
        if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
13✔
504
                return 0;
505

506
        r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
12✔
507
        if (r < 0)
12✔
508
                return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
×
509

510
        fprintf(f, "#timeout 3\n"
12✔
511
                   "#console-mode keep\n");
512

513
        if (arg_make_entry_directory) {
12✔
514
                assert(arg_entry_token);
6✔
515
                fprintf(f, "default %s-*\n", arg_entry_token);
6✔
516
        }
517

518
        r = flink_tmpfile(f, t, p, LINK_TMPFILE_SYNC);
12✔
519
        if (r == -EEXIST)
12✔
520
                return 0; /* Silently skip creation if the file exists now (recheck) */
521
        if (r < 0)
12✔
522
                return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
×
523

524
        t = mfree(t);
12✔
525
        return 1;
12✔
526
}
527

528
static int install_loader_specification(const char *root) {
133✔
529
        _cleanup_(unlink_and_freep) char *t = NULL;
×
530
        _cleanup_fclose_ FILE *f = NULL;
133✔
531
        _cleanup_free_ char *p = NULL;
133✔
532
        int r;
133✔
533

534
        p = path_join(root, "/loader/entries.srel");
133✔
535
        if (!p)
133✔
536
                return log_oom();
×
537

538
        if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
133✔
539
                return 0;
540

541
        r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
12✔
542
        if (r < 0)
12✔
543
                return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
×
544

545
        fprintf(f, "type1\n");
12✔
546

547
        r = flink_tmpfile(f, t, p, LINK_TMPFILE_SYNC);
12✔
548
        if (r == -EEXIST)
12✔
549
                return 0; /* Silently skip creation if the file exists now (recheck) */
550
        if (r < 0)
12✔
551
                return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
×
552

553
        t = mfree(t);
12✔
554
        return 1;
12✔
555
}
556

557
static int install_entry_directory(const char *root) {
13✔
558
        assert(root);
13✔
559
        assert(arg_make_entry_directory >= 0);
13✔
560

561
        if (!arg_make_entry_directory)
13✔
562
                return 0;
563

564
        assert(arg_entry_token);
7✔
565
        return mkdir_one(root, arg_entry_token);
7✔
566
}
567

568
static int install_entry_token(void) {
13✔
569
        _cleanup_free_ char* p = NULL;
13✔
570
        int r;
13✔
571

572
        assert(arg_make_entry_directory >= 0);
13✔
573
        assert(arg_entry_token);
13✔
574

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

578
        if (!arg_make_entry_directory && arg_entry_token_type == BOOT_ENTRY_TOKEN_MACHINE_ID)
13✔
579
                return 0;
580

581
        p = path_join(arg_root, getenv("KERNEL_INSTALL_CONF_ROOT") ?: "/etc/kernel/", "entry-token");
26✔
582
        if (!p)
13✔
583
                return log_oom();
×
584

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

589
        return 0;
590
}
591

592
#if HAVE_OPENSSL
593
static int efi_timestamp(EFI_TIME *ret) {
1✔
594
        uint64_t epoch = UINT64_MAX;
1✔
595
        struct tm tm = {};
1✔
596
        int r;
1✔
597

598
        assert(ret);
1✔
599

600
        r = secure_getenv_uint64("SOURCE_DATE_EPOCH", &epoch);
1✔
601
        if (r != -ENXIO)
1✔
602
                log_debug_errno(r, "Failed to parse $SOURCE_DATE_EPOCH, ignoring: %m");
×
603

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

608
        *ret = (EFI_TIME) {
1✔
609
                .Year = 1900 + tm.tm_year,
1✔
610
                /* tm_mon starts at 0, EFI_TIME months start at 1. */
611
                .Month = tm.tm_mon + 1,
1✔
612
                .Day = tm.tm_mday,
1✔
613
                .Hour = tm.tm_hour,
1✔
614
                .Minute = tm.tm_min,
1✔
615
                .Second = tm.tm_sec,
1✔
616
        };
617

618
        return 0;
1✔
619
}
620
#endif
621

622
static int install_secure_boot_auto_enroll(const char *esp, X509 *certificate, EVP_PKEY *private_key) {
1✔
623
#if HAVE_OPENSSL
624
        int r;
1✔
625

626
        _cleanup_free_ uint8_t *dercert = NULL;
1✔
627
        int dercertsz;
1✔
628
        dercertsz = i2d_X509(certificate, &dercert);
1✔
629
        if (dercertsz < 0)
1✔
630
                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert X.509 certificate to DER: %s",
×
631
                                       ERR_error_string(ERR_get_error(), NULL));
632

633
        r = mkdir_one(esp, "loader/keys/auto");
1✔
634
        if (r < 0)
1✔
635
                return r;
636

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

641
        uint32_t siglistsz = offsetof(EFI_SIGNATURE_LIST, Signatures) + offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz;
1✔
642
        /* We use malloc0() to zero-initialize the SignatureOwner field of Signatures[0]. */
643
        _cleanup_free_ EFI_SIGNATURE_LIST *siglist = malloc0(siglistsz);
2✔
644
        if (!siglist)
1✔
645
                return log_oom();
×
646

647
        *siglist = (EFI_SIGNATURE_LIST) {
1✔
648
                .SignatureType = EFI_CERT_X509_GUID,
649
                .SignatureListSize = siglistsz,
650
                .SignatureSize = offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz,
1✔
651
        };
652

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

655
        EFI_TIME timestamp;
1✔
656
        r = efi_timestamp(&timestamp);
1✔
657
        if (r < 0)
1✔
658
                return r;
659

660
        uint32_t attrs =
1✔
661
                EFI_VARIABLE_NON_VOLATILE|
662
                EFI_VARIABLE_BOOTSERVICE_ACCESS|
663
                EFI_VARIABLE_RUNTIME_ACCESS|
664
                EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
665

666
        FOREACH_STRING(db, "PK", "KEK", "db") {
4✔
667
                _cleanup_(BIO_freep) BIO *bio = NULL;
3✔
668

669
                bio = BIO_new(BIO_s_mem());
3✔
670
                if (!bio)
3✔
671
                        return log_oom();
×
672

673
                _cleanup_free_ char16_t *db16 = utf8_to_utf16(db, SIZE_MAX);
6✔
674
                if (!db16)
3✔
675
                        return log_oom();
×
676

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

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

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

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

689
                if (BIO_write(bio, &timestamp, sizeof(timestamp)) < 0)
3✔
690
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write timestamp to bio");
×
691

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

695
                _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
3✔
696
                p7 = PKCS7_sign(certificate, private_key, /*certs=*/ NULL, bio, PKCS7_DETACHED|PKCS7_NOATTR|PKCS7_BINARY|PKCS7_NOSMIMECAP);
3✔
697
                if (!p7)
3✔
698
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to calculate PKCS7 signature: %s",
×
699
                                               ERR_error_string(ERR_get_error(), NULL));
700

701
                _cleanup_free_ uint8_t *sig = NULL;
×
702
                int sigsz = i2d_PKCS7(p7, &sig);
3✔
703
                if (sigsz < 0)
3✔
704
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert PKCS7 signature to DER: %s",
×
705
                                               ERR_error_string(ERR_get_error(), NULL));
706

707
                size_t authsz = offsetof(EFI_VARIABLE_AUTHENTICATION_2, AuthInfo.CertData) + sigsz;
3✔
708
                _cleanup_free_ EFI_VARIABLE_AUTHENTICATION_2 *auth = malloc(authsz);
×
709
                if (!auth)
3✔
710
                        return log_oom();
×
711

712
                *auth = (EFI_VARIABLE_AUTHENTICATION_2) {
3✔
713
                        .TimeStamp = timestamp,
714
                        .AuthInfo = {
715
                                .Hdr = {
716
                                        .dwLength = offsetof(WIN_CERTIFICATE_UEFI_GUID, CertData) + sigsz,
3✔
717
                                        .wRevision = 0x0200,
718
                                        .wCertificateType = 0x0EF1, /* WIN_CERT_TYPE_EFI_GUID */
719
                                },
720
                                .CertType = EFI_CERT_TYPE_PKCS7_GUID,
721
                        }
722
                };
723

724
                memcpy(auth->AuthInfo.CertData, sig, sigsz);
3✔
725

726
                _cleanup_free_ char *filename = strjoin(db, ".auth");
6✔
727
                if (!filename)
3✔
728
                        return log_oom();
×
729

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

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

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

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

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

748
        return 0;
1✔
749
#else
750
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL is not supported, cannot set up secure boot auto-enrollment.");
751
#endif
752
}
753

754
static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
×
755
        _cleanup_free_ char *opath = NULL;
×
756
        sd_id128_t ouuid;
×
757
        int r;
×
758

759
        r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
×
760
        if (r < 0)
×
761
                return false;
762
        if (!sd_id128_equal(uuid, ouuid))
×
763
                return false;
×
764

765
        /* Some motherboards convert the path to uppercase under certain circumstances
766
         * (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
767
         * so use case-insensitive checking */
768
        if (!strcaseeq_ptr(path, opath))
×
769
                return false;
×
770

771
        return true;
772
}
773

774
static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
×
775
        _cleanup_free_ uint16_t *options = NULL;
×
776

777
        int n = efi_get_boot_options(&options);
×
778
        if (n < 0)
×
779
                return n;
780

781
        /* find already existing systemd-boot entry */
782
        for (int i = 0; i < n; i++)
×
783
                if (same_entry(options[i], uuid, path)) {
×
784
                        *id = options[i];
×
785
                        return 1;
×
786
                }
787

788
        /* find free slot in the sorted BootXXXX variable list */
789
        for (int i = 0; i < n; i++)
×
790
                if (i != options[i]) {
×
791
                        *id = i;
×
792
                        return 0;
×
793
                }
794

795
        /* use the next one */
796
        if (n == 0xffff)
×
797
                return -ENOSPC;
798
        *id = n;
×
799
        return 0;
×
800
}
801

802
static int insert_into_order(uint16_t slot, bool first) {
×
803
        _cleanup_free_ uint16_t *order = NULL;
×
804
        uint16_t *t;
×
805
        int n;
×
806

807
        n = efi_get_boot_order(&order);
×
808
        if (n <= 0)
×
809
                /* no entry, add us */
810
                return efi_set_boot_order(&slot, 1);
×
811

812
        /* are we the first and only one? */
813
        if (n == 1 && order[0] == slot)
×
814
                return 0;
815

816
        /* are we already in the boot order? */
817
        for (int i = 0; i < n; i++) {
×
818
                if (order[i] != slot)
×
819
                        continue;
×
820

821
                /* we do not require to be the first one, all is fine */
822
                if (!first)
×
823
                        return 0;
824

825
                /* move us to the first slot */
826
                memmove(order + 1, order, i * sizeof(uint16_t));
×
827
                order[0] = slot;
×
828
                return efi_set_boot_order(order, n);
×
829
        }
830

831
        /* extend array */
832
        t = reallocarray(order, n + 1, sizeof(uint16_t));
×
833
        if (!t)
×
834
                return -ENOMEM;
835
        order = t;
×
836

837
        /* add us to the top or end of the list */
838
        if (first) {
×
839
                memmove(order + 1, order, n * sizeof(uint16_t));
×
840
                order[0] = slot;
×
841
        } else
842
                order[n] = slot;
×
843

844
        return efi_set_boot_order(order, n + 1);
×
845
}
846

847
static int remove_from_order(uint16_t slot) {
×
848
        _cleanup_free_ uint16_t *order = NULL;
×
849
        int n;
×
850

851
        n = efi_get_boot_order(&order);
×
852
        if (n <= 0)
×
853
                return n;
854

855
        for (int i = 0; i < n; i++) {
×
856
                if (order[i] != slot)
×
857
                        continue;
×
858

859
                if (i + 1 < n)
×
860
                        memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
×
861
                return efi_set_boot_order(order, n - 1);
×
862
        }
863

864
        return 0;
865
}
866

867
static const char *pick_efi_boot_option_description(void) {
×
868
        return arg_efi_boot_option_description ?: "Linux Boot Manager";
×
869
}
870

871
static int install_variables(
×
872
                const char *esp_path,
873
                uint32_t part,
874
                uint64_t pstart,
875
                uint64_t psize,
876
                sd_id128_t uuid,
877
                const char *path,
878
                bool first,
879
                bool graceful) {
880

881
        uint16_t slot;
×
882
        int r;
×
883

884
        r = chase_and_access(path, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, F_OK, NULL);
×
885
        if (r == -ENOENT)
×
886
                return 0;
×
887
        if (r < 0)
×
888
                return log_error_errno(r, "Cannot access \"%s/%s\": %m", esp_path, skip_leading_slash(path));
×
889

890
        r = find_slot(uuid, path, &slot);
×
891
        if (r < 0) {
×
892
                int level = graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
×
893
                const char *skip = graceful ? ", skipping" : "";
894

895
                log_full_errno(level, r,
×
896
                               r == -ENOENT ?
897
                               "Failed to access EFI variables%s. Is the \"efivarfs\" filesystem mounted?" :
898
                               "Failed to determine current boot order%s: %m", skip);
899

900
                return graceful ? 0 : r;
×
901
        }
902

903
        if (first || r == 0) {
×
904
                r = efi_add_boot_option(slot, pick_efi_boot_option_description(),
×
905
                                        part, pstart, psize,
906
                                        uuid, path);
907
                if (r < 0) {
×
908
                        int level = graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
×
909
                        const char *skip = graceful ? ", skipping" : "";
910

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

913
                        return graceful ? 0 : r;
×
914
                }
915

916
                log_info("Created EFI boot entry \"%s\".", pick_efi_boot_option_description());
×
917
        }
918

919
        return insert_into_order(slot, first);
×
920
}
921

922
static int are_we_installed(const char *esp_path) {
135✔
923
        int r;
135✔
924

925
        /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
926
         * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
927
         * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
928
         * should be a suitable and very minimal check for a number of reasons:
929
         *
930
         *  → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
931
         *    not a specific one.)
932
         *
933
         *  → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
934
         *    /EFI/BOOT/BOOT*.EFI fallback binary.
935
         *
936
         *  → It specifically checks for systemd-boot, not for other boot loaders (which a check for
937
         *    /boot/loader/entries would do). */
938

939
        _cleanup_free_ char *p = path_join(esp_path, "/EFI/systemd/");
270✔
940
        if (!p)
135✔
941
                return log_oom();
×
942

943
        log_debug("Checking whether %s contains any files%s", p, glyph(GLYPH_ELLIPSIS));
252✔
944
        r = dir_is_empty(p, /* ignore_hidden_or_backup= */ false);
135✔
945
        if (r < 0 && r != -ENOENT)
135✔
946
                return log_error_errno(r, "Failed to check whether %s contains any files: %m", p);
×
947

948
        return r == 0;
135✔
949
}
950

951
int verb_install(int argc, char *argv[], void *userdata) {
136✔
952
        _cleanup_(X509_freep) X509 *certificate = NULL;
136✔
953
        _cleanup_(openssl_ask_password_ui_freep) OpenSSLAskPasswordUI *ui = NULL;
136✔
954
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *private_key = NULL;
136✔
955
        sd_id128_t uuid = SD_ID128_NULL;
136✔
956
        uint64_t pstart = 0, psize = 0;
136✔
957
        uint32_t part = 0;
136✔
958
        bool install, graceful;
136✔
959
        int r;
136✔
960

961
        /* Invoked for both "update" and "install" */
962

963
        install = streq(argv[0], "install");
136✔
964
        graceful = !install && arg_graceful; /* support graceful mode for updates */
136✔
965

966
        if (arg_secure_boot_auto_enroll) {
136✔
967
                if (arg_certificate_source_type == OPENSSL_CERTIFICATE_SOURCE_FILE) {
1✔
968
                        r = parse_path_argument(arg_certificate, /*suppress_root=*/ false, &arg_certificate);
1✔
969
                        if (r < 0)
1✔
970
                                return r;
×
971
                }
972

973
                r = openssl_load_x509_certificate(
1✔
974
                                arg_certificate_source_type,
975
                                arg_certificate_source,
976
                                arg_certificate,
977
                                &certificate);
978
                if (r < 0)
1✔
979
                        return log_error_errno(r, "Failed to load X.509 certificate from %s: %m", arg_certificate);
×
980

981
                if (arg_private_key_source_type == OPENSSL_KEY_SOURCE_FILE) {
1✔
982
                        r = parse_path_argument(arg_private_key, /* suppress_root= */ false, &arg_private_key);
1✔
983
                        if (r < 0)
1✔
984
                                return log_error_errno(r, "Failed to parse private key path %s: %m", arg_private_key);
×
985
                }
986

987
                r = openssl_load_private_key(
2✔
988
                                arg_private_key_source_type,
989
                                arg_private_key_source,
990
                                arg_private_key,
991
                                &(AskPasswordRequest) {
1✔
992
                                        .tty_fd = -EBADF,
993
                                        .id = "bootctl-private-key-pin",
994
                                        .keyring = arg_private_key,
995
                                        .credential = "bootctl.private-key-pin",
996
                                        .until = USEC_INFINITY,
997
                                        .hup_fd = -EBADF,
998
                                },
999
                                &private_key,
1000
                                &ui);
1001
                if (r < 0)
1✔
1002
                        return log_error_errno(r, "Failed to load private key from %s: %m", arg_private_key);
×
1003
        }
1004

1005
        r = acquire_esp(/* unprivileged_mode= */ false, graceful, &part, &pstart, &psize, &uuid, NULL);
136✔
1006
        if (graceful && r == -ENOKEY)
136✔
1007
                return 0; /* If --graceful is specified and we can't find an ESP, handle this cleanly */
1008
        if (r < 0)
136✔
1009
                return r;
1010

1011
        if (!install) {
136✔
1012
                /* If we are updating, don't do anything if sd-boot wasn't actually installed. */
1013
                r = are_we_installed(arg_esp_path);
123✔
1014
                if (r < 0)
123✔
1015
                        return r;
1016
                if (r == 0) {
123✔
1017
                        log_debug("Skipping update because sd-boot is not installed in the ESP.");
×
1018
                        return 0;
×
1019
                }
1020
        }
1021

1022
        r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
136✔
1023
        if (r < 0)
136✔
1024
                return r;
1025

1026
        r = settle_make_entry_directory();
136✔
1027
        if (r < 0)
136✔
1028
                return r;
1029

1030
        const char *arch = arg_arch_all ? "" : get_efi_arch();
136✔
1031

1032
        WITH_UMASK(0002) {
272✔
1033
                if (install) {
136✔
1034
                        /* Don't create any of these directories when we are just updating. When we update
1035
                         * we'll drop-in our files (unless there are newer ones already), but we won't create
1036
                         * the directories for them in the first place. */
1037
                        r = create_subdirs(arg_esp_path, esp_subdirs);
13✔
1038
                        if (r < 0)
13✔
1039
                                return r;
1040

1041
                        r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
18✔
1042
                        if (r < 0)
13✔
1043
                                return r;
1044
                }
1045

1046
                r = install_binaries(arg_esp_path, arch, install);
136✔
1047
                if (r < 0)
136✔
1048
                        return r;
1049

1050
                if (install) {
133✔
1051
                        r = install_loader_config(arg_esp_path);
13✔
1052
                        if (r < 0)
13✔
1053
                                return r;
1054

1055
                        r = install_entry_directory(arg_dollar_boot_path());
18✔
1056
                        if (r < 0)
13✔
1057
                                return r;
1058

1059
                        r = install_entry_token();
13✔
1060
                        if (r < 0)
13✔
1061
                                return r;
1062

1063
                        if (arg_install_random_seed) {
13✔
1064
                                r = install_random_seed(arg_esp_path);
13✔
1065
                                if (r < 0)
13✔
1066
                                        return r;
1067
                        }
1068

1069
                        if (arg_secure_boot_auto_enroll) {
13✔
1070
                                r = install_secure_boot_auto_enroll(arg_esp_path, certificate, private_key);
1✔
1071
                                if (r < 0)
1✔
1072
                                        return r;
1073
                        }
1074
                }
1075

1076
                r = install_loader_specification(arg_dollar_boot_path());
200✔
1077
                if (r < 0)
133✔
1078
                        return r;
1079
        }
1080

1081
        (void) sync_everything();
133✔
1082

1083
        if (!touch_variables())
133✔
1084
                return 0;
1085

1086
        if (arg_arch_all) {
×
1087
                log_info("Not changing EFI variables with --all-architectures.");
×
1088
                return 0;
×
1089
        }
1090

1091
        char *path = strjoina("/EFI/systemd/systemd-boot", arch, ".efi");
×
1092
        return install_variables(arg_esp_path, part, pstart, psize, uuid, path, install, graceful);
×
1093
}
1094

1095
static int remove_boot_efi(const char *esp_path) {
13✔
1096
        _cleanup_closedir_ DIR *d = NULL;
13✔
1097
        _cleanup_free_ char *p = NULL;
13✔
1098
        int r, c = 0;
13✔
1099

1100
        r = chase_and_opendir("/EFI/BOOT", esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &p, &d);
13✔
1101
        if (r == -ENOENT)
13✔
1102
                return 0;
1103
        if (r < 0)
13✔
1104
                return log_error_errno(r, "Failed to open directory \"%s/EFI/BOOT\": %m", esp_path);
×
1105

1106
        FOREACH_DIRENT(de, d, break) {
63✔
1107
                _cleanup_close_ int fd = -EBADF;
24✔
1108
                _cleanup_free_ char *v = NULL;
24✔
1109

1110
                if (!endswith_no_case(de->d_name, ".efi"))
24✔
1111
                        continue;
×
1112

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

1117
                r = pe_is_native_fd(fd);
24✔
1118
                if (r < 0) {
24✔
1119
                        log_warning_errno(r, "Failed to detect if \"%s/%s\" is native architecture, ignoring: %m", p, de->d_name);
×
1120
                        continue;
×
1121
                }
1122
                if (r == 0)
24✔
1123
                        continue;
11✔
1124

1125
                r = get_file_version(fd, &v);
13✔
1126
                if (r == -ESRCH)
13✔
1127
                        continue;  /* No version information */
×
1128
                if (r < 0)
13✔
1129
                        return r;
1130
                if (startswith(v, "systemd-boot ")) {
13✔
1131
                        if (unlinkat(dirfd(d), de->d_name, 0) < 0)
13✔
1132
                                return log_error_errno(errno, "Failed to remove \"%s/%s\": %m", p, de->d_name);
×
1133

1134
                        log_info("Removed \"%s/%s\".", p, de->d_name);
13✔
1135
                }
1136

1137
                c++;
13✔
1138
        }
1139

1140
        return c;
1141
}
1142

1143
static int rmdir_one(const char *prefix, const char *suffix) {
172✔
1144
        _cleanup_free_ char *p = path_join(prefix, suffix);
344✔
1145
        if (!p)
172✔
1146
                return log_oom();
×
1147

1148
        if (rmdir(p) < 0) {
172✔
1149
                bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
98✔
1150

1151
                log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
98✔
1152
                               "Failed to remove directory \"%s\": %m", p);
1153
                if (!ignore)
98✔
1154
                        return -errno;
×
1155
        } else
1156
                log_info("Removed \"%s\".", p);
74✔
1157

1158
        return 0;
1159
}
1160

1161
static int remove_subdirs(const char *root, const char *const *subdirs) {
183✔
1162
        int r, q;
183✔
1163

1164
        /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
1165
         * short the array is. */
1166

1167
        if (!subdirs[0]) /* A the end of the list */
183✔
1168
                return 0;
1169

1170
        r = remove_subdirs(root, subdirs + 1);
149✔
1171
        q = rmdir_one(root, subdirs[0]);
149✔
1172

1173
        return r < 0 ? r : q;
149✔
1174
}
1175

1176
static int remove_entry_directory(const char *root) {
21✔
1177
        assert(root);
21✔
1178
        assert(arg_make_entry_directory >= 0);
21✔
1179

1180
        if (!arg_make_entry_directory || !arg_entry_token)
21✔
1181
                return 0;
1182

1183
        return rmdir_one(root, arg_entry_token);
10✔
1184
}
1185

1186
static int remove_binaries(const char *esp_path) {
13✔
1187
        int r, q;
13✔
1188

1189
        _cleanup_free_ char *p = path_join(esp_path, "/EFI/systemd");
26✔
1190
        if (!p)
13✔
1191
                return log_oom();
×
1192

1193
        r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
13✔
1194

1195
        q = remove_boot_efi(esp_path);
13✔
1196
        if (q < 0 && r == 0)
13✔
1197
                r = q;
×
1198

1199
        return r;
1200
}
1201

1202
static int remove_file(const char *root, const char *file) {
86✔
1203
        assert(root);
86✔
1204
        assert(file);
86✔
1205

1206
        _cleanup_free_ char *p = path_join(root, file);
172✔
1207
        if (!p)
86✔
1208
                return log_oom();
×
1209

1210
        if (unlink(p) < 0) {
86✔
1211
                log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
44✔
1212
                               "Failed to unlink file \"%s\": %m", p);
1213

1214
                return errno == ENOENT ? 0 : -errno;
44✔
1215
        }
1216

1217
        log_info("Removed \"%s\".", p);
42✔
1218
        return 1;
1219
}
1220

1221
static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
×
1222
        uint16_t slot;
×
1223
        int r;
×
1224

1225
        r = find_slot(uuid, path, &slot);
×
1226
        if (r != 1)
×
1227
                return 0;
×
1228

1229
        r = efi_remove_boot_option(slot);
×
1230
        if (r < 0)
×
1231
                return r;
1232

1233
        if (in_order)
×
1234
                return remove_from_order(slot);
×
1235

1236
        return 0;
1237
}
1238

1239
static int remove_loader_variables(void) {
×
1240
        int r = 0;
×
1241

1242
        /* Remove all persistent loader variables we define */
1243

1244
        FOREACH_STRING(var,
×
1245
                       EFI_LOADER_VARIABLE_STR("LoaderConfigConsoleMode"),
1246
                       EFI_LOADER_VARIABLE_STR("LoaderConfigTimeout"),
1247
                       EFI_LOADER_VARIABLE_STR("LoaderConfigTimeoutOneShot"),
1248
                       EFI_LOADER_VARIABLE_STR("LoaderEntryDefault"),
1249
                       EFI_LOADER_VARIABLE_STR("LoaderEntrySysFail"),
1250
                       EFI_LOADER_VARIABLE_STR("LoaderEntryLastBooted"),
1251
                       EFI_LOADER_VARIABLE_STR("LoaderEntryOneShot"),
1252
                       EFI_LOADER_VARIABLE_STR("LoaderSystemToken")) {
1253

1254
                int q;
×
1255

1256
                q = efi_set_variable(var, NULL, 0);
×
1257
                if (q == -ENOENT)
×
1258
                        continue;
×
1259
                if (q < 0) {
×
1260
                        log_warning_errno(q, "Failed to remove EFI variable %s: %m", var);
×
1261
                        if (r >= 0)
×
1262
                                r = q;
×
1263
                } else
1264
                        log_info("Removed EFI variable %s.", var);
×
1265
        }
1266

1267
        return r;
×
1268
}
1269

1270
int verb_remove(int argc, char *argv[], void *userdata) {
13✔
1271
        sd_id128_t uuid = SD_ID128_NULL;
13✔
1272
        int r, q;
13✔
1273

1274
        r = acquire_esp(/* unprivileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, &uuid, NULL);
13✔
1275
        if (r < 0)
13✔
1276
                return r;
13✔
1277

1278
        r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
13✔
1279
        if (r < 0)
13✔
1280
                return r;
1281

1282
        r = settle_make_entry_directory();
13✔
1283
        if (r < 0)
13✔
1284
                return r;
1285

1286
        r = remove_binaries(arg_esp_path);
13✔
1287

1288
        q = remove_file(arg_esp_path, "/loader/loader.conf");
13✔
1289
        if (q < 0 && r >= 0)
13✔
1290
                r = q;
×
1291

1292
        q = remove_file(arg_esp_path, "/loader/random-seed");
13✔
1293
        if (q < 0 && r >= 0)
13✔
1294
                r = q;
×
1295

1296
        q = remove_file(arg_esp_path, "/loader/entries.srel");
13✔
1297
        if (q < 0 && r >= 0)
13✔
1298
                r = q;
×
1299

1300
        FOREACH_STRING(db, "PK.auth", "KEK.auth", "db.auth") {
52✔
1301
                _cleanup_free_ char *p = path_join("/loader/keys/auto", db);
78✔
1302
                if (!p)
39✔
1303
                        return log_oom();
×
1304

1305
                q = remove_file(arg_esp_path, p);
39✔
1306
                if (q < 0 && r >= 0)
39✔
1307
                        r = q;
×
1308
        }
1309

1310
        q = rmdir_one(arg_esp_path, "/loader/keys/auto");
13✔
1311
        if (q < 0 && r >= 0)
13✔
1312
                r = q;
×
1313

1314
        q = remove_subdirs(arg_esp_path, esp_subdirs);
13✔
1315
        if (q < 0 && r >= 0)
13✔
1316
                r = q;
×
1317

1318
        q = remove_subdirs(arg_esp_path, dollar_boot_subdirs);
13✔
1319
        if (q < 0 && r >= 0)
13✔
1320
                r = q;
×
1321

1322
        q = remove_entry_directory(arg_esp_path);
13✔
1323
        if (q < 0 && r >= 0)
13✔
1324
                r = q;
×
1325

1326
        if (arg_xbootldr_path) {
13✔
1327
                /* Remove a subset of these also from the XBOOTLDR partition if it exists */
1328

1329
                q = remove_file(arg_xbootldr_path, "/loader/entries.srel");
8✔
1330
                if (q < 0 && r >= 0)
8✔
1331
                        r = q;
×
1332

1333
                q = remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs);
8✔
1334
                if (q < 0 && r >= 0)
8✔
1335
                        r = q;
×
1336

1337
                q = remove_entry_directory(arg_xbootldr_path);
8✔
1338
                if (q < 0 && r >= 0)
8✔
1339
                        r = q;
×
1340
        }
1341

1342
        (void) sync_everything();
13✔
1343

1344
        if (!touch_variables())
13✔
1345
                return r;
1346

1347
        if (arg_arch_all) {
×
1348
                log_info("Not changing EFI variables with --all-architectures.");
×
1349
                return r;
×
1350
        }
1351

1352
        char *path = strjoina("/EFI/systemd/systemd-boot", get_efi_arch(), ".efi");
×
1353
        q = remove_variables(uuid, path, true);
×
1354
        if (q < 0 && r >= 0)
×
1355
                r = q;
×
1356

1357
        q = remove_loader_variables();
×
1358
        if (q < 0 && r >= 0)
×
1359
                r = q;
×
1360

1361
        return r;
1362
}
1363

1364
int verb_is_installed(int argc, char *argv[], void *userdata) {
12✔
1365
        int r;
12✔
1366

1367
        r = acquire_esp(/* unprivileged_mode= */ false,
12✔
1368
                        /* graceful= */ arg_graceful,
1369
                        NULL, NULL, NULL, NULL, NULL);
1370
        if (r < 0)
12✔
1371
                return r;
1372

1373
        r = are_we_installed(arg_esp_path);
12✔
1374
        if (r < 0)
12✔
1375
                return r;
1376

1377
        if (r > 0) {
12✔
1378
                if (!arg_quiet)
6✔
1379
                        puts("yes");
6✔
1380
                return EXIT_SUCCESS;
6✔
1381
        } else {
1382
                if (!arg_quiet)
6✔
1383
                        puts("no");
6✔
1384
                return EXIT_FAILURE;
6✔
1385
        }
1386
}
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