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

systemd / systemd / 24165447443

08 Apr 2026 10:44PM UTC coverage: 72.303% (+0.1%) from 72.175%
24165447443

push

github

bluca
compress: write sparse files when decompressing to regular files

Core dumps are often very sparse, containing large zero-filled regions
whose actual disk usage can be significantly reduced by preserving
holes. Previously, decompress_stream() always wrote dense output,
expanding all zero regions into allocated disk blocks.

Each decompression backend (xz, lz4, zstd) now auto-detects whether the
output fd is suitable for sparse writes via a shared should_sparse()
helper. The check requires both S_ISREG (regular file) and !O_APPEND,
since O_APPEND causes write() to ignore the file position set by
lseek(), which would collapse the holes and corrupt the output. For
pipes, sockets, and append-mode files, dense writes are preserved via
loop_write_full() with USEC_INFINITY timeout, matching the original
behavior. After sparse decompression, finalize_sparse() sets the final
file size to account for any trailing holes.

This is transparent to callers — all public signatures are unchanged.
coredumpctl benefits automatically:
- coredumpctl debug: temp file in /var/tmp is now sparse
- coredumpctl dump -o file: output file is now sparse
- coredumpctl dump > file: redirected stdout is now sparse
- coredumpctl dump | ...: pipe output unchanged (dense)
- coredumpctl dump >> file: append mode, falls back to dense

Co-developed-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-developed-by: Codex (GPT-5) <noreply@openai.com>

123 of 132 new or added lines in 2 files covered. (93.18%)

5704 existing lines in 82 files now uncovered.

319660 of 442111 relevant lines covered (72.3%)

1196031.58 hits per line

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

74.81
/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 "sd-device.h"
7
#include "sd-varlink.h"
8

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

48
typedef enum InstallOperation {
49
        INSTALL_NEW,
50
        INSTALL_UPDATE,
51
        INSTALL_REMOVE,
52
        INSTALL_TEST,
53
        _INSTALL_OPERATION_MAX,
54
        _INSTALL_OPERATION_INVALID = -1,
55
} InstallOperation;
56

57
typedef struct InstallContext {
58
        InstallOperation operation;
59
        bool graceful;
60
        char *root;
61
        int root_fd;
62
        sd_id128_t machine_id;
63
        char *install_layout;
64
        BootEntryTokenType entry_token_type;
65
        char *entry_token;
66
        int make_entry_directory; /* tri-state */
67
        InstallSource install_source;
68
        char *esp_path;
69
        int esp_fd;
70
        uint32_t esp_part;
71
        uint64_t esp_pstart;
72
        uint64_t esp_psize;
73
        sd_id128_t esp_uuid;
74
        char *xbootldr_path;
75
        int xbootldr_fd;
76
#if HAVE_OPENSSL
77
        X509 *secure_boot_certificate;
78
        EVP_PKEY *secure_boot_private_key;
79
#endif
80
        int touch_variables; /* tri-state */
81
} InstallContext;
82

83
#define INSTALL_CONTEXT_NULL                                            \
84
        (InstallContext) {                                              \
85
                .operation = _INSTALL_OPERATION_INVALID,                \
86
                .root_fd = -EBADF,                                      \
87
                .entry_token_type = _BOOT_ENTRY_TOKEN_TYPE_INVALID,     \
88
                .make_entry_directory = -1,                             \
89
                .install_source = _INSTALL_SOURCE_INVALID,              \
90
                .esp_part = UINT32_MAX,                                 \
91
                .esp_pstart = UINT64_MAX,                               \
92
                .esp_psize = UINT64_MAX,                                \
93
                .esp_fd = -EBADF,                                       \
94
                .xbootldr_fd = -EBADF,                                  \
95
                .touch_variables = -1,                                  \
96
        }
97

98
static const char* install_operation_table[_INSTALL_OPERATION_MAX] = {
99
        [INSTALL_NEW]    = "new",
100
        [INSTALL_UPDATE] = "update",
101
        [INSTALL_REMOVE] = "remove",
102
        [INSTALL_TEST]   = "test",
103
};
104

UNCOV
105
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(install_operation, InstallOperation);
×
106

107
static void install_context_done(InstallContext *c) {
330✔
108
        assert(c);
330✔
109

110
        c->root = mfree(c->root);
330✔
111
        c->root_fd = safe_close(c->root_fd);
330✔
112
        c->install_layout = mfree(c->install_layout);
330✔
113
        c->entry_token = mfree(c->entry_token);
330✔
114
        c->esp_path = mfree(c->esp_path);
330✔
115
        c->esp_fd = safe_close(c->esp_fd);
330✔
116
        c->xbootldr_path = mfree(c->xbootldr_path);
330✔
117
        c->xbootldr_fd = safe_close(c->xbootldr_fd);
330✔
118
#if HAVE_OPENSSL
119
        if (c->secure_boot_private_key) {
330✔
120
                EVP_PKEY_free(c->secure_boot_private_key);
1✔
121
                c->secure_boot_private_key = NULL;
1✔
122
        }
123
        if (c->secure_boot_certificate) {
330✔
124
                X509_free(c->secure_boot_certificate);
1✔
125
                c->secure_boot_certificate = NULL;
1✔
126
        }
127
#endif
128
}
330✔
129

130
static int install_context_from_cmdline(
165✔
131
                InstallContext *ret,
132
                InstallOperation operation) {
133

134
        int r;
165✔
135

136
        assert(ret);
165✔
137
        assert(operation >= 0);
165✔
138
        assert(operation < _INSTALL_OPERATION_MAX);
165✔
139

140
        _cleanup_(install_context_done) InstallContext b = INSTALL_CONTEXT_NULL;
165✔
141
        b.operation = operation;
165✔
142
        b.graceful = arg_graceful() == ARG_GRACEFUL_FORCE ||
165✔
143
                (operation == INSTALL_UPDATE && arg_graceful() != ARG_GRACEFUL_NO);
125✔
144
        b.machine_id = arg_machine_id;
165✔
145
        b.entry_token_type = arg_entry_token_type;
165✔
146
        b.make_entry_directory = arg_make_entry_directory;
165✔
147
        b.install_source = arg_install_source;
165✔
148

149
        if (strdup_to(&b.entry_token, arg_entry_token) < 0 ||
165✔
150
            strdup_to(&b.install_layout, arg_install_layout) < 0)
165✔
151
                return log_oom();
×
152

153
        if (arg_root) {
165✔
154
                b.root_fd = open(arg_root, O_CLOEXEC|O_DIRECTORY|O_PATH);
28✔
155
                if (b.root_fd < 0)
28✔
156
                        return log_error_errno(errno, "Failed to open root directory '%s': %m", arg_root);
×
157

158
                r = strdup_to(&b.root, arg_root);
28✔
159
                if (r < 0)
28✔
160
                        return log_oom();
×
161
        } else
162
                b.root_fd = XAT_FDROOT;
137✔
163

164
        r = acquire_esp(/* unprivileged_mode= */ false,
330✔
165
                        b.graceful,
165✔
166
                        &b.esp_part,
167
                        &b.esp_pstart,
168
                        &b.esp_psize,
169
                        &b.esp_uuid,
170
                        /* ret_devid= */ NULL);
171
        /* If --graceful is specified and we can't find an ESP, handle this cleanly */
172
        if (r < 0 && (!b.graceful || r != -ENOKEY))
165✔
173
                return r;
174

175
        if (r >= 0) { /* An ESP has been found */
165✔
176
                assert(arg_esp_path);
165✔
177

178
                if (arg_root) {
165✔
179
                        const char *e = path_startswith(arg_esp_path, arg_root);
28✔
180
                        if (!e)
28✔
181
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "ESP path '%s' not below specified root '%s', refusing.", arg_esp_path, arg_root);
×
182

183
                        r = strdup_to(&b.esp_path, e);
28✔
184
                } else
185
                        r = strdup_to(&b.esp_path, arg_esp_path);
137✔
186
                if (r < 0)
165✔
187
                        return log_oom();
×
188
        }
189

190
        r = acquire_xbootldr(
165✔
191
                        /* unprivileged_mode= */ false,
192
                        /* ret_uuid= */ NULL,
193
                        /* ret_devid= */ NULL);
194
        if (r < 0)
165✔
195
                return r;
196
        if (r > 0) { /* XBOOTLDR has been found */
165✔
197
                assert(arg_xbootldr_path);
28✔
198

199
                if (arg_root) {
28✔
200
                        const char *e = path_startswith(arg_xbootldr_path, arg_root);
28✔
201
                        if (!e)
28✔
202
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "XBOOTLDR path '%s' not below specified root '%s', refusing.", arg_xbootldr_path, arg_root);
×
203

204
                        r = strdup_to(&b.xbootldr_path, e);
28✔
205
                } else
206
                        r = strdup_to(&b.xbootldr_path, arg_xbootldr_path);
×
207
                if (r < 0)
28✔
208
                        return log_oom();
×
209
        }
210

211
        *ret = TAKE_GENERIC(b, InstallContext, INSTALL_CONTEXT_NULL);
165✔
212

213
        return !!ret->esp_path; /* return positive if we found an ESP */
165✔
214
}
215

216
static int acquire_esp_fd(InstallContext *c) {
858✔
217
        int r;
858✔
218

219
        assert(c);
858✔
220

221
        if (c->esp_fd >= 0)
858✔
222
                return c->esp_fd;
858✔
223

224
        assert(c->esp_path);
165✔
225

226
        _cleanup_free_ char *j = path_join(c->root, c->esp_path);
330✔
227
        if (!j)
165✔
228
                return log_oom();
×
229

230
        r = chaseat(c->root_fd,
330✔
231
                    c->esp_path,
165✔
232
                    CHASE_AT_RESOLVE_IN_ROOT|CHASE_TRIGGER_AUTOFS|CHASE_MUST_BE_DIRECTORY,
233
                    /* ret_path= */ NULL,
234
                    &c->esp_fd);
235
        if (r < 0)
165✔
236
                return log_error_errno(r, "Failed to open ESP '%s': %m", j);
×
237

238
        return c->esp_fd;
165✔
239
}
240

241
static int acquire_dollar_boot_fd(InstallContext *c) {
293✔
242
        int r;
293✔
243

244
        assert(c);
293✔
245

246
        if (c->xbootldr_fd >= 0)
293✔
247
                return c->xbootldr_fd;
293✔
248

249
        if (!c->xbootldr_path)
279✔
250
                return acquire_esp_fd(c);
259✔
251

252
        _cleanup_free_ char *j = path_join(c->root, c->xbootldr_path);
40✔
253
        if (!j)
20✔
254
                return log_oom();
×
255

256
        r = chaseat(c->root_fd,
40✔
257
                    c->xbootldr_path,
20✔
258
                    CHASE_AT_RESOLVE_IN_ROOT|CHASE_TRIGGER_AUTOFS|CHASE_MUST_BE_DIRECTORY,
259
                    /* ret_path= */ NULL,
260
                    &c->xbootldr_fd);
261
        if (r < 0)
20✔
262
                return log_error_errno(r, "Failed to open XBOOTLDR '%s': %m", j);
×
263

264
        return c->xbootldr_fd;
20✔
265
}
266

267
static const char* dollar_boot_path(InstallContext *c) {
293✔
268
        assert(c);
293✔
269

270
        return c->xbootldr_path ?: c->esp_path;
293✔
271
}
272

