HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/dissect/dissect.c

93,809 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 29bf4218191eb6f1dd3491b091dfaed8940e5beb

Lines 1–1000 of 2,160

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fcntl.h>
#include <linux/loop.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>
#include <unistd.h>
 
#include "sd-device.h"
 
#include "architecture.h"
#include "argv-util.h"
#include "blockdev-util.h"
#include "build.h"
#include "capability-util.h"
#include "chase.h"
#include "copy.h"
#include "device-util.h"
#include "discover-image.h"
#include "dissect-image.h"
#include "dlopen-note.h"
#include "env-util.h"
#include "errno-util.h"
#include "escape.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-table.h"
#include "format-util.h"
#include "fs-util.h"
#include "hashmap.h"
#include "hexdecoct.h"
#include "image-policy.h"
#include "json-util.h"
#include "libarchive-util.h"
#include "log.h"
#include "loop-util.h"
#include "main-func.h"
#include "mkdir.h"
#include "mount-util.h"
#include "mountpoint-util.h"
#include "namespace-util.h"
#include "nsresource.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "path-util.h"
#include "pretty-print.h"
#include "process-util.h"
#include "recurse-dir.h"
#include "runtime-scope.h"
#include "sha256.h"
#include "shift-uid.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
#include "tar-util.h"
#include "terminal-util.h"
#include "tmpfile-util.h"
#include "uid-classification.h"
#include "user-util.h"
#include "verbs.h"
#include "vpick.h"
 
static enum {
        ACTION_DISSECT,
        ACTION_MOUNT,
        ACTION_UMOUNT,
        ACTION_ATTACH,
        ACTION_DETACH,
        ACTION_LIST,
        ACTION_MTREE,
        ACTION_WITH,
        ACTION_COPY_FROM,
        ACTION_COPY_TO,
        ACTION_DISCOVER,
        ACTION_VALIDATE,
        ACTION_MAKE_ARCHIVE,
        ACTION_SHIFT,
} arg_action = ACTION_DISSECT;
static char *arg_image = NULL;
static char *arg_root = NULL;
static char *arg_path = NULL;
static const char *arg_source = NULL;
static const char *arg_target = NULL;
static DissectImageFlags arg_flags =
        DISSECT_IMAGE_GENERIC_ROOT |
        DISSECT_IMAGE_DISCARD_ON_LOOP |
        DISSECT_IMAGE_RELAX_VAR_CHECK |
        DISSECT_IMAGE_FSCK |
        DISSECT_IMAGE_USR_NO_ROOT |
        DISSECT_IMAGE_GROWFS |
        DISSECT_IMAGE_PIN_PARTITION_DEVICES |
        DISSECT_IMAGE_ADD_PARTITION_DEVICES |
        DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
static VeritySettings arg_verity_settings = VERITY_SETTINGS_DEFAULT;
static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
static PagerFlags arg_pager_flags = 0;
static bool arg_legend = true;
static bool arg_rmdir = false;
static bool arg_in_memory = false;
static char **arg_argv = NULL;
static char *arg_loop_ref = NULL;
static bool arg_loop_ref_auto = false;
static ImagePolicy *arg_image_policy = NULL;
static bool arg_mtree_hash = true;
static bool arg_via_service = false;
static RuntimeScope arg_runtime_scope = _RUNTIME_SCOPE_INVALID;
static bool arg_all = false;
static uid_t arg_uid_base = UID_INVALID;
static bool arg_quiet = false;
static ImageFilter *arg_image_filter = NULL;
static int arg_copy_ownership = -1;
 
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
STATIC_DESTRUCTOR_REGISTER(arg_path, freep);
STATIC_DESTRUCTOR_REGISTER(arg_verity_settings, verity_settings_done);
STATIC_DESTRUCTOR_REGISTER(arg_argv, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_loop_ref, freep);
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
STATIC_DESTRUCTOR_REGISTER(arg_image_filter, image_filter_freep);
 
COMMAND(
        "systemd-dissect\0",
        "Dissect a Discoverable Disk Image (DDI).",
        .argspec =
               "IMAGE\0"
               "--mount IMAGE PATH\0"
               "--umount PATH\0"
               "--attach IMAGE\0"
               "--detach PATH\0"
               "--list IMAGE\0"
               "--mtree IMAGE\0"
               "--with IMAGE [COMMAND…]\0"
               "--copy-from IMAGE PATH [TARGET]\0"
               "--copy-to IMAGE [SOURCE] PATH\0"
               "--make-archive IMAGE [TARGET]\0"
               "--discover\0"
               "--validate IMAGE\0"
               "--shift IMAGE UIDBASE\0",
        .man_pages = "systemd-dissect(1)\0",
        .option_namespace = "systemd-dissect",
        .pager_flags = &arg_pager_flags,
);
 
static int parse_image_path_argument(const char *path, char **ret_root, char **ret_image) {
        _cleanup_free_ char *p = NULL;
        struct stat st;
        int r;
 
        assert(ret_image);
 
        r = parse_path_argument(path, /* suppress_root= */ false, &p);
        if (r < 0)
                return r;
 
        /* If we got a sysfs path (e.g. from a udev-instantiated template unit's %f specifier),
         * resolve it to the corresponding devnode. */
        if (path_startswith(p, "/sys/")) {
                _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
                const char *devname;
 
                r = sd_device_new_from_syspath(&dev, p);
                if (r < 0)
                        return log_error_errno(r, "Failed to get device from syspath '%s': %m", p);
 
                r = sd_device_get_devname(dev, &devname);
                if (r < 0)
                        return log_error_errno(r, "Failed to get devname for '%s': %m", p);
 
                r = free_and_strdup(&p, devname);
                if (r < 0)
                        return log_oom();
        }
 
        if (stat(p, &st) < 0)
                return log_error_errno(errno, "Failed to stat %s: %m", p);
 
        if (S_ISDIR(st.st_mode)) {
                if (!ret_root)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s is not an image file.", p);
 
                *ret_root = TAKE_PTR(p);
        } else
                *ret_image = TAKE_PTR(p);
 
        return 0;
}
 
static int parse_argv(int argc, char *argv[]) {
        bool system_scope_requested = false, user_scope_requested = false;
        int r;
 
        assert(argc >= 0);
        assert(argv);
 
        OptionParser opts = { argc, argv, .namespace = "systemd-dissect" };
 
        FOREACH_OPTION_OR_RETURN(c, &opts)
                switch (c) {
 
                OPTION_NAMESPACE("systemd-dissect"): {}
 
                OPTION_COMMON_NO_PAGER:
                        arg_pager_flags |= PAGER_DISABLE;
                        break;
 
                OPTION_COMMON_NO_LEGEND:
                        arg_legend = false;
                        break;
 
                OPTION_LONG("mkdir", NULL, "Make mount directory before mounting, if missing"):
                        arg_flags |= DISSECT_IMAGE_MKDIR;
                        break;
 
                OPTION_LONG("rmdir", NULL, "Remove mount directory after unmounting"):
                        arg_rmdir = true;
                        break;
 
                OPTION('r', "read-only", NULL, "Mount read-only"):
                        arg_flags |= DISSECT_IMAGE_READ_ONLY;
                        break;
 
                OPTION_LONG("discard", "MODE", "Choose discard mode (disabled, loop, all, crypto)"): {
                        DissectImageFlags flags;
 
                        if (streq(opts.arg, "disabled"))
                                flags = 0;
                        else if (streq(opts.arg, "loop"))
                                flags = DISSECT_IMAGE_DISCARD_ON_LOOP;
                        else if (streq(opts.arg, "all"))
                                flags = DISSECT_IMAGE_DISCARD_ON_LOOP | DISSECT_IMAGE_DISCARD;
                        else if (streq(opts.arg, "crypt"))
                                flags = DISSECT_IMAGE_DISCARD_ANY;
                        else if (streq(opts.arg, "list")) {
                                puts("disabled\n"
                                     "all\n"
                                     "crypt\n"
                                     "loop");
                                return 0;
                        } else
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Unknown --discard= parameter: %s", opts.arg);
                        arg_flags = (arg_flags & ~DISSECT_IMAGE_DISCARD_ANY) | flags;
 
                        break;
                }
 
                OPTION_LONG("in-memory", NULL, "Copy image into memory"):
                        arg_in_memory = true;
                        break;
 
                OPTION_LONG("root-hash", "HASH", "Specify root hash for verity"): {}
                OPTION_LONG("usr-hash", "HASH", "Same, but for the usr partition"): {
                        _cleanup_(iovec_done) struct iovec roothash = {};
 
                        PartitionDesignator d = streq(opts.opt->long_code, "root-hash") ? PARTITION_ROOT : PARTITION_USR;
                        if (arg_verity_settings.designator >= 0 &&
                            arg_verity_settings.designator != d)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Cannot combine --root-hash=/--root-hash-sig= and --usr-hash=/--usr-hash-sig= options.");
 
                        r = unhexmem(opts.arg, &roothash.iov_base, &roothash.iov_len);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse root hash '%s': %m", opts.arg);
                        if (roothash.iov_len < sizeof(sd_id128_t))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Root hash must be at least 128-bit long: %s", opts.arg);
 
                        iovec_done(&arg_verity_settings.root_hash);
                        arg_verity_settings.root_hash = TAKE_STRUCT(roothash);
                        arg_verity_settings.designator = d;
                        break;
                }
 
                OPTION_LONG("root-hash-sig", "SIG",
                            "Specify signature of root hash for verity as DER-encoded PKCS7, "
                            "either as a path to a file or as an ASCII base64-encoded string "
                            "prefixed by 'base64:'"): {}
                OPTION_LONG("usr-hash-sig", "SIG", "Same, but for the usr partition"): {
                        const char *value;
                        _cleanup_(iovec_done) struct iovec sig = {};
 
                        PartitionDesignator d = streq(opts.opt->long_code, "root-hash-sig") ? PARTITION_ROOT : PARTITION_USR;
                        if (arg_verity_settings.designator >= 0 &&
                            arg_verity_settings.designator != d)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Cannot combine --root-hash=/--root-hash-sig= and --usr-hash=/--usr-hash-sig= options.");
 
                        if ((value = startswith(opts.arg, "base64:"))) {
                                r = unbase64mem(value, &sig.iov_base, &sig.iov_len);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to parse root hash signature '%s': %m", opts.arg);
                        } else {
                                r = read_full_file(opts.arg, (char**) &sig.iov_base, &sig.iov_len);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to read root hash signature file '%s': %m", opts.arg);
                        }
 
                        iovec_done(&arg_verity_settings.root_hash_sig);
                        arg_verity_settings.root_hash_sig = TAKE_STRUCT(sig);
                        arg_verity_settings.designator = d;
                        break;
                }
 
                OPTION_LONG("verity-data", "PATH",
                            "Specify data file with hash tree for verity if it is not embedded in IMAGE"):
                        r = parse_path_argument(opts.arg, false, &arg_verity_settings.data_path);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("fsck", "BOOL", "Run fsck before mounting"):
                        r = parse_boolean(opts.arg);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --fsck= parameter: %s", opts.arg);
 
                        SET_FLAG(arg_flags, DISSECT_IMAGE_FSCK, r);
                        break;
 
                OPTION_LONG("growfs", "BOOL", "Grow file system to partition size, if marked"):
                        r = parse_boolean(opts.arg);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --growfs= parameter: %s", opts.arg);
 
                        SET_FLAG(arg_flags, DISSECT_IMAGE_GROWFS, r);
                        break;
 
                OPTION_COMMON_JSON:
                        r = parse_json_argument(opts.arg, &arg_json_format_flags);
                        if (r <= 0)
                                return r;
                        break;
 
                OPTION_LONG("loop-ref", "NAME", "Set reference string for loopback device"):
                        if (isempty(opts.arg)) {
                                arg_loop_ref = mfree(arg_loop_ref);
                                arg_loop_ref_auto = false;
                                break;
                        }
 
                        if (strlen(opts.arg) >= sizeof_field(struct loop_info64, lo_file_name))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Loop device ref string '%s' is too long.", opts.arg);
 
                        r = free_and_strdup_warn(&arg_loop_ref, opts.arg);
                        if (r < 0)
                                return r;
 
                        arg_loop_ref_auto = false;
                        break;
 
                OPTION_LONG("loop-ref-auto", NULL, "Derive reference string from image file name"):
                        arg_loop_ref = mfree(arg_loop_ref);
                        arg_loop_ref_auto = true;
                        break;
 
                OPTION_LONG("image-policy", "POLICY", "Specify image dissection policy"):
                        r = parse_image_policy_argument(opts.arg, &arg_image_policy);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("mtree-hash", "BOOL", "Whether to include SHA256 hash in the mtree output"):
                        r = parse_boolean_argument("--mtree-hash=", opts.arg, &arg_mtree_hash);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("system", NULL, "Discover system images"):
                        system_scope_requested = true;
                        break;
 
                OPTION_LONG("user", NULL, "Discover user images"):
                        user_scope_requested = true;
                        break;
 
                OPTION_LONG("all", NULL, "Show hidden images too"):
                        arg_all = true;
                        break;
 
                OPTION('q', "quiet", NULL, "Suppress output of chosen loopback block device"):
                        arg_quiet = true;
                        break;
 
                OPTION_LONG("image-filter", "FILTER", "Specify image dissection filter"): {
                        _cleanup_(image_filter_freep) ImageFilter *f = NULL;
                        r = image_filter_parse(opts.arg, &f);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse image filter expression: %s", opts.arg);
 
                        image_filter_free(arg_image_filter);
                        arg_image_filter = TAKE_PTR(f);
                        break;
                }
 
                OPTION_LONG("copy-ownership", "BOOL", "Whether to copy ownership when copying files"):
                        r = parse_tristate_argument_with_auto("--copy-ownership=", opts.arg, &arg_copy_ownership);
                        if (r < 0)
                                return r;
                        break;
 
                /************************************ Commands ***************************************/
                OPTION_GROUP("Commands"): {}
 
                OPTION_COMMON_HELP:
                        return command_print_help();
 
                OPTION_COMMON_VERSION:
                        return version();
 
                OPTION('m', "mount", NULL, "Mount the image to the specified directory"):
                        arg_action = ACTION_MOUNT;
                        break;
 
                OPTION_SHORT('M', NULL, "Shortcut for --mount --mkdir"):
                        arg_action = ACTION_MOUNT;
                        arg_flags |= DISSECT_IMAGE_MKDIR;
                        break;
 
                OPTION('u', "umount", NULL, "Unmount the image from the specified directory"):
                        arg_action = ACTION_UMOUNT;
                        break;
 
                OPTION_SHORT('U', NULL, "Shortcut for --umount --rmdir"):
                        arg_action = ACTION_UMOUNT;
                        arg_rmdir = true;
                        break;
 
                OPTION_LONG("attach", NULL, "Attach the disk image to a loopback block device"):
                        arg_action = ACTION_ATTACH;
                        break;
 
                OPTION_LONG("detach", NULL, "Detach a loopback block device again"):
                        arg_action = ACTION_DETACH;
                        break;
 
                OPTION('l', "list", NULL, "List all the files and directories of the specified OS image"):
                        arg_action = ACTION_LIST;
                        arg_flags |= DISSECT_IMAGE_READ_ONLY;
                        break;
 
                OPTION_LONG("mtree", NULL, "Show BSD mtree manifest of OS image"):
                        arg_action = ACTION_MTREE;
                        arg_flags |= DISSECT_IMAGE_READ_ONLY;
                        break;
 
                OPTION_FULL(OPTION_STOPS_PARSING, /* sc= */ 0, "with", NULL, "Mount, run command, unmount"):
                        arg_action = ACTION_WITH;
                        break;
 
                OPTION('x', "copy-from", NULL, "Copy files from image to host"):
                        arg_action = ACTION_COPY_FROM;
                        arg_flags |= DISSECT_IMAGE_READ_ONLY;
                        break;
 
                OPTION('a', "copy-to", NULL, "Copy files from host to image"):
                        arg_action = ACTION_COPY_TO;
                        break;
 
                OPTION_LONG("make-archive", NULL, "Convert the DDI to an archive file"):
                        r = dlopen_libarchive(LOG_ERR);
                        if (r < 0)
                                return r;
 
                        arg_action = ACTION_MAKE_ARCHIVE;
                        break;
 
                OPTION_LONG("discover", NULL, "Discover DDIs in well known directories"):
                        arg_action = ACTION_DISCOVER;
                        break;
 
                OPTION_LONG("validate", NULL, "Validate image and image policy"):
                        arg_action = ACTION_VALIDATE;
                        break;
 
                OPTION_LONG("shift", NULL, "Shift UID range to selected base"):
                        arg_action = ACTION_SHIFT;
                        break;
 
                OPTION_COMMON_INTROSPECT_CLI:
                        return introspect_cli(arg_json_format_flags);
                }
 
        if (system_scope_requested || user_scope_requested)
                arg_runtime_scope = system_scope_requested && user_scope_requested ? _RUNTIME_SCOPE_INVALID :
                        system_scope_requested ? RUNTIME_SCOPE_SYSTEM : RUNTIME_SCOPE_USER;
 
        char **args = option_parser_get_args(&opts);
 
        switch (arg_action) {
 
        case ACTION_DISSECT:
                if (strv_length(args) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file path as only argument.");
 
                r = parse_image_path_argument(args[0], NULL, &arg_image);
                if (r < 0)
                        return r;
 
                /* when dumping image info be even more liberal than otherwise, do not even require a single valid partition */
                arg_flags |= DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_ALLOW_EMPTY;
                break;
 
        case ACTION_MOUNT:
                if (strv_length(args) != 2)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file path and mount point path as only arguments.");
 
                r = parse_image_path_argument(args[0], NULL, &arg_image);
                if (r < 0)
                        return r;
 
                r = parse_path_argument(args[1], /* suppress_root= */ false, &arg_path);
                if (r < 0)
                        return r;
 
                arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
                break;
 
        case ACTION_UMOUNT:
                if (strv_length(args) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected a mount point path as only argument.");
 
                r = parse_path_argument(args[0], /* suppress_root= */ false, &arg_path);
                if (r < 0)
                        return r;
                break;
 
        case ACTION_ATTACH:
                if (strv_length(args) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file path as only argument.");
 
                r = parse_image_path_argument(args[0], NULL, &arg_image);
                if (r < 0)
                        return r;
                break;
 
        case ACTION_DETACH:
                if (strv_length(args) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file path or loopback device as only argument.");
 
                r = parse_image_path_argument(args[0], NULL, &arg_image);
                if (r < 0)
                        return r;
                break;
 
        case ACTION_LIST:
        case ACTION_MTREE:
                if (strv_length(args) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file or directory path as only argument.");
 
                r = parse_image_path_argument(args[0], &arg_root, &arg_image);
                if (r < 0)
                        return r;
 
                arg_flags |= DISSECT_IMAGE_READ_ONLY | DISSECT_IMAGE_REQUIRE_ROOT;
                break;
 
        case ACTION_MAKE_ARCHIVE:
                if (!IN_SET(strv_length(args), 1, 2))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file, and an optional target path as only arguments.");
 
                r = parse_image_path_argument(args[0], &arg_root, &arg_image);
                if (r < 0)
                        return r;
 
                arg_target = empty_or_dash_to_null(args[1]);
                arg_flags |= DISSECT_IMAGE_READ_ONLY | DISSECT_IMAGE_REQUIRE_ROOT;
                break;
 
        case ACTION_COPY_FROM:
                if (!IN_SET(strv_length(args), 2, 3))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file or directory path, a source path and an optional destination path as only arguments.");
 
                r = parse_image_path_argument(args[0], &arg_root, &arg_image);
                if (r < 0)
                        return r;
                arg_source = args[1];
                arg_target = args[2] ?: "-"; /* this means stdout */ ;
 
                arg_flags |= DISSECT_IMAGE_READ_ONLY | DISSECT_IMAGE_REQUIRE_ROOT;
                break;
 
        case ACTION_COPY_TO:
                if (!IN_SET(strv_length(args), 2, 3))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file or directory path, an optional source path and a destination path as only arguments.");
 
                r = parse_image_path_argument(args[0], &arg_root, &arg_image);
                if (r < 0)
                        return r;
 
                if (args[2]) {
                        arg_source = args[1];
                        arg_target = args[2];
                } else {
                        arg_source = "-"; /* this means stdin */
                        arg_target = args[1];
                }
 
                arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
                break;
 
        case ACTION_WITH:
                if (strv_isempty(args))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file path and an optional command line.");
 
                r = parse_image_path_argument(args[0], NULL, &arg_image);
                if (r < 0)
                        return r;
 
                if (args[1]) {
                        arg_argv = strv_copy(args + 1);
                        if (!arg_argv)
                                return log_oom();
                }
 
                break;
 
        case ACTION_DISCOVER:
                if (!strv_isempty(args))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected no argument.");
                break;
 
        case ACTION_VALIDATE:
                if (strv_length(args) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image file path as only argument.");
 
                r = parse_image_path_argument(args[0], NULL, &arg_image);
                if (r < 0)
                        return r;
 
                arg_flags |= DISSECT_IMAGE_READ_ONLY;
                arg_flags &= ~(DISSECT_IMAGE_PIN_PARTITION_DEVICES|DISSECT_IMAGE_ADD_PARTITION_DEVICES);
                break;
 
        case ACTION_SHIFT:
                if (strv_length(args) != 2)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Expected an image path and a UID base as only argument.");
 
                r = parse_image_path_argument(args[0], &arg_root, &arg_image);
                if (r < 0)
                        return r;
 
                if (streq(args[1], "foreign"))
                        arg_uid_base = FOREIGN_UID_BASE;
                else {
                        r = parse_uid(args[1], &arg_uid_base);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse UID base: %s", args[1]);
 
                        if ((arg_uid_base & 0xFFFF) != 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Selected UID base not a multiple of 64K: " UID_FMT, arg_uid_base);
                        if (arg_uid_base != 0 &&
                            !uid_is_container(arg_uid_base) &&
                            !uid_is_foreign(arg_uid_base))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Selected UID range is not in the container range, nor the foreign one, refusing.");
                }
 
                arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
                break;
 
        default:
                assert_not_reached();
        }
 
        r = getenv_bool("SYSTEMD_USE_MOUNTFSD");
        if (r < 0) {
                if (r != -ENXIO)
                        return log_error_errno(r, "Failed to parse $SYSTEMD_USE_MOUNTFSD: %m");
        } else
                arg_via_service = r;
 
        if (IN_SET(arg_action, ACTION_MOUNT, ACTION_UMOUNT)) {
                r = have_effective_cap(CAP_SYS_ADMIN);
                if (r < 0)
                        return log_error_errno(r, "Failed to determine if we have CAP_SYS_ADMIN: %m");
                if (r == 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to have CAP_SYS_ADMIN to mount/unmount images");
        }
 
        if (arg_action == ACTION_SHIFT) {
                r = have_effective_cap(CAP_CHOWN);
                if (r < 0)
                        return log_error_errno(r, "Failed to determine if we have CAP_CHOWN: %m");
                if (r == 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to have CAP_CHOWN to shift UID ranges");
        }
 
        if (IN_SET(arg_action, ACTION_ATTACH, ACTION_DETACH)) {
                r = must_be_root();
                if (r < 0)
                        return r;
        }
 
        SET_FLAG(arg_flags, DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH, isatty_safe(STDIN_FILENO));
 
        return 1;
}
 
COMMAND(
        "mount.ddi\0",
        "External helper for mount.8 to mount Discoverable Disk Images (DDIs).",
        .man_pages = "systemd-dissect(1)\0",
        .option_namespace = "mount.ddi",
);
 
static int parse_argv_as_mount_helper(int argc, char *argv[]) {
        const char *options = NULL;
        bool fake = false;
        int r;
 
        /* Implements util-linux "external helper" command line interface, as per mount(8) man page. */
 
        OptionParser opts = { argc, argv, .namespace = "mount.ddi" };
        FOREACH_OPTION_OR_RETURN(c, &opts)
                switch (c) {
 
                OPTION_NAMESPACE("mount.ddi"): {}
 
                OPTION_SHORT('f', NULL, /* help= */ NULL):
                        fake = true;
                        break;
 
                OPTION_SHORT('o', "OPTIONS", /* help= */ NULL):
                        options = opts.arg;
                        break;
 
                OPTION_SHORT('t', "FSTYPE", /* help= */ NULL):
                        if (!streq(opts.arg, "ddi"))
                                log_debug("Unexpected file system type '%s', ignoring.", opts.arg);
                        break;
 
                OPTION_SHORT('s', NULL, /* help= */ NULL): {} /* sloppy mount options */
                OPTION_SHORT('n', NULL, /* help= */ NULL): {} /* aka --no-mtab */
                OPTION_SHORT('v', NULL, /* help= */ NULL):    /* aka --verbose */
                        log_debug("Ignoring option -%c, not implemented.", opts.opt->short_code);
                        break;
 
                OPTION_SHORT('N', "NS", /* help= */ NULL): /* aka --namespace= */
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                               "Option -%c is not implemented, refusing.",
                                               opts.opt->short_code);
                }
 
        char **args = option_parser_get_args(&opts);
        size_t n_args = option_parser_get_n_args(&opts);
 
        if (n_args != 2)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Expected an image file path and target directory as only argument.");
 
        for (const char *p = options;;) {
                _cleanup_free_ char *word = NULL;
 
                r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
                if (r < 0)
                        return log_error_errno(r, "Failed to extract mount option: %m");
                if (r == 0)
                        break;
 
                if (streq(word, "ro"))
                        SET_FLAG(arg_flags, DISSECT_IMAGE_READ_ONLY, true);
                else if (streq(word, "rw"))
                        SET_FLAG(arg_flags, DISSECT_IMAGE_READ_ONLY, false);
                else if (streq(word, "discard"))
                        SET_FLAG(arg_flags, DISSECT_IMAGE_DISCARD_ANY, true);
                else if (streq(word, "nodiscard"))
                        SET_FLAG(arg_flags, DISSECT_IMAGE_DISCARD_ANY, false);
                else
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Unknown mount option '%s'.", word);
        }
 
        if (fake)
                return 0;
 
        r = parse_path_argument(args[0], /* suppress_root= */ false, &arg_image);
        if (r < 0)
                return r;
 
        r = parse_path_argument(args[1], /* suppress_root= */ false, &arg_path);
        if (r < 0)
                return r;
 
        arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
        arg_action = ACTION_MOUNT;
        return 1;
}
 
static void strv_pair_print(char **l, const char *prefix) {
        assert(prefix);
 
        STRV_FOREACH_PAIR(p, q, l)
                if (p == l)
                        printf("%s %s=%s\n", prefix, *p, *q);
                else
                        printf("%*s %s=%s\n", (int) strlen(prefix), "", *p, *q);
}
 
static int get_extension_scopes(DissectedImage *m, ImageClass class, char ***ret_scopes) {
        _cleanup_strv_free_ char **l = NULL;
        const char *e, *field_name;
        char **release_data;
 
        assert(m);
        assert(ret_scopes);
 
        switch (class) {
 
        case IMAGE_SYSEXT:
                release_data = m->sysext_release;
                field_name = "SYSEXT_SCOPE";
                break;
 
        case IMAGE_CONFEXT:
                release_data = m->confext_release;
                field_name = "CONFEXT_SCOPE";
                break;
 
        default:
                return -EINVAL;
        }
 
        /* If there's no extension-release file its not a system extension. Otherwise the SYSEXT_SCOPE
         * field for sysext images and the CONFEXT_SCOPE field for confext images indicates which scope
         * it is for — and it defaults to "system" + "portable" if unset. */
 
        if (!release_data) {
                *ret_scopes = NULL;
                return 0;
        }
 
        e = strv_env_pairs_get(release_data, field_name);
        if (e)
                l = strv_split(e, WHITESPACE);
        else
                l = strv_new("system", "portable");
        if (!l)
                return -ENOMEM;
 
        *ret_scopes = TAKE_PTR(l);
        return 1;
}
 
static int action_dissect(
                DissectedImage *m,
                LoopDevice *d,
                int userns_fd) {
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        _cleanup_(table_unrefp) Table *t = NULL;
        _cleanup_free_ char *bn = NULL;
        int r;
 
        assert(m);
 
        r = path_extract_filename(arg_image, &bn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract file name from image path '%s': %m", arg_image);
 
        if (arg_json_format_flags & (SD_JSON_FORMAT_OFF|SD_JSON_FORMAT_PRETTY|SD_JSON_FORMAT_PRETTY_AUTO))
                pager_open(arg_pager_flags);
 
        if (!sd_json_format_enabled(arg_json_format_flags)) {
                printf(" File Name: %s%s%s\n",
                       ansi_highlight(), bn, ansi_normal());
 
                printf("      Size: %s\n",
                       FORMAT_BYTES(m->image_size));
 
                printf(" Sec. Size: %" PRIu32 "\n",
                       m->sector_size);
 
                printf("     Arch.: %s\n",
                       strna(architecture_to_string(dissected_image_architecture(m))));
 
                if (!sd_id128_is_null(m->image_uuid))
                        printf("Image UUID: %s\n",
                               SD_ID128_TO_UUID_STRING(m->image_uuid));
 
                if (m->image_name && !streq(m->image_name, bn))
                        printf("Image Name: %s\n", m->image_name);
 
                putc('\n', stdout);
                fflush(stdout);
        }
 
        r = dissected_image_acquire_metadata(m, userns_fd, /* extra_flags= */ 0);
        if (r == -ENXIO)
                return log_error_errno(r, "No root partition discovered.");
        if (r == -EUCLEAN)
                return log_error_errno(r, "File system check of image failed.");
        if (r == -EMEDIUMTYPE)
                log_warning_errno(r, "Not a valid OS image, no os-release file included. Proceeding anyway.");
        else if (r == -EUNATCH)
                log_warning_errno(r, "OS image is encrypted, proceeding without showing OS image metadata.");
        else if (r == -EBUSY)
                log_warning_errno(r, "OS image is currently in use, proceeding without showing OS image metadata.");
        else if (r < 0)
                return log_error_errno(r, "Failed to acquire image metadata: %m");
        else if (!sd_json_format_enabled(arg_json_format_flags)) {
 
                if (m->hostname)
                        printf("  Hostname: %s\n", m->hostname);
 
                if (!sd_id128_is_null(m->machine_id))
                        printf("Machine ID: " SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(m->machine_id));
 
                strv_pair_print(m->machine_info,
                               "Mach. Info:");
                strv_pair_print(m->os_release,
                               "OS Release:");
                strv_pair_print(m->initrd_release,
                                "initrd R.:");
                strv_pair_print(m->sysext_release,
                               " sysext R.:");
                strv_pair_print(m->confext_release,
                               "confext R.:");
 
                if (m->hostname ||
                    !sd_id128_is_null(m->machine_id) ||
                    !strv_isempty(m->machine_info) ||
                    !strv_isempty(m->os_release) ||
                    !strv_isempty(m->initrd_release) ||
                    !strv_isempty(m->sysext_release) ||
                    !strv_isempty(m->confext_release))
                        putc('\n', stdout);
 
                printf("    Use As: %s bootable system for UEFI\n",
                       COLOR_MARK_BOOL(dissected_image_is_bootable_uefi(m)));
                printf("            %s bootable system for container\n",
                       COLOR_MARK_BOOL(dissected_image_is_bootable_os(m)));
                printf("            %s portable service\n",
                       COLOR_MARK_BOOL(dissected_image_is_portable(m)));
                printf("            %s initrd\n",
                       COLOR_MARK_BOOL(dissected_image_is_initrd(m)));
 
                for (ImageClass c = _IMAGE_CLASS_EXTENSION_FIRST; c <= _IMAGE_CLASS_EXTENSION_LAST; c++) {
                        const char *string_class = image_class_to_string(c);
                        _cleanup_strv_free_ char **extension_scopes = NULL;
 
                        r = get_extension_scopes(m, c, &extension_scopes);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse scopes: %m");
 
                        printf("            %s %s for system\n",
                               COLOR_MARK_BOOL(strv_contains(extension_scopes, "system")), string_class);
                        printf("            %s %s for portable service\n",
                               COLOR_MARK_BOOL(strv_contains(extension_scopes, "portable")), string_class);
                        printf("            %s %s for initrd\n",
                               COLOR_MARK_BOOL(strv_contains(extension_scopes, "initrd")), string_class);
                }
 
                putc('\n', stdout);
        } else {
                _cleanup_strv_free_ char **sysext_scopes = NULL, **confext_scopes = NULL;
 
                r = get_extension_scopes(m, IMAGE_SYSEXT, &sysext_scopes);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse sysext scopes: %m");
 
                r = get_extension_scopes(m, IMAGE_CONFEXT, &confext_scopes);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse confext scopes: %m");
 
                Architecture a = dissected_image_architecture(m);
 
                r = sd_json_buildo(
                                &v,
                                SD_JSON_BUILD_PAIR_STRING("name", bn),
                                SD_JSON_BUILD_PAIR_CONDITION(m->image_size != UINT64_MAX, "size", SD_JSON_BUILD_INTEGER(m->image_size)),
                                SD_JSON_BUILD_PAIR_INTEGER("sectorSize", m->sector_size),
                                SD_JSON_BUILD_PAIR_CONDITION(a >= 0, "architecture", SD_JSON_BUILD_STRING(architecture_to_string(a))),
                                SD_JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(m->image_uuid), "imageUuid", SD_JSON_BUILD_UUID(m->image_uuid)),
                                SD_JSON_BUILD_PAIR_CONDITION(!!m->hostname, "hostname", SD_JSON_BUILD_STRING(m->hostname)),
                                SD_JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(m->machine_id), "machineId", SD_JSON_BUILD_ID128(m->machine_id)),
                                SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->machine_info), "machineInfo", JSON_BUILD_STRV_ENV_PAIR(m->machine_info)),
                                SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->os_release), "osRelease", JSON_BUILD_STRV_ENV_PAIR(m->os_release)),
                                SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->initrd_release), "initrdRelease", JSON_BUILD_STRV_ENV_PAIR(m->initrd_release)),
                                SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->sysext_release), "sysextRelease", JSON_BUILD_STRV_ENV_PAIR(m->sysext_release)),
                                SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->confext_release), "confextRelease", JSON_BUILD_STRV_ENV_PAIR(m->confext_release)),
                                SD_JSON_BUILD_PAIR_BOOLEAN("useBootableUefi", dissected_image_is_bootable_uefi(m)),
                                SD_JSON_BUILD_PAIR_BOOLEAN("useBootableContainer", dissected_image_is_bootable_os(m)),
                                SD_JSON_BUILD_PAIR_BOOLEAN("useInitrd", dissected_image_is_initrd(m)),
                                SD_JSON_BUILD_PAIR_BOOLEAN("usePortableService", dissected_image_is_portable(m)),