HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/bootctl/bootctl-link.c

69,849 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: b6dacfc17cb04bbbc6ad315929b6d88dd1e9d6f6

Lines 1001–1721 of 1,721

                if (r < 0) {
                        if (!ERRNO_IS_NEG_DISK_SPACE(r))
                                return r;
                } else
                        break;
 
                log_notice("Attempt to link entry failed due to exhausted disk space, trying to remove oldest boot menu entry.");
 
                link_context_unlink_temporary(c);
                link_context_clear_profiles(c);
 
                if (link_context_unlink_oldest(c) <= 0) {
                        log_warning("Attempted to make space on $BOOT, but this failed, attempt to link entry failed.");
                        return r; /* propagate original error */
                }
 
                /* Close entry token dir here, quite possible the unlinking above might have removed it too, in case it was empty */
                c->entry_token_dir_fd = safe_close(c->entry_token_dir_fd);
 
                log_info("Removing oldest boot menu entry succeeded, will retry to create boot loader menu entry.");
                n_removals++;
        }
 
        _cleanup_free_ char *j = strv_join(c->linked_ids, "', '");
        if (!j)
                return log_oom();
 
        if (n_removals > 0)
                log_info("Successfully installed boot loader entries '%s', after removing %u old entries.", j, n_removals);
        else
                log_info("Successfully installed boot loader entries '%s'.", j);
 
        return 0;
}
 
int verb_link(int argc, char *argv[], uintptr_t data, void *userdata) {
        int r;
 
        assert(argc == 2);
 
        _cleanup_free_ char *x = NULL;
        r = parse_path_argument(argv[1], /* suppress_root= */ false, &x);
        if (r < 0)
                return r;
 
        _cleanup_(link_context_done) LinkContext c = LINK_CONTEXT_NULL;
        r = link_context_from_cmdline(&c, x);
        if (r < 0)
                return r;
 
        return run_link(&c);
}
 
/* Directories (relative to the operative root) below which "bootctl link-auto" looks for a staged UKI and
 * extra resources, in decreasing priority order. /var/lib/systemd/uki/ is where systemd-sysupdate stages
 * downloaded resources; the others follow the usual configuration search path precedence, with
 * /var/lib/ slotted in just below the volatile locations and above the vendor trees. */
static const char* const uki_auto_dirs[] = {
        "etc/systemd/uki",
        "run/systemd/uki",
        "var/lib/systemd/uki",
        "usr/local/lib/systemd/uki",
        "usr/lib/systemd/uki",
};
 
static const PickFilter pick_filter_uki = {
        .type_mask = UINT32_C(1) << DT_REG,
        .architecture = _ARCHITECTURE_INVALID,
        .suffix = ".efi",
};
 
/* The recognized suffixes of extra resources we pick up alongside the UKI. Each may appear as a plain file
 * (e.g. foo.sysext.raw) or as a versioned directory (e.g. foo.sysext.raw.v/) resolved via the vpick
 * mechanism. */
static const char* const auto_link_extra_suffixes[] = {
        ".sysext.raw",
        ".confext.raw",
        ".cred",
};
 
static int link_context_add_extra(LinkContext *c, int dir_fd, const char *path, const char *filename) {
        assert(c);
        assert(dir_fd >= 0);
        assert(path);
        assert(filename);
 
        if (!efi_loader_entry_resource_filename_valid(filename))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Extra file '%s' is not suitable for reference in a boot menu entry, refusing.", filename);
 
        _cleanup_close_ int fd = xopenat_full(dir_fd, path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY, XO_REGULAR, /* mode= */ MODE_INVALID);
        if (fd < 0)
                return log_error_errno(fd, "Failed to open extra file '%s': %m", path);
 
        _cleanup_free_ char *fn = strdup(filename);
        if (!fn)
                return log_oom();
 
        if (!GREEDY_REALLOC(c->extra, c->n_extra + 1))
                return log_oom();
 
        c->extra[c->n_extra++] = (ExtraFile) {
                .source_fd = TAKE_FD(fd),
                .filename = TAKE_PTR(fn),
                .temp_fd = -EBADF,
        };
 
        return 0;
}
 