273
static bool should_touch_install_variables(InstallContext *c) {
148✔
274
        assert(c);
148✔
275

276
        if (c->touch_variables >= 0)
148✔
UNCOV
277
                return c->touch_variables;
×
278

279
        if (!is_efi_boot())  /* NB: this internally checks if we run in a container */
148✔
280
                return false;
281

282
        return empty_or_root(c->root);
38✔
283
}
284

285
static int load_etc_machine_id(InstallContext *c) {
151✔
286
        int r;
151✔
287

288
        assert(c);
151✔
289

290
        r = id128_get_machine_at(c->root_fd, &c->machine_id);
151✔
291
        if (ERRNO_IS_NEG_MACHINE_ID_UNSET(r)) /* Not set or empty */
151✔
292
                return 0;
293
        if (r < 0)
131✔
294
                return log_error_errno(r, "Failed to get machine-id: %m");
×
295

296
        log_debug("Loaded machine ID %s from '%s/etc/machine-id'.", strempty(c->root), SD_ID128_TO_STRING(c->machine_id));
250✔
297
        return 0;
131✔
298
}
299

300
static int load_etc_machine_info(InstallContext *c) {
151✔
301
        /* systemd v250 added support to store the kernel-install layout setting and the machine ID to use
302
         * for setting up the ESP in /etc/machine-info. The newer /etc/kernel/entry-token file, as well as
303
         * the $layout field in /etc/kernel/install.conf are better replacements for this though, hence this
304
         * has been deprecated and is only returned for compatibility. */
305
        _cleanup_free_ char *s = NULL, *layout = NULL;
×
306
        int r;
151✔
307

308
        assert(c);
151✔
309

310
        _cleanup_free_ char *j = path_join(c->root, "/etc/machine-info");
302✔
311
        if (!j)
151✔
312
                return log_oom();
×
313

314
        _cleanup_close_ int fd =
151✔
315
                chase_and_openat(
151✔
316
                                c->root_fd,
317
                                "/etc/machine-info",
318
                                CHASE_AT_RESOLVE_IN_ROOT|CHASE_MUST_BE_REGULAR,
319
                                O_RDONLY|O_CLOEXEC,
320
                                /* ret_path= */ NULL);
321
        if (fd == -ENOENT)
151✔
322
                return 0;
323
        if (fd < 0)
×
324
                return log_error_errno(fd, "Failed to open '%s': %m", j);
×
325

326
        r = parse_env_file_fd(
×
327
                        fd, "/etc/machine-info",
328
                        "KERNEL_INSTALL_LAYOUT", &layout,
329
                        "KERNEL_INSTALL_MACHINE_ID", &s);
330
        if (r < 0)
×
331
                return log_error_errno(r, "Failed to parse '%s': %m", j);
×
332

333
        if (!isempty(s)) {
×
334
                if (!arg_quiet)
×
335
                        log_notice("Read $KERNEL_INSTALL_MACHINE_ID from '%s'. "
×
336
                                   "Please move it to '%s/etc/kernel/entry-token'.", j, strempty(c->root));
337

338
                r = sd_id128_from_string(s, &c->machine_id);
×
339
                if (r < 0)
×
340
                        return log_error_errno(r, "Failed to parse KERNEL_INSTALL_MACHINE_ID=\"%s\" in '%s': %m", s, j);
×
341

342
                log_debug("Loaded KERNEL_INSTALL_MACHINE_ID=\"%s\" from '%s'.",
×
343
                          SD_ID128_TO_STRING(c->machine_id), j);
344
        }
345

346
        if (!isempty(layout)) {
151✔
347
                if (!arg_quiet)
×
348
                        log_notice("Read $KERNEL_INSTALL_LAYOUT from '%s'. "
×
349
                                   "Please move it to the layout= setting of '%s/etc/kernel/install.conf'.", j, strempty(c->root));
350

351
                log_debug("KERNEL_INSTALL_LAYOUT=\"%s\" is specified in '%s'.", layout, j);
×
352
                free_and_replace(c->install_layout, layout);
×
353
        }
354

355
        return 0;
356
}
357

358
static int load_kernel_install_layout(InstallContext *c) {
151✔
359
        _cleanup_free_ char *layout = NULL;
151✔
360
        int r;
151✔
361

362
        assert(c);
151✔
363

364
        const char *e = secure_getenv("KERNEL_INSTALL_CONF_ROOT");
151✔
365
        r = load_kernel_install_conf_at(
151✔
366
                        e ? NULL : c->root,
367
                        e ? XAT_FDROOT : c->root_fd,
368
                        e,
369
                        /* ret_machine_id= */ NULL,
370
                        /* ret_boot_root= */ NULL,
371
                        &layout,
372
                        /* ret_initrd_generator= */ NULL,
373
                        /* ret_uki_generator= */ NULL);
374
        if (r <= 0)
151✔
375
                return r;
376

377
        if (!isempty(layout)) {
151✔
378
                log_debug("layout=\"%s\" is specified in config.", layout);
×
379
                free_and_replace(c->install_layout, layout);
×
380
        }
381

382
        return 0;
383
}
384

385
static bool use_boot_loader_spec_type1(InstallContext *c) {
151✔
386
        assert(c);
151✔
387
        /* If the layout is not specified, or if it is set explicitly to "bls" we assume Boot Loader
388
         * Specification Type #1 is the chosen format for our boot loader entries */
389
        return !c->install_layout || streq(c->install_layout, "bls");
151✔
390
}
391

392
static int settle_make_entry_directory(InstallContext *c) {
151✔
393
        int r;
151✔
394

395
        assert(c);
151✔
396

397
        r = load_etc_machine_id(c);
151✔
398
        if (r < 0)
151✔
399
                return r;
400

401
        r = load_etc_machine_info(c);
151✔
402
        if (r < 0)
151✔
403
                return r;
404

405
        r = load_kernel_install_layout(c);
151✔
406
        if (r < 0)
151✔
407
                return r;
408

409
        const char *e = secure_getenv("KERNEL_INSTALL_CONF_ROOT");
151✔
410
        r = boot_entry_token_ensure_at(
151✔
411
                        e ? XAT_FDROOT : c->root_fd,
412
                        e,
413
                        c->machine_id,
414
                        /* machine_id_is_random= */ false,
415
                        &c->entry_token_type,
416
                        &c->entry_token);
417
        if (r < 0)
151✔
418
                return r;
419

420
        log_debug("Using entry token: %s", c->entry_token);
151✔
421

422
        bool layout_type1 = use_boot_loader_spec_type1(c);
151✔
423
        if (c->make_entry_directory < 0) { /* Automatic mode */
151✔
UNCOV
424
                if (layout_type1) {
×
UNCOV
425
                        if (c->entry_token_type == BOOT_ENTRY_TOKEN_MACHINE_ID) {
×
426
                                _cleanup_free_ char *j = path_join(c->root, "/etc/machine-id");
×
427
                                if (!j)
×
428
                                        return log_oom();
×
429

430
                                _cleanup_close_ int fd = -EBADF;
×
431
                                r = chaseat(c->root_fd,
×
432
                                            "/etc/machine-id",
433
                                            CHASE_AT_RESOLVE_IN_ROOT|CHASE_MUST_BE_REGULAR,
434
                                            /* ret_path= */ NULL,
435
                                            &fd);
436
                                if (r < 0)
×
437
                                        return log_debug_errno(r, "Unable to open '%s': %m", j);
×
438

439
                                r = fd_is_temporary_fs(fd);
×
440
                                if (r < 0)
×
441
                                        return log_debug_errno(r, "Couldn't determine whether '%s' is on a temporary file system: %m", j);
×
442

443
                                c->make_entry_directory = r == 0;
×
444
                        } else
UNCOV
445
                                c->make_entry_directory = true;
×
446
                } else
447
                        c->make_entry_directory = false;
×
448
        }
449

450
        if (c->make_entry_directory > 0 && !layout_type1)
151✔
451
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
452
                                       "KERNEL_INSTALL_LAYOUT=\"%s\" is configured, but Boot Loader Specification Type #1 entry directory creation was requested.",
453
                                       c->install_layout);
454

455
        return 0;
456
}
457

458
static int compare_product(const char *a, const char *b) {
250✔
459
        size_t x, y;
250✔
460

461
        assert(a);
250✔
462
        assert(b);
250✔
463

464
        x = strcspn(a, " ");
250✔
465
        y = strcspn(b, " ");
250✔
466
        if (x != y)
250✔
467
                return x < y ? -1 : x > y ? 1 : 0;
×
468

469
        return strncmp(a, b, x);
250✔
470
}
471

472
static int compare_version(const char *a, const char *b) {
250✔
473
        assert(a);
250✔
474
        assert(b);
250✔
475

476
        a += strcspn(a, " ");
250✔
477
        a += strspn(a, " ");
250✔
478
        b += strcspn(b, " ");
250✔
479
        b += strspn(b, " ");
250✔
480

481
        return strverscmp_improved(a, b);
250✔
482
}
483

484
static int version_check(int fd_from, const char *from, int fd_to, const char *to) {
250✔
485
        _cleanup_free_ char *a = NULL, *b = NULL;
250✔
486
        int r;
250✔
487

488
        assert(fd_from >= 0);
250✔
489
        assert(from);
250✔
490
        assert(fd_to >= 0);
250✔
491
        assert(to);
250✔
492

493
        /* Does not reposition file offset */
494

495
        r = get_file_version(fd_from, &a);
250✔
496
        if (r == -ESRCH)
250✔
497
                return log_notice_errno(r, "Source file \"%s\" does not carry version information!", from);
×
498
        if (r < 0)
250✔
499
                return r;
500

501
        r = get_file_version(fd_to, &b);
250✔
502
        if (r == -ESRCH)
250✔
503
                return log_info_errno(r, "Skipping \"%s\", it's owned by another boot loader (no version info found).", to);
×
504
        if (r < 0)
250✔
505
                return r;
506
        if (compare_product(a, b) != 0)
250✔
507
                return log_info_errno(SYNTHETIC_ERRNO(ESRCH),
×
508
                                      "Skipping \"%s\", it's owned by another boot loader.", to);
509

510
        r = compare_version(a, b);
250✔
511
        log_debug("Comparing versions: \"%s\" %s \"%s\"", a, comparison_operator(r), b);
488✔
512
        if (r < 0)
250✔
513
                return log_warning_errno(SYNTHETIC_ERRNO(ESTALE),
×
514
                                         "Skipping \"%s\", newer boot loader version in place already.", to);
515
        if (r == 0)
250✔
516
                return log_info_errno(SYNTHETIC_ERRNO(ESTALE),
250✔
517
                                      "Skipping \"%s\", same boot loader version in place already.", to);
518

519
        return 0;
520
}
521

522
static int copy_file_with_version_check(
288✔
523
                const char *source_path,
524
                int source_fd,
525
                const char *dest_path,
526
                int dest_parent_fd,
527
                const char *dest_filename,
528
                int dest_fd,
529
                bool force) {
530

531
        int r;
288✔
532

533
        assert(source_path);
288✔
534
        assert(source_fd >= 0);
288✔
535
        assert(dest_path);
288✔
536
        assert(dest_parent_fd >= 0);
288✔
537
        assert(dest_filename);
288✔
538

539
        if (!force && dest_fd >= 0) {
288✔
540
                r = version_check(source_fd, source_path, dest_fd, dest_path);
250✔
541
                if (r < 0)
250✔
542
                        return r;
288✔
543
        }
544

545
        _cleanup_free_ char *t = NULL;
38✔
546
        _cleanup_close_ int write_fd = -EBADF;
38✔
547
        write_fd = open_tmpfile_linkable_at(dest_parent_fd, dest_filename, O_WRONLY|O_CLOEXEC, &t);
38✔
548
        if (write_fd < 0)
38✔
549
                return log_error_errno(write_fd, "Failed to open \"%s\" for writing: %m", dest_path);
×
550

551
        CLEANUP_TMPFILE_AT(dest_parent_fd, t);
38✔
552

553
        /* Reset file offset before we start copying, since we copy this file multiple times, and the offset
554
         * might be left at the end of the file. (Resetting before rather than after a copy attempt is safer
555
         * because a previous attempt might have failed half-way, leaving the file offset at some undefined
556
         * place.) */
557
        r = copy_bytes(source_fd, write_fd, UINT64_MAX, COPY_REFLINK|COPY_SEEK0_SOURCE);
38✔
558
        if (r < 0)
38✔
559
                return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", source_path, dest_path);
×
560

561
        (void) copy_times(source_fd, write_fd, /* flags= */ 0);
38✔
562
        (void) fchmod(write_fd, 0644);
38✔
563

564
        r = link_tmpfile_at(write_fd, dest_parent_fd, t, dest_filename, LINK_TMPFILE_REPLACE|LINK_TMPFILE_SYNC);
38✔
565
        if (r < 0)
38✔
566
                return log_error_errno(r, "Failed to move data from \"%s\" to \"%s\": %m", source_path, dest_path);
×
567

568
        t = mfree(t); /* disarm CLEANUP_TMPFILE_AT() */
38✔
569

570
        log_info("Copied \"%s\" to \"%s\".", source_path, dest_path);
38✔
571
        return 0;
572
}
573

574
static int mkdir_one(const char *root, int root_fd, const char *path) {
124✔
575
        int r;
124✔
576

577
        assert(root);
124✔
578
        assert(root_fd >= 0);
124✔
579
        assert(path);
124✔
580

581
        _cleanup_free_ char *p = path_join(empty_to_root(root), path);
248✔
582
        if (!p)
124✔
583
                return log_oom();
×
584

585
        r = chaseat(root_fd,
124✔
586
                    path,
587
                    CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
588
                    /* ret_path= */ NULL,
589
                    /* ret_fd= */ NULL);
590
        if (r < 0)
124✔
591
                return log_error_errno(r, "Failed to create \"%s\": %m", p);
×
592

593
        log_info("Created directory \"%s\".", p);
124✔
594
        return 0;
595
}
596

597
static const char *const esp_subdirs[] = {
598
        /* The directories to place in the ESP */
599
        "EFI",
600
        "EFI/systemd",
601
        "EFI/BOOT",
602
        "loader",
603
        "loader/keys",
604
        NULL
605
};
606

607
static const char *const dollar_boot_subdirs[] = {
608
        /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
609
        "loader",
610
        "loader/entries",  /* Type #1 entries */
611
        "EFI",
612
        "EFI/Linux",       /* Type #2 entries */
613
        NULL
614
};
615

616
static int create_subdirs(const char *root, int root_fd, const char * const *subdirs) {
26✔
617
        int r;
26✔
618

619
        assert(root);
26✔
620
        assert(root_fd >= 0);
26✔
621

622
        STRV_FOREACH(i, subdirs) {
143✔
623
                r = mkdir_one(root, root_fd, *i);
117✔
624
                if (r < 0)
117✔
625
                        return r;
626
        }
627

628
        return 0;
629
}
630

631
static int update_efi_boot_binaries(
125✔
632
                InstallContext *c,
633
                const char *source_path,
634
                int source_fd,
635
                const char *ignore_filename) {
636

637
        int r, ret = 0;
125✔
638

639
        assert(c);
125✔
640
        assert(source_path);
125✔
641

642
        int esp_fd = acquire_esp_fd(c);
125✔
643
        if (esp_fd < 0)
125✔
644
                return esp_fd;
125✔
645

646
        _cleanup_free_ char *j = path_join(c->root, c->esp_path);
250✔
647
        if (!j)
125✔
648
                return log_oom();
×
649

650
        _cleanup_closedir_ DIR *d = NULL;
125✔
651
        r = chase_and_opendirat(
125✔
652
                        esp_fd,
653
                        "/EFI/BOOT",
654
                        CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MUST_BE_DIRECTORY,
655
                        /* ret_path= */ NULL,
656
                        &d);
657
        if (r == -ENOENT)
125✔
658
                return 0;
659
        if (r < 0)
125✔
660
                return log_error_errno(r, "Failed to open directory \"%s/EFI/BOOT\": %m", j);
×
661

662
        FOREACH_DIRENT(de, d, break) {
625✔
663
                _cleanup_close_ int fd = -EBADF;
625✔
664

665
                if (!endswith_no_case(de->d_name, ".efi"))
250✔
666
                        continue;
×
667

668
                if (strcaseeq_ptr(ignore_filename, de->d_name))
250✔
669
                        continue;
125✔
670

671
                fd = xopenat_full(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW, XO_REGULAR, /* mode= */ MODE_INVALID);
125✔
672
                if (fd < 0)
125✔
673
                        return log_error_errno(fd, "Failed to open \"%s/%s\" for reading: %m", j, de->d_name);
×
674

675
                r = pe_is_native_fd(fd);
125✔
676
                if (r < 0) {
125✔
677
                        log_warning_errno(r, "Failed to detect if \"%s/%s\" is for native architecture, ignoring: %m", j, de->d_name);
×
678
                        continue;
×
679
                }
680
                if (r == 0)
125✔
681
                        continue;
125✔
682

683
                _cleanup_free_ char *dest_path = path_join(j, "/EFI/BOOT", de->d_name);
×
684
                if (!dest_path)
×
685
                        return log_oom();
×
686

687
                r = copy_file_with_version_check(source_path, source_fd, dest_path, dirfd(d), de->d_name, fd, /* force= */ false);
×
688
                if (IN_SET(r, -ESTALE, -ESRCH))
×
689
                        continue;
×
690
                RET_GATHER(ret, r);
×
691
        }
692

693
        return ret;
694
}
695

696
static int copy_one_file(
144✔
697
                InstallContext *c,
698
                const char *name,
699
                bool force) {
700

701
        int r, ret = 0;
144✔
702

703
        assert(c);
144✔
704

705
        _cleanup_free_ char *dest_name = strdup(name);
144✔
706
        if (!dest_name)
144✔
707
                return log_oom();
×
708
        char *s = endswith_no_case(dest_name, ".signed");
144✔
709
        if (s)
144✔
710
                *s = 0;
144✔
711

712
        _cleanup_free_ char *sp = path_join(BOOTLIBDIR, name);
288✔
713
        if (!sp)
144✔
714
                return log_oom();
×
715

716
        _cleanup_free_ char *source_path = NULL;
144✔
717
        _cleanup_close_ int source_fd = -EBADF;
144✔
718
        if (IN_SET(c->install_source, INSTALL_SOURCE_AUTO, INSTALL_SOURCE_IMAGE)) {
144✔
719
                source_fd = chase_and_openat(
144✔
720
                                c->root_fd,
721
                                sp,
722
                                CHASE_AT_RESOLVE_IN_ROOT|CHASE_MUST_BE_REGULAR,
723
                                O_RDONLY|O_CLOEXEC,
724
                                &source_path);
725
                if (source_fd < 0 && (source_fd != -ENOENT || c->install_source != INSTALL_SOURCE_AUTO))
144✔
726
                        return log_error_errno(source_fd, "Failed to resolve path '%s' under directory '%s': %m", sp, c->root);
×
727

728
                /* If we had a root directory to try, we didn't find it and we are in auto mode, retry on the host */
729
        }
730
        if (source_fd < 0) {
16✔
731
                source_fd = chase_and_open(
16✔
732
                                sp,
733
                                /* root= */ NULL,
734
                                CHASE_MUST_BE_REGULAR,
735
                                O_RDONLY|O_CLOEXEC,
736
                                &source_path);
737
                if (source_fd < 0)
16✔
738
                        return log_error_errno(source_fd, "Failed to resolve path '%s': %m", sp);
×
739
        }
740

741
        int esp_fd = acquire_esp_fd(c);
144✔
742
        if (esp_fd < 0)
144✔
743
                return esp_fd;
744

745
        _cleanup_free_ char *j = path_join(c->root, c->esp_path);
288✔
746
        if (!j)
144✔
747
                return log_oom();
×
748

749
        _cleanup_close_ int dest_parent_fd = -EBADF;
144✔
750
        r = chaseat(esp_fd,
144✔
751
                    "/EFI/systemd",
752
                    CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
753
                    /* ret_path= */ NULL,
754
                    &dest_parent_fd);
755
        if (r < 0)
144✔
756
                return log_error_errno(r, "Failed to resolve path '/EFI/systemd' under directory '%s': %m", j);
×
757

758
        _cleanup_free_ char *dest_path = path_join(j, "/EFI/systemd", dest_name);
288✔
759
        if (!dest_path)
144✔
760
                return log_oom();
×
761

762
        _cleanup_close_ int dest_fd = xopenat_full(dest_parent_fd, dest_name, O_RDONLY|O_CLOEXEC, XO_REGULAR, MODE_INVALID);
288✔
763
        if (dest_fd < 0 && dest_fd != -ENOENT)
144✔
764
                return log_error_errno(dest_fd, "Failed to open '%s' under '%s/EFI/systemd' directory: %m", dest_name, j);
×
765

766
        /* Note that if this fails we do the second copy anyway, but return this error code,
767
         * so we stash it away in a separate variable. */
768
        ret = copy_file_with_version_check(source_path, source_fd, dest_path, dest_parent_fd, dest_name, dest_fd, force);
144✔
769

770
        const char *e = startswith(dest_name, "systemd-boot");
144✔
771
        if (e) {
144✔
772

773
                /* Create the EFI default boot loader name (specified for removable devices) */
774
                _cleanup_free_ char *boot_dot_efi = strjoin("BOOT", e);
288✔
775
                if (!boot_dot_efi)
144✔
776
                        return log_oom();
×
777

778
                ascii_strupper(boot_dot_efi);
144✔
779

780
                _cleanup_close_ int default_dest_parent_fd = -EBADF;
144✔
781
                r = chaseat(esp_fd,
144✔
782
                            "/EFI/BOOT",
783
                            CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
784
                            /* ret_path= */ NULL,
785
                            &default_dest_parent_fd);
786
                if (r < 0)
144✔
787
                        return log_error_errno(r, "Failed to resolve path '/EFI/BOOT/' under directory '%s': %m", j);
×
788

789
                _cleanup_free_ char *default_dest_path = path_join(j, "/EFI/BOOT", boot_dot_efi);
288✔
790
                if (!default_dest_path)
144✔
791
                        return log_oom();
×
792

793
                _cleanup_close_ int default_dest_fd = xopenat_full(default_dest_parent_fd, boot_dot_efi, O_RDONLY|O_CLOEXEC, XO_REGULAR, MODE_INVALID);
288✔
794
                if (default_dest_fd < 0 && default_dest_fd != -ENOENT)
144✔
795
                        return log_error_errno(default_dest_fd, "Failed to open '%s' under '%s/EFI/BOOT' directory: %m", boot_dot_efi, j);
×
796

797
                RET_GATHER(ret, copy_file_with_version_check(source_path, source_fd, default_dest_path, default_dest_parent_fd, boot_dot_efi, default_dest_fd, force));
144✔
798

799
                /* If we were installed under any other name in /EFI/BOOT/, make sure we update those
800
                 * binaries as well. */
801
                if (!force)
144✔
802
                        RET_GATHER(ret, update_efi_boot_binaries(c, source_path, source_fd, boot_dot_efi));
125✔
803
        }
804

805
        return ret;
806
}
807

808
static int install_binaries(
138✔
809
                InstallContext *c,
810
                const char *arch) {
811

812
        int r;
138✔
813

814
        assert(c);
138✔
815

816
        _cleanup_free_ char *source_path = NULL;
138✔
817
        _cleanup_closedir_ DIR *d = NULL;
138✔
818
        if (IN_SET(c->install_source, INSTALL_SOURCE_AUTO, INSTALL_SOURCE_IMAGE)) {
138✔
819
                r = chase_and_opendirat(
138✔
820
                                c->root_fd,
821
                                BOOTLIBDIR,
822
                                CHASE_AT_RESOLVE_IN_ROOT|CHASE_MUST_BE_DIRECTORY,
823
                                &source_path,
824
                                &d);
825
                if (r < 0 && (r != -ENOENT || c->install_source != INSTALL_SOURCE_AUTO))
138✔
826
                        return log_error_errno(r, "Failed to resolve path '%s' under directory '%s': %m", BOOTLIBDIR, c->root);
×
827

828
                /* If we had a root directory to try, we didn't find it and we are in auto mode, retry on the host */
829
        }
830
        if (!d) {
138✔
831
                r = chase_and_opendir(
12✔
832
                                BOOTLIBDIR,
833
                                /* root= */ NULL,
834
                                CHASE_MUST_BE_DIRECTORY,
835
                                &source_path,
836
                                &d);
837
                if (r == -ENOENT && c->graceful) {
12✔
838
                        log_debug("Source directory '%s' does not exist, ignoring.", BOOTLIBDIR);
×
839
                        return 0;
×
840
                }
841
                if (r < 0)
12✔
842
                        return log_error_errno(r, "Failed to resolve path '%s': %m", BOOTLIBDIR);
×
843
        }
844

845
        const char *suffix = strjoina(arch, ".efi");
690✔
846
        const char *suffix_signed = strjoina(arch, ".efi.signed");
690✔
847

848
        FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read \"%s\": %m", source_path)) {
1,518✔
849
                int k;
1,104✔
850

851
                if (endswith_no_case(de->d_name, suffix)) {
1,104✔
852
                        /* skip the .efi file, if there's a .signed version of it */
853
                        _cleanup_free_ const char *s = strjoin(de->d_name, ".signed");
288✔
854
                        if (!s)
144✔
855
                                return log_oom();
×
856
                        if (faccessat(dirfd(d), s, F_OK, 0) >= 0)
144✔
857
                                continue;
144✔
858
                } else if (!endswith_no_case(de->d_name, suffix_signed))
960✔
859
                        continue;
816✔
860

861
                k = copy_one_file(c, de->d_name, c->operation == INSTALL_NEW);
144✔
862
                /* Don't propagate an error code if no update necessary, installed version already equal or
863
                 * newer version, or other boot loader in place. */
864
                if (c->graceful && IN_SET(k, -ESTALE, -ESRCH))
144✔
865
                        continue;
122✔
866
                RET_GATHER(r, k);
22✔
867
        }
868

869
        return r;
870
}
871

872
static int install_loader_config(InstallContext *c) {
13✔
873
        int r;
13✔
874

875
        assert(c);
13✔
876
        assert(c->make_entry_directory >= 0);
13✔
877

878
        int esp_fd = acquire_esp_fd(c);
13✔
879
        if (esp_fd < 0)
13✔
880
                return esp_fd;
13✔
881

882
        _cleanup_free_ char *j = path_join(c->root, c->esp_path);
26✔
883
        if (!j)
13✔
884
                return log_oom();
×
885

886
        _cleanup_close_ int loader_dir_fd = -EBADF;
13✔
887
        r = chaseat(esp_fd,
13✔
888
                    "loader",
889
                    CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
890
                    /* ret_path= */ NULL,
891
                    &loader_dir_fd);
892
        if (r < 0)
13✔
893
                return log_error_errno(r, "Failed to open '/loader/' directory below '%s': %m", j);
×
894

895
        if (faccessat(loader_dir_fd, "loader.conf", F_OK, AT_SYMLINK_NOFOLLOW) < 0) {
13✔
896
                if (errno != ENOENT)
13✔
897
                        return log_error_errno(errno, "Failed to check if '/loader/loader.conf' exists below '%s': %m", j);
×
898
        } else /* Silently skip creation if the file already exists (early check) */
899
                return 0;
900

901
        _cleanup_free_ char *t = NULL;
13✔
902
        _cleanup_fclose_ FILE *f = NULL;
13✔
903
        r = fopen_tmpfile_linkable_at(loader_dir_fd, "loader.conf", O_WRONLY|O_CLOEXEC, &t, &f);
13✔
904
        if (r < 0)
13✔
905
                return log_error_errno(r, "Failed to open '%s/loader/loader.conf' for writing: %m", j);
×
906

907
        CLEANUP_TMPFILE_AT(loader_dir_fd, t);
13✔
908

909
        fprintf(f, "#timeout 3\n"
13✔
910
                   "#console-mode keep\n");
911

912
        if (c->make_entry_directory) {
13✔
913
                assert(c->entry_token);
7✔
914
                fprintf(f, "default %s-*\n", c->entry_token);
7✔
915
        }
916

917
        r = flink_tmpfile_at(f, loader_dir_fd, t, "loader.conf", LINK_TMPFILE_SYNC);
13✔
918
        if (r == -EEXIST)
13✔
919
                return 0; /* Silently skip creation if the file exists now (recheck) */
920
        if (r < 0)
13✔
921
                return log_error_errno(r, "Failed to move '%s/loader/loader.conf' into place: %m", j);
×
922

923
        t = mfree(t); /* disarm CLEANUP_TMPFILE_AT() */
13✔
924
        return 1;
13✔
925
}
926

927
static int install_loader_specification(InstallContext *c) {
135✔
928
        int r;
135✔
929

930
        assert(c);
135✔
931

932
        int dollar_boot_fd = acquire_dollar_boot_fd(c);
135✔
933
        if (dollar_boot_fd < 0)
135✔
934
                return dollar_boot_fd;
135✔
935

936
        _cleanup_free_ char *j = path_join(c->root, dollar_boot_path(c));
270✔
937
        if (!j)
135✔
938
                return log_oom();
×
939

940
        _cleanup_close_ int loader_dir_fd = -EBADF;
135✔
941
        r = chaseat(dollar_boot_fd,
135✔
942
                    "loader",
943
                    CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
944
                    /* ret_path= */ NULL,
945
                    &loader_dir_fd);
946
        if (r < 0)
135✔
947
                return log_error_errno(r, "Failed to pin '/loader' directory below '%s': %m", j);
×
948

949
        if (faccessat(loader_dir_fd, "entries.srel", F_OK, AT_SYMLINK_NOFOLLOW) < 0) {
135✔
950
                if (errno != ENOENT)
13✔
951
                        return log_error_errno(errno, "Failed to check if '/loader/entries.srel' exists below '%s': %m", j);
×
952
        } else /* Silently skip creation if the file already exists (early check) */
953
                return 0;
954

955
        _cleanup_free_ char *t = NULL;
13✔
956
        _cleanup_fclose_ FILE *f = NULL;
13✔
957
        r = fopen_tmpfile_linkable_at(loader_dir_fd, "entries.srel", O_WRONLY|O_CLOEXEC, &t, &f);
13✔
958
        if (r < 0)
13✔
959
                return log_error_errno(r, "Failed to open '%s/loader/entries.srel' for writing: %m", j);
×
960

961
        CLEANUP_TMPFILE_AT(loader_dir_fd, t);
13✔
962

963
        fprintf(f, "type1\n");
13✔
964

965
        r = flink_tmpfile_at(f, loader_dir_fd, t, "entries.srel", LINK_TMPFILE_SYNC);
13✔
966
        if (r == -EEXIST)
13✔
967
                return 0; /* Silently skip creation if the file exists now (recheck) */
968
        if (r < 0)
13✔
969
                return log_error_errno(r, "Failed to move '%s/loader/entries.srel' into place: %m", j);
×
970

971
        t = mfree(t); /* disarm CLEANUP_TMPFILE_AT() */
13✔
972
        return 1;
13✔
973
}
974

975
static int install_entry_directory(InstallContext *c) {
13✔
976
        assert(c);
13✔
977
        assert(c->make_entry_directory >= 0);
13✔
978

979
        if (!c->make_entry_directory)
13✔
980
                return 0;
13✔
981

982
        assert(c->entry_token);
7✔
983

984
        int dollar_boot_fd = acquire_dollar_boot_fd(c);
7✔
985
        if (dollar_boot_fd < 0)
7✔
986
                return dollar_boot_fd;
987

988
        _cleanup_free_ char *j = path_join(c->root, dollar_boot_path(c));
14✔
989
        if (!j)
7✔
990
                return log_oom();
×
991

992
        return mkdir_one(j, dollar_boot_fd, c->entry_token);
7✔
993
}
994

995
static int install_entry_token(InstallContext *c) {
13✔
996
        int r;
13✔
997

998
        assert(c);
13✔
999
        assert(c->make_entry_directory >= 0);
13✔
1000
        assert(c->entry_token);
13✔
1001

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

1005
        if (!c->make_entry_directory && c->entry_token_type == BOOT_ENTRY_TOKEN_MACHINE_ID)
13✔
1006
                return 0;
13✔
1007

1008
        const char *confdir = secure_getenv("KERNEL_INSTALL_CONF_ROOT") ?: "/etc/kernel/";
13✔
1009

1010
        _cleanup_free_ char *j = path_join(c->root, confdir);
26✔
1011
        if (!j)
13✔
1012
                return log_oom();
×
1013

1014
        _cleanup_close_ int dfd = -EBADF;
13✔
1015
        r = chaseat(c->root_fd,
13✔
1016
                    confdir,
1017
                    CHASE_AT_RESOLVE_IN_ROOT|CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
1018
                    /* ret_path= */ NULL,
1019
                    &dfd);
1020
        if (r < 0)
13✔
1021
                return log_error_errno(r, "Failed to open '%s': %m", j);
×
1022

1023
        r = write_string_file_at(dfd, "entry-token", c->entry_token, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755);
13✔
1024
        if (r < 0)
13✔
1025
                return log_error_errno(r, "Failed to write entry token '%s' to '%s/entry-token': %m", c->entry_token, j);
×
1026

1027
        return 0;
1028
}
1029

1030
#if HAVE_OPENSSL
1031
static int efi_timestamp(EFI_TIME *ret) {
1✔
1032
        struct tm tm = {};
1✔
1033
        int r;
1✔
1034

1035
        assert(ret);
1✔
1036

1037
        r = localtime_or_gmtime_usec(source_date_epoch_or_now(), /* utc= */ true, &tm);
1✔
1038
        if (r < 0)
1✔
1039
                return log_error_errno(r, "Failed to convert timestamp to calendar time: %m");
×
1040

1041
        *ret = (EFI_TIME) {
1✔
1042
                .Year = 1900 + tm.tm_year,
1✔
1043
                /* tm_mon starts at 0, EFI_TIME months start at 1. */
1044
                .Month = tm.tm_mon + 1,
1✔
1045
                .Day = tm.tm_mday,
1✔
1046
                .Hour = tm.tm_hour,
1✔
1047
                .Minute = tm.tm_min,
1✔
1048
                .Second = tm.tm_sec,
1✔
1049
        };
1050

1051
        return 0;
1✔
1052
}
1053
#endif
1054

1055
static int install_secure_boot_auto_enroll(InstallContext *c) {
13✔
1056
#if HAVE_OPENSSL
1057
        int r;
13✔
1058
#endif
1059

1060
        if (!arg_secure_boot_auto_enroll)
13✔
1061
                return 0;
13✔
1062

1063
#if HAVE_OPENSSL
1064
        if (!c->secure_boot_certificate || !c->secure_boot_private_key)
1✔
1065
                return 0;
1066

1067
        _cleanup_free_ uint8_t *dercert = NULL;
1✔
1068
        int dercertsz;
1✔
1069
        dercertsz = i2d_X509(c->secure_boot_certificate, &dercert);
1✔
1070
        if (dercertsz < 0)
1✔
1071
                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert X.509 certificate to DER: %s",
×
1072
                                       ERR_error_string(ERR_get_error(), NULL));
1073

1074
        int esp_fd = acquire_esp_fd(c);
1✔
1075
        if (esp_fd < 0)
1✔
1076
                return esp_fd;
1077

1078
        _cleanup_free_ char *j = path_join(c->root, c->esp_path);
2✔
1079
        if (!j)
1✔
1080
                return log_oom();
×
1081

1082
        _cleanup_close_ int keys_fd = -EBADF;
1✔
1083
        r = chaseat(esp_fd,
1✔
1084
                    "loader/keys/auto",
1085
                    CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
1086
                    /* ret_path= */ NULL,
1087
                    &keys_fd);
1088
        if (r < 0)
1✔
1089
                return log_error_errno(r, "Failed to chase /loader/keys/auto/ below '%s': %m", j);
×
1090

1091
        uint32_t siglistsz = offsetof(EFI_SIGNATURE_LIST, Signatures) + offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz;
1✔
1092
        /* We use malloc0() to zero-initialize the SignatureOwner field of Signatures[0]. */
1093
        _cleanup_free_ EFI_SIGNATURE_LIST *siglist = malloc0(siglistsz);
2✔
1094
        if (!siglist)
1✔
1095
                return log_oom();
×
1096

1097
        *siglist = (EFI_SIGNATURE_LIST) {
1✔
1098
                .SignatureType = EFI_CERT_X509_GUID,
1099
                .SignatureListSize = siglistsz,
1100
                .SignatureSize = offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz,
1✔
1101
        };
1102

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

1105
        EFI_TIME timestamp;
1✔
1106
        r = efi_timestamp(&timestamp);
1✔
1107
        if (r < 0)
1✔
1108
                return r;
1109

1110
        uint32_t attrs =
1✔
1111
                EFI_VARIABLE_NON_VOLATILE|
1112
                EFI_VARIABLE_BOOTSERVICE_ACCESS|
1113
                EFI_VARIABLE_RUNTIME_ACCESS|
1114
                EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1115

1116
        FOREACH_STRING(db, "PK", "KEK", "db") {
4✔
1117
                _cleanup_(BIO_freep) BIO *bio = NULL;
3✔
1118

1119
                bio = BIO_new(BIO_s_mem());
3✔
1120
                if (!bio)
3✔
1121
                        return log_oom();
×
1122

1123
                _cleanup_free_ char16_t *db16 = utf8_to_utf16(db, SIZE_MAX);
6✔
1124
                if (!db16)
3✔
1125
                        return log_oom();
×
1126

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

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

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

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

1139
                if (BIO_write(bio, &timestamp, sizeof(timestamp)) < 0)
3✔
1140
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write timestamp to bio");
×
1141

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

1145
                _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
3✔
1146
                p7 = PKCS7_sign(c->secure_boot_certificate, c->secure_boot_private_key, /* certs= */ NULL, bio, PKCS7_DETACHED|PKCS7_NOATTR|PKCS7_BINARY|PKCS7_NOSMIMECAP);
3✔
1147
                if (!p7)
3✔
1148
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to calculate PKCS7 signature: %s",
×
1149
                                               ERR_error_string(ERR_get_error(), NULL));
1150

1151
                _cleanup_free_ uint8_t *sig = NULL;
×
1152
                int sigsz = i2d_PKCS7(p7, &sig);
3✔
1153
                if (sigsz < 0)
3✔
1154
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert PKCS7 signature to DER: %s",
×
1155
                                               ERR_error_string(ERR_get_error(), NULL));
1156

1157
                size_t authsz = offsetof(EFI_VARIABLE_AUTHENTICATION_2, AuthInfo.CertData) + sigsz;
3✔
1158
                _cleanup_free_ EFI_VARIABLE_AUTHENTICATION_2 *auth = malloc(authsz);
×
1159
                if (!auth)
3✔
1160
                        return log_oom();
×
1161

1162
                *auth = (EFI_VARIABLE_AUTHENTICATION_2) {
3✔
1163
                        .TimeStamp = timestamp,
1164
                        .AuthInfo = {
1165
                                .Hdr = {
1166
                                        .dwLength = offsetof(WIN_CERTIFICATE_UEFI_GUID, CertData) + sigsz,
3✔
1167
                                        .wRevision = 0x0200,
1168
                                        .wCertificateType = 0x0EF1, /* WIN_CERT_TYPE_EFI_GUID */
1169
                                },
1170
                                .CertType = EFI_CERT_TYPE_PKCS7_GUID,
1171
                        }
1172
                };
1173

1174
                memcpy(auth->AuthInfo.CertData, sig, sigsz);
3✔
1175

1176
                _cleanup_free_ char *filename = strjoin(db, ".auth");
3✔
1177
                if (!filename)
3✔
1178
                        return log_oom();
×
1179

1180
                _cleanup_free_ char *t = NULL;
3✔
1181
                _cleanup_close_ int fd = open_tmpfile_linkable_at(keys_fd, filename, O_WRONLY|O_CLOEXEC, &t);
6✔
1182
                if (fd < 0)
3✔
1183
                        return log_error_errno(fd, "Failed to open secure boot auto-enrollment file for writing: %m");
×
1184

1185
                CLEANUP_TMPFILE_AT(keys_fd, t);
×
1186

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

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

1195
                r = link_tmpfile_at(fd, keys_fd, t, filename, LINK_TMPFILE_SYNC);
3✔
1196
                if (r < 0)
3✔
1197
                        return log_error_errno(errno, "Failed to link secure boot auto-enrollment file: %m");
×
1198

1199
                t = mfree(t); /* Disarm CLEANUP_TMPFILE_AT() */
3✔
1200

1201
                log_info("Secure boot auto-enrollment file '%s/loader/keys/auto/%s' successfully written.", j, filename);
3✔
1202
        }
1203

1204
        return 0;
1✔
1205
#else
1206
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Built without OpenSSL support, cannot set up auto-enrollment.");
1207
#endif
1208
}
1209

1210
static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
58✔
1211
        _cleanup_free_ char *opath = NULL;
58✔
1212
        sd_id128_t ouuid;
58✔
1213
        int r;
58✔
1214

1215
        r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
58✔
1216
        if (r < 0)
58✔
1217
                return false;
1218
        if (!sd_id128_equal(uuid, ouuid))
58✔
1219
                return false;
42✔
1220

1221
        /* Some motherboards convert the path to uppercase under certain circumstances
1222
         * (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
1223
         * so use case-insensitive checking */
1224
        if (!strcaseeq_ptr(path, opath))
16✔
1225
                return false;
9✔
1226

1227
        return true;
1228
}
1229

1230
static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
16✔
1231
        _cleanup_free_ uint16_t *options = NULL;
16✔
1232

1233
        assert(id);
16✔
1234

1235
        int n = efi_get_boot_options(&options);
16✔
1236
        if (n < 0)
16✔
1237
                return n;
1238

1239
        /* find already existing systemd-boot entry */
1240
        for (int i = 0; i < n; i++)
67✔
1241
                if (same_entry(options[i], uuid, path)) {
58✔
1242
                        *id = options[i];
7✔
1243
                        return 1;
7✔
1244
                }
1245

1246
        /* find free slot in the sorted BootXXXX variable list */
1247
        for (int i = 0; i < n; i++)
39✔
1248
                if (i != options[i]) {
30✔
1249
                        *id = i;
×
1250
                        return 0;
×
1251
                }
1252

1253
        /* use the next one */
1254
        if (n == 0xffff)
9✔
1255
                return -ENOSPC;
1256
        *id = n;
9✔
1257
        return 0;
9✔
1258
}
1259

1260
static int insert_into_order(InstallContext *c, uint16_t slot) {
13✔
1261
        _cleanup_free_ uint16_t *order = NULL;
13✔
1262
        uint16_t *t;
13✔
1263
        int n;
13✔
1264

1265
        assert(c);
13✔
1266

1267
        n = efi_get_boot_order(&order);
13✔
1268
        if (n <= 0)
13✔
1269
                /* no entry, add us */
1270
                return efi_set_boot_order(&slot, 1);
×
1271

1272
        /* are we the first and only one? */
1273
        if (n == 1 && order[0] == slot)
13✔
1274
                return 0;
1275

1276
        /* are we already in the boot order? */
1277
        for (int i = 0; i < n; i++) {
31✔
1278
                if (order[i] != slot)
25✔
1279
                        continue;
18✔
1280

1281
                /* we do not require to be the first one, all is fine */
1282
                if (c->operation != INSTALL_NEW)
7✔
1283
                        return 0;
1284

1285
                /* move us to the first slot */
1286
                memmove(order + 1, order, i * sizeof(uint16_t));
3✔
1287
                order[0] = slot;
3✔
1288
                return efi_set_boot_order(order, n);
3✔
1289
        }
1290

1291
        /* extend array */
1292
        t = reallocarray(order, n + 1, sizeof(uint16_t));
6✔
1293
        if (!t)
6✔
1294
                return -ENOMEM;
1295
        order = t;
6✔
1296

1297
        /* add us to the top or end of the list */
1298
        if (c->operation != INSTALL_NEW) {
6✔
1299
                memmove(order + 1, order, n * sizeof(uint16_t));
6✔
1300
                order[0] = slot;
6✔
1301
        } else
1302
                order[n] = slot;
×
1303

1304
        return efi_set_boot_order(order, n + 1);
6✔
1305
}
1306

1307
static int remove_from_order(uint16_t slot) {
×
1308
        _cleanup_free_ uint16_t *order = NULL;
×
1309
        int n;
×
1310

1311
        n = efi_get_boot_order(&order);
×
1312
        if (n <= 0)
×
1313
                return n;
1314

1315
        for (int i = 0; i < n; i++) {
×
1316
                if (order[i] != slot)
×
1317
                        continue;
×
1318

1319
                if (i + 1 < n)
×
1320
                        memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
×
1321
                return efi_set_boot_order(order, n - 1);
×
1322
        }
1323

1324
        return 0;
1325
}
1326

1327
static int pick_efi_boot_option_description(int esp_fd, char **ret) {
9✔
1328
        int r;
9✔
1329

1330
        assert(esp_fd >= 0);
9✔
1331
        assert(ret);
9✔
1332

1333
        /* early declarations, so that they are definitely initialized even if we follow any of the gotos */
1334
        _cleanup_(sd_device_unrefp) sd_device *d = NULL;
9✔
1335
        _cleanup_free_ char *j = NULL;
9✔
1336

1337
        const char *b = arg_efi_boot_option_description ?: "Linux Boot Manager";
9✔
1338
        if (!arg_efi_boot_option_description_with_device)
9✔
1339
                goto fallback;
9✔
1340

1341
        r = block_device_new_from_fd(
×
1342
                        esp_fd,
1343
                        BLOCK_DEVICE_LOOKUP_WHOLE_DISK|BLOCK_DEVICE_LOOKUP_BACKING,
1344
                        &d);
1345
        if (r < 0) {
×
1346
                log_debug_errno(r, "Failed to find backing device of ESP: %m");
×
1347
                goto fallback;
×
1348
        }
1349

1350
        const char *serial;
×
1351
        r = sd_device_get_property_value(d, "ID_SERIAL", &serial);
×
1352
        if (r < 0) {
×
1353
                log_debug_errno(r, "Unable to read ID_SERIAL field of backing device of ESP: %m");
×
1354
                goto fallback;
×
1355
        }
1356

1357
        j = strjoin(b, " (", serial, ")");
×
1358
        if (!j)
×
1359
                return log_oom();
×
1360

1361
        if (strlen(j) > EFI_BOOT_OPTION_DESCRIPTION_MAX) {
×
1362
                log_debug("Boot option string suffixed with device serial would be too long, skipping: %s", j);
×
1363
                j = mfree(j);
×
1364
                goto fallback;
×
1365
        }
1366

1367
        *ret = TAKE_PTR(j);
×
1368
        return 0;
×
1369

1370
fallback:
9✔
1371
        j = strdup(b);
9✔
1372
        if (!j)
9✔
1373
                return log_oom();
×
1374

1375
        *ret = TAKE_PTR(j);
9✔
1376
        return 0;
9✔
1377
}
1378

1379
static int install_variables(
13✔
1380
                InstallContext *c,
1381
                const char *path) {
1382

1383
        uint16_t slot;
13✔
1384
        int r;
13✔
1385

1386
        assert(c);
13✔
1387

1388
        int esp_fd = acquire_esp_fd(c);
13✔
1389
        if (esp_fd < 0)
13✔
1390
                return esp_fd;
13✔
1391

1392
        _cleanup_free_ char *j = path_join(c->root, c->esp_path);
26✔
1393
        if (!j)
13✔
1394
                return log_oom();
×
1395

1396
        r = chase_and_accessat(
13✔
1397
                        esp_fd,
1398
                        path,
1399
                        CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MUST_BE_REGULAR,
1400
                        F_OK,
1401
                        /* ret_path= */ NULL);
1402
        if (r == -ENOENT)
13✔
1403
                return 0;
1404
        if (r < 0)
13✔
1405
                return log_error_errno(r, "Cannot access \"%s/%s\": %m", j, skip_leading_slash(path));
×
1406

1407
        r = find_slot(c->esp_uuid, path, &slot);
13✔
1408
        if (r < 0) {
13✔
1409
                int level = c->graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
×
1410
                const char *skip = c->graceful ? ", skipping" : "";
×
1411

1412
                log_full_errno(level, r,
×
1413
                               r == -ENOENT ?
1414
                               "Failed to access EFI variables%s. Is the \"efivarfs\" filesystem mounted?" :
1415
                               "Failed to determine current boot order%s: %m", skip);
1416

1417
                return c->graceful ? 0 : r;
×
1418
        }
1419

1420
        bool existing = r > 0;
13✔
1421

1422
        if (c->operation == INSTALL_NEW || !existing) {
13✔
1423
                _cleanup_free_ char *description = NULL;
9✔
1424

1425
                r = pick_efi_boot_option_description(esp_fd, &description);
9✔
1426
                if (r < 0)
9✔
1427
                        return r;
1428

1429
                r = efi_add_boot_option(
9✔
1430
                                slot,
1431
                                description,
1432
                                c->esp_part,
1433
                                c->esp_pstart,
1434
                                c->esp_psize,
1435
                                c->esp_uuid,
1436
                                path);
1437
                if (r < 0) {
9✔
1438
                        int level = c->graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
×
1439
                        const char *skip = c->graceful ? ", skipping" : "";
×
1440

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

1443
                        return c->graceful ? 0 : r;
×
1444
                }
1445

1446
                log_info("%s EFI boot entry \"%s\".",
15✔
1447
                         existing ? "Updated" : "Created",
1448
                         description);
1449
        }
1450

1451
        return insert_into_order(c, slot);
13✔
1452
}
1453

1454
static int are_we_installed(InstallContext *c) {
139✔
1455
        int r;
139✔
1456

1457
        assert(c);
139✔
1458

1459
        /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
1460
         * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
1461
         * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
1462
         * should be a suitable and very minimal check for a number of reasons:
1463
         *
1464
         *  → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
1465
         *    not a specific one.)
1466
         *
1467
         *  → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
1468
         *    /EFI/BOOT/BOOT*.EFI fallback binary.
1469
         *
1470
         *  → It specifically checks for systemd-boot, not for other boot loaders (which a check for
1471
         *    /boot/loader/entries would do). */
1472

1473
        _cleanup_free_ char *p = path_join(c->esp_path, "/EFI/systemd");
278✔
1474
        if (!p)
139✔
1475
                return log_oom();
×
1476

1477
        int esp_fd = acquire_esp_fd(c);
139✔
1478
        if (esp_fd < 0)
139✔
1479
                return esp_fd;
1480

1481
        _cleanup_close_ int fd = chase_and_openat(
278✔
1482
                        esp_fd,
1483
                        "/EFI/systemd",
1484
                        CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MUST_BE_DIRECTORY,
1485
                        O_RDONLY|O_CLOEXEC|O_DIRECTORY,
1486
                        /* ret_path= */ NULL);
1487
        if (fd == -ENOENT)
139✔
1488
                return 0;
1489
        if (fd < 0)
132✔
1490
                return log_error_errno(fd, "Failed to open '%s': %m", p);
×
1491

1492
        log_debug("Checking whether '%s' contains any files%s", p, glyph(GLYPH_ELLIPSIS));
251✔
1493
        r = dir_is_empty_at(fd, /* path= */ NULL, /* ignore_hidden_or_backup= */ false);
132✔
1494
        if (r < 0 && r != -ENOENT)
132✔
1495
                return log_error_errno(r, "Failed to check whether '%s' contains any files: %m", p);
×
1496

1497
        return r == 0;
132✔
1498
}
1499

1500
#if HAVE_OPENSSL
1501
static int load_secure_boot_auto_enroll(
138✔
1502
                X509 **ret_certificate,
1503
                EVP_PKEY **ret_private_key,
1504
                OpenSSLAskPasswordUI **ret_ui) {
1505

1506
        int r;
138✔
1507

1508
        assert(ret_certificate);
138✔
1509
        assert(ret_private_key);
138✔
1510
        assert(ret_ui);
138✔
1511

1512
        if (!arg_secure_boot_auto_enroll) {
138✔
1513
                *ret_certificate = NULL;
137✔
1514
                *ret_private_key = NULL;
137✔
1515
                return 0;
137✔
1516
        }
1517

1518
        if (arg_certificate_source_type == OPENSSL_CERTIFICATE_SOURCE_FILE) {
1✔
1519
                r = parse_path_argument(arg_certificate, /* suppress_root= */ false, &arg_certificate);
1✔
1520
                if (r < 0)
1✔
1521
                        return r;
1522
        }
1523

1524
        _cleanup_(X509_freep) X509 *certificate = NULL;
138✔
1525
        r = openssl_load_x509_certificate(
1✔
1526
                        arg_certificate_source_type,
1527
                        arg_certificate_source,
1528
                        arg_certificate,
1529
                        &certificate);
1530
        if (r < 0)
1✔
1531
                return log_error_errno(r, "Failed to load X.509 certificate from %s: %m", arg_certificate);
×
1532

1533
        if (arg_private_key_source_type == OPENSSL_KEY_SOURCE_FILE) {
1✔
1534
                r = parse_path_argument(arg_private_key, /* suppress_root= */ false, &arg_private_key);
1✔
1535
                if (r < 0)
1✔
1536
                        return log_error_errno(r, "Failed to parse private key path %s: %m", arg_private_key);
×
1537
        }
1538

1539
        r = openssl_load_private_key(
2✔
1540
                        arg_private_key_source_type,
1541
                        arg_private_key_source,
1542
                        arg_private_key,
1543
                        &(AskPasswordRequest) {
1✔
1544
                                .tty_fd = -EBADF,
1545
                                .id = "bootctl-private-key-pin",
1546
                                .keyring = arg_private_key,
1547
                                .credential = "bootctl.private-key-pin",
1548
                                .until = USEC_INFINITY,
1549
                                .hup_fd = -EBADF,
1550
                        },
1551
                        ret_private_key,
1552
                        ret_ui);
1553
        if (r < 0)
1✔
1554
                return log_error_errno(r, "Failed to load private key from %s: %m", arg_private_key);
×
1555

1556
        *ret_certificate = TAKE_PTR(certificate);
1✔
1557

1558
        return 0;
1✔
1559
}
1560
#endif
1561

1562
static int run_install(InstallContext *c) {
138✔
1563
        int r;
138✔
1564

1565
        assert(c);
138✔
1566
        assert(c->operation >= 0);
138✔
1567

1568
        if (c->operation == INSTALL_UPDATE) {
138✔
1569
                /* If we are updating, don't do anything if sd-boot wasn't actually installed. */
1570
                r = are_we_installed(c);
125✔
1571
                if (r < 0)
125✔
1572
                        return r;
138✔
1573
                if (r == 0) {
125✔
1574
                        log_debug("Skipping update because sd-boot is not installed in the ESP.");
×
1575
                        return 0;
×
1576
                }
1577
        }
1578

1579
        r = settle_make_entry_directory(c);
138✔
1580
        if (r < 0)
138✔
1581
                return r;
1582

1583
        const char *arch = arg_arch_all ? "" : get_efi_arch();
138✔
1584

1585
        int esp_fd = acquire_esp_fd(c);
138✔
1586
        if (esp_fd < 0)
138✔
1587
                return esp_fd;
1588

1589
        _cleanup_free_ char *j = path_join(c->root, c->esp_path);
276✔
1590
        if (!j)
138✔
1591
                return log_oom();
×
1592

1593
        int dollar_boot_fd = acquire_dollar_boot_fd(c);
138✔
1594
        if (dollar_boot_fd < 0)
138✔
1595
                return dollar_boot_fd;
1596

1597
        _cleanup_free_ char *w = path_join(c->root, dollar_boot_path(c));
276✔
1598
        if (!w)
138✔
1599
                return log_oom();
×
1600

1601
        WITH_UMASK(0002) {
276✔
1602
                if (c->operation == INSTALL_NEW) {
138✔
1603
                        /* Don't create any of these directories when we are just updating. When we update
1604
                         * we'll drop-in our files (unless there are newer ones already), but we won't create
1605
                         * the directories for them in the first place. */
1606

1607
                        r = create_subdirs(j, esp_fd, esp_subdirs);
13✔
1608
                        if (r < 0)
13✔
1609
                                return r;
1610

1611
                        r = create_subdirs(w, dollar_boot_fd, dollar_boot_subdirs);
13✔
1612
                        if (r < 0)
13✔
1613
                                return r;
1614
                }
1615

1616
                r = install_binaries(c, arch);
138✔
1617
                if (r < 0)
138✔
1618
                        return r;
1619

1620
                if (c->operation == INSTALL_NEW) {
135✔
1621
                        r = install_loader_config(c);
13✔
1622
                        if (r < 0)
13✔
1623
                                return r;
1624

1625
                        r = install_entry_directory(c);
13✔
1626
                        if (r < 0)
13✔
1627
                                return r;
1628

1629
                        r = install_entry_token(c);
13✔
1630
                        if (r < 0)
13✔
1631
                                return r;
1632

1633
                        if (arg_install_random_seed && !c->root) {
13✔
1634
                                r = install_random_seed(c->esp_path);
5✔
1635
                                if (r < 0)
5✔
1636
                                        return r;
1637
                        }
1638

1639
                        r = install_secure_boot_auto_enroll(c);
13✔
1640
                        if (r < 0)
13✔
1641
                                return r;
1642
                }
1643

1644
                r = install_loader_specification(c);
135✔
1645
                if (r < 0)
135✔
1646
                        return r;
1647
        }
1648

1649
        (void) sync_everything();
135✔
1650

1651
        if (!should_touch_install_variables(c))
135✔
1652
                return 0;
1653

1654
        if (arg_arch_all) {
15✔
1655
                log_info("Not changing EFI variables with --all-architectures.");
2✔
1656
                return 0;
2✔
1657
        }
1658

1659
        char *path = strjoina("/EFI/systemd/systemd-boot", arch, ".efi");
91✔
1660
        return install_variables(c, path);
13✔
1661
}
1662

1663
int verb_install(int argc, char *argv[], uintptr_t _data, void *userdata) {
138✔
1664
        int r;
138✔
1665

1666
        /* Invoked for both "update" and "install" */
1667

1668
        _cleanup_(install_context_done) InstallContext c = INSTALL_CONTEXT_NULL;
×
1669
        r = install_context_from_cmdline(&c, streq(argv[0], "install") ? INSTALL_NEW : INSTALL_UPDATE);
138✔
1670
        if (r < 0)
138✔
1671
                return r;
1672
        if (r == 0) {
138✔
1673
                log_debug("No ESP found and operating in graceful mode, skipping.");
×
1674
                return 0;
×
1675
        }
1676

1677
#if HAVE_OPENSSL
1678
        _cleanup_(openssl_ask_password_ui_freep) OpenSSLAskPasswordUI *ui = NULL;
138✔
1679
        r = load_secure_boot_auto_enroll(&c.secure_boot_certificate, &c.secure_boot_private_key, &ui);
138✔
1680
        if (r < 0)
138✔
1681
                return r;
1682
#endif
1683

1684
        return run_install(&c);
138✔
1685
}
1686

1687
static int remove_boot_efi(InstallContext *c) {
13✔
1688
        int r, n = 0;
13✔
1689

1690
        assert(c);
13✔
1691

1692
        int esp_fd = acquire_esp_fd(c);
13✔
1693
        if (esp_fd < 0)
13✔
1694
                return esp_fd;
13✔
1695

1696
        _cleanup_free_ char *w = path_join(c->root, c->esp_path);
26✔
1697
        if (!w)
13✔
1698
                return log_oom();
×
1699

1700
        _cleanup_closedir_ DIR *d = NULL;
13✔
1701
        _cleanup_free_ char *p = NULL;
13✔
1702
        r = chase_and_opendirat(
13✔
1703
                        esp_fd,
1704
                        "/EFI/BOOT",
1705
                        CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MUST_BE_DIRECTORY,
1706
                        &p,
1707
                        &d);
1708
        if (r == -ENOENT)
13✔
1709
                return 0;
1710
        if (r < 0)
13✔
1711
                return log_error_errno(r, "Failed to open directory \"%s/EFI/BOOT\": %m", w);
×
1712

1713
        _cleanup_free_ char *j = path_join(w, p);
26✔
1714
        if (!j)
13✔
1715
                return log_oom();
×
1716

1717
        FOREACH_DIRENT(de, d, break) {
61✔
1718
                _cleanup_close_ int fd = -EBADF;
22✔
1719

1720
                if (!endswith_no_case(de->d_name, ".efi"))
22✔
1721
                        continue;
×
1722

1723
                _cleanup_free_ char *z = path_join(j, de->d_name);
31✔
1724
                if (!z)
22✔
1725
                        return log_oom();
×
1726

1727
                fd = xopenat_full(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW, XO_REGULAR, /* mode= */ MODE_INVALID);
22✔
1728
                if (fd < 0)
22✔
1729
                        return log_error_errno(fd, "Failed to open '%s' for reading: %m", z);
×
1730

1731
                r = pe_is_native_fd(fd);
22✔
1732
                if (r < 0) {
22✔
1733
                        log_warning_errno(r, "Failed to detect if '%s' is native architecture, ignoring: %m", z);
×
1734
                        continue;
×
1735
                }
1736
                if (r == 0)
22✔
1737
                        continue;
9✔
1738

1739
                _cleanup_free_ char *v = NULL;
13✔
1740
                r = get_file_version(fd, &v);
13✔
1741
                if (r == -ESRCH)
13✔
1742
                        continue;  /* No version information */
×
1743
                if (r < 0)
13✔
1744
                        return r;
1745
                if (!startswith(v, "systemd-boot "))
13✔
1746
                        continue;
×
1747

1748
                if (unlinkat(dirfd(d), de->d_name, 0) < 0)
13✔
1749
                        return log_error_errno(errno, "Failed to remove '%s': %m", z);
×
1750

1751
                log_info("Removed '%s'.", z);
13✔
1752

1753
                n++;
13✔
1754
        }
1755

1756
        log_debug("Removed %i EFI binaries from '%s'.", n, j);
13✔
1757
        return n;
1758
}
1759

1760
static int unlink_inode(const char *root, int root_fd, const char *path, mode_t type) {
271✔
1761
        int r;
271✔
1762

1763
        assert(root);
271✔
1764
        assert(root_fd >= 0);
271✔
1765
        assert(path);
271✔
1766
        assert(IN_SET(type, S_IFREG, S_IFDIR));
271✔
1767

1768
        _cleanup_free_ char *p = path_join(empty_to_root(root), path);
542✔
1769
        if (!p)
271✔
1770
                return log_oom();
×
1771

1772
        r = chase_and_unlinkat(
271✔
1773
                        root_fd,
1774
                        path,
1775
                        CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS,
1776
                        S_ISDIR(type) ? AT_REMOVEDIR : 0,
271✔
1777
                        /* ret_path= */ NULL);
1778
        if (r < 0) {
271✔
1779
                bool ignore = IN_SET(r, -ENOENT, -ENOTEMPTY);
152✔
1780
                log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, r, "Failed to remove '%s': %m", p);
152✔
1781
                return ignore ? 0 : r;
152✔
1782
        }
1783

1784
        log_info("Removed %s\"%s\".", S_ISDIR(type) ? "directory " : "", p);
155✔
1785
        return 0;
1786
}
1787

1788
static int remove_subdirs(const char *root, int root_fd, const char *const *subdirs) {
34✔
1789
        int r = 0;
34✔
1790

1791
        assert(root);
34✔
1792
        assert(root_fd);
34✔
1793

1794
        STRV_FOREACH_BACKWARDS(i, (char**) subdirs)
332✔
1795
                RET_GATHER(r, unlink_inode(root, root_fd, *i, S_IFDIR));
149✔
1796

1797
        return r;
34✔
1798
}
1799

1800
static int remove_entry_directory(InstallContext *c, const char *path, int fd) {
21✔
1801
        assert(c);
21✔
1802
        assert(c->make_entry_directory >= 0);
21✔
1803
        assert(path);
21✔
1804
        assert(fd >= 0);
21✔
1805

1806
        if (!c->make_entry_directory || !c->entry_token)
21✔
1807
                return 0;
1808

1809
        return unlink_inode(path, fd, c->entry_token, S_IFDIR);
10✔
1810
}
1811

1812
static int remove_binaries(InstallContext *c) {
13✔
1813
        int r;
13✔
1814

1815
        _cleanup_free_ char *p = path_join(c->root, "/EFI/systemd");
26✔
1816
        if (!p)
13✔
1817
                return log_oom();
×
1818

1819
        _cleanup_close_ int efi_fd = -EBADF;
13✔
1820
        r = chaseat(c->esp_fd,
13✔
1821
                    "EFI",
1822
                    CHASE_AT_RESOLVE_IN_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_MUST_BE_DIRECTORY,
1823
                    /* ret_path= */ NULL,
1824
                    &efi_fd);
1825
        if (r < 0) {
13✔
1826
                if (r != -ENOENT)
×
1827
                        return log_error_errno(r, "Failed to remove '%s': %m", p);
×
1828

1829
                r = 0;
1830
        } else
1831
                r = rm_rf_at(efi_fd, "systemd", REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK);
13✔
1832

1833
        return RET_GATHER(r, remove_boot_efi(c));
13✔
1834
}
1835

1836
static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
3✔
1837
        uint16_t slot;
3✔
1838
        int r;
3✔
1839

1840
        r = find_slot(uuid, path, &slot);
3✔
1841
        if (r != 1)
3✔
1842
                return 0;
3✔
1843

1844
        r = efi_remove_boot_option(slot);
×
1845
        if (r < 0)
×
1846
                return r;
1847

1848
        if (in_order)
×
1849
                return remove_from_order(slot);
×
1850

1851
        return 0;
1852
}
1853

1854
static int remove_loader_variables(void) {
3✔
1855
        int r = 0;
3✔
1856

1857
        /* Remove all persistent loader variables we define */
1858

1859
        FOREACH_STRING(var,
30✔
1860
                       EFI_LOADER_VARIABLE_STR("LoaderConfigConsoleMode"),
1861
                       EFI_LOADER_VARIABLE_STR("LoaderConfigTimeout"),
1862
                       EFI_LOADER_VARIABLE_STR("LoaderConfigTimeoutOneShot"),
1863
                       EFI_LOADER_VARIABLE_STR("LoaderEntryPreferred"),
1864
                       EFI_LOADER_VARIABLE_STR("LoaderEntryDefault"),
1865
                       EFI_LOADER_VARIABLE_STR("LoaderEntrySysFail"),
1866
                       EFI_LOADER_VARIABLE_STR("LoaderEntryLastBooted"),
1867
                       EFI_LOADER_VARIABLE_STR("LoaderEntryOneShot"),
1868
                       EFI_LOADER_VARIABLE_STR("LoaderSystemToken")) {
1869

1870
                int q;
27✔
1871

1872
                q = efi_set_variable(var, NULL, 0);
27✔
1873
                if (q == -ENOENT)
27✔
1874
                        continue;
24✔
1875
                if (q < 0)
3✔
1876
                        RET_GATHER(r, log_warning_errno(q, "Failed to remove EFI variable %s: %m", var));
×
1877
                else
1878
                        log_info("Removed EFI variable %s.", var);
3✔
1879
        }
1880

1881
        return r;
3✔
1882
}
1883

1884
int verb_remove(int argc, char *argv[], uintptr_t _data, void *userdata) {
13✔
1885
        sd_id128_t uuid = SD_ID128_NULL;
13✔
1886
        int r;
13✔
1887

1888
        _cleanup_(install_context_done) InstallContext c = INSTALL_CONTEXT_NULL;
13✔
1889
        r = install_context_from_cmdline(&c, INSTALL_REMOVE);
13✔
1890
        if (r < 0)
13✔
1891
                return r;
1892
        if (r == 0) {
13✔
1893
                log_debug("No ESP found and operating in graceful mode, skipping.");
×
1894
                return 0;
×
1895
        }
1896

1897
        r = settle_make_entry_directory(&c);
13✔
1898
        if (r < 0)
13✔
1899
                return r;
1900

1901
        int esp_fd = acquire_esp_fd(&c);
13✔
1902
        if (esp_fd < 0)
13✔
1903
                return esp_fd;
1904

1905
        _cleanup_free_ char *j = path_join(c.root, c.esp_path);
26✔
1906
        if (!j)
13✔
1907
                return log_oom();
×
1908

1909
        int dollar_boot_fd = acquire_dollar_boot_fd(&c); /* this will initialize .xbootldr_fd */
13✔
1910
        if (dollar_boot_fd < 0)
13✔
1911
                return dollar_boot_fd;
1912

1913
        _cleanup_free_ char *w = path_join(c.root, dollar_boot_path(&c));
26✔
1914
        if (!w)
13✔
1915
                return log_oom();
×
1916

1917
        r = remove_binaries(&c);
13✔
1918
        RET_GATHER(r, unlink_inode(j, esp_fd, "/loader/loader.conf", S_IFREG));
13✔
1919
        RET_GATHER(r, unlink_inode(j, esp_fd, "/loader/random-seed", S_IFREG));
13✔
1920
        RET_GATHER(r, unlink_inode(j, esp_fd, "/loader/entries.srel", S_IFREG));
13✔
1921

1922
        FOREACH_STRING(db, "PK.auth", "KEK.auth", "db.auth") {
52✔
1923
                _cleanup_free_ char *p = path_join("/loader/keys/auto", db);
78✔
1924
                if (!p)
39✔
1925
                        return log_oom();
×
1926

1927
                RET_GATHER(r, unlink_inode(j, esp_fd, p, S_IFREG));
39✔
1928
        }
1929
        RET_GATHER(r, unlink_inode(j, esp_fd, "/loader/keys/auto", S_IFDIR));
13✔
1930
        RET_GATHER(r, unlink_inode(j, esp_fd, "/loader/entries.srel", S_IFREG));
13✔
1931

1932
        RET_GATHER(r, remove_subdirs(j, esp_fd, esp_subdirs));
13✔
1933
        RET_GATHER(r, remove_subdirs(j, esp_fd, dollar_boot_subdirs));
13✔
1934
        RET_GATHER(r, remove_entry_directory(&c, j, esp_fd));
13✔
1935

1936
        if (c.xbootldr_fd >= 0) {
13✔
1937
                /* Remove a subset of these also from the XBOOTLDR partition if it exists */
1938
                RET_GATHER(r, unlink_inode(w, c.xbootldr_fd, "/loader/entries.srel", S_IFREG));
8✔
1939
                RET_GATHER(r, remove_subdirs(w, c.xbootldr_fd, dollar_boot_subdirs));
8✔
1940
                RET_GATHER(r, remove_entry_directory(&c, w, c.xbootldr_fd));
8✔
1941
        }
1942

1943
        (void) sync_everything();
13✔
1944

1945
        if (!should_touch_install_variables(&c))
13✔
1946
                return r;
1947

1948
        if (arg_arch_all) {
5✔
1949
                log_info("Not changing EFI variables with --all-architectures.");
2✔
1950
                return r;
2✔
1951
        }
1952

1953
        char *path = strjoina("/EFI/systemd/systemd-boot", get_efi_arch(), ".efi");
21✔
1954
        RET_GATHER(r, remove_variables(uuid, path, /* in_order= */ true));
3✔
1955
        return RET_GATHER(r, remove_loader_variables());
3✔
1956
}
1957

1958
int verb_is_installed(int argc, char *argv[], uintptr_t _data, void *userdata) {
14✔
1959
        int r;
14✔
1960

1961
        _cleanup_(install_context_done) InstallContext c = INSTALL_CONTEXT_NULL;
14✔
1962
        r = install_context_from_cmdline(&c, INSTALL_TEST);
14✔
1963
        if (r < 0)
14✔
1964
                return r;
1965
        if (r == 0) {
14✔
1966
                log_debug("No ESP found and operating in graceful mode, claiming not installed.");
×
1967
                if (!arg_quiet)
×
1968
                        puts("no");
×
1969
                return EXIT_FAILURE;
×
1970
        }
1971

1972
        r = are_we_installed(&c);
14✔
1973
        if (r < 0)
14✔
1974
                return r;
1975

1976
        if (r > 0) {
14✔
1977
                if (!arg_quiet)
7✔
1978
                        puts("yes");
7✔
1979
                return EXIT_SUCCESS;
7✔
1980
        } else {
1981
                if (!arg_quiet)
7✔
1982
                        puts("no");
7✔
1983
                return EXIT_FAILURE;
7✔
1984
        }
1985
}
1986

UNCOV
1987
static JSON_DISPATCH_ENUM_DEFINE(json_dispatch_install_operation, InstallOperation, install_operation_from_string);
×
1988
static JSON_DISPATCH_ENUM_DEFINE(json_dispatch_boot_entry_token_type, BootEntryTokenType, boot_entry_token_type_from_string);
×
1989

1990
typedef struct InstallParameters {
1991
        InstallContext context;
1992
        unsigned root_fd_index;
1993
} InstallParameters;
1994

UNCOV
1995
static void install_parameters_done(InstallParameters *p) {
×
UNCOV
1996
        assert(p);
×
1997

UNCOV
1998
        install_context_done(&p->context);
×
UNCOV
1999
}
×
2000

UNCOV
2001
int vl_method_install(
×
2002
                sd_varlink *link,
2003
                sd_json_variant *parameters,
2004
                sd_varlink_method_flags_t flags,
2005
                void *userdata) {
2006

UNCOV
2007
        int r;
×
2008

UNCOV
2009
        assert(link);
×
2010

UNCOV
2011
        _cleanup_(install_parameters_done) InstallParameters p = {
×
2012
                .context = INSTALL_CONTEXT_NULL,
2013
                .root_fd_index = UINT_MAX,
2014
        };
2015

UNCOV
2016
        static const sd_json_dispatch_field dispatch_table[] = {
×
2017
                { "operation",          SD_JSON_VARIANT_STRING,        json_dispatch_install_operation,     voffsetof(p, context.operation),        SD_JSON_MANDATORY },
2018
                { "graceful",           SD_JSON_VARIANT_BOOLEAN,       sd_json_dispatch_stdbool,            voffsetof(p, context.graceful),         0                 },
2019
                { "rootFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint,               voffsetof(p, root_fd_index),            0                 },
2020
                { "rootDirectory",      SD_JSON_VARIANT_STRING,        json_dispatch_path,                  voffsetof(p, context.root),             0                 },
2021
                { "bootEntryTokenType", SD_JSON_VARIANT_STRING,        json_dispatch_boot_entry_token_type, voffsetof(p, context.entry_token_type), 0                 },
2022
                { "touchVariables",     SD_JSON_VARIANT_BOOLEAN,       sd_json_dispatch_tristate,           voffsetof(p, context.touch_variables),  0                 },
2023
                {},
2024
        };
2025

UNCOV
2026
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
×
UNCOV
2027
        if (r != 0)
×
2028
                return r;
2029

UNCOV
2030
        if (!IN_SET(p.context.operation, INSTALL_NEW, INSTALL_UPDATE))
×
2031
                return sd_varlink_error_invalid_parameter_name(link, "operation");
×
2032

UNCOV
2033
        if (p.root_fd_index != UINT_MAX) {
×
2034
                p.context.root_fd = sd_varlink_peek_dup_fd(link, p.root_fd_index);
×
2035
                if (p.context.root_fd < 0)
×
2036
                        return log_debug_errno(p.context.root_fd, "Failed to acquire root fd from Varlink: %m");
×
2037

2038
                r = fd_verify_safe_flags_full(p.context.root_fd, O_DIRECTORY);
×
2039
                if (r < 0)
×
2040
                        return sd_varlink_error_invalid_parameter_name(link, "rootFileDescriptor");
×
2041

2042
                r = fd_verify_directory(p.context.root_fd);
×
2043
                if (r < 0)
×
2044
                        return log_debug_errno(r, "Specified file descriptor does not refer to a directory: %m");
×
2045

2046
                if (!p.context.root) {
×
2047
                        r = fd_get_path(p.context.root_fd, &p.context.root);
×
2048
                        if (r < 0)
×
2049
                                return log_debug_errno(r, "Failed to get path of file descriptor: %m");
×
2050

2051
                        if (empty_or_root(p.context.root))
×
2052
                                p.context.root = mfree(p.context.root);
×
2053
                }
UNCOV
2054
        } else if (p.context.root) {
×
2055
                p.context.root_fd = open(p.context.root, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
×
2056
                if (p.context.root_fd < 0)
×
2057
                        return log_debug_errno(errno, "Failed to open '%s': %m", p.context.root);
×
2058
        } else
UNCOV
2059
                p.context.root_fd = XAT_FDROOT;
×
2060

UNCOV
2061
        if (p.context.entry_token_type < 0)
×
UNCOV
2062
                p.context.entry_token_type = BOOT_ENTRY_TOKEN_AUTO;
×
2063

UNCOV
2064
        r = find_esp_and_warn_at_full(
×
2065
                        p.context.root_fd,
2066
                        /* path= */ NULL,
2067
                        /* unprivileged_mode= */ false,
2068
                        &p.context.esp_path,
2069
                        &p.context.esp_part,
2070
                        &p.context.esp_pstart,
2071
                        &p.context.esp_psize,
2072
                        &p.context.esp_uuid,
2073
                        /* ret_devid= */ NULL);
UNCOV
2074
        if (r == -ENOKEY)
×
2075
                return sd_varlink_error(link, "io.systemd.BootControl.NoESPFound", NULL);
×
UNCOV
2076
        if (r < 0)
×
2077
                return r;
2078

UNCOV
2079
        r = find_xbootldr_and_warn_at(
×
2080
                        p.context.root_fd,
2081
                        /* path= */ NULL,
2082
                        /* unprivileged_mode= */ false,
2083
                        &p.context.xbootldr_path);
UNCOV
2084
        if (r == -ENOKEY)
×
UNCOV
2085
                log_debug_errno(r, "Didn't find an XBOOTLDR partition, using ESP as $BOOT.");
×
2086
        else if (r < 0)
×
2087
                return r;
2088

UNCOV
2089
        r = run_install(&p.context);
×
UNCOV
2090
        if (r == -EUNATCH) /* no boot entry token is set */
×
2091
                return sd_varlink_error(link, "io.systemd.BootControl.BootEntryTokenUnavailable", NULL);
×
UNCOV
2092
        if (r < 0)
×
2093
                return r;
2094

UNCOV
2095
        return sd_varlink_reply(link, NULL);
×
2096
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc