HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/sysinstall/sysinstall.c

86,594 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 15f9030eead93872d6f325ccefe6e02869266389

Lines 1–1000 of 2,226

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <locale.h>
#include <sys/stat.h>
#include <unistd.h>
 
#include "sd-json.h"
#include "sd-varlink.h"
 
#include "alloc-util.h"
#include "ansi-color.h"
#include "blockdev-list.h"
#include "build.h"
#include "build-path.h"
#include "bus-polkit.h"
#include "chase.h"
#include "conf-files.h"
#include "constants.h"
#include "dlopen-note.h"
#include "efi-loader.h"
#include "efivars.h"
#include "env-file.h"
#include "escape.h"
#include "fd-util.h"
#include "find-esp.h"
#include "format-table.h"
#include "format-util.h"
#include "fs-util.h"
#include "glyph-util.h"
#include "hashmap.h"
#include "image-policy.h"
#include "json-util.h"
#include "locale-setup.h"
#include "log.h"
#include "loop-util.h"
#include "machine-credential.h"
#include "main-func.h"
#include "mount-util.h"
#include "os-util.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "path-util.h"
#include "prompt-util.h"
#include "string-table.h"
#include "strv.h"
#include "terminal-util.h"
#include "varlink-io.systemd.SysInstall.h"
#include "varlink-util.h"
#include "verbs.h"
 
static char *arg_node = NULL;
static bool arg_welcome = true;
static int arg_erase = -1;            /* tri-state */
static bool arg_confirm = true;
static bool arg_summary = true;
static char **arg_definitions = NULL;
static char *arg_kernel_image = NULL;
static bool arg_reboot = false;
static int arg_touch_variables = -1;  /* tri-state */
static MachineCredentialContext arg_credentials = {};
static bool arg_copy_locale = true;
static bool arg_copy_keymap = true;
static bool arg_copy_timezone = true;
static bool arg_chrome = true;
static bool arg_mute_console = false;
static bool arg_varlink = false;
 
STATIC_DESTRUCTOR_REGISTER(arg_node, freep);
STATIC_DESTRUCTOR_REGISTER(arg_definitions, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_kernel_image, freep);
STATIC_DESTRUCTOR_REGISTER(arg_credentials, machine_credential_context_done);
 
COMMAND(
        "systemd-sysinstall\0",
        "Install the OS to another block device.",
        .argspec = "[DEVICE]\0",
        .man_pages = "systemd-sysinstall(8)\0",
);
 
typedef enum ProgressPhase {
        PROGRESS_ENCRYPT_CREDENTIALS,
        PROGRESS_INSTALL_PARTITIONS,
        PROGRESS_MOUNT_PARTITIONS,
        PROGRESS_INSTALL_KERNEL,
        PROGRESS_INSTALL_BOOTLOADER,
        PROGRESS_UNMOUNT_PARTITIONS,
        _PROGRESS_PHASE_MAX,
        _PROGRESS_PHASE_INVALID = -EINVAL,
} ProgressPhase;
 
static const char *progress_phase_table[_PROGRESS_PHASE_MAX] = {
        [PROGRESS_ENCRYPT_CREDENTIALS] = "encrypt-credentials",
        [PROGRESS_INSTALL_PARTITIONS]  = "install-partitions",
        [PROGRESS_MOUNT_PARTITIONS]    = "mount-partitions",
        [PROGRESS_INSTALL_KERNEL]      = "install-kernel",
        [PROGRESS_INSTALL_BOOTLOADER]  = "install-bootloader",
        [PROGRESS_UNMOUNT_PARTITIONS]  = "unmount-partitions",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(progress_phase, ProgressPhase);
 
static const char *progress_phase_log_table[_PROGRESS_PHASE_MAX] = {
        [PROGRESS_ENCRYPT_CREDENTIALS] = "Encrypting credentials...",
        [PROGRESS_INSTALL_PARTITIONS]  = "Installing partitions...",
        [PROGRESS_MOUNT_PARTITIONS]    = "Mounting partitions...",
        [PROGRESS_INSTALL_KERNEL]      = "Installing kernel...",
        [PROGRESS_INSTALL_BOOTLOADER]  = "Installing boot loader...",
        [PROGRESS_UNMOUNT_PARTITIONS]  = "Unmounting partitions...",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(progress_phase_log, ProgressPhase);
 
typedef enum DeviceFit {
        DEVICE_FIT_ENOUGH_FREE_SPACE,
        DEVICE_FIT_INSUFFICIENT_FREE_SPACE,
        DEVICE_FIT_DISK_TOO_SMALL,
        DEVICE_FIT_CONFLICTING_DISK_LABEL_PRESENT,
        _DEVICE_FIT_MAX,
        _DEVICE_FIT_INVALID = -EINVAL,
} DeviceFit;
 
static const char *device_fit_table[_DEVICE_FIT_MAX] = {
        [DEVICE_FIT_ENOUGH_FREE_SPACE]              = "enough-free-space",
        [DEVICE_FIT_INSUFFICIENT_FREE_SPACE]        = "insufficient-free-space",
        [DEVICE_FIT_DISK_TOO_SMALL]                 = "disk-too-small",
        [DEVICE_FIT_CONFLICTING_DISK_LABEL_PRESENT] = "conflicting-disk-label-present",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(device_fit, DeviceFit);
 
typedef struct SysInstallContext {
        bool copy_locale;
        bool copy_keymap;
        bool copy_timezone;
        MachineCredentialContext credentials;
        char **definitions;
        bool erase;
        char *node;
        char *kernel_filename;
        int kernel_fd;
        bool touch_variables;
 
        sd_varlink *repart_link;
 
        sd_varlink *link; /* If 'more' is used on the Varlink call, we'll send progress info over this link */
} SysInstallContext;
 
static void sysinstall_context_done(SysInstallContext *c) {
        assert(c);
 
        strv_free(c->definitions);
 
        free(c->node);
 
        free(c->kernel_filename);
        safe_close(c->kernel_fd);
 
        machine_credential_context_done(&c->credentials);
 
        sd_varlink_flush_close_unref(c->repart_link);
 
        sd_varlink_unref(c->link);
}
 
static int parse_argv(int argc, char *argv[]) {
        int r;
 
        assert(argc >= 0);
        assert(argv);
 
        OptionParser opts = { argc, argv };
 
        FOREACH_OPTION_OR_RETURN(c, &opts)
                switch (c) {
 
                OPTION_COMMON_HELP:
                        return command_print_help();
 
                OPTION_COMMON_VERSION:
                        return version();
 
                OPTION_LONG("welcome", "no", "Disable the welcome text"):
                        r = parse_boolean_argument("--welcome=", opts.arg, &arg_welcome);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("erase", "BOOL", "Whether to erase the target disk"):
                        r = parse_tristate_argument_with_auto("--erase=", opts.arg, &arg_erase);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("confirm", "no", "Disable query for confirmation"):
                        r = parse_boolean_argument("--confirm=", opts.arg, &arg_confirm);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("summary", "no", "Disable summary before beginning operation"):
                        r = parse_boolean_argument("--summary=", opts.arg, &arg_summary);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("definitions", "DIR", "Find partition definitions in specified directory"): {
                        _cleanup_free_ char *path = NULL;
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &path);
                        if (r < 0)
                                return r;
                        if (strv_consume(&arg_definitions, TAKE_PTR(path)) < 0)
                                return log_oom();
                        break;
                }
 
                OPTION_LONG("reboot", "BOOL", "Whether to reboot after installation is complete"):
                        r = parse_boolean_argument("--reboot=", opts.arg, &arg_reboot);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("variables", "BOOL", "Whether to modify EFI variables"):
                        r = parse_tristate_argument_with_auto("--variables=", opts.arg, &arg_touch_variables);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("kernel", "IMAGE", "Explicitly pick kernel image to install"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_kernel_image);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("set-credential", "ID:VALUE", "Install a credential with literal value to target system"):
                        r = machine_credential_set(&arg_credentials, opts.arg);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("load-credential", "ID:PATH", "Load a credential to install to new system from file or AF_UNIX stream socket"):
                        r = machine_credential_load(&arg_credentials, opts.arg);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("copy-locale", "no", "Don't copy current locale to target system"):
                        r = parse_boolean_argument("--copy-locale=", opts.arg, &arg_copy_locale);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("copy-keymap", "no", "Don't copy current keymap to target system"):
                        r = parse_boolean_argument("--copy-keymap=", opts.arg, &arg_copy_keymap);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("copy-timezone", "no", "Don't copy current timezone to target system"):
                        r = parse_boolean_argument("--copy-timezone=", opts.arg, &arg_copy_timezone);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("chrome", "no", "Whether to show a color bar at top and bottom of terminal"):
                        r = parse_boolean_argument("--chrome=", opts.arg, &arg_chrome);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("mute-console", "BOOL", "Whether to disallow kernel/PID 1 writes to the console while running"):
                        r = parse_boolean_argument("--mute-console=", opts.arg, &arg_mute_console);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_COMMON_INTROSPECT_CLI:
                        return introspect_cli(SD_JSON_FORMAT_OFF);
                }
 
        char **args = option_parser_get_args(&opts);
 
        if (strv_length(args) > 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too many arguments.");
        if (!strv_isempty(args)) {
                arg_node = strdup(args[0]);
                if (!arg_node)
                        return log_oom();
        }
 
        r = sd_varlink_invocation(SD_VARLINK_ALLOW_ACCEPT);
        if (r < 0)
                return log_error_errno(r, "Failed to check if invoked in Varlink mode: %m");
        if (r > 0)
                arg_varlink = true;
 
        return 1;
}
 
static int print_welcome(sd_varlink **mute_console_link) {
        _cleanup_free_ char *pretty_name = NULL, *os_name = NULL, *ansi_color = NULL, *fancy_name = NULL;
        const char *pn, *ac;
        int r;
 
        assert(mute_console_link);
 
        if (!*mute_console_link && arg_mute_console)
                (void) mute_console(mute_console_link);
 
        if (!arg_welcome)
                return 0;
 
        r = parse_os_release(
                        /* root= */ NULL,
                        "PRETTY_NAME", &pretty_name,
                        "FANCY_NAME",  &fancy_name,
                        "NAME",        &os_name,
                        "ANSI_COLOR",  &ansi_color);
        if (r < 0)
                log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
                               "Failed to read os-release file, ignoring: %m");
 
        pn = os_release_pretty_name(pretty_name, os_name);
        ac = isempty(ansi_color) ? "0" : ansi_color;
 
        if (use_fancy_name(unescape_fancy_name(&fancy_name)))
                printf(ANSI_HIGHLIGHT "Welcome to the " ANSI_NORMAL "%s" ANSI_HIGHLIGHT " Installer!" ANSI_NORMAL "\n", fancy_name);
        else if (colors_enabled())
                printf(ANSI_HIGHLIGHT "Welcome to the " ANSI_NORMAL "\x1B[%sm%s" ANSI_HIGHLIGHT " Installer!" ANSI_NORMAL "\n", ac, pn);
        else
                printf("Welcome to the %s Installer!\n", pn);
 
        putchar('\n');
 
        return 0;
}
 
static int connect_to_repart(sd_varlink **link) {
        int r;
 
        assert(link);
 
        if (*link) {
                /* Reset the time-out to default here, since we are reusing the connection, but might enqueue
                 * a different operation */
                r = sd_varlink_set_relative_timeout(*link, 0);
                if (r < 0)
                        return r;
 
                return 0;
        }
 
        _cleanup_close_ int fd = -EBADF;
        _cleanup_free_ char *repart = NULL;
        fd = pin_callout_binary("systemd-repart", &repart);
        if (fd < 0)
                return log_error_errno(fd, "Failed to find systemd-repart binary: %m");
 
        r = sd_varlink_connect_exec(link, repart, /* argv= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to connect to systemd-repart: %m");
 
        return 1;
}
 
static int acquire_device_list(
                sd_varlink **link,
                char ***ret_menu,
                char ***ret_accepted) {
 
        int r;
 
        assert(link);
        assert(ret_menu);
        assert(ret_accepted);
 
        r = connect_to_repart(link);
        if (r < 0)
                return r;
 
        _cleanup_strv_free_ char **menu = NULL, **accepted = NULL;
 
        sd_json_variant *reply = NULL;
        const char *error_id = NULL;
        r = sd_varlink_collectbo(
                        *link,
                        "io.systemd.Repart.ListCandidateDevices",
                        &reply,
                        &error_id,
                        SD_JSON_BUILD_PAIR_BOOLEAN("ignoreRoot", true));
        if (r < 0)
                return log_error_errno(r, "Failed to issue io.systemd.Repart.ListCandidateDevices() varlink call: %m");
        if (streq_ptr(error_id, "io.systemd.Repart.NoCandidateDevices"))
                log_debug("No candidate devices found.");
        else if (error_id) {
                r = sd_varlink_error_to_errno(error_id, reply); /* If this is a system errno style error, output it with %m */
                if (r != -EBADR)
                        return log_error_errno(r, "Failed to issue io.systemd.Repart.ListCandidateDevices() varlink call: %m");
 
                return log_error_errno(r, "Failed to issue io.systemd.Repart.ListCandidateDevices() varlink call: %s", error_id);
        } else {
                sd_json_variant *i;
                JSON_VARIANT_ARRAY_FOREACH(i, reply) {
                        _cleanup_(block_device_done) BlockDevice bd = BLOCK_DEVICE_NULL;
 
                        static const sd_json_dispatch_field dispatch_table[] = {
                                { "node",     SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(BlockDevice, node),     SD_JSON_MANDATORY },
                                { "symlinks", SD_JSON_VARIANT_ARRAY,  sd_json_dispatch_strv,   offsetof(BlockDevice, symlinks), 0                 },
                                {}
                        };
 
                        r = sd_json_dispatch(i, dispatch_table, SD_JSON_LOG|SD_JSON_ALLOW_EXTENSIONS, &bd);
                        if (r < 0)
                                return r;
 
                        if (strv_extend(&accepted, bd.node) < 0)
                                return log_oom();
                        if (strv_extend_strv(&accepted, bd.symlinks, /* filter_duplicates= */ true) < 0)
                                return log_oom();
 
                        /* Prefer the by-id and by-loop-ref because they typically contain the strings most
                         * directly understood by the user */
                        const char *n = strv_find_prefix(bd.symlinks, "/dev/disk/by-id/");
                        if (!n)
                                n = strv_find_prefix(bd.symlinks, "/dev/disk/by-loop-ref/");
                        if (!n)
                                n = bd.node;
 
                        if (strv_extend(&menu, n) < 0)
                                return log_oom();
                }
        }
 
        *ret_menu = TAKE_PTR(menu);
        *ret_accepted = TAKE_PTR(accepted);
        return 0;
}
 
static int device_is_valid(const char *node, void *userdata) {
 
        if (!path_is_valid(node) || !path_is_absolute(node)) {
                log_error("Not a valid absolute file system path, refusing: %s", node);
                return false;
        }
 
        struct stat st;
        if (stat(node, &st) < 0) {
                log_error_errno(errno, "Failed to check if '%s' is a valid block device node: %m", node);
                return false;
        }
        if (!S_ISBLK(st.st_mode)) {
                log_error("Path '%s' does not refer to a valid block device node, refusing.", node);
                return false;
        }
 
        return true;
}
 
static int refresh_devices(char ***ret_menu, char ***ret_accepted, void *userdata) {
        sd_varlink **repart_link = ASSERT_PTR(userdata);
 
        (void) acquire_device_list(repart_link, ret_menu, ret_accepted);
        return 0;
}
 
static int prompt_block_device(sd_varlink **repart_link, char **ret_node) {
        int r;
 
        putchar('\n');
 
        _cleanup_strv_free_ char **menu = NULL, **accepted = NULL;
        (void) acquire_device_list(repart_link, &menu, &accepted);
 
        r = prompt_loop("Please enter target disk device",
                        GLYPH_COMPUTER_DISK,
                        /* prefill= */ NULL,
                        menu,
                        accepted,
                        /* ellipsize_percentage= */ 20,
                        /* n_columns= */ 1,
                        /* column_width= */ 80,
                        device_is_valid,
                        refresh_devices,
                        /* userdata= */ repart_link,
                        PROMPT_SHOW_MENU|PROMPT_SHOW_MENU_NOW|PROMPT_MAY_SKIP|PROMPT_HIDE_SKIP_HINT|PROMPT_HIDE_MENU_HINT,
                        ret_node);
        if (r < 0)
                return r;
        if (r == 0)
                return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Installation cancelled.");
 
        return 0;
}
 
static int sysinstall_context_notify(
                SysInstallContext *context,
                ProgressPhase phase,
                const char *object,
                unsigned percent) {
 
        int r;
 
        assert(context);
        assert(phase >= 0);
        assert(phase < _PROGRESS_PHASE_MAX);
 
        log_notice("%s%s%s",
                   emoji_enabled() ? phase == PROGRESS_ENCRYPT_CREDENTIALS ?  glyph(GLYPH_LOCK_AND_KEY) : glyph(GLYPH_COMPUTER_DISK) : "",
                   emoji_enabled() ? " " : "",
                   progress_phase_log_to_string(phase));
 
        if (context->link) {
                r = sd_varlink_notifybo(
                                context->link,
                                JSON_BUILD_PAIR_ENUM("phase", progress_phase_to_string(phase)),
                                JSON_BUILD_PAIR_STRING_NON_EMPTY("object", object),
                                JSON_BUILD_PAIR_UNSIGNED_NOT_EQUAL("progress", percent, UINT_MAX));
                if (r < 0)
                        log_debug_errno(r, "Failed to send varlink notify progress notification, ignoring: %m");
 
                r = sd_varlink_flush(context->link);
                if (r < 0)
                        log_debug_errno(r, "Failed to flush varlink notify progress notification, ignoring: %m");
        }
 
        return 0;
}
 
typedef struct RepartResult {
        int ret;
        SysInstallContext *context;
} RepartResult;
 
static int handle_repart_reply(
                sd_varlink *link,
                sd_json_variant *reply,
                const char *error_id,
                sd_varlink_reply_flags_t flags,
                void *userdata) {
 
        RepartResult *result = userdata;
        int r;
 
        assert(result);
 
        struct {
                uint64_t min_size;
                uint64_t current_size;
                uint64_t need_free;
 
                const char *phase;
                const char *object;
                unsigned progress;
        } p = {
                .min_size = UINT64_MAX,
                .current_size = UINT64_MAX,
                .need_free = UINT64_MAX,
                .progress = UINT_MAX,
        };
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "minimalSizeBytes", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64,       voffsetof(p, min_size),     0 },
                { "currentSizeBytes", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64,       voffsetof(p, current_size), 0 },
                { "needFreeBytes",    _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64,       voffsetof(p, need_free),    0 },
                { "phase",            _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_const_string, voffsetof(p, phase),        0 },
                { "object",           _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_const_string, voffsetof(p, object),       0 },
                { "progress",         _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint,         voffsetof(p, progress),     0 },
                {}
        };
 
        r = sd_json_dispatch(reply, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &p);
        if (r < 0)
                return result->ret = r;
 
        if (error_id) {
                const char *sysinstall_error_id = NULL;
 
                if (streq(error_id, "io.systemd.Repart.InsufficientFreeSpace")) {
                        sysinstall_error_id = "io.systemd.SysInstall.InsufficientFreeSpace";
                        result->ret = log_error_errno(SYNTHETIC_ERRNO(ENOSPC), "Not enough free space on disk, cannot install.");
                } else if (streq(error_id, "io.systemd.Repart.DiskTooSmall")) {
                        sysinstall_error_id = "io.systemd.SysInstall.DiskTooSmall";
 
                        result->ret = log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Disk too small for installation, cannot install.");
                } else if (streq(error_id, "io.systemd.Repart.ConflictingDiskLabelPresent")) {
                        sysinstall_error_id = "io.systemd.SysInstall.ConflictingDiskLabelPresent";
 
                        result->ret = log_error_errno(
                                        SYNTHETIC_ERRNO(EHWPOISON),
                                        "A conflicting disk label is already present on the target disk, cannot install unless disk is erased.");
                }
 
                if (sysinstall_error_id && result->context->link) {
                        r = sd_varlink_errorbo(
                                        result->context->link,
                                        sysinstall_error_id,
                                        JSON_BUILD_PAIR_UNSIGNED_NOT_EQUAL("currentSizeBytes", p.current_size, UINT64_MAX),
                                        JSON_BUILD_PAIR_UNSIGNED_NOT_EQUAL("needFreeBytes", p.need_free, UINT64_MAX),
                                        JSON_BUILD_PAIR_UNSIGNED_NOT_EQUAL("minimalSizeBytes", p.min_size, UINT64_MAX));
 
                        if (r < 0)
                                return result->ret = r;
 
                        return result->ret;
                }
 
                r = sd_varlink_error_to_errno(error_id, reply); /* If this is a system errno style error, output it with %m */
                if (r != -EBADR)
                        return result->ret = log_error_errno(r, "Failed to issue io.systemd.Repart.Run() varlink call: %m");
 
                return result->ret = log_error_errno(r, "Failed to issue io.systemd.Repart.Run() varlink call: %s", error_id);
        }
 
        if ((p.progress != UINT_MAX || p.object) && result->context->link)
                (void) sysinstall_context_notify(result->context, PROGRESS_INSTALL_PARTITIONS, p.object, p.progress);
 
        return result->ret = 0;
}
 
static int sysinstall_context_invoke_repart_run(SysInstallContext *context) {
 
        int r;
 
        assert(context);
 
        r = connect_to_repart(&context->repart_link);
        if (r < 0)
                return r;
 
        /* Seeding the partitions might be very slow, disable timeout */
        r = sd_varlink_set_relative_timeout(context->repart_link, UINT64_MAX);
        if (r < 0)
                return log_error_errno(r, "Failed to disable IPC timeout: %m");
 
        RepartResult result = {
                .context = context,
        };
 
        sd_varlink_set_userdata(context->repart_link, &result);
 
        r = sd_varlink_bind_reply(context->repart_link, handle_repart_reply);
        if (r < 0)
                return log_error_errno(r, "Failed to bind repart reply callback: %m");
 
        r = sd_varlink_observebo(
                        context->repart_link,
                        "io.systemd.Repart.Run",
                        SD_JSON_BUILD_PAIR_STRING("node", context->node),
                        SD_JSON_BUILD_PAIR_STRING("empty", context->erase ? "force" : "allow"),
                        SD_JSON_BUILD_PAIR_BOOLEAN("dryRun", false),
                        SD_JSON_BUILD_PAIR_CONDITION(!!context->definitions, "definitions", SD_JSON_BUILD_STRV(context->definitions)),
                        SD_JSON_BUILD_PAIR_BOOLEAN("deferPartitionsEmpty", true),
                        SD_JSON_BUILD_PAIR_BOOLEAN("deferPartitionsFactoryReset", true));
        if (r < 0)
                return log_error_errno(r, "Failed to issue io.systemd.Repart.Run() varlink call: %m");
 
        for (;;) {
                r = sd_varlink_is_idle(context->repart_link);
                if (r < 0)
                        return log_error_errno(r, "Failed to check if varlink connection is idle: %m");
                if (r > 0)
                        break;
 
                r = sd_varlink_process(context->repart_link);
                if (r < 0)
                        return log_error_errno(r, "Failed to process varlink connection: %m");
                if (r != 0)
                        continue;
 
                r = sd_varlink_wait(context->repart_link, USEC_INFINITY);
                if (r < 0)
                        return log_error_errno(r, "Failed to wait for varlink connection events: %m");
        }
 
        sd_varlink_set_userdata(context->repart_link, NULL);
 
        r = sd_varlink_bind_reply(context->repart_link, NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to unbind repart reply callback: %m");
 
        return result.ret;
}
 
static int read_repart_metrics(
                sd_json_variant *v,
                uint64_t *min_size,
                uint64_t *current_size,
                uint64_t *need_free,
                uint64_t *n_partitions) {
 
        int r;
 
        struct {
                uint64_t min_size;
                uint64_t current_size;
                uint64_t need_free;
                uint64_t n_partitions;
        } p = {
                .min_size = UINT64_MAX,
                .current_size = UINT64_MAX,
                .need_free = UINT64_MAX,
                .n_partitions = UINT64_MAX,
        };
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "minimalSizeBytes", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, voffsetof(p, min_size),     0 },
                { "currentSizeBytes", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, voffsetof(p, current_size), 0 },
                { "needFreeBytes",    _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, voffsetof(p, need_free),    0 },
                { "partitionCount",   _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, voffsetof(p, n_partitions), 0 },
                {}
        };
 
        r = sd_json_dispatch(v, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &p);
        if (r < 0)
                return r;
 
        if (min_size)
                *min_size = p.min_size;
        if (current_size)
                *current_size = p.current_size;
        if (need_free)
                *need_free = p.need_free;
        if (n_partitions)
                *n_partitions = p.n_partitions;
 
        return 0;
}
 
static int invoke_repart(
                sd_varlink **link,
                const char *node,
                bool erase,
                bool dry_run,
                char **definitions,
                uint64_t *min_size,        /* initialized both on success and error */
                uint64_t *current_size,    /* ditto */
                uint64_t *need_free,       /* ditto */
                uint64_t *n_partitions) {  /* ditto; UINT64_MAX if not determined */
 
        int r;
 
        assert(link);
 
        /* Note, if dry_run is true, then ENOSPC, E2BIG, EHWPOISON will not be logged about beyond LOG_DEBUG,
         * but all other errors will be */
 
        r = connect_to_repart(link);
        if (r < 0) {
                read_repart_metrics(/* v= */ NULL, min_size, current_size, need_free, n_partitions);
                return r;
        }
 
        if (!dry_run) {
                /* Seeding the partitions might be very slow, disable timeout */
                r = sd_varlink_set_relative_timeout(*link, UINT64_MAX);
                if (r < 0)
                        return log_error_errno(r, "Failed to disable IPC timeout: %m");
        }
 
        sd_json_variant *reply = NULL;
        const char *error_id = NULL;
        r = sd_varlink_callbo(
                        *link,
                        "io.systemd.Repart.Run",
                        &reply,
                        &error_id,
                        SD_JSON_BUILD_PAIR_STRING("node", node),
                        SD_JSON_BUILD_PAIR_STRING("empty", erase ? "force" : "allow"),
                        SD_JSON_BUILD_PAIR_BOOLEAN("dryRun", dry_run),
                        SD_JSON_BUILD_PAIR_CONDITION(!!definitions, "definitions", SD_JSON_BUILD_STRV(definitions)),
                        SD_JSON_BUILD_PAIR_BOOLEAN("deferPartitionsEmpty", true),
                        SD_JSON_BUILD_PAIR_BOOLEAN("deferPartitionsFactoryReset", true));
        if (r < 0) {
                read_repart_metrics(/* v= */ NULL, min_size, current_size, need_free, n_partitions);
                return log_error_errno(r, "Failed to issue io.systemd.Repart.Run() varlink call: %m");
        }
        if (error_id) {
                if (streq(error_id, "io.systemd.Repart.InsufficientFreeSpace")) {
                        (void) read_repart_metrics(reply, min_size, current_size, need_free, n_partitions);
                        return log_full_errno(
                                        dry_run ? LOG_DEBUG : LOG_ERR,
                                        SYNTHETIC_ERRNO(ENOSPC),
                                        "Not enough free space on disk, cannot install.");
                }
                if (streq(error_id, "io.systemd.Repart.DiskTooSmall")) {
                        (void) read_repart_metrics(reply, min_size, current_size, need_free, n_partitions);
                        return log_full_errno(
                                        dry_run ? LOG_DEBUG : LOG_ERR,
                                        SYNTHETIC_ERRNO(E2BIG),
                                        "Disk too small for installation, cannot install.");
                }
 
                /* For all other errors reset the metrics */
                read_repart_metrics(/* v= */ NULL, min_size, current_size, need_free, n_partitions);
 
                if (streq(error_id, "io.systemd.Repart.ConflictingDiskLabelPresent"))
                        return log_full_errno(
                                        dry_run ? LOG_DEBUG : LOG_ERR,
                                        SYNTHETIC_ERRNO(EHWPOISON),
                                        "A conflicting disk label is already present on the target disk, cannot install unless disk is erased.");
 
                r = sd_varlink_error_to_errno(error_id, reply); /* If this is a system errno style error, output it with %m */
                if (r != -EBADR)
                        return log_error_errno(r, "Failed to issue io.systemd.Repart.Run() varlink call: %m");
 
                return log_error_errno(r, "Failed to issue io.systemd.Repart.Run() varlink call: %s", error_id);
        }
 
        (void) read_repart_metrics(reply, min_size, current_size, need_free, n_partitions);
 
        return 0;
}
 
static int prompt_erase(
                bool can_add,
                int *ret_erase) {
        int r;
 
        assert(ret_erase);
 
        putchar('\n');
 
        char **l = can_add ? STRV_MAKE("keep", "erase") : STRV_MAKE("erase");
 
        _cleanup_free_ char *reply = NULL;
        r = prompt_loop(can_add ?
                        "Please type 'keep' to install the OS in addition to what the disk already contains, or 'erase' to erase all data on the disk" :
                        "Please type 'erase' to confirm that all data on the disk shall be erased",
                        GLYPH_BROOM,
                        /* prefill= */ NULL,
                        /* menu= */ l,
                        /* accepted= */ l,
                        /* ellipsize_percentage= */ 20,
                        /* n_columns= */ 2,
                        /* column_width= */ 40,
                        /* is_valid= */ NULL,
                        /* refresh= */ NULL,
                        /* userdata= */ NULL,
                        PROMPT_SHOW_MENU|PROMPT_MAY_SKIP|PROMPT_HIDE_MENU_HINT|PROMPT_HIDE_SKIP_HINT,
                        &reply);
        if (r < 0)
                return r;
        if (r == 0)
                return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Installation cancelled.");
 
        if (streq(reply, "erase"))
                *ret_erase = true;
        else if (streq(reply, "keep"))
                *ret_erase = false;
        else
                assert_not_reached();
 
        return 0;
}
 
static int prompt_touch_variables(void) {
        int r;
 
        if (arg_touch_variables >= 0)
                return 0;
 
        putchar('\n');
 
        char **l = STRV_MAKE("yes", "no");
 
        _cleanup_free_ char *reply = NULL;
        r = prompt_loop("Type 'yes' to register OS installation in firmware variables of the local system, 'no' otherwise",
                        GLYPH_ROCKET,
                        /* prefill= */ "yes",
                        /* menu= */ l,
                        /* accepted= */ l,
                        /* ellipsize_percentage= */ 20,
                        /* n_columns= */ 2,
                        /* column_width= */ 40,
                        /* is_valid= */ NULL,
                        /* refresh= */ NULL,
                        /* userdata= */ NULL,
                        PROMPT_SHOW_MENU|PROMPT_MAY_SKIP|PROMPT_HIDE_MENU_HINT|PROMPT_HIDE_SKIP_HINT,
                        &reply);
        if (r < 0)
                return r;
        if (r == 0)
                return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Installation cancelled.");
 
        r = parse_boolean(reply);
        if (r < 0)
                return log_error_errno(r, "Failed to parse reply: %s", reply);
 
        arg_touch_variables = r;
 
        return 0;
}
 
static int prompt_confirm(void) {
        int r;
 
        if (!arg_confirm)
                return 0;
 
        putchar('\n');
 
        bool yes;
        r = prompt_loop_yes_no(arg_summary ? "Please type 'yes' to confirm the choices above and begin the installation" :
                                             "Please type 'yes' to begin the installation",
                               /* prefill= */ NULL,
                               /* def= */ false,
                               &yes);
        if (r < 0)
                return r;
        if (!yes)
                return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Installation not confirmed, cancelling.");
 
        return 0;
}
 
static int validate_run(sd_varlink **repart_link, const char *node) {
        int r;
 
        assert(repart_link);
        assert(node);
 
        /* First loop: either with explicitly configured --erase= value, or false. A second loop only if not configured explicitly. */
        bool try_erase = arg_erase > 0, conflicting_disk_label = false;
        for (;;) {
                uint64_t min_size = UINT64_MAX, current_size = UINT64_MAX, need_free = UINT64_MAX,
                        n_partitions = UINT64_MAX;
                r = invoke_repart(
                                repart_link,
                                node,
                                try_erase,
                                /* dry_run= */ true,
                                arg_definitions,
                                &min_size,
                                &current_size,
                                &need_free,
                                &n_partitions);
                if (r == -ENOSPC) {
                        /* The disk is large enough, but there's not enough unallocated space. Hence proceed, but require erasing */
                        if (try_erase || arg_erase >= 0)
                                return log_error_errno(r, "The selected disk is big enough for the installation but does not have enough free space.");
 
                        log_notice("The selected disk is big enough for the installation but does not have enough free space. Installation will require erasing.");
                        if (need_free != UINT64_MAX)
                                log_info("Required free space is %s.", FORMAT_BYTES(need_free));
 
                        try_erase = true;
                } else if (r == -E2BIG) {
                        /* Won't fit, whatever we do */
                        log_error_errno(r, "The selected disk is not large enough for an OS installation.");
                        if (current_size != UINT64_MAX)
                                log_info("The size of the selected disk is %s, but a minimal size of %s is required.",
                                         FORMAT_BYTES(current_size),
                                         FORMAT_BYTES(min_size));
                        return r;
                } else if (r == -EHWPOISON) {
                        if (try_erase || arg_erase >= 0)
                                return log_error_errno(r, "The selected disk contains a conflicting disk label, refusing.");
 
                        log_debug("Disk contains a conflicting disk label, checking if we could install the OS after erasing it.");
                        try_erase = true;
                        conflicting_disk_label = true;
                        continue;
                } else if (r < 0)
                        /* invoke_repart() already logged about all other errors */
                        return r;
                else
                        /* Nice, we can add the OS to the disk, without erasing anything. */
                        log_info("The selected disk has enough free space for an installation of the OS.");
 
                if (conflicting_disk_label)
                        log_warning("A conflicting disk label has been found, and must be erased for installation.");
 
                if (arg_erase < 0) {
                        if (n_partitions == 0) {
                                /* If the disk contains no partitions there's nothing worth preserving on
                                 * it, hence don't bother asking whether to erase it. */
                                log_info("The selected disk contains no partitions, proceeding.");
                                arg_erase = false;
                        } else {
                                r = prompt_erase(/* can_add= */ !try_erase, &arg_erase);
                                if (r < 0)
                                        return r;
                        }
                }
 
                return 0;
        }
}
 
static int sysinstall_context_show_summary(SysInstallContext *context) {
        int r;
 
        printf("\n"
               "%sSummary:%s\n", ansi_underline(), ansi_normal());
 
        _cleanup_(table_unrefp) Table *table = table_new_vertical();
        if (!table)
                return log_oom();