HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/dissect-image.c

242,096 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 9280a90974918216809a09219e8a3162bddcf789

Lines 2001–3000 of 5,731

            (verity->designator >= 0 && verity->designator != PARTITION_ROOT) ||
            !iovec_is_set(&verity->root_hash))
                return -ENOPKG;
 
        /* The policy fstype flags translate to the literal fstype name of each filesystem.
         * Input must be a single filesystem image, if the policy specifies more than one, we need to dissect */
        r = partition_policy_determine_fstype(image_policy, PARTITION_ROOT, &encrypted, &root_fstype_string);
        if (r < 0)
                return r;
        if (!root_fstype_string)
                return -ENOPKG;
 
        if (verity_settings_data_covers(verity, PARTITION_ROOT))
                found_flags = iovec_is_set(&verity->root_hash_sig) ? PARTITION_POLICY_SIGNED : PARTITION_POLICY_VERITY;
        else
                found_flags = encrypted ? PARTITION_POLICY_ENCRYPTED : PARTITION_POLICY_UNPROTECTED;
 
        root_hash_encoded = hexmem(verity->root_hash.iov_base, verity->root_hash.iov_len);
        if (!root_hash_encoded)
                return -ENOMEM;
 
        node = strjoin("/dev/mapper/", root_hash_encoded, "-verity");
        if (!node)
                return -ENOMEM;
 
        r = dissected_image_new(src, &dissected_image);
        if (r < 0)
                return r;
 
        mount_node_fd = open_partition(node, /* is_partition= */ false, /* loop= */ NULL);
        if (mount_node_fd < 0)
                return mount_node_fd;
 
        r = dissect_image_from_unpartitioned(
                        node,
                        /* diskseq= */ 0,
                        /* uuid= */ NULL,
                        encrypted,
                        verity,
                        options,
                        image_policy,
                        image_filter,
                        &mount_node_fd,
                        &root_fstype_string,
                        dissected_image,
                        dissect_image_flags,
                        found_flags);
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(dissected_image);
 
        return 0;
#else
        return -EOPNOTSUPP;
#endif
}
 
int dissect_image_file(
                const char *path,
                const VeritySettings *verity,
                const MountOptions *mount_options,
                const ImagePolicy *image_policy,
                const ImageFilter *image_filter,
                DissectImageFlags flags,
                DissectedImage **ret) {
 
#if HAVE_BLKID
        _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
        _cleanup_close_ int fd = -EBADF;
        struct stat st;
        int r;
 
        assert(path);
 
        fd = open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
        if (fd < 0)
                return -errno;
 
        if (fstat(fd, &st) < 0)
                return -errno;
 
        r = stat_verify_regular(&st);
        if (r < 0)
                return r;
 
        r = dissected_image_new(path, &m);
        if (r < 0)
                return r;
 
        m->image_size = st.st_size;
 
        r = probe_sector_size(fd, &m->sector_size);
        if (r < 0)
                return r;
 
        r = dissect_image(m, fd, path, verity, mount_options, image_policy, image_filter, flags);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = TAKE_PTR(m);
        return 0;
#else
        return -EOPNOTSUPP;
#endif
}
 
int dissect_log_error(int log_level, int r, const char *name, const VeritySettings *verity) {
        assert(log_level >= 0 && log_level <= LOG_DEBUG);
        assert(name);
 
        switch (r) {
 
        case 0 ... INT_MAX: /* success! */
                return r;
 
        case -EOPNOTSUPP:
                return log_full_errno(log_level, r, "Dissecting images is not supported, compiled without blkid support.");
 
        case -ENOPKG:
                return log_full_errno(log_level, r, "%s: Couldn't identify a suitable partition table or file system.", name);
 
        case -ENOMEDIUM:
                return log_full_errno(log_level, r, "%s: The image does not pass os-release/extension-release validation.", name);
 
        case -EADDRNOTAVAIL:
                return log_full_errno(log_level, r, "%s: No root/usr partition for specified root/usr hash found.", name);
 
        case -EREMOTE:
                return log_full_errno(log_level, r, "%s: Found root and usr partitions with different architectures", name);
 
        case -ENOTUNIQ:
                return log_full_errno(log_level, r, "%s: Multiple suitable root partitions found in image.", name);
 
        case -ENXIO:
                return log_full_errno(log_level, r, "%s: No suitable root partition found in image.", name);
 
        case -EPROTONOSUPPORT:
                return log_full_errno(log_level, r, "Device '%s' is a loopback block device with partition scanning turned off, please turn it on.", name);
 
        case -ENOTBLK:
                return log_full_errno(log_level, r, "%s: Image is not a block device.", name);
 
        case -EBADR:
                return log_full_errno(log_level, r,
                                      "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
                                      "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
                                      name, strna(verity ? verity->data_path : NULL));
 
        case -ERFKILL:
                return log_full_errno(log_level, r, "%s: Image does not match image policy.", name);
 
        case -ENOMSG:
                return log_full_errno(log_level, r, "%s: No suitable partitions found.", name);
 
        case -EUCLEAN:
                return log_full_errno(log_level, r, "%s: Partition with ambiguous file system superblock signature found.", name);
 
        default:
                return log_full_errno(log_level, r, "%s: Cannot dissect image: %m", name);
        }
}
 
int dissect_image_file_and_warn(
                const char *path,
                const VeritySettings *verity,
                const MountOptions *mount_options,
                const ImagePolicy *image_policy,
                const ImageFilter *image_filter,
                DissectImageFlags flags,
                DissectedImage **ret) {
 
        return dissect_log_error(
                        LOG_ERR,
                        dissect_image_file(path, verity, mount_options, image_policy, image_filter, flags, ret),
                        path,
                        verity);
}
 
void dissected_image_close(DissectedImage *m) {
        if (!m)
                return;
 
        /* Closes all fds we keep open associated with this, but nothing else */
 
        FOREACH_ARRAY(p, m->partitions, _PARTITION_DESIGNATOR_MAX) {
                p->mount_node_fd = safe_close(p->mount_node_fd);
                p->fsmount_fd = safe_close(p->fsmount_fd);
        }
 
        m->loop = loop_device_unref(m->loop);
}
 
DissectedImage* dissected_image_unref(DissectedImage *m) {
        if (!m)
                return NULL;
 
        /* First, clear dissected partitions. */
        for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
                dissected_partition_done(m->partitions + i);
 
        /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
         * DecryptedImage may try to deactivate partitions. */
        decrypted_image_unref(m->decrypted_image);
 
        /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
         * remove existing partitions on the loopback block device. */
        loop_device_unref(m->loop);
 
        free(m->image_name);
        free(m->hostname);
        strv_free(m->machine_info);
        strv_free(m->os_release);
        strv_free(m->initrd_release);
        strv_free(m->confext_release);
        strv_free(m->sysext_release);
 
        return mfree(m);
}
 
static int is_loop_device(const char *path) {
        char s[SYS_BLOCK_PATH_MAX("/../loop/")];
        struct stat st;
        int r;
 
        assert(path);
 
        if (stat(path, &st) < 0)
                return -errno;
 
        r = stat_verify_block(&st);
        if (r < 0)
                return r;
 
        xsprintf_sys_block_path(s, "/loop/", st.st_dev);
        if (access(s, F_OK) < 0) {
                if (errno != ENOENT)
                        return -errno;
 
                /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
                xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
                if (access(s, F_OK) < 0)
                        return errno == ENOENT ? false : -errno;
        }
 
        return true;
}
 
static int run_fsck(int node_fd, const char *fstype) {
        int r, exit_status;
 
        assert(node_fd >= 0);
        assert(fstype);
 
        r = fsck_exists_for_fstype(fstype);
        if (r < 0) {
                log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
                return 0;
        }
        if (r == 0) {
                log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd), fstype);
                return 0;
        }
 
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
        r = pidref_safe_fork_full(
                        "(fsck)",
                        NULL,
                        &node_fd, 1, /* Leave the node fd open */
                        FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG_SIGTERM|FORK_REARRANGE_STDIO|FORK_CLOEXEC_OFF,
                        &pidref);
        if (r < 0)
                return log_debug_errno(r, "Failed to fork off fsck: %m");
        if (r == 0) {
                /* Child */
                execlp("fsck", "fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd), NULL);
                log_open();
                log_debug_errno(errno, "Failed to execl() fsck: %m");
                _exit(FSCK_OPERATIONAL_ERROR);
        }
 
        exit_status = pidref_wait_for_terminate_and_check("fsck", &pidref, 0);
        if (exit_status < 0)
                return log_debug_errno(exit_status, "Failed to fork off fsck: %m");
 
        if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
                log_debug("fsck failed with exit status %i.", exit_status);
 
                if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
                        return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
 
                log_debug("Ignoring fsck error.");
        }
 
        return 0;
}
 
static int fs_grow(const char *node_path, int mount_fd, const char *mount_path) {
        _cleanup_close_ int _mount_fd = -EBADF, node_fd = -EBADF;
        uint64_t size, newsize;
        const char *id;
        int r;
 
        assert(node_path);
        assert(mount_fd >= 0 || mount_path);
 
        node_fd = open(node_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
        if (node_fd < 0)
                return log_debug_errno(errno, "Failed to open node device %s: %m", node_path);
 
        r = blockdev_get_device_size(node_fd, &size);
        if (r < 0)
                return log_debug_errno(r, "Failed to get block device size of %s: %m", node_path);
 
        if (mount_fd < 0) {
                assert(mount_path);
 
                _mount_fd = open(mount_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
                if (_mount_fd < 0)
                        return log_debug_errno(errno, "Failed to open mounted file system %s: %m", mount_path);
 
                mount_fd = _mount_fd;
        } else {
                mount_fd = fd_reopen_condition(mount_fd, O_RDONLY|O_DIRECTORY|O_CLOEXEC, O_RDONLY|O_DIRECTORY|O_CLOEXEC, &_mount_fd);
                if (mount_fd < 0)
                        return log_debug_errno(errno, "Failed to reopen mount node: %m");
        }
 
        id = mount_path ?: node_path;
 
        log_debug("Resizing \"%s\" to %"PRIu64" bytes...", id, size);
        r = resize_fs(mount_fd, size, &newsize);
        if (r < 0)
                return log_debug_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m", id, size);
 
        if (newsize == size)
                log_debug("Successfully resized \"%s\" to %s bytes.",
                          id, FORMAT_BYTES(newsize));
        else {
                assert(newsize < size);
                log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
                          id, FORMAT_BYTES(newsize), size - newsize);
        }
 
        return 0;
}
 
int partition_pick_mount_options(
                PartitionDesignator d,
                const char *fstype,
                bool rw,
                bool discard,
                char **ret_options,
                unsigned long *ret_ms_flags) {
 
        _cleanup_free_ char *options = NULL;
 
        assert(ret_options);
 
        /* Selects a baseline of bind mount flags, that should always apply.
         *
         * Firstly, we set MS_NODEV universally on all mounts, since we don't want to allow device nodes outside of /dev/.
         *
         * On /var/tmp/ we'll also set MS_NOSUID, same as we set for /tmp/ on the host.
         *
         * On the ESP and XBOOTLDR partitions we'll also disable symlinks, and execution. These file systems
         * are generally untrusted (i.e. not encrypted or authenticated), and typically VFAT hence we should
         * be as restrictive as possible, and this shouldn't hurt, since the functionality is not available
         * there anyway. */
 
        unsigned long flags = MS_NODEV;
 
        if (!rw)
                flags |= MS_RDONLY;
 
        switch (d) {
 
        case PARTITION_ESP:
        case PARTITION_XBOOTLDR:
                flags |= MS_NOSUID|MS_NOEXEC|MS_NOSYMFOLLOW;
 
                /* The ESP might contain a pre-boot random seed. Let's make this inaccessible to regular
                 * userspace. ESP/XBOOTLDR is almost certainly VFAT, hence if we don't know assume it is. */
                if (!fstype || fstype_can_fmask_dmask(fstype))
                        if (!strextend_with_separator(&options, ",", "fmask=0177,dmask=0077"))
                                return -ENOMEM;
                break;
 
        case PARTITION_TMP:
                flags |= MS_NOSUID;
                break;
 
        default:
                ;
        }
 
        /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
         * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
         * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
         * from the upper file system still get propagated through to the underlying file system,
         * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
         * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
         * carry a per file system table here.
         *
         * Note that this means that we might not be able to mount corrupted file systems as read-only
         * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
         * read-only and "norecovery" is specified). But I think for the case of automatically determined
         * mount options for loopback devices this is the right choice, since otherwise using the same
         * loopback file twice even in read-only mode, is going to fail badly sooner or later. The use case of
         * making reuse of the immutable images "just work" is more relevant to us than having read-only
         * access that actually modifies stuff work on such image files. Or to say this differently: if
         * people want their file systems to be fixed up they should just open them in writable mode, where
         * all these problems don't exist. */
        if (!rw && fstype) {
                const char *option = fstype_norecovery_option(fstype);
 
                if (option && !strextend_with_separator(&options, ",", option))
                        return -ENOMEM;
        }
 
        if (discard && fstype && fstype_can_discard(fstype))
                if (!strextend_with_separator(&options, ",", "discard"))
                        return -ENOMEM;
 
        if (!ret_ms_flags) /* Fold flags into option string if ret_flags specified as NULL */
                if (!strextend_with_separator(&options, ",",
                                              FLAGS_SET(flags, MS_RDONLY) ? "ro" : "rw",
                                              FLAGS_SET(flags, MS_NODEV) ? "nodev" : "dev",
                                              FLAGS_SET(flags, MS_NOSUID) ? "nosuid" : "suid",
                                              FLAGS_SET(flags, MS_NOEXEC) ? "noexec" : "exec",
                                              FLAGS_SET(flags, MS_NOSYMFOLLOW) ? "nosymfollow" : NULL))
                        /* NB: we suppress 'symfollow' here, since it's the default, and old /bin/mount might not know it */
                        return -ENOMEM;
 
        if (ret_ms_flags)
                *ret_ms_flags = flags;
 
        *ret_options = TAKE_PTR(options);
        return 0;
}
 
static bool need_user_mapping(uid_t uid_shift, uid_t uid_range) {
 
        if (!uid_is_valid(uid_shift))
                return false;
 
        return uid_shift != 0 || uid_range != UINT32_MAX;
}
 
static int mount_partition(
                PartitionDesignator d,
                DissectedPartition *m,
                const char *where,
                const char *directory,
                uid_t uid_shift,
                uid_t uid_range,
                int userns_fd,
                DissectImageFlags flags) {
 
        _cleanup_free_ char *chased = NULL, *options = NULL;
        const char *p = NULL, *node, *fstype = NULL;
        bool rw, discard, grow;
        unsigned long ms_flags;
        int r;
 
        assert(m);
 
        if (!m->found)
                return 0;
 
        /* Check the various combinations when we can't do anything anymore */
        if (m->fsmount_fd < 0 && m->mount_node_fd < 0)
                return 0;
        if (m->fsmount_fd >= 0 && !where)
                return 0;
        if (!where && m->mount_node_fd < 0)
                return 0;
 
        if (m->fsmount_fd < 0) {
                fstype = dissected_partition_fstype(m);
                if (!fstype)
                        return -EAFNOSUPPORT;
 
                /* We are looking at an encrypted partition? This either means stacked encryption, or the
                 * caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error
                 * for this case. */
                if (streq(fstype, "crypto_LUKS"))
                        return -EUNATCH;
 
                r = dissect_fstype_ok(fstype);
                if (r < 0)
                        return r;
                if (!r)
                        return -EIDRM; /* Recognizable error */
        }
 
        node = m->mount_node_fd < 0 ? NULL : FORMAT_PROC_FD_PATH(m->mount_node_fd);
        rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
 
        discard = ((flags & DISSECT_IMAGE_DISCARD) ||
                   ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && (m->node && is_loop_device(m->node) > 0)));
 
        grow = rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS);
 
        if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw && m->mount_node_fd >= 0 && m->fsmount_fd < 0) {
                r = run_fsck(m->mount_node_fd, fstype);
                if (r < 0)
                        return r;
        }
 
        if (where) {
                if (directory) {
                        /* Automatically create missing mount points inside the image, if necessary. */
                        r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
                        if (r < 0 && r != -EROFS)
                                return r;
 
                        r = chase(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
                        if (r < 0)
                                return r;
 
                        p = chased;
                } else {
                        /* Create top-level mount if missing – but only if this is asked for. This won't modify the
                         * image (as the branch above does) but the host hierarchy, and the created directory might
                         * survive our mount in the host hierarchy hence. */
                        if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
                                r = mkdir_p(where, 0755);
                                if (r < 0)
                                        return r;
                        }
 
                        p = where;
                }
        }
 
        if (m->fsmount_fd < 0) {
                r = partition_pick_mount_options(d, fstype, rw, discard, &options, &ms_flags);
                if (r < 0)
                        return r;
 
                if (need_user_mapping(uid_shift, uid_range) && fstype_can_uid_gid(fstype)) {
                        _cleanup_free_ char *uid_option = NULL;
 
                        if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
                                return -ENOMEM;
 
                        if (!strextend_with_separator(&options, ",", uid_option))
                                return -ENOMEM;
 
                        userns_fd = -EBADF; /* Not needed */
                }
 
                if (!isempty(m->mount_options))
                        if (!strextend_with_separator(&options, ",", m->mount_options))
                                return -ENOMEM;
        }
 
        if (p) {
                if (m->fsmount_fd >= 0) {
                        /* Case #1: Attach existing fsmount fd to the file system */
 
                        r = mount_exchange_graceful(
                                        m->fsmount_fd,
                                        p,
                                        FLAGS_SET(flags, DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE));
                        if (r < 0)
                                return log_debug_errno(r, "Failed to mount image on '%s': %m", p);
 
                } else {
                        assert(node);
 
                        /* Case #2: Mount directly into place */
                        r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, ms_flags, options);
                        if (r < 0)
                                return r;
 
                        if (grow)
                                (void) fs_grow(node, -EBADF, p);
 
                        if (userns_fd >= 0) {
                                r = remount_idmap_fd(STRV_MAKE(p), userns_fd, /* extra_mount_attr_set= */ 0);
                                if (r < 0)
                                        return r;
                        }
                }
        } else {
                assert(node);
 
                /* Case #3: Create fsmount fd */
 
                m->fsmount_fd = make_fsmount(LOG_DEBUG, node, fstype, ms_flags, options, userns_fd);
                if (m->fsmount_fd < 0)
                        return m->fsmount_fd;
 
                if (grow)
                        (void) fs_grow(node, m->fsmount_fd, NULL);
        }
 
        return 1;
}
 
static int mount_root_tmpfs(const char *where, uid_t uid_shift, uid_t uid_range, DissectImageFlags flags) {
        _cleanup_free_ char *options = NULL;
        int r;
 
        assert(where);
 
        /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
 
        if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
                r = mkdir_p(where, 0755);
                if (r < 0)
                        return r;
        }
 
        if (need_user_mapping(uid_shift, uid_range)) {
                if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
                        return -ENOMEM;
        }
 
        r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
        if (r < 0)
                return r;
 
        return 1;
}
 
static int mount_point_is_available(const char *where, const char *path, bool missing_ok) {
        _cleanup_free_ char *p = NULL;
        int r;
 
        /* Check whether <path> is suitable as a mountpoint, i.e. is an empty directory
         * or does not exist at all (when missing_ok). */
 
        r = chase(path, where, CHASE_PREFIX_ROOT, &p, NULL);
        if (r == -ENOENT)
                return missing_ok;
        if (r < 0)
                return log_debug_errno(r, "Failed to chase \"%s\": %m", path);
 
        r = dir_is_empty(p, /* ignore_hidden_or_backup= */ false);
        if (r == -ENOTDIR)
                return false;
        if (r < 0)
                return log_debug_errno(r, "Failed to check directory \"%s\": %m", p);
        return r > 0;
}
 
int dissected_image_mount(
                DissectedImage *m,
                const char *where,
                uid_t uid_shift,
                uid_t uid_range,
                int userns_fd,
                DissectImageFlags flags) {
 
        _cleanup_close_ int my_userns_fd = -EBADF;
        int r;
 
        assert(m);
 
        if (FLAGS_SET(flags, DISSECT_IMAGE_FOREIGN_UID)) /* For image based mounts we currently require an identity mapping */
                return -EOPNOTSUPP;
 
        /* If 'where' is NULL then we'll use the new mount API to create fsmount() fds for the mounts and
         * store them in DissectedPartition.fsmount_fd.
         *
         * If 'where' is not NULL then we'll either mount the partitions to the right places ourselves,
         * or use DissectedPartition.fsmount_fd and bind it to the right places.
         *
         * This allows splitting the setting up the superblocks and the binding to file systems paths into
         * two distinct and differently privileged components: one that gets the fsmount fds, and the other
         * that then applies them.
         *
         * Returns:
         *
         *  -ENXIO        → No root partition found
         *  -EMEDIUMTYPE  → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
         *  -EUNATCH      → Encrypted partition found for which no dm-crypt was set up yet
         *  -EUCLEAN      → fsck for file system failed
         *  -EBUSY        → File system already mounted/used elsewhere (kernel)
         *  -EAFNOSUPPORT → File system type not supported or not known
         *  -EIDRM        → File system is not among allowlisted "common" file systems
         */
 
        if (!where && (flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0)
                return -EOPNOTSUPP; /* for now, not supported */
 
        if (!(m->partitions[PARTITION_ROOT].found ||
              (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
                return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
 
        if (userns_fd < 0 && need_user_mapping(uid_shift, uid_range) && FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED)) {
 
                my_userns_fd = make_userns(uid_shift, uid_range, UID_INVALID, UID_INVALID, REMOUNT_IDMAPPING_HOST_ROOT);
                if (my_userns_fd < 0)
                        return my_userns_fd;
 
                userns_fd = my_userns_fd;
        }
 
        if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
 
                /* First mount the root fs. If there's none we use a tmpfs. */
                if (m->partitions[PARTITION_ROOT].found) {
                        r = mount_partition(PARTITION_ROOT, m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, userns_fd, flags);
                        if (r < 0)
                                return r;
 
                } else if (where) {
                        r = mount_root_tmpfs(where, uid_shift, uid_range, flags);
                        if (r < 0)
                                return r;
                }
 
                /* For us mounting root always means mounting /usr as well */
                r = mount_partition(PARTITION_USR, m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, userns_fd, flags);
                if (r < 0)
                        return r;
        }
 
        if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0 &&
            (flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
                /* If either one of the validation flags are set, ensure that the image qualifies as
                 * one or the other (or both). */
                bool ok = false;
 
                assert(where);
 
                if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
                        log_debug("Checking if '%s' is an OS tree", where);
 
                        r = path_is_os_tree(where);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to check is '%s' is an OS tree: %m", where);
                        if (r > 0) {
                                log_debug("Successfully identified '%s' as an OS tree", where);
                                ok = true;
                        }
                }
                if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT) && m->image_name) {
                        log_debug("Checking if '%s' is an extension tree", where);
 
                        r = extension_has_forbidden_content(where);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to check if '%s' contains content forbidden for an extension image: %m", where);
                        if (r == 0) {
                                ImageClass class = IMAGE_SYSEXT;
                                r = path_is_extension_tree(class, where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_EXTENSION_CHECK));
                                if (r == 0) {
                                        class = IMAGE_CONFEXT;
                                        r = path_is_extension_tree(class, where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_EXTENSION_CHECK));
                                }
                                if (r < 0)
                                        return log_debug_errno(r, "Failed to check if '%s' is an extension tree: %m", where);
                                if (r > 0) {
                                        log_debug("Successfully identified '%s' as a %s extension tree", where, image_class_to_string(class));
                                        ok = true;
                                }
                        }
                }
 
                if (!ok)
                        return -ENOMEDIUM;
        }
 
        if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
                return 0;
 
        r = mount_partition(PARTITION_HOME, m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, userns_fd, flags);
        if (r < 0)
                return r;
 
        r = mount_partition(PARTITION_SRV, m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, userns_fd, flags);
        if (r < 0)
                return r;
 
        r = mount_partition(PARTITION_VAR, m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, userns_fd, flags);
        if (r < 0)
                return r;
 
        r = mount_partition(PARTITION_TMP, m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, userns_fd, flags);
        if (r < 0)
                return r;
 
        int slash_boot_is_available = 0;
        if (where) {
                r = slash_boot_is_available = mount_point_is_available(where, "/boot", /* missing_ok= */ true);
                if (r < 0)
                        return r;
        }
        if (!where || slash_boot_is_available) {
                r = mount_partition(PARTITION_XBOOTLDR, m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, userns_fd, flags);
                if (r < 0)
                        return r;
                slash_boot_is_available = !r;
        }
 
        if (m->partitions[PARTITION_ESP].found) {
                const char *esp_path = NULL;
 
                if (where) {
                        /* Mount the ESP to /boot/ if it exists and is empty and we didn't already mount the
                         * XBOOTLDR partition into it. Otherwise, use /efi instead, but only if it exists
                         * and is empty. */
 
                        if (slash_boot_is_available) {
                                r = mount_point_is_available(where, "/boot", /* missing_ok= */ false);
                                if (r < 0)
                                        return r;
                                if (r > 0)
                                        esp_path = "/boot";
                        }
 
                        if (!esp_path) {
                                r = mount_point_is_available(where, "/efi", /* missing_ok= */ true);
                                if (r < 0)
                                        return r;
                                if (r > 0)
                                        esp_path = "/efi";
                        }
                }
 
                /* OK, let's mount the ESP now (possibly creating the dir if missing) */
                r = mount_partition(PARTITION_ESP, m->partitions + PARTITION_ESP, where, esp_path, uid_shift, uid_range, userns_fd, flags);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
int dissected_image_mount_and_warn(
                DissectedImage *m,
                const char *where,
                uid_t uid_shift,
                uid_t uid_range,
                int userns_fd,
                DissectImageFlags flags) {
 
        int r;
 
        assert(m);
 
        r = dissected_image_mount(m, where, uid_shift, uid_range, userns_fd, flags);
        if (r == -ENXIO)
                return log_error_errno(r, "Failed to mount image: No root file system found in image.");
        if (r == -EMEDIUMTYPE)
                return log_error_errno(r, "Failed to mount image: No suitable os-release/extension-release file in image found.");
        if (r == -EUNATCH)
                return log_error_errno(r, "Failed to mount image: Encrypted file system discovered, but decryption not requested.");
        if (r == -EUCLEAN)
                return log_error_errno(r, "Failed to mount image: File system check on image failed.");
        if (r == -EBUSY)
                return log_error_errno(r, "Failed to mount image: File system already mounted elsewhere.");
        if (r == -EAFNOSUPPORT)
                return log_error_errno(r, "Failed to mount image: File system type not supported or not known.");
        if (r == -EIDRM)
                return log_error_errno(r, "Failed to mount image: File system is too uncommon, refused.");
        if (r < 0)
                return log_error_errno(r, "Failed to mount image: %m");
 
        return r;
}
 
#if HAVE_LIBCRYPTSETUP
struct DecryptedPartition {
        struct crypt_device *device;
        char *name;
        bool relinquished;
};
#endif
 
typedef struct DecryptedPartition DecryptedPartition;
 
struct DecryptedImage {
        unsigned n_ref;
        DecryptedPartition *decrypted;
        size_t n_decrypted;
};
 
static DecryptedImage* decrypted_image_free(DecryptedImage *d) {
#if HAVE_LIBCRYPTSETUP
        int r;
 
        if (!d)
                return NULL;
 
        /* Detach in reverse order so that nested dm-verity and dm-crypt are detached in the right order. */
        for (size_t i = d->n_decrypted; i > 0; i--) {
                DecryptedPartition *p = d->decrypted + i - 1;
 
                if (p->device && p->name && !p->relinquished) {
                        _cleanup_free_ char *node = NULL;
 
                        node = path_join("/dev/mapper", p->name);
                        if (node) {
                                r = btrfs_forget_device(node);
                                if (r < 0 && r != -ENOENT)
                                        log_debug_errno(r, "Failed to forget btrfs device %s, ignoring: %m", node);
                        } else
                                log_oom_debug();
 
                        /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
                        r = sym_crypt_deactivate_by_name(p->device, p->name, CRYPT_DEACTIVATE_DEFERRED);
                        if (r < 0)
                                log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
                }
 
                if (p->device)
                        sym_crypt_free(p->device);
                free(p->name);
        }
 
        free(d->decrypted);
        free(d);
#endif
        return NULL;
}
 
DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage, decrypted_image, decrypted_image_free);
 
#if HAVE_LIBCRYPTSETUP
static int decrypted_image_new(DecryptedImage **ret) {
        _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
 
        assert(ret);
 
        d = new(DecryptedImage, 1);
        if (!d)
                return -ENOMEM;
 
        *d = (DecryptedImage) {
                .n_ref = 1,
        };
 
        *ret = TAKE_PTR(d);
        return 0;
}
 
static uint64_t dissected_image_diskseq(const DissectedImage *di) {
        assert(di);
 
        return di->loop ? di->loop->diskseq : 0;
}
 
static int make_dm_name_and_node(
                const char *base,
                uint64_t diskseq,
                const char *suffix,
                char **ret_name,
                char **ret_node) {
 
        assert(base);
        assert(suffix);
        assert(ret_name);
        assert(ret_node);
 
        _cleanup_free_ char *name = NULL;
        if (diskseq != 0)
                name = asprintf_safe("%s-%" PRIu64 "%s", base, diskseq, suffix);
        else
                name = strjoin(base, suffix);
        if (!name)
                return -ENOMEM;
        if (!filename_is_valid(name))
                return -EINVAL;
 
        _cleanup_free_ char *node = path_join(sym_crypt_get_dir(), name);
        if (!node)
                return -ENOMEM;
 
        *ret_name = TAKE_PTR(name);
        *ret_node = TAKE_PTR(node);
 
        return 0;
}
 
static int make_dm_name_and_node_from_node(
                const char *original_node,
                uint64_t diskseq,
                const char *suffix,
                char **ret_name,
                char **ret_node) {
 
        int r;
 
        assert(original_node);
 
        _cleanup_free_ char *base = NULL;
        r = path_extract_filename(original_node, &base);
        if (r < 0)
                return r;
 
        return make_dm_name_and_node(base, diskseq, suffix, ret_name, ret_node);
}
 
static int decrypt_partition(