HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/discover-image.c

95,819 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: da1f55c7ddd81787d9a22d44703d5ef5a7c4cf54

Lines 1–1000 of 2,569

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fcntl.h>
#include <linux/loop.h>
#include <linux/magic.h>
#include <stdio.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>
 
#include "sd-json.h"
#include "sd-path.h"
#include "sd-varlink.h"
 
#include "alloc-util.h"
#include "blockdev-util.h"
#include "btrfs-util.h"
#include "bus-get-properties.h"
#include "chase.h"
#include "chattr-util.h"
#include "copy.h"
#include "devnum-util.h"
#include "dirent-util.h"
#include "discover-image.h"
#include "dissect-image.h"
#include "env-file.h"
#include "env-util.h"
#include "errno-util.h"
#include "extension-util.h"
#include "fd-util.h"
#include "fs-util.h"
#include "hashmap.h"
#include "hostname-setup.h"
#include "id128-util.h"
#include "label-util.h"
#include "lock-util.h"
#include "log.h"
#include "loop-util.h"
#include "mountpoint-util.h"
#include "mstack.h"
#include "namespace-util.h"
#include "nsresource.h"
#include "nulstr-util.h"
#include "os-util.h"
#include "path-lookup.h"
#include "path-util.h"
#include "process-util.h"
#include "recurse-dir.h"
#include "rm-rf.h"
#include "runtime-scope.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "time-util.h"
#include "uid-classification.h"
#include "vpick.h"
#include "xattr-util.h"
 
const char* const image_search_path[_IMAGE_CLASS_MAX] = {
        [IMAGE_MACHINE] =   "/etc/machines\0"              /* only place symlinks here */
                            "/run/machines\0"              /* and here too */
                            "/var/lib/machines\0"          /* the main place for images */
                            "/var/lib/container\0"         /* legacy */
                            "/usr/local/lib/machines\0"
                            "/usr/lib/machines\0",
 
        [IMAGE_PORTABLE] =  "/etc/portables\0"             /* only place symlinks here */
                            "/run/portables\0"             /* and here too */
                            "/var/lib/portables\0"         /* the main place for images */
                            "/usr/local/lib/portables\0"
                            "/usr/lib/portables\0",
 
        /* Note that we don't allow storing extensions under /usr/, unlike with other image types. That's
         * because extension images are supposed to extend /usr/, so you get into recursive races, especially
         * with directory-based extensions, as the kernel's OverlayFS explicitly checks for this and errors
         * out with -ELOOP if it finds that a lowerdir= is a child of another lowerdir=. */
        [IMAGE_SYSEXT] =    "/etc/extensions\0"            /* only place symlinks here */
                            "/run/extensions\0"            /* and here too */
                            "/var/lib/extensions\0",       /* the main place for images */
 
        [IMAGE_CONFEXT] =   "/run/confexts\0"              /* only place symlinks here */
                            "/var/lib/confexts\0"          /* the main place for images */
                            "/usr/local/lib/confexts\0"
                            "/usr/lib/confexts\0",
};
 
/* Inside the initrd, use a slightly different set of search path (i.e. include .extra/sysext/,
 * /.extra/global_sysext, .extra/confext/, and /.extra/global_confext in extension search dir) */
static const char* const image_search_path_initrd[_IMAGE_CLASS_MAX] = {
        /* (entries that aren't listed here will get the same search path as for the non initrd-case) */
 
        [IMAGE_SYSEXT] =    "/etc/extensions\0"            /* only place symlinks here */
                            "/run/extensions\0"            /* and here too */
                            "/var/lib/extensions\0"        /* the main place for images */
                            "/.extra/sysext\0"             /* put sysext (per-UKI and global) picked up by systemd-stub */
                            "/.extra/global_sysext\0",     /* last, since not trusted */
 
        [IMAGE_CONFEXT] =   "/run/confexts\0"              /* only place symlinks here */
                            "/var/lib/confexts\0"          /* the main place for images */
                            "/usr/local/lib/confexts\0"
                            "/.extra/confext\0"            /* put confext (per-UKI and global) picked up by systemd-stub */
                            "/.extra/global_confext\0",    /* last, since not trusted. */
};
 
static const char* image_class_suffix_table[_IMAGE_CLASS_MAX] = {
        [IMAGE_SYSEXT]  = ".sysext",
        [IMAGE_CONFEXT] = ".confext",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_class_suffix, ImageClass);
 
static const char *const image_root_table[_IMAGE_CLASS_MAX] = {
        [IMAGE_MACHINE]  = "/var/lib/machines",
        [IMAGE_PORTABLE] = "/var/lib/portables",
        [IMAGE_SYSEXT]   = "/var/lib/extensions",
        [IMAGE_CONFEXT]  = "/var/lib/confexts",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_root, ImageClass);
 
static const char *const image_root_runtime_table[_IMAGE_CLASS_MAX] = {
        [IMAGE_MACHINE]  = "/run/machines",
        [IMAGE_PORTABLE] = "/run/portables",
        [IMAGE_SYSEXT]   = "/run/extensions",
        [IMAGE_CONFEXT]  = "/run/confexts",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_root_runtime, ImageClass);
 
static const char *const image_dirname_table[_IMAGE_CLASS_MAX] = {
        [IMAGE_MACHINE]  = "machines",
        [IMAGE_PORTABLE] = "portables",
        [IMAGE_SYSEXT]   = "extensions",
        [IMAGE_CONFEXT]  = "confexts",
};
 
static const char auxiliary_suffixes_nulstr[] =
        ".nspawn\0"
        ".oci-config\0"
        ".roothash\0"
        ".roothash.p7s\0"
        ".usrhash\0"
        ".usrhash.p7s\0"
        ".verity\0"
        ".raw.tpmstate\0"
        ".raw.efinvramstate\0";
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(image_dirname, ImageClass);
 
static Image* image_free(Image *i) {
        assert(i);
 
        free(i->name);
        free(i->path);
 
        free(i->fh);
 
        free(i->hostname);
        strv_free(i->machine_info);
        strv_free(i->os_release);
        strv_free(i->sysext_release);
        strv_free(i->confext_release);
 
        return mfree(i);
}
 
DEFINE_TRIVIAL_REF_UNREF_FUNC(Image, image, image_free);
DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(image_hash_ops, char, string_hash_func, string_compare_func,
                                      Image, image_unref);
 
static char** image_settings_path(Image *image, RuntimeScope scope) {
        _cleanup_strv_free_ char **l = NULL;
        _cleanup_free_ char *fn = NULL;
        size_t i = 0;
        int r;
 
        assert(image);
 
        l = new0(char*, 5);
        if (!l)
                return NULL;
 
        fn = strjoin(image->name, ".nspawn");
        if (!fn)
                return NULL;
 
        static const uint64_t system_locations[] = {
                SD_PATH_SYSTEM_CONFIGURATION,
                SD_PATH_SYSTEM_RUNTIME,
                SD_PATH_SYSTEM_LIBRARY_PRIVATE,
                _SD_PATH_INVALID
        };
        static const uint64_t user_locations[] = {
                SD_PATH_USER_CONFIGURATION,
                SD_PATH_USER_RUNTIME,
                SD_PATH_USER_LIBRARY_PRIVATE,
                _SD_PATH_INVALID
        };
        const uint64_t *locations;
 
        switch (scope) {
        case RUNTIME_SCOPE_SYSTEM:
                locations = system_locations;
                break;
 
        case RUNTIME_SCOPE_USER:
                locations = user_locations;
                break;
 
        default:
                assert_not_reached();
        }
 
        for (size_t k = 0; locations[k] != _SD_PATH_INVALID; k++) {
                _cleanup_free_ char *s = NULL;
                r = sd_path_lookup(locations[k], "systemd/nspawn", &s);
                if (r == -ENXIO)
                        continue;
                if (r < 0)
                        return NULL;
 
                l[i] = path_join(s, fn);
                if (!l[i])
                        return NULL;
 
                i++;
        }
 
        r = file_in_same_dir(image->path, fn, l + i);
        if (r == -ENOMEM)
                return NULL;
        if (r < 0)
                log_debug_errno(r, "Failed to generate .nspawn settings path from image path, ignoring: %m");
 
        strv_uniq(l);
 
        return TAKE_PTR(l);
}
 
static int image_auxiliary_path(Image *image, const char *suffix, char **ret) {
        assert(image);
        assert(suffix);
 
        _cleanup_free_ char *fn = strjoin(image->name, suffix);
        if (!fn)
                return -ENOMEM;
 
        return file_in_same_dir(image->path, fn, ret);
}
 
static int image_new(
                ImageType t,
                ImageClass c,
                const char *pretty,
                const char *path,
                bool read_only,
                usec_t crtime,
                usec_t mtime,
                struct file_handle *fh,
                uint64_t on_mount_id,
                uint64_t inode,
                Image **ret) {
 
        _cleanup_(image_unrefp) Image *i = NULL;
 
        assert(t >= 0);
        assert(t < _IMAGE_TYPE_MAX);
        assert(pretty);
        assert(path);
        assert(ret);
 
        i = new(Image, 1);
        if (!i)
                return -ENOMEM;
 
        *i = (Image) {
                .n_ref = 1,
                .type = t,
                .class = c,
                .read_only = read_only,
                .crtime = crtime,
                .mtime = mtime,
                .on_mount_id = on_mount_id,
                .inode = inode,
                .usage = UINT64_MAX,
                .usage_exclusive = UINT64_MAX,
                .limit = UINT64_MAX,
                .limit_exclusive = UINT64_MAX,
        };
 
        if (fh) {
                i->fh = file_handle_dup(fh);
                if (!i->fh)
                        return -ENOMEM;
        }
 
        i->name = strdup(pretty);
        if (!i->name)
                return -ENOMEM;
 
        i->path = strdup(path);
        if (!i->path)
                return -ENOMEM;
 
        path_simplify(i->path);
 
        *ret = TAKE_PTR(i);
 
        return 0;
}
 
static int extract_image_basename(
                const char *path,
                const char *class_suffix,  /* e.g. ".sysext" (this is an optional suffix) */
                char **format_suffixes,    /* e.g. ".raw"    (one of these will be required) */
                char **ret_basename,
                char **ret_suffix) {
 
        _cleanup_free_ char *name = NULL, *suffix = NULL;
        int r;
 
        assert(path);
 
        r = path_extract_filename(path, &name);
        if (r < 0)
                return r;
 
        if (format_suffixes) {
                char *e = endswith_strv(name, format_suffixes);
                if (!e) /* Format suffix is required */
                        return -EINVAL;
 
                if (ret_suffix) {
                        suffix = strdup(e);
                        if (!suffix)
                                return -ENOMEM;
                }
 
                *e = 0;
        }
 
        if (class_suffix) {
                char *e = endswith(name, class_suffix);
                if (e) { /* Class suffix is optional */
                        if (ret_suffix) {
                                _cleanup_free_ char *j = strjoin(e, suffix);
                                if (!j)
                                        return -ENOMEM;
 
                                free_and_replace(suffix, j);
                        }
 
                        *e = 0;
                }
        }
 
        if (!image_name_is_valid(name))
                return -EINVAL;
 
        if (ret_suffix)
                *ret_suffix = TAKE_PTR(suffix);
 
        if (ret_basename)
                *ret_basename = TAKE_PTR(name);
 
        return 0;
}
 
static int image_update_quota(Image *i, int fd) {
        _cleanup_close_ int fd_close = -EBADF;
        int r;
 
        assert(i);
 
        if (image_is_vendor(i) || image_is_host(i))
                return -EROFS;
 
        if (i->type != IMAGE_SUBVOLUME)
                return -EOPNOTSUPP;
 
        if (fd < 0) {
                fd_close = open(i->path, O_CLOEXEC|O_DIRECTORY);
                if (fd_close < 0)
                        return -errno;
                fd = fd_close;
        } else {
                /* Convert from O_PATH to proper fd, if needed */
                fd = fd_reopen_condition(fd, O_CLOEXEC|O_DIRECTORY, O_PATH, &fd_close);
                if (fd < 0)
                        return fd;
        }
 
        r = btrfs_quota_scan_ongoing(fd);
        if (r < 0)
                return r;
        if (r > 0)
                return 0;
 
        BtrfsQuotaInfo quota;
        r = btrfs_subvol_get_subtree_quota_fd(fd, 0, &quota);
        if (r < 0)
                return r;
 
        i->usage = quota.referenced;
        i->usage_exclusive = quota.exclusive;
        i->limit = quota.referenced_max;
        i->limit_exclusive = quota.exclusive_max;
 
        return 1;
}
 
static int image_make(
                ImageClass c,
                const char *pretty,
                int fd, /* O_PATH fd */
                const char *path,
                const struct stat *st,
                Image **ret) {
 
        _cleanup_free_ char *pretty_buffer = NULL;
        bool read_only;
        int r;
 
        assert(path);
        assert(path_is_absolute(path));
 
        /* We explicitly *do* follow symlinks here, since we want to allow symlinking trees, raw files and block
         * devices into /var/lib/machines/, and treat them normally.
         * Note that if the caller does not want to follow symlinks (and does not care about symlink races)
         * then the caller should pass in a resolved path and an fd.
         *
         * This function returns -ENOENT if we can't find the image after all, and -EMEDIUMTYPE if it's not a file we
         * recognize. */
 
        _cleanup_close_ int _fd = -EBADF;
        if (fd < 0) {
                /* If we didn't get an fd passed in, then let's pin it via O_PATH now */
                _fd = open(path, O_PATH|O_CLOEXEC);
                if (_fd < 0)
                        return -errno;
 
                fd = _fd;
                st = NULL; /* refresh stat() data now that we have the inode pinned */
        }
 
        struct stat stbuf;
        if (!st) {
                if (fstat(fd, &stbuf) < 0)
                        return -errno;
 
                st = &stbuf;
        }
 
        read_only =
                path_startswith(path, "/usr") ||
                (faccessat(fd, "", W_OK, AT_EACCESS|AT_EMPTY_PATH) < 0 && errno == EROFS);
 
        _cleanup_free_ struct file_handle *fh = NULL;
        uint64_t on_mount_id;
        int _mnt_id;
 
        /* The fallback is required for CentOS 9 compatibility when working on a directory located on an
         * overlayfs. */
        r = name_to_handle_at_try_fid(fd, /* path= */ NULL, &fh, &_mnt_id, &on_mount_id, AT_EMPTY_PATH);
        if (r < 0) {
                if (is_name_to_handle_at_fatal_error(r))
                        return r;
 
                r = path_get_unique_mnt_id_at(fd, /* path= */ NULL, &on_mount_id);
                if (r < 0) {
                        if (!ERRNO_IS_NEG_NOT_SUPPORTED(r) && r != -EUNATCH)
                                return r;
 
                        int on_mount_id_fallback = -1;
                        r = path_get_mnt_id_at(fd, /* path= */ NULL, &on_mount_id_fallback);
                        if (r < 0)
                                return r;
 
                        on_mount_id = on_mount_id_fallback;
                }
        } else if (r == 0)
                on_mount_id = _mnt_id;
 
        if (S_ISDIR(st->st_mode)) {
 
                if (!ret)
                        return 0;
 
                if (endswith(path, ".mstack")) {
                        usec_t crtime = 0;
                        r = fd_getcrtime(fd, &crtime);
                        if (r < 0)
                                log_debug_errno(r, "Unable to read creation time of '%s', ignoring: %m", path);
 
                        if (!pretty) {
                                r = extract_image_basename(
                                                path,
                                                image_class_suffix_to_string(c),
                                                STRV_MAKE(".mstack"),
                                                &pretty_buffer,
                                                /* ret_suffix= */ NULL);
                                if (r < 0)
                                        return r;
 
                                pretty = pretty_buffer;
                        }
 
                        _cleanup_(mstack_freep) MStack *mstack = NULL;
                        r = mstack_load(path, fd, &mstack);
                        if (r < 0) {
                                log_debug_errno(r, "Failed to load mstack '%s', ignoring: %m", path);
                                read_only = true;
                        } else if (!read_only) {
                                r = mstack_is_read_only(mstack);
                                if (r < 0)
                                        log_debug_errno(r, "Failed to determine if mstack '%s' is read-only, assuming it is: %m", path);
 
                                read_only = r != 0;
                        }
 
                        r = image_new(IMAGE_MSTACK,
                                      c,
                                      pretty,
                                      path,
                                      read_only,
                                      crtime,
                                      /* mtime= */ 0,
                                      fh,
                                      on_mount_id,
                                      (uint64_t) st->st_ino,
                                      ret);
                        if (r < 0)
                                return r;
 
                        if (mstack) {
                                r = mstack_is_foreign_uid_owned(mstack);
                                if (r < 0)
                                        log_debug_errno(r, "Failed to determine if mstack '%s' is foreign UID owned, assuming it is not: %m", path);
                                if (r > 0)
                                        (*ret)->foreign_uid_owned = true;
                        }
 
                        return 0;
                }
 
                if (!pretty) {
                        r = extract_image_basename(
                                        path,
                                        image_class_suffix_to_string(c),
                                        /* format_suffixes= */ NULL,
                                        &pretty_buffer,
                                        /* ret_suffix= */ NULL);
                        if (r < 0)
                                return r;
 
                        pretty = pretty_buffer;
                }
 
                if (btrfs_might_be_subvol(st)) {
 
                        r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
                        if (r < 0)
                                return r;
                        if (r > 0) {
                                BtrfsSubvolInfo info;
 
                                /* It's a btrfs subvolume */
 
                                r = btrfs_subvol_get_info_fd(fd, 0, &info);
                                if (r < 0)
                                        return r;
 
                                r = image_new(IMAGE_SUBVOLUME,
                                              c,
                                              pretty,
                                              path,
                                              info.read_only || read_only,
                                              info.otime,
                                              info.ctime,
                                              fh,
                                              on_mount_id,
                                              (uint64_t) st->st_ino,
                                              ret);
                                if (r < 0)
                                        return r;
 
                                (*ret)->foreign_uid_owned = uid_is_foreign(st->st_uid);
                                (void) image_update_quota(*ret, fd);
                                return 0;
                        }
                }
 
                /* Get directory creation time (not available everywhere, but that's OK */
                usec_t crtime = 0;
                (void) fd_getcrtime(fd, &crtime);
 
                /* If the IMMUTABLE bit is set, we consider the directory read-only. Since the ioctl is not
                 * supported everywhere we ignore failures. */
                unsigned file_attr = 0;
                (void) read_attr_fd(fd, &file_attr);
 
                /* It's just a normal directory. */
                r = image_new(IMAGE_DIRECTORY,
                              c,
                              pretty,
                              path,
                              read_only || (file_attr & FS_IMMUTABLE_FL),
                              crtime,
                              0, /* we don't use mtime of stat() here, since it's not the time of last change of the tree, but only of the top-level dir */
                              fh,
                              on_mount_id,
                              (uint64_t) st->st_ino,
                              ret);
                if (r < 0)
                        return r;
 
                (*ret)->foreign_uid_owned = uid_is_foreign(st->st_uid);
                return 0;
 
        } else if (S_ISREG(st->st_mode) && (endswith(path, ".raw") || pretty)) {
                usec_t crtime = 0;
 
                /* It's a RAW disk image */
 
                if (!ret)
                        return 0;
 
                (void) fd_getcrtime(fd, &crtime);
 
                if (!pretty) {
                        r = extract_image_basename(
                                        path,
                                        image_class_suffix_to_string(c),
                                        STRV_MAKE(".raw"),
                                        &pretty_buffer,
                                        /* ret_suffix= */ NULL);
                        if (r < 0)
                                return r;
 
                        pretty = pretty_buffer;
                }
 
                r = image_new(IMAGE_RAW,
                              c,
                              pretty,
                              path,
                              !(st->st_mode & 0222) || read_only,
                              crtime,
                              timespec_load(&st->st_mtim),
                              fh,
                              on_mount_id,
                              (uint64_t) st->st_ino,
                              ret);
                if (r < 0)
                        return r;
 
                (*ret)->usage = (*ret)->usage_exclusive = st->st_blocks * 512;
                (*ret)->limit = (*ret)->limit_exclusive = st->st_size;
 
                return 0;
 
        } else if (S_ISBLK(st->st_mode)) {
                uint64_t size = UINT64_MAX;
 
                /* A block device */
 
                if (!ret)
                        return 0;
 
                if (!pretty) {
                        r = extract_image_basename(
                                        path,
                                        /* class_suffix= */ NULL,
                                        /* format_suffix= */ NULL,
                                        &pretty_buffer,
                                        /* ret_suffix= */ NULL);
                        if (r < 0)
                                return r;
 
                        pretty = pretty_buffer;
                }
 
                _cleanup_close_ int block_fd = fd_reopen(fd, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
                if (block_fd < 0)
                        log_debug_errno(errno, "Failed to open block device '%s', ignoring: %m", path);
                else {
                        if (!read_only) {
                                int state = 0;
 
                                if (ioctl(block_fd, BLKROGET, &state) < 0)
                                        log_debug_errno(errno, "Failed to issue BLKROGET on device '%s', ignoring: %m", path);
                                else if (state)
                                        read_only = true;
                        }
 
                        r = blockdev_get_device_size(block_fd, &size);
                        if (r < 0)
                                log_debug_errno(r, "Failed to issue BLKGETSIZE64 on device '%s', ignoring: %m", path);
 
                        block_fd = safe_close(block_fd);
                }
 
                r = image_new(IMAGE_BLOCK,
                              c,
                              pretty,
                              path,
                              !(st->st_mode & 0222) || read_only,
                              0,
                              0,
                              fh,
                              on_mount_id,
                              (uint64_t) st->st_ino,
                              ret);
                if (r < 0)
                        return r;
 
                if (!IN_SET(size, 0, UINT64_MAX))
                        (*ret)->usage = (*ret)->usage_exclusive = (*ret)->limit = (*ret)->limit_exclusive = size;
 
                return 0;
        }
 
        return -EMEDIUMTYPE;
}
 
static int pick_image_search_path(
                RuntimeScope scope,
                ImageClass class,
                const char *root,
                char ***ret) {
 
        int r;
 
        assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
        assert(class < _IMAGE_CLASS_MAX);
        assert(ret);
 
        if (class < 0) {
                *ret = NULL;
                return 0;
        }
 
        if (scope < 0) {
                _cleanup_strv_free_ char **a = NULL, **b = NULL;
 
                r = pick_image_search_path(RUNTIME_SCOPE_USER, class, root, &a);
                if (r < 0)
                        return r;
 
                r = pick_image_search_path(RUNTIME_SCOPE_SYSTEM, class, root, &b);
                if (r < 0)
                        return r;
 
                r = strv_extend_strv(&a, b, /* filter_duplicates= */ false);
                if (r < 0)
                        return r;
 
                *ret = TAKE_PTR(a);
                return 0;
        }
 
        switch (scope) {
 
        case RUNTIME_SCOPE_SYSTEM: {
                const char *ns;
                bool is_initrd;
 
                r = chase_and_access("/etc/initrd-release", root, CHASE_PREFIX_ROOT, F_OK, /* ret_path= */ NULL);
                if (r < 0 && r != -ENOENT)
                        return r;
                is_initrd = r >= 0;
 
                /* Use the initrd search path if there is one, otherwise use the common one */
                ns = is_initrd && image_search_path_initrd[class] ?
                        image_search_path_initrd[class] :
                        image_search_path[class];
                if (!ns)
                        break;
 
                _cleanup_strv_free_ char **search = strv_split_nulstr(ns);
                if (!search)
                        return -ENOMEM;
 
                *ret = TAKE_PTR(search);
                return 0;
        }
 
        case RUNTIME_SCOPE_USER: {
                if (!IN_SET(class, IMAGE_MACHINE, IMAGE_PORTABLE))
                        break;
 
                static const uint64_t dirs[] = {
                        SD_PATH_USER_RUNTIME,
                        SD_PATH_USER_STATE_PRIVATE,
                        SD_PATH_USER_LIBRARY_PRIVATE,
                };
 
                _cleanup_strv_free_ char **search = NULL;
                FOREACH_ELEMENT(d, dirs) {
                        _cleanup_free_ char *p = NULL;
 
                        r = sd_path_lookup(*d, image_dirname_to_string(class), &p);
                        if (r == -ENXIO) /* No XDG_RUNTIME_DIR set */
                                continue;
                        if (r < 0)
                                return r;
 
                        r = strv_consume(&search, TAKE_PTR(p));
                        if (r < 0)
                                return r;
                }
 
                *ret = TAKE_PTR(search);
                return 0;
        }
 
        default:
                assert_not_reached();
        }
 
        *ret = NULL;
        return 0;
}
 
static char** make_possible_filenames(ImageClass class, const char *image_name) {
        _cleanup_strv_free_ char **l = NULL;
 
        assert(image_name);
 
        FOREACH_STRING(v_suffix, "", ".v")
                FOREACH_STRING(format_suffix, "", ".raw", ".mstack") {
                        _cleanup_free_ char *j = NULL;
                        const char *class_suffix;
 
                        class_suffix = image_class_suffix_to_string(class);
                        if (class_suffix) {
                                j = strjoin(image_name, class_suffix, format_suffix, v_suffix);
                                if (!j)
                                        return NULL;
 
                                if (strv_consume(&l, TAKE_PTR(j)) < 0)
                                        return NULL;
                        }
 
                        j = strjoin(image_name, format_suffix, v_suffix);
                        if (!j)
                                return NULL;
 
                        if (strv_consume(&l, TAKE_PTR(j)) < 0)
                                return NULL;
                }
 
        return TAKE_PTR(l);
}
 
int image_find(RuntimeScope scope,
               ImageClass class,
               const char *name,
               const char *root,
               Image **ret) {
 
        int r;
 
        assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
        assert(class >= 0);
        assert(class < _IMAGE_CLASS_MAX);
        assert(name);
 
        /* There are no images with invalid names */
        if (!image_name_is_valid(name))
                return -ENOENT;
 
        _cleanup_strv_free_ char **names = make_possible_filenames(class, name);
        if (!names)
                return -ENOMEM;
 
        _cleanup_close_ int rfd = XAT_FDROOT; /* We only expect absolute paths */
        if (root) {
                rfd = open(root, O_CLOEXEC|O_DIRECTORY|O_PATH);
                if (rfd < 0)
                        return log_debug_errno(errno, "Failed to open root directory '%s': %m", root);
        }
 
        _cleanup_strv_free_ char **search = NULL;
        r = pick_image_search_path(scope, class, root, &search);
        if (r < 0)
                return r;
 
        STRV_FOREACH(s, search) {
                _cleanup_closedir_ DIR *d = NULL;
                _cleanup_free_ char *search_path = NULL;
 
                r = chase_and_opendirat(rfd, rfd, *s, /* chase_flags= */ 0, &search_path, &d);
                if (r == -ENOENT)
                        continue;
                if (r < 0)
                        return r;
 
                STRV_FOREACH(n, names) {
                        const char *fname = *n;
                        _cleanup_free_ char *fname_path = NULL, *chased_path = NULL, *resolved_file = NULL;
                        _cleanup_close_ int fd = -EBADF;
 
                        fname_path = path_join(search_path, fname);
                        if (!fname_path)
                                return -ENOMEM;
 
                        /* Follow symlinks only inside given root */
                        r = chaseat(rfd, rfd, fname_path, /* flags= */ 0, &chased_path, &fd);
                        if (r == -ENOENT)
                                continue;
                        if (r < 0)
                                return r;
 
                        r = chaseat_prefix_root(chased_path, root, &resolved_file);
                        if (r < 0)
                                return r;
 
                        struct stat st;
                        if (fstat(fd, &st) < 0)
                                return -errno;
 
                        if (endswith(fname, ".raw")) {
                                if (!S_ISREG(st.st_mode)) {
                                        log_debug("Ignoring non-regular file '%s' with .raw suffix.", fname);
                                        continue;
                                }
                        } else if (endswith(fname, ".mstack")) {
 
                                if (!S_ISDIR(st.st_mode)) {
                                        log_debug("Ignoring non-directory '%s' with .mstack suffix.", fname);
                                        continue;
                                }
 
                        } else if (endswith(fname, ".v")) {
 
                                if (!S_ISDIR(st.st_mode)) {
                                        log_debug("Ignoring non-directory file '%s' with .v suffix.", fname);
                                        continue;
                                }
 
                                _cleanup_free_ char *suffix = NULL;
                                suffix = strdup(ASSERT_PTR(startswith(fname, name)));
                                if (!suffix)
                                        return -ENOMEM;
 
                                *ASSERT_PTR(endswith(suffix, ".v")) = 0;
 
                                PickFilter filter = {
                                        .type_mask = endswith(suffix, ".raw") ? (UINT32_C(1) << DT_REG) | (UINT32_C(1) << DT_BLK) : (UINT32_C(1) << DT_DIR),
                                        .basename = name,
                                        .architecture = _ARCHITECTURE_INVALID,
                                        .suffix = suffix,
                                };
 
                                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
                                r = path_pick(root,
                                              rfd,
                                              rfd,
                                              fname_path, /* This has to be the unresolved entry with the .v suffix */
                                              &filter,
                                              /* n_filters= */ 1,
                                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
                                              &result);
                                if (r < 0) {
                                        log_debug_errno(r, "Failed to pick versioned image on '%s%s', skipping: %m", empty_to_root(root), skip_leading_slash(fname_path));
                                        continue;
                                }
                                if (!result.path) {
                                        log_debug("Found versioned directory '%s%s', without matching entry, skipping.", empty_to_root(root), skip_leading_slash(fname_path));
                                        continue;
                                }
 
                                /* Refresh the stat data for the discovered target */
                                st = result.st;
                                close_and_replace(fd, result.fd);
                                free(resolved_file);
                                resolved_file = path_join(root, result.path);
                                if (!resolved_file)
                                        return -ENOMEM;
 
                                /* fname and fname_path are invalid now because they would need to be set
                                 * from result.path by extracting the filename to set
                                 * fname = path_join(fname, filename) and then
                                 * fname_path = path_join(*s, fname) but since they are unused we don't do it */
                                fname = NULL;
                                fname_path = mfree(fname_path);
                        } else if (!S_ISDIR(st.st_mode) && !S_ISBLK(st.st_mode)) {
                                log_debug("Ignoring non-directory and non-block device file '%s' without suffix.", fname);
                                continue;
                        }
 
                        /* Only put resolved paths into the image entry (incl. --root=).
                         * Defending against symlink races is not done
                         * and would be a TODO. */
                        r = image_make(class, name, fd, resolved_file, &st, ret);
                        if (IN_SET(r, -ENOENT, -EMEDIUMTYPE))
                                continue;