/* Adds the extra resources found in <uki_dir_fd>/extras.d/ to the link context. The 'seen' set tracks the
 * logical resource names already added by a higher-priority directory, so the same resource appearing in
 * multiple directories is taken from the highest-priority one only. */
static int link_context_add_extras(LinkContext *c, int uki_dir_fd, Set **seen) {
        int r;
 
        assert(c);
        assert(uki_dir_fd >= 0);
        assert(seen);
 
        _cleanup_close_ int extras_dir_fd = chase_and_openat(
                        c->root_fd,
                        uki_dir_fd,
                        "extras.d",
                        /* chase_flags= */ 0,
                        O_DIRECTORY|O_CLOEXEC,
                        /* ret_path= */ NULL);
        if (extras_dir_fd == -ENOENT)
                return 0;
        if (extras_dir_fd < 0)
                return log_error_errno(extras_dir_fd, "Failed to open extras.d/ directory: %m");
 
        _cleanup_free_ DirectoryEntries *des = NULL;
        r = readdir_all(extras_dir_fd, RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE|RECURSE_DIR_SORT, &des);
        if (r < 0)
                return log_error_errno(r, "Failed to enumerate extras.d/ directory: %m");
 
        FOREACH_ARRAY(i, des->entries, des->n_entries) {
                struct dirent *de = *i;
 
                if (!IN_SET(de->d_type, DT_DIR, DT_REG))
                        continue;
 
                FOREACH_ELEMENT(suffix, auto_link_extra_suffixes) {
                        _cleanup_free_ char *dot_v = strjoin(*suffix, ".v");
                        if (!dot_v)
                                return log_oom();
 
                        bool versioned;
                        _cleanup_free_ char *key = NULL;
                        if (endswith(de->d_name, *suffix)) {
                                if (de->d_type != DT_REG)
                                        continue;
 
                                versioned = false;
                                key = strdup(de->d_name);
 
                        } else if (endswith(de->d_name, dot_v)) {
                                if (de->d_type != DT_DIR)
                                        continue;
 
                                /* The dedup key is the directory entry name with any trailing ".v" stripped, so that
                                 * a plain file and a versioned directory of the same resource collapse, and a
                                 * higher-priority directory wins. */
                                versioned = true;
                                key = strndup(de->d_name, strlen(de->d_name) - strlen(".v"));
                        } else
                                continue;
                        if (!key)
                                return log_oom();
 
                        if (set_contains(*seen, key))
                                break;
 
                        if (versioned) {
                                /* A versioned directory: resolve the best version via vpick, relative to the
                                 * extras directory fd. We deliberately do not honour boot-counting suffixes
                                 * here. */
                                _cleanup_(pick_result_done) PickResult pick = PICK_RESULT_NULL;
                                const PickFilter filter = {
                                        .type_mask = UINT32_C(1) << DT_REG,
                                        .architecture = _ARCHITECTURE_INVALID,
                                        .suffix = *suffix,
                                };
 
                                r = path_pick(/* root_path= */ NULL,
                                              /* root_fd= */ c->root_fd,
                                              /* dir_fd= */ extras_dir_fd,
                                              de->d_name,
                                              &filter,
                                              /* n_filters= */ 1,
                                              /* flags= */ 0,
                                              &pick);
                                if (r == -ENOENT || r == 0) {
                                        log_debug("No matching entry in versioned directory '%s', skipping.", de->d_name);
                                        break;
                                }
                                if (r < 0)
                                        return log_error_errno(r, "Failed to pick version in '%s': %m", de->d_name);
 
                                _cleanup_free_ char *fn = NULL;
                                r = path_extract_filename(pick.path, &fn);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to extract filename from '%s': %m", pick.path);
 
                                r = link_context_add_extra(c, extras_dir_fd, pick.path, fn);
                        } else
                                /* A plain file. */
                                r = link_context_add_extra(c, extras_dir_fd, de->d_name, de->d_name);
                        if (r < 0)
                                return r;
 
                        r = set_ensure_consume(seen, &string_hash_ops_free, TAKE_PTR(key));
                        if (r < 0)
                                return log_oom();
 
                        break;
                }
        }
 
        return 0;
}
 
/* Looks for a UKI (kernel.efi, or the best version in kernel.efi.v/) in the directory referenced by
 * uki_dir_fd and, if found, fills c->kernel_fd and c->kernel_filename. Returns 1 if found, 0 if not, and a
 * negative errno on error. We deliberately do not honour boot-counting suffixes here. */
static int link_context_find_kernel(LinkContext *c, int uki_dir_fd) {
        int r;
 
        assert(c);
        assert(uki_dir_fd >= 0);
 
        _cleanup_free_ char *filename = NULL;
        _cleanup_close_ int kernel_fd = xopenat_full(
                        uki_dir_fd, "kernel.efi",
                        O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW,
                        XO_REGULAR,
                        /* mode= */ MODE_INVALID);
        if (kernel_fd == -ENOENT) {
                _cleanup_(pick_result_done) PickResult pick = PICK_RESULT_NULL;
                r = path_pick(/* root_path= */ NULL,
                              /* root_fd= */ c->root_fd,
                              /* dir_fd= */ uki_dir_fd,
                              "kernel.efi.v",
                              &pick_filter_uki,
                              /* n_filters= */ 1,
                              /* flags= */ 0,
                              &pick);
                if (r == -ENOENT || r == 0)
                        return 0;
                if (r < 0)
                        return log_error_errno(r, "Failed to pick UKI version in 'kernel.efi.v': %m");
 
                r = path_extract_filename(pick.path, &filename);
                if (r < 0)
                        return log_error_errno(r, "Failed to extract filename from '%s': %m", pick.path);
 
                kernel_fd = fd_reopen(pick.fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
                if (kernel_fd < 0)
                        return log_error_errno(kernel_fd, "Failed to open UKI '%s': %m", pick.path);
 
                r = fd_verify_regular(kernel_fd);
                if (r < 0)
                        return log_error_errno(r, "UKI '%s' is not a regular file: %m", pick.path);
 
        } else if (kernel_fd < 0)
                return log_error_errno(kernel_fd, "Failed to open 'kernel.efi': %m");
        else {
                filename = strdup("kernel.efi");
                if (!filename)
                        return log_oom();
        }
 
        if (!efi_loader_entry_resource_filename_valid(filename))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "UKI '%s' is not suitable for reference in a boot menu entry.", filename);
 
        r = validate_kernel(kernel_fd, filename);
        if (r < 0)
                return r;
 
        c->kernel_fd = TAKE_FD(kernel_fd);
        c->kernel_filename = TAKE_PTR(filename);
        return 1;
}
 
/* Discovers the staged UKI and extra resources below the uki_auto_dirs[] (relative to the already-pinned
 * c->root_fd) and fills c->kernel_fd, c->kernel_filename and c->extra[] accordingly. The directories are
 * searched in priority order: the UKI is taken from the first directory that has one, and extra resources
 * are combined across all directories with higher-priority directories winning on conflicts. Returns 1 if a
 * UKI was found, 0 if there is nothing to link, and a negative errno on error. */
static int link_context_discover_resources(LinkContext *c) {
        _cleanup_set_free_ Set *seen = NULL;
        int r;
 
        assert(c);
 
        FOREACH_ELEMENT(dir, uki_auto_dirs) {
                _cleanup_close_ int uki_dir_fd = chase_and_openat(
                                /* root_fd= */ c->root_fd,
                                /* dir_fd= */ c->root_fd,
                                *dir,
                                CHASE_MUST_BE_DIRECTORY,
                                O_RDONLY|O_DIRECTORY|O_CLOEXEC,
                                /* ret_path= */ NULL);
                if (uki_dir_fd == -ENOENT)
                        continue;
                if (uki_dir_fd < 0)
                        return log_error_errno(uki_dir_fd, "Failed to open '%s': %m", *dir);
 
                /* Take the UKI from the first (highest-priority) directory that has one. */
                if (c->kernel_fd < 0) {
                        r = link_context_find_kernel(c, uki_dir_fd);
                        if (r < 0)
                                return r;
                }
 
                r = link_context_add_extras(c, uki_dir_fd, &seen);
                if (r < 0)
                        return r;
        }
 
        if (c->kernel_fd < 0) {
                log_debug("No UKI found in any of the search directories, nothing to link.");
                return 0;
        }
 
        return 1;
}
 
int verb_link_auto(int argc, char *argv[], uintptr_t data, void *userdata) {
        int r;
 
        assert(argc == 1);
 
        _cleanup_(link_context_done) LinkContext c = LINK_CONTEXT_NULL;
        r = link_context_from_cmdline_common(&c);
        if (r < 0)
                return r;
 
        r = link_context_discover_resources(&c);
        if (r < 0)
                return r;
        if (r == 0) {
                log_info("No UKI staged for linking, nothing to do.");
                return 0;
        }
 
        /* In addition to the auto-discovered resources, also honour any files passed via --extra=. */
        r = link_context_add_cmdline_extras(&c);
        if (r < 0)
                return r;
 
        r = link_context_acquire_dollar_boot(&c);
        if (r < 0)
                return r;
 
        return run_link(&c);
}
 
static JSON_DISPATCH_ENUM_DEFINE(json_dispatch_boot_entry_token_type, BootEntryTokenType, boot_entry_token_type_from_string);
 
typedef struct LinkParameters {
        LinkContext context;
        unsigned root_fd_index;
        unsigned kernel_fd_index;
        char *esp_path;
        char *xbootldr_path;
        sd_varlink *link;
} LinkParameters;
 
static void link_parameters_done(LinkParameters *p) {
        assert(p);
 
        link_context_done(&p->context);
        free(p->esp_path);
        free(p->xbootldr_path);
}
 
typedef struct ExtraParameters {
        ExtraFile extra_file;
        unsigned fd_index;
} ExtraParameters;
 
static void extra_parameters_done(ExtraParameters *p) {
        assert(p);
 
        extra_file_done(&p->extra_file);
}
 
static int json_dispatch_loader_entry_resource_filename(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
        char **n = ASSERT_PTR(userdata);
        const char *filename;
        int r;
 
        assert(variant);
 
        r = json_dispatch_const_filename(name, variant, flags, &filename);
        if (r < 0)
                return r;
 
        if (filename && !efi_loader_entry_resource_filename_valid(filename))
                return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a valid boot entry resource filename.", strna(name));
 
        if (free_and_strdup(n, filename) < 0)
                return json_log_oom(variant, flags);
 
        return 0;
}
 
static int dispatch_extras(const char *name, sd_json_variant *v, sd_json_dispatch_flags_t flags, void *userdata) {
        LinkParameters *c = ASSERT_PTR(userdata);
        int r;
 
        if (!sd_json_variant_is_array(v))
                return json_log(v, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an array.", strna(name));
 
        sd_json_variant *i;
        JSON_VARIANT_ARRAY_FOREACH(i, v) {
                _cleanup_(extra_parameters_done) ExtraParameters xp = {
                        .extra_file = EXTRA_FILE_NULL,
                        .fd_index = UINT_MAX,
                };
 
                static const sd_json_dispatch_field dispatch_table[] = {
                        { "filename",       SD_JSON_VARIANT_STRING,        json_dispatch_loader_entry_resource_filename, offsetof(ExtraParameters, extra_file.filename),  SD_JSON_MANDATORY },
                        { "fileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint,                        offsetof(ExtraParameters, fd_index),             0                 },
                        { "data",           SD_JSON_VARIANT_STRING,        json_dispatch_unbase64_iovec,                 offsetof(ExtraParameters, extra_file.data),      0                 },
                        {},
                };
 
                r = sd_json_dispatch(i, dispatch_table, /* flags= */ 0, &xp);
                if (r < 0)
                        return r;
 
                if (iovec_is_set(&xp.extra_file.data) == (xp.fd_index != UINT_MAX))
                        return sd_varlink_error_invalid_parameter_name(c->link, name);
                if (xp.fd_index != UINT_MAX) {
                        xp.extra_file.source_fd = sd_varlink_peek_dup_fd(c->link, xp.fd_index);
                        if (xp.extra_file.source_fd < 0)
                                return log_debug_errno(xp.extra_file.source_fd, "Failed to acquire extra fd from Varlink: %m");
 
                        r = fd_verify_safe_flags(xp.extra_file.source_fd);
                        if (r < 0)
                                return sd_varlink_error_invalid_parameter_name(c->link, name);
 
                        r = fd_verify_regular(xp.extra_file.source_fd);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to validate that the extra file is a regular file descriptor: %m");
                }
 
                if (!GREEDY_REALLOC(c->context.extra, c->context.n_extra+1))
                        return log_oom();
 
                c->context.extra[c->context.n_extra++] = TAKE_GENERIC(xp.extra_file, ExtraFile, EXTRA_FILE_NULL);
        }
 
        return 0;
}
 
/* Resolves the root_fd of the LinkContext from the dispatched Link/LinkAuto parameters, fills in the
 * boot entry token type default, and validates the entry title/version/commit fields. Returns 0 on success,
 * non-zero (Varlink error or negative errno) otherwise. */
static int vl_link_prepare(sd_varlink *link, LinkParameters *p) {
        int r;
 
        assert(link);
        assert(p);
 
        if (p->root_fd_index != UINT_MAX) {
                p->context.root_fd = sd_varlink_peek_dup_fd(link, p->root_fd_index);
                if (p->context.root_fd < 0)
                        return log_debug_errno(p->context.root_fd, "Failed to acquire root fd from Varlink: %m");
 
                r = fd_verify_safe_flags_full(p->context.root_fd, O_DIRECTORY);
                if (r < 0)
                        return sd_varlink_error_invalid_parameter_name(link, "rootFileDescriptor");
 
                r = fd_verify_directory(p->context.root_fd);
                if (r < 0)
                        return log_debug_errno(r, "Specified file descriptor does not refer to a directory: %m");
 
                if (!p->context.root) {
                        r = fd_get_path(p->context.root_fd, &p->context.root);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to get path of file descriptor: %m");
 
                        if (empty_or_root(p->context.root))
                                p->context.root = mfree(p->context.root);
                }
        } else if (p->context.root) {
                p->context.root_fd = open(p->context.root, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
                if (p->context.root_fd < 0)
                        return log_debug_errno(errno, "Failed to open '%s': %m", p->context.root);
        } else
                p->context.root_fd = XAT_FDROOT;
 
        if (p->context.entry_token_type < 0)
                p->context.entry_token_type = BOOT_ENTRY_TOKEN_AUTO;
 
        if (p->context.entry_title && !efi_loader_entry_title_valid(p->context.entry_title))
                return sd_varlink_error_invalid_parameter_name(link, "entryTitle");
 
        if (p->context.entry_version && !version_is_valid(p->context.entry_version, /* flags= */ 0))
                return sd_varlink_error_invalid_parameter_name(link, "entryVersion");
 
        if (p->context.entry_commit != 0 && !entry_commit_valid(p->context.entry_commit))
                return sd_varlink_error_invalid_parameter_name(link, "entryCommit");
 
        return 0;
}
 
/* Resolves $BOOT, runs the link operation and sends the reply. Expects the kernel and extra files to already
 * be set up in the context. If with_ids is true the reply carries the list of created entry IDs (as expected
 * by Link()/LinkAuto()), otherwise an empty reply is sent (as expected by
 * io.systemd.SysUpdate.Notify.OnCompletedUpdate(), which declares no output fields). */
static int vl_link_finish(sd_varlink *link, LinkParameters *p, bool with_ids) {
        int r;
 
        assert(link);
        assert(p);
 
        r = find_xbootldr_and_warn_at(
                        p->context.root_fd,
                        p->xbootldr_path,
                        /* unprivileged_mode= */ false,
                        &p->context.dollar_boot_path,
                        &p->context.dollar_boot_fd);
        if (r < 0) {
                if (r != -ENOKEY)
                        return r;
 
                /* No XBOOTLDR found, let's look for ESP then. */
 
                r = find_esp_and_warn_at(
                                p->context.root_fd,
                                p->esp_path,
                                /* unprivileged_mode= */ false,
                                &p->context.dollar_boot_path,
                                &p->context.dollar_boot_fd);
                if (r == -ENOKEY)
                        return sd_varlink_error(link, "io.systemd.BootControl.NoDollarBootFound", NULL);
                if (r < 0)
                        return r;
 
                p->context.dollar_boot_source = BOOT_ENTRY_ESP;
        } else
                p->context.dollar_boot_source = BOOT_ENTRY_XBOOTLDR;
 
        r = run_link(&p->context);
        if (r == -EUNATCH) /* no boot entry token is set */
                return sd_varlink_error(link, "io.systemd.BootControl.BootEntryTokenUnavailable", NULL);
        if (r < 0)
                return r;
 
        if (with_ids)
                return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_STRV("ids", p->context.linked_ids));
 
        return sd_varlink_reply(link, NULL);
}
 
int vl_method_link(
                sd_varlink *link,
                sd_json_variant *parameters,
                sd_varlink_method_flags_t flags,
                void *userdata) {
 
        int r;
 
        assert(link);
 
        _cleanup_(link_parameters_done) LinkParameters p = {
                .context = LINK_CONTEXT_NULL,
                .root_fd_index = UINT_MAX,
                .kernel_fd_index = UINT_MAX,
                .link = link,
        };
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "rootFileDescriptor",   _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint,                        voffsetof(p, root_fd_index),            0                 },
                { "rootDirectory",        SD_JSON_VARIANT_STRING,        json_dispatch_path,                           voffsetof(p, context.root),             0                 },
                { "espPath",              SD_JSON_VARIANT_STRING,        json_dispatch_path,                           voffsetof(p, esp_path),                 0                 },
                { "xbootldrPath",         SD_JSON_VARIANT_STRING,        json_dispatch_path,                           voffsetof(p, xbootldr_path),            0                 },
                { "bootEntryTokenType",   SD_JSON_VARIANT_STRING,        json_dispatch_boot_entry_token_type,          voffsetof(p, context.entry_token_type), 0                 },
                { "entryTitle",           SD_JSON_VARIANT_STRING,        sd_json_dispatch_string,                      voffsetof(p, context.entry_title),      0                 },
                { "entryVersion",         SD_JSON_VARIANT_STRING,        sd_json_dispatch_string,                      voffsetof(p, context.entry_version),    0                 },
                { "entryCommit",          SD_JSON_VARIANT_INTEGER,       sd_json_dispatch_uint64,                      voffsetof(p, context.entry_commit),     0                 },
                { "kernelFilename",       SD_JSON_VARIANT_STRING,        json_dispatch_loader_entry_resource_filename, voffsetof(p, context.kernel_filename),  SD_JSON_MANDATORY },
                { "kernelFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint,                        voffsetof(p, kernel_fd_index),          SD_JSON_MANDATORY },
                { "extraFiles",           SD_JSON_VARIANT_ARRAY,         dispatch_extras,                              0,                                      0                 },
                { "triesLeft",            _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint,                        voffsetof(p, context.tries_left),       0                 },
                { "keepFree",             _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64,                      voffsetof(p, context.keep_free),        0                 },
                {},
        };
 
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
        if (r != 0)
                return r;
 
        r = varlink_check_privileged_peer(link);
        if (r < 0)
                return r;
 
        r = vl_link_prepare(link, &p);
        if (r != 0)
                return r;
 
        p.context.kernel_fd = sd_varlink_peek_dup_fd(link, p.kernel_fd_index);
        if (p.context.kernel_fd < 0)
                return log_debug_errno(p.context.kernel_fd, "Failed to acquire kernel fd from Varlink: %m");
 
        r = fd_verify_safe_flags(p.context.kernel_fd);
        if (r < 0)
                return sd_varlink_error_invalid_parameter_name(link, "kernelFileDescriptor");
        r = fd_verify_regular(p.context.kernel_fd);
        if (r < 0)
                return log_debug_errno(r, "Failed to validate that kernel image file is a regular file descriptor: %m");
 
        /* Refuse non-UKIs for now. */
        KernelImageType kit = _KERNEL_IMAGE_TYPE_INVALID;
        r = inspect_kernel(p.context.kernel_fd, /* filename= */ NULL, &kit);
        if (r == -EBADMSG)
                return sd_varlink_error(link, "io.systemd.BootControl.InvalidKernelImage", NULL);
        if (r < 0)
                return r;
        if (kit != KERNEL_IMAGE_TYPE_UKI)
                return sd_varlink_error(link, "io.systemd.BootControl.InvalidKernelImage", NULL);
 
        return vl_link_finish(link, &p, /* with_ids= */ true);
}
 
int vl_method_link_auto(
                sd_varlink *link,
                sd_json_variant *parameters,
                sd_varlink_method_flags_t flags,
                void *userdata) {
 
        int r;
 
        assert(link);
 
        _cleanup_(link_parameters_done) LinkParameters p = {
                .context = LINK_CONTEXT_NULL,
                .root_fd_index = UINT_MAX,
                .kernel_fd_index = UINT_MAX,
                .link = link,
        };
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "rootFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint,               voffsetof(p, root_fd_index),            0 },
                { "rootDirectory",      SD_JSON_VARIANT_STRING,        json_dispatch_path,                  voffsetof(p, context.root),             0 },
                { "espPath",            SD_JSON_VARIANT_STRING,        json_dispatch_path,                  voffsetof(p, esp_path),                 0 },
                { "xbootldrPath",       SD_JSON_VARIANT_STRING,        json_dispatch_path,                  voffsetof(p, xbootldr_path),            0 },
                { "bootEntryTokenType", SD_JSON_VARIANT_STRING,        json_dispatch_boot_entry_token_type, voffsetof(p, context.entry_token_type), 0 },
                { "entryTitle",         SD_JSON_VARIANT_STRING,        sd_json_dispatch_string,             voffsetof(p, context.entry_title),      0 },
                { "entryVersion",       SD_JSON_VARIANT_STRING,        sd_json_dispatch_string,             voffsetof(p, context.entry_version),    0 },
                { "entryCommit",        SD_JSON_VARIANT_INTEGER,       sd_json_dispatch_uint64,             voffsetof(p, context.entry_commit),     0 },
                { "triesLeft",          _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint,               voffsetof(p, context.tries_left),       0 },
                { "keepFree",           _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64,             voffsetof(p, context.keep_free),        0 },
                {},
        };
 
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
        if (r != 0)
                return r;
 
        r = varlink_check_privileged_peer(link);
        if (r < 0)
                return r;
 
        r = vl_link_prepare(link, &p);
        if (r != 0)
                return r;
 
        r = link_context_discover_resources(&p.context);
        if (r < 0)
                return r;
        if (r == 0) /* Nothing staged for linking. */
                return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_STRV("ids", STRV_EMPTY));
 
        return vl_link_finish(link, &p, /* with_ids= */ true);
}
 
int vl_method_on_completed_update(
                sd_varlink *link,
                sd_json_variant *parameters,
                sd_varlink_method_flags_t flags,
                void *userdata) {
 
        int r;
 
        assert(link);
 
        /* Only honour update notifications if they come from root */
        r = varlink_check_privileged_peer(link);
        if (r < 0)
                return r;
 
        /* Triggered by systemd-sysupdate after an update completed. We deliberately ignore all parameters
         * (we don't even dispatch them) and behave like LinkAuto() with default parameters: discover the
         * staged UKI and extra resources and link them in. Contrary to LinkAuto() we reply without any
         * parameters, matching the io.systemd.SysUpdate.Notify.OnCompletedUpdate() signature. */
 
        _cleanup_(link_parameters_done) LinkParameters p = {
                .context = LINK_CONTEXT_NULL,
                .root_fd_index = UINT_MAX,
                .kernel_fd_index = UINT_MAX,
                .link = link,
        };
 
        r = vl_link_prepare(link, &p);
        if (r != 0)
                return r;
 
        r = link_context_discover_resources(&p.context);
        if (r < 0)
                return r;
        if (r == 0) /* Nothing staged for linking. */
                return sd_varlink_reply(link, NULL);
 
        return vl_link_finish(link, &p, /* with_ids= */ false);
}