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 1001–2000 of 2,160

                                SD_JSON_BUILD_PAIR_BOOLEAN("useSystemExtension", strv_contains(sysext_scopes, "system")),
                                SD_JSON_BUILD_PAIR_BOOLEAN("useInitRDSystemExtension", strv_contains(sysext_scopes, "initrd")),
                                SD_JSON_BUILD_PAIR_BOOLEAN("usePortableSystemExtension", strv_contains(sysext_scopes, "portable")),
                                SD_JSON_BUILD_PAIR_BOOLEAN("useConfigurationExtension", strv_contains(confext_scopes, "system")),
                                SD_JSON_BUILD_PAIR_BOOLEAN("useInitRDConfigurationExtension", strv_contains(confext_scopes, "initrd")),
                                SD_JSON_BUILD_PAIR_BOOLEAN("usePortableConfigurationExtension", strv_contains(confext_scopes, "portable")));
                if (r < 0)
                        return log_oom();
        }
 
        t = table_new("rw", "designator", "partition uuid", "partition label", "fstype", "architecture", "verity", "growfs", "node", "partno");
        if (!t)
                return log_oom();
 
        table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
        (void) table_set_align_percent(t, table_get_cell(t, 0, 9), 100);
 
        /* Hide the device path if this is a loopback device that is not relinquished, since that means the
         * device node is not going to be useful the instant our command exits */
        if ((!d || d->created) && !sd_json_format_enabled(arg_json_format_flags))
                table_hide_column_from_display(t, 8);
 
        for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
                DissectedPartition *p = m->partitions + i;
 
                if (!p->found)
                        continue;
 
                r = table_add_many(
                                t,
                                TABLE_STRING, p->rw ? "rw" : "ro",
                                TABLE_STRING, partition_designator_to_string(i));
                if (r < 0)
                        return table_log_add_error(r);
 
                if (sd_id128_is_null(p->uuid))
                        r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
                else
                        r = table_add_cell(t, NULL, TABLE_UUID, &p->uuid);
                if (r < 0)
                        return table_log_add_error(r);
 
                r = table_add_many(
                                t,
                                TABLE_STRING, p->label,
                                TABLE_STRING, p->fstype,
                                TABLE_STRING, architecture_to_string(p->architecture));
                if (r < 0)
                        return table_log_add_error(r);
 
                if (arg_verity_settings.data_path)
                        r = table_add_cell(t, NULL, TABLE_STRING, "external");
                else if (dissected_image_verity_candidate(m, i))
                        r = table_add_cell(t, NULL, TABLE_STRING,
                                           dissected_image_verity_sig_ready(m, i) ? "signed" :
                                           yes_no(dissected_image_verity_ready(m, i)));
                else
                        r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
                if (r < 0)
                        return table_log_add_error(r);
 
                r = table_add_many(t, TABLE_BOOLEAN, (int) p->growfs);
                if (r < 0)
                        return table_log_add_error(r);
 
                if (p->partno < 0) /* no partition table, naked file system */ {
                        r = table_add_cell(t, NULL, TABLE_PATH_BASENAME, arg_image);
                        if (r < 0)
                                return table_log_add_error(r);
 
                        r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
                } else {
                        r = table_add_cell(t, NULL, TABLE_STRING, p->node);
                        if (r < 0)
                                return table_log_add_error(r);
 
                        r = table_add_cell(t, NULL, TABLE_INT, &p->partno);
                }
                if (r < 0)
                        return table_log_add_error(r);
        }
 
        if (!sd_json_format_enabled(arg_json_format_flags)) {
                table_set_header(t, arg_legend);
 
                r = table_print_or_warn(t);
                if (r < 0)
                        return r;
        } else {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *jt = NULL;
 
                r = table_to_json(t, &jt);
                if (r < 0)
                        return log_error_errno(r, "Failed to convert table to JSON: %m");
 
                r = sd_json_variant_set_field(&v, "mounts", jt);
                if (r < 0)
                        return log_oom();
 
                sd_json_variant_dump(v, arg_json_format_flags, stdout, NULL);
        }
 
        return 0;
}
 
static int action_mount(DissectedImage *m, LoopDevice *d) {
        int r;
 
        assert(m);
        assert(arg_action == ACTION_MOUNT);
 
        r = dissected_image_mount_and_warn(
                        m,
                        arg_path,
                        /* uid_shift= */ UID_INVALID,
                        /* uid_range= */ UID_INVALID,
                        /* userns_fd= */ -EBADF,
                        arg_flags);
        if (r < 0)
                return r;
 
        if (d) {
                r = loop_device_flock(d, LOCK_UN);
                if (r < 0)
                        return log_error_errno(r, "Failed to unlock loopback block device: %m");
        }
 
        r = dissected_image_relinquish(m);
        if (r < 0)
                return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
 
        return 0;
}
 
static int list_print_item(
                RecurseDirEvent event,
                const char *path,
                int dir_fd,
                int inode_fd,
                const struct dirent *de,
                const struct statx *sx,
                void *userdata) {
 
        assert(path);
 
        if (event == RECURSE_DIR_ENTER)
                printf("%s%s/%s\n", path, ansi_grey(), ansi_normal());
        else if (event == RECURSE_DIR_ENTRY)
                printf("%s\n", path);
 
        return RECURSE_DIR_CONTINUE;
}
 
static int get_file_sha256(int inode_fd, uint8_t ret[static SHA256_DIGEST_SIZE]) {
        _cleanup_close_ int fd = -EBADF;
 
        /* convert O_PATH fd into a regular one */
        fd = fd_reopen(inode_fd, O_RDONLY|O_CLOEXEC);
        if (fd < 0)
                return fd;
 
        /* Calculating the SHA sum might be slow, hence let's flush STDOUT first, to give user an idea where we are slow. */
        fflush(stdout);
 
        return sha256_fd(fd, UINT64_MAX, ret);
}
 
static const char *pick_color_for_uid_gid(uid_t uid) {
        if (uid == UID_NOBODY)
                return ansi_highlight_yellow4(); /* files should never be owned by 'nobody' (but might happen due to userns mapping) */
        if (uid_is_system(uid))
                return ansi_normal();            /* files in disk images are typically owned by root and other system users, no issue there */
        if (uid_is_dynamic(uid) || uid_is_greeter(uid))
                return ansi_highlight_red();     /* files should never be owned persistently by dynamic users, and there are just no excuses */
        if (uid_is_container(uid) || uid_is_foreign(uid))
                return ansi_highlight_cyan();
 
        return ansi_highlight();
}
 
static int mtree_print_item(
                RecurseDirEvent event,
                const char *path,
                int dir_fd,
                int inode_fd,
                const struct dirent *de,
                const struct statx *sx,
                void *userdata) {
 
        _cleanup_free_ char *escaped = NULL;
        int r;
 
        assert(path);
 
        if (!IN_SET(event, RECURSE_DIR_ENTER, RECURSE_DIR_ENTRY))
                return RECURSE_DIR_CONTINUE;
 
        assert(sx);
 
        if (isempty(path))
                path = ".";
        else {
                /* BSD mtree uses either C or octal escaping, and covers whitespace, comments and glob characters. We use C style escaping and follow suit */
                path = escaped = xescape(path, WHITESPACE COMMENTS GLOB_CHARS);
                if (!escaped)
                        return log_oom();
        }
 
        printf("%s", isempty(path) ? "." : path);
 
        if (FLAGS_SET(sx->stx_mask, STATX_TYPE)) {
                if (S_ISDIR(sx->stx_mode))
                        printf("%s/%s", ansi_grey(), ansi_normal());
 
                printf(" %stype=%s%s%s%s",
                       ansi_grey(),
                       ansi_normal(),
                       S_ISDIR(sx->stx_mode) ? ansi_highlight_blue() :
                       S_ISLNK(sx->stx_mode) ? ansi_highlight_cyan() :
                       (S_ISFIFO(sx->stx_mode) || S_ISCHR(sx->stx_mode) || S_ISBLK(sx->stx_mode)) ? ansi_highlight_yellow4() :
                       S_ISSOCK(sx->stx_mode) ? ansi_highlight_magenta() : "",
                       ASSERT_PTR(S_ISDIR(sx->stx_mode) ? "dir" :
                                  S_ISREG(sx->stx_mode) ? "file" :
                                  S_ISLNK(sx->stx_mode) ? "link" :
                                  S_ISFIFO(sx->stx_mode) ? "fifo" :
                                  S_ISBLK(sx->stx_mode) ? "block" :
                                  S_ISCHR(sx->stx_mode) ? "char" :
                                  S_ISSOCK(sx->stx_mode) ? "socket" : NULL),
                       ansi_normal());
        }
 
        if (FLAGS_SET(sx->stx_mask, STATX_MODE) && (!FLAGS_SET(sx->stx_mask, STATX_TYPE) || !S_ISLNK(sx->stx_mode)))
                printf(" %smode=%s%04o",
                       ansi_grey(),
                       ansi_normal(),
                       (unsigned) (sx->stx_mode & 0777));
 
        if (FLAGS_SET(sx->stx_mask, STATX_UID))
                printf(" %suid=%s" UID_FMT "%s",
                       ansi_grey(),
                       pick_color_for_uid_gid(sx->stx_uid),
                       sx->stx_uid,
                       ansi_normal());
 
        if (FLAGS_SET(sx->stx_mask, STATX_GID))
                printf(" %sgid=%s" GID_FMT "%s",
                       ansi_grey(),
                       pick_color_for_uid_gid(sx->stx_gid),
                       sx->stx_gid,
                       ansi_normal());
 
        if (FLAGS_SET(sx->stx_mask, STATX_TYPE|STATX_SIZE) && S_ISREG(sx->stx_mode)) {
                printf(" %ssize=%s%" PRIu64,
                       ansi_grey(),
                       ansi_normal(),
                       (uint64_t) sx->stx_size);
 
                if (arg_mtree_hash && inode_fd >= 0 && sx->stx_size > 0) {
                        uint8_t hash[SHA256_DIGEST_SIZE];
 
                        r = get_file_sha256(inode_fd, hash);
                        if (r < 0)
                                log_warning_errno(r, "Failed to calculate file SHA256 sum for '%s', ignoring: %m", path);
                        else {
                                _cleanup_free_ char *h = NULL;
 
                                h = hexmem(hash, sizeof(hash));
                                if (!h)
                                        return log_oom();
 
                                printf(" %ssha256sum=%s%s",
                                       ansi_grey(),
                                       ansi_normal(),
                                       h);
                        }
                }
        }
 
        if (FLAGS_SET(sx->stx_mask, STATX_TYPE) && S_ISLNK(sx->stx_mode) && inode_fd >= 0) {
                _cleanup_free_ char *target = NULL;
 
                r = readlinkat_malloc(inode_fd, "", &target);
                if (r < 0)
                        log_warning_errno(r, "Failed to read symlink '%s', ignoring: %m", path);
                else {
                        _cleanup_free_ char *target_escaped = NULL;
 
                        target_escaped = xescape(target, WHITESPACE COMMENTS GLOB_CHARS);
                        if (!target_escaped)
                                return log_oom();
 
                        printf(" %slink=%s%s",
                               ansi_grey(),
                               ansi_normal(),
                               target_escaped);
                }
        }
 
        if (FLAGS_SET(sx->stx_mask, STATX_TYPE) && (S_ISBLK(sx->stx_mode) || S_ISCHR(sx->stx_mode)))
                printf(" %sdevice=%slinux,%" PRIu64 ",%" PRIu64,
                       ansi_grey(),
                       ansi_normal(),
                       (uint64_t) sx->stx_rdev_major,
                       (uint64_t) sx->stx_rdev_minor);
 
        printf("\n");
 
        return RECURSE_DIR_CONTINUE;
}
 
static int action_list_or_mtree_or_copy_or_make_archive(DissectedImage *m, LoopDevice *d, int userns_fd) {
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
        _cleanup_free_ char *t = NULL;
        const char *root;
        int r;
 
        assert(IN_SET(arg_action, ACTION_LIST, ACTION_MTREE, ACTION_COPY_FROM, ACTION_COPY_TO, ACTION_MAKE_ARCHIVE, ACTION_SHIFT));
 
        /* Determine whether to copy ownership:
         * --copy-ownership=yes: always try to preserve ownership
         *  --copy-ownership=no: never preserve ownership, use current user
         *              default: preserve ownership for directory trees,
         *                       but not for regular files (since DDI password tables are typically
         *                       distinct from the host ones, individual file ownership is less meaningful) */
 
        if (arg_image) {
                assert(m);
 
                if (userns_fd < 0)
                        r = detach_mount_namespace_harder(0, 0);
                else
                        r = detach_mount_namespace_userns(userns_fd);
                if (r < 0)
                        return log_error_errno(r, "Failed to detach mount namespace: %m");
 
                /* Create a place we can mount things onto soon. We use a fixed path shared by all invocations. Given
                 * the mounts are done in a mount namespace there's not going to be a collision here */
                r = get_common_dissect_directory(&t);
                if (r < 0)
                        return log_error_errno(r, "Failed to generate private mount directory: %m");
 
                r = dissected_image_mount_and_warn(
                                m,
                                t,
                                /* uid_shift= */ UID_INVALID,
                                /* uid_range= */ UID_INVALID,
                                /* userns_fd= */ -EBADF,
                                arg_flags);
                if (r < 0)
                        return r;
 
                root = mounted_dir = TAKE_PTR(t);
 
                if (d) {
                        r = loop_device_flock(d, LOCK_UN);
                        if (r < 0)
                                return log_error_errno(r, "Failed to unlock loopback block device: %m");
                }
 
                r = dissected_image_relinquish(m);
                if (r < 0)
                        return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
 
                dissected_image_close(m);
        } else
                root = arg_root;
 
        switch (arg_action) {
 
        case ACTION_COPY_FROM: {
                _cleanup_close_ int source_fd = -EBADF, target_fd = -EBADF;
 
                source_fd = chase_and_open(arg_source, root, CHASE_PREFIX_ROOT|CHASE_WARN, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
                if (source_fd < 0)
                        return log_error_errno(source_fd, "Failed to open source path '%s' in image '%s': %m", arg_source, arg_image);
 
                /* Copying to stdout? */
                if (streq(arg_target, "-")) {
                        r = copy_bytes(source_fd, STDOUT_FILENO, UINT64_MAX, /* copy_flags= */ 0);
                        if (r < 0)
                                return log_error_errno(r, "Failed to copy bytes from %s in mage '%s' to stdout: %m", arg_source, arg_image);
 
                        /* When we copy to stdout we don't copy any attributes (i.e. no access mode, no ownership, no xattr, no times) */
                        return 0;
                }
 
                /* Try to copy as directory? */
                r = copy_directory_at(
                                source_fd, /* from= */ NULL,
                                AT_FDCWD, arg_target,
                                arg_copy_ownership == 0 ? getuid() : UID_INVALID,
                                arg_copy_ownership == 0 ? getgid() : GID_INVALID,
                                COPY_MERGE|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS);
                if (r >= 0)
                        return 0;
                if (r != -ENOTDIR)
                        return log_error_errno(r, "Failed to copy %s in image '%s' to '%s': %m", arg_source, arg_image, arg_target);
 
                r = fd_verify_regular(source_fd);
                if (r == -EISDIR)
                        return log_error_errno(r, "Target '%s' exists already and is not a directory.", arg_target);
                if (r < 0)
                        return log_error_errno(r, "Source path %s in image '%s' is neither regular file nor directory, refusing: %m", arg_source, arg_image);
 
                /* Nah, it's a plain file! */
                target_fd = open(arg_target, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
                if (target_fd < 0)
                        return log_error_errno(errno, "Failed to create regular file at target path '%s': %m", arg_target);
 
                r = copy_bytes(source_fd, target_fd, UINT64_MAX, /* copy_flags= */ 0);
                if (r < 0)
                        return log_error_errno(r, "Failed to copy bytes from %s in mage '%s' to '%s': %m", arg_source, arg_image, arg_target);
 
                (void) copy_xattr(source_fd, NULL, target_fd, NULL, 0);
                (void) copy_access(source_fd, target_fd);
                if (arg_copy_ownership > 0)
                        (void) copy_owner(source_fd, target_fd);
                (void) copy_times(source_fd, target_fd, 0);
 
                return 0;
        }
 
        case ACTION_COPY_TO: {
                _cleanup_close_ int source_fd = -EBADF, target_fd = -EBADF, dfd = -EBADF;
                _cleanup_free_ char *dn = NULL, *bn = NULL;
                bool is_dir;
 
                r = path_extract_directory(arg_target, &dn);
                if (r < 0)
                        return log_error_errno(r, "Failed to extract directory from target path '%s': %m", arg_target);
                r = path_extract_filename(arg_target, &bn);
                if (r < 0)
                        return log_error_errno(r, "Failed to extract filename from target path '%s': %m", arg_target);
                is_dir = r == O_DIRECTORY;
 
                r = chase(dn, root, CHASE_PREFIX_ROOT|CHASE_WARN, NULL, &dfd);
                if (r < 0)
                        return log_error_errno(r, "Failed to open '%s': %m", dn);
 
                /* Are we reading from stdin? */
                if (streq(arg_source, "-")) {
                        if (is_dir)
                                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot copy STDIN to a directory, refusing.");
 
                        target_fd = openat(dfd, bn, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_EXCL, 0644);
                        if (target_fd < 0)
                                return log_error_errno(errno, "Failed to open target file '%s': %m", arg_target);
 
                        r = copy_bytes(STDIN_FILENO, target_fd, UINT64_MAX, /* copy_flags= */ 0);
                        if (r < 0)
                                return log_error_errno(r, "Failed to copy bytes from stdin to '%s' in image '%s': %m", arg_target, arg_image);
 
                        /* When we copy from stdin we don't copy any attributes (i.e. no access mode, no ownership, no xattr, no times) */
                        return 0;
                }
 
                source_fd = open(arg_source, O_RDONLY|O_CLOEXEC|O_NOCTTY);
                if (source_fd < 0)
                        return log_error_errno(source_fd, "Failed to open source path '%s': %m", arg_source);
 
                r = fd_verify_regular(source_fd);
                if (r < 0) {
                        if (r != -EISDIR)
                                return log_error_errno(r, "Source '%s' is neither regular file nor directory: %m", arg_source);
 
                        /* We are looking at a directory. */
 
                        target_fd = openat(dfd, bn, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
                        if (target_fd < 0) {
                                if (errno == ELOOP)
                                        return log_error_errno(SYNTHETIC_ERRNO(ELOOP),
                                                        "Refusing to copy directory to symlink destination '%s'.", arg_target);
 
                                if (errno != ENOENT)
                                        return log_error_errno(errno, "Failed to open destination '%s': %m", arg_target);
 
                                r = copy_tree_at(
                                                source_fd, ".",
                                                dfd, bn,
                                                arg_copy_ownership == 0 ? getuid() : UID_INVALID,
                                                arg_copy_ownership == 0 ? getgid() : GID_INVALID,
                                                COPY_MERGE|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS,
                                                /* denylist= */ NULL,
                                                /* subvolumes= */ NULL);
                        } else
                                r = copy_tree_at(
                                                source_fd, ".",
                                                target_fd, ".",
                                                arg_copy_ownership == 0 ? getuid() : UID_INVALID,
                                                arg_copy_ownership == 0 ? getgid() : GID_INVALID,
                                                COPY_MERGE|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS,
                                                /* denylist= */ NULL,
                                                /* subvolumes= */ NULL);
                        if (r < 0)
                                return log_error_errno(r, "Failed to copy '%s' to '%s' in image '%s': %m", arg_source, arg_target, arg_image);
 
                        return 0;
                }
 
                if (is_dir)
                        return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Source is a regular file, but target is not, refusing.");
 
                /* We area looking at a regular file */
                target_fd = openat(dfd, bn, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_EXCL, 0600);
                if (target_fd < 0)
                        return log_error_errno(errno, "Failed to open target file '%s': %m", arg_target);
 
                r = copy_bytes(source_fd, target_fd, UINT64_MAX, /* copy_flags= */ 0);
                if (r < 0)
                        return log_error_errno(r, "Failed to copy bytes from '%s' to '%s' in image '%s': %m", arg_source, arg_target, arg_image);
 
                (void) copy_xattr(source_fd, NULL, target_fd, NULL, 0);
                (void) copy_access(source_fd, target_fd);
                if (arg_copy_ownership > 0)
                        (void) copy_owner(source_fd, target_fd);
                (void) copy_times(source_fd, target_fd, 0);
 
                return 0;
        }
 
        case ACTION_LIST:
        case ACTION_MTREE: {
                _cleanup_close_ int dfd = -EBADF;
 
                dfd = open(root, O_DIRECTORY|O_CLOEXEC|O_RDONLY);
                if (dfd < 0)
                        return log_error_errno(errno, "Failed to open mount directory: %m");
 
                pager_open(arg_pager_flags);
 
                if (arg_action == ACTION_LIST)
                        r = recurse_dir(dfd, NULL, 0, UINT_MAX, RECURSE_DIR_SORT, list_print_item, NULL);
                else if (arg_action == ACTION_MTREE)
                        r = recurse_dir(dfd, ".", STATX_TYPE|STATX_MODE|STATX_UID|STATX_GID|STATX_SIZE, UINT_MAX, RECURSE_DIR_SORT|RECURSE_DIR_INODE_FD|RECURSE_DIR_TOPLEVEL, mtree_print_item, NULL);
                else
                        assert_not_reached();
                if (r < 0)
                        return log_error_errno(r, "Failed to list image: %m");
                return 0;
        }
 
        case ACTION_MAKE_ARCHIVE: {
#if HAVE_LIBARCHIVE
                _cleanup_close_ int dfd = -EBADF;
 
                dfd = open(root, O_DIRECTORY|O_CLOEXEC|O_RDONLY);
                if (dfd < 0)
                        return log_error_errno(errno, "Failed to open mount directory: %m");
 
                _cleanup_(unlink_and_freep) char *tar = NULL;
                _cleanup_close_ int tmp_fd = -EBADF;
                int output_fd;
                if (arg_target) {
                        tmp_fd = open_tmpfile_linkable(arg_target, O_WRONLY|O_CLOEXEC, &tar);
                        if (tmp_fd < 0)
                                return log_error_errno(tmp_fd, "Failed to create target file '%s': %m", arg_target);
 
                        output_fd = tmp_fd;
                } else {
                        if (isatty_safe(STDOUT_FILENO))
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Refusing to write archive to TTY.");
 
                        output_fd = STDOUT_FILENO;
                }
 
                r = tar_c(dfd, output_fd, arg_target, /* hardlink_db_fd= */ -EBADF, /* flags= */ 0);
                if (r < 0)
                        return r;
 
                if (arg_target) {
                        r = link_tmpfile(tmp_fd, tar, arg_target, LINK_TMPFILE_REPLACE);
                        if (r < 0)
                                return log_error_errno(r, "Failed to move archive file into place: %m");
 
                        tar = mfree(tar);
                }
 
                return 0;
#else
                assert_not_reached();
#endif
        }
 
        case ACTION_SHIFT:
                r = path_patch_uid(root, arg_uid_base, 0x10000);
                if (r < 0)
                        return log_error_errno(r, "Failed to shift UID base: %m");
 
                return 0;
 
        default:
                assert_not_reached();
        }
}
 
static int action_umount(const char *path) {
        _cleanup_close_ int fd = -EBADF;
        _cleanup_free_ char *canonical = NULL;
        _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
        int r;
 
        fd = chase_and_open(path, NULL, 0, O_DIRECTORY, &canonical);
        if (fd == -ENOTDIR)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTDIR), "'%s' is not a directory", path);
        if (fd < 0)
                return log_error_errno(fd, "Failed to resolve path '%s': %m", path);
 
        r = is_mount_point_at(fd, NULL, 0);
        if (r == 0)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "'%s' is not a mount point", canonical);
        if (r < 0)
                return log_error_errno(r, "Failed to determine whether '%s' is a mount point: %m", canonical);
 
        r = block_device_new_from_fd(fd, BLOCK_DEVICE_LOOKUP_WHOLE_DISK | BLOCK_DEVICE_LOOKUP_BACKING, &dev);
        if (r < 0) {
                _cleanup_close_ int usr_fd = -EBADF;
 
                /* The command `systemd-dissect --mount` expects that the image at least has the root or /usr
                 * partition. If it does not have the root partition, then we mount the /usr partition on a
                 * tmpfs. Hence, let's try to find the backing block device through the /usr partition. */
 
                usr_fd = openat(fd, "usr", O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
                if (usr_fd < 0)
                        return log_error_errno(errno, "Failed to open '%s/usr': %m", canonical);
 
                r = block_device_new_from_fd(usr_fd, BLOCK_DEVICE_LOOKUP_WHOLE_DISK | BLOCK_DEVICE_LOOKUP_BACKING, &dev);
        }
        if (r < 0)
                return log_error_errno(r, "Failed to find backing block device for '%s': %m", canonical);
 
        r = loop_device_open(dev, 0, LOCK_EX, &d);
        if (r < 0) {
                if (!ERRNO_IS_PRIVILEGE(r))
                        return log_device_error_errno(dev, r, "Failed to open loopback block device: %m");
 
                log_device_debug_errno(dev, r, "Lacking privileges to open loopback block device, ignoring.");
        }
 
        /* We've locked the loop device, now we're ready to unmount. To allow the unmount to succeed, we have
         * to close the O_PATH fd we opened earlier. */
        fd = safe_close(fd);
 
        r = umount_recursive(canonical, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to unmount '%s': %m", canonical);
 
        /* We managed to lock and unmount successfully? That means we can try to remove the loop device. */
        if (d)
                loop_device_unrelinquish(d);
 
        if (arg_rmdir) {
                r = RET_NERRNO(rmdir(canonical));
                if (r < 0)
                        return log_error_errno(r, "Failed to remove mount directory '%s': %m", canonical);
        }
 
        return 0;
}
 
static int action_with(DissectedImage *m, LoopDevice *d) {
        _cleanup_(umount_and_rmdir_and_freep) char *mounted_dir = NULL;
        _cleanup_(rmdir_and_freep) char *created_dir = NULL;
        _cleanup_free_ char *temp = NULL;
        int r, rcode;
 
        assert(m);
        assert(arg_action == ACTION_WITH);
 
        r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
        if (r < 0)
                return log_error_errno(r, "Failed to generate temporary mount directory: %m");
 
        r = mkdir_p(temp, 0700);
        if (r < 0)
                return log_error_errno(r, "Failed to create mount point: %m");
 
        created_dir = TAKE_PTR(temp);
 
        r = dissected_image_mount_and_warn(
                        m,
                        created_dir,
                        /* uid_shift= */ UID_INVALID,
                        /* uid_range= */ UID_INVALID,
                        /* userns_fd= */ -EBADF,
                        arg_flags);
        if (r < 0)
                return r;
 
        mounted_dir = TAKE_PTR(created_dir);
 
        r = dissected_image_relinquish(m);
        if (r < 0)
                return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
 
        if (d) {
                r = loop_device_flock(d, LOCK_UN);
                if (r < 0)
                        return log_error_errno(r, "Failed to unlock loopback block device: %m");
        }
 
        rcode = pidref_safe_fork("(with)", FORK_CLOSE_ALL_FDS|FORK_LOG|FORK_REOPEN_LOG|FORK_WAIT, /* ret= */ NULL);
        if (rcode == 0) {
                /* Child */
 
                if (chdir(mounted_dir) < 0) {
                        log_error_errno(errno, "Failed to change to '%s' directory: %m", mounted_dir);
                        _exit(EXIT_FAILURE);
                }
 
                if (setenv("SYSTEMD_DISSECT_ROOT", mounted_dir, /* overwrite= */ true) < 0) {
                        log_error_errno(errno, "Failed to set $SYSTEMD_DISSECT_ROOT: %m");
                        _exit(EXIT_FAILURE);
                }
 
                if (d && setenv("SYSTEMD_DISSECT_DEVICE", d->node, /* overwrite= */ true) < 0) {
                        log_error_errno(errno, "Failed to set $SYSTEMD_DISSECT_DEVICE: %m");
                        _exit(EXIT_FAILURE);
                }
 
                if (strv_isempty(arg_argv)) {
                        const char *sh;
 
                        sh = secure_getenv("SHELL");
                        if (sh) {
                                execvp(sh, STRV_MAKE(sh));
                                log_warning_errno(errno, "Failed to execute $SHELL, falling back to /bin/sh: %m");
                        }
 
                        execl("/bin/sh", "sh", NULL);
                        log_error_errno(errno, "Failed to invoke /bin/sh: %m");
                } else {
                        execvp(arg_argv[0], arg_argv);
                        log_error_errno(errno, "Failed to execute '%s': %m", arg_argv[0]);
                }
 
                _exit(EXIT_FAILURE);
        }
 
        /* Let's manually detach everything, to make things synchronous */
        if (d) {
                r = loop_device_flock(d, LOCK_SH);
                if (r < 0)
                        log_warning_errno(r, "Failed to lock loopback block device, ignoring: %m");
        }
 
        r = umount_recursive(mounted_dir, 0);
        if (r < 0)
                log_warning_errno(r, "Failed to unmount '%s', ignoring: %m", mounted_dir);
        else if (d)
                loop_device_unrelinquish(d); /* Let's try to destroy the loopback device */
 
        created_dir = TAKE_PTR(mounted_dir);
 
        if (rmdir(created_dir) < 0)
                log_warning_errno(errno, "Failed to remove directory '%s', ignoring: %m", created_dir);
 
        temp = TAKE_PTR(created_dir);
 
        return rcode;
}
 
static int action_discover(void) {
        _cleanup_hashmap_free_ Hashmap *images = NULL;
        int r;
 
        for (ImageClass cl = 0; cl < _IMAGE_CLASS_MAX; cl++) {
                r = image_discover(arg_runtime_scope, cl, NULL, &images);
                if (r < 0)
                        return log_error_errno(r, "Failed to discover images: %m");
        }
 
        if (hashmap_isempty(images) && !sd_json_format_enabled(arg_json_format_flags)) {
                log_info("No images found.");
                return 0;
        }
 
        _cleanup_(table_unrefp) Table *t = table_new("name", "type", "class", "ro", "path", "time", "usage");
        if (!t)
                return log_oom();
 
        table_set_align_percent(t, table_get_cell(t, 0, 6), 100);
        table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
 
        Image *img;
        HASHMAP_FOREACH(img, images) {
 
                if (!arg_all && startswith(img->name, "."))
                        continue;
 
                r = table_add_many(
                                t,
                                TABLE_STRING, img->name,
                                TABLE_SET_COLOR, startswith(img->name, ".") ? ANSI_GREY : NULL,
                                TABLE_STRING, image_type_to_string(img->type),
                                TABLE_STRING, image_class_to_string(img->class),
                                TABLE_BOOLEAN, image_is_read_only(img),
                                TABLE_SET_COLOR, image_is_read_only(img) ? ANSI_HIGHLIGHT_RED : ANSI_HIGHLIGHT_GREEN,
                                TABLE_PATH, img->path,
                                TABLE_TIMESTAMP, img->mtime != 0 ? img->mtime : img->crtime,
                                TABLE_SIZE, img->usage,
                                TABLE_SET_COLOR, img->usage <= 0 ? ANSI_HIGHLIGHT_RED : NULL);
                if (r < 0)
                        return table_log_add_error(r);
        }
 
        (void) table_set_sort(t, (size_t) 0);
 
        return table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
}
 
static int action_attach(DissectedImage *m, LoopDevice *d) {
        int r;
 
        assert(m);
        assert(d);
 
        r = loop_device_set_autoclear(d, false);
        if (r < 0)
                return log_error_errno(r, "Failed to disable auto-clear logic on loopback device: %m");
 
        r = dissected_image_relinquish(m);
        if (r < 0)
                return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
 
        if (!arg_quiet)
                puts(d->node);
 
        return 0;
}
 
static int action_detach(const char *path) {
        _cleanup_(loop_device_unrefp) LoopDevice *loop = NULL;
        _cleanup_close_ int fd = -EBADF;
        struct stat st;
        int r;
 
        assert(path);
 
        fd = open(path, O_PATH|O_CLOEXEC);
        if (fd < 0)
                return log_error_errno(errno, "Failed to open '%s': %m", path);
 
        if (fstat(fd, &st) < 0)
                return log_error_errno(errno, "Failed to stat '%s': %m", path);
 
        if (S_ISBLK(st.st_mode)) {
                r = loop_device_open_from_fd(fd, O_RDONLY, LOCK_EX, &loop);
                if (r < 0)
                        return log_error_errno(r, "Failed to open '%s' as loopback block device: %m", path);
 
        } else if (S_ISREG(st.st_mode)) {
                _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
 
                /* If a regular file is specified, search for a loopback block device that is backed by it */
 
                r = sd_device_enumerator_new(&e);
                if (r < 0)
                        return log_error_errno(r, "Failed to allocate enumerator: %m");
 
                r = sd_device_enumerator_add_match_subsystem(e, "block", true);
                if (r < 0)
                        return log_error_errno(r, "Failed to match block devices: %m");
 
                r = sd_device_enumerator_add_match_sysname(e, "loop*");
                if (r < 0)
                        return log_error_errno(r, "Failed to match loopback block devices: %m");
 
                (void) sd_device_enumerator_allow_uninitialized(e);
 
                FOREACH_DEVICE(e, d) {
                        _cleanup_(loop_device_unrefp) LoopDevice *entry_loop = NULL;
 
                        r = device_is_devtype(d, "disk");
                        if (r < 0) {
                                log_device_warning_errno(d, r, "Failed to check if device is a whole disk, skipping: %m");
                                continue;
                        }
                        if (r == 0)
                                continue; /* Filter out partition block devices */
 
                        r = loop_device_open(d, O_RDONLY, LOCK_SH, &entry_loop);
                        if (r < 0) {
                                log_device_warning_errno(d, r, "Failed to open loopback block device, skipping: %m");
                                continue;
                        }
 
                        if (entry_loop->backing_devno == st.st_dev && entry_loop->backing_inode == st.st_ino) {
                                /* Found it! The kernel allows attaching a single file to multiple loopback
                                 * devices. Let's destruct them in reverse order, i.e. find the last matching
                                 * loopback device here, rather than the first. */
 
                                loop_device_unref(loop);
                                loop = TAKE_PTR(entry_loop);
                        }
                }
 
                if (!loop)
                        return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "No loopback block device backed by '%s' found.", path);
 
                r = loop_device_flock(loop, LOCK_EX);
                if (r < 0)
                        return log_error_errno(r, "Failed to upgrade device lock: %m");
        }
 
        r = loop_device_set_autoclear(loop, true);
        if (r < 0)
                log_warning_errno(r, "Failed to enable autoclear logic on '%s', ignoring: %m", loop->node);
 
        loop_device_unrelinquish(loop);
        return 0;
}
 
static int action_validate(void) {
        int r;
 
        r = dissect_image_file_and_warn(
                        arg_image,
                        &arg_verity_settings,
                        /* mount_options= */ NULL,
                        arg_image_policy,
                        arg_image_filter,
                        arg_flags,
                        /* ret= */ NULL);
        if (r < 0)
                return r;
 
        if (isatty_safe(STDOUT_FILENO) && emoji_enabled())
                printf("%s ", glyph(GLYPH_SPARKLES));
 
        printf("%sOK%s", ansi_highlight_green(), ansi_normal());
 
        if (isatty_safe(STDOUT_FILENO) && emoji_enabled())
                printf(" %s", glyph(GLYPH_SPARKLES));
 
        putc('\n', stdout);
        return 0;
}
 
static int run(int argc, char *argv[]) {
        _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
        _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
        _cleanup_close_ int userns_fd = -EBADF;
        int r;
 
        LIBACL_NOTE(recommended);
        LIBARCHIVE_NOTE(recommended);
        LIBBLKID_NOTE(recommended);
        LIBCRYPTO_NOTE(suggested);
        LIBCRYPTSETUP_NOTE(suggested);
        LIBMOUNT_NOTE(recommended);
        LIBSELINUX_NOTE(recommended);
 
        log_setup();
 
        if (invoked_as(argv, "mount.ddi"))
                r = parse_argv_as_mount_helper(argc, argv);
        else
                r = parse_argv(argc, argv);
        if (r <= 0)
                return r;
 
        if (arg_image) {
                r = path_pick_update_warn(
                                &arg_image,
                                pick_filter_image_raw,
                                ELEMENTSOF(pick_filter_image_raw),
                                PICK_ARCHITECTURE|PICK_TRIES,
                                /* ret_result= */ NULL);
                if (r < 0)
                        return r;
        }
 
        if (arg_root) {
                r = path_pick_update_warn(
                                &arg_root,
                                pick_filter_image_dir,
                                ELEMENTSOF(pick_filter_image_dir),
                                PICK_ARCHITECTURE|PICK_TRIES,
                                /* ret_result= */ NULL);
                if (r < 0)
                        return r;
        }
 
        switch (arg_action) {
        case ACTION_UMOUNT:
                return action_umount(arg_path);
 
        case ACTION_DETACH:
                return action_detach(arg_image);
 
        case ACTION_DISCOVER:
                return action_discover();
 
        default:
                /* All other actions need the image dissected (except for ACTION_VALIDATE, see below) */
                ;
        }
 
        if (arg_image) {