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

                        if (r < 0)
                                return r;
 
                        if (ret)
                                (*ret)->discoverable = true;
 
                        return 1;
                }
        }
 
        if (scope == RUNTIME_SCOPE_SYSTEM && class == IMAGE_MACHINE && streq(name, ".host")) {
                r = image_make(class,
                               ".host",
                               /* fd= */ -EBADF,
                               /* path= */ empty_to_root(root),
                               /* st= */ NULL,
                               ret);
                if (r < 0)
                        return r;
 
                if (ret)
                        (*ret)->discoverable = true;
 
                return 1;
        }
 
        return -ENOENT;
};
 
int image_from_path(const char *path, Image **ret) {
        int r;
 
        /* Note that we don't set the 'discoverable' field of the returned object, because we don't check here whether
         * the image is in the image search path. And if it is we don't know if the path we used is actually not
         * overridden by another, different image earlier in the search path */
 
        if (path_equal(path, "/"))
                return image_make(
                                IMAGE_MACHINE,
                                ".host",
                                /* fd= */ -EBADF,
                                /* path= */ "/",
                                /* st= */ NULL,
                                ret);
 
        _cleanup_free_ char *absolute = NULL;
        r = path_make_absolute_cwd(path, &absolute);
        if (r < 0)
                return r;
 
        return image_make(
                        _IMAGE_CLASS_INVALID,
                        /* pretty= */ NULL,
                        /* fd= */ -EBADF,
                        absolute,
                        /* st= */ NULL,
                        ret);
}
 
int image_find_harder(
                RuntimeScope scope,
                ImageClass class,
                const char *name_or_path,
                const char *root,
                Image **ret) {
 
        if (image_name_is_valid(name_or_path))
                return image_find(scope, class, name_or_path, root, ret);
 
        return image_from_path(name_or_path, ret);
}
 
int image_discover(
                RuntimeScope scope,
                ImageClass class,
                const char *root,
                Hashmap **images) {
 
        int r;
 
        assert(scope < _RUNTIME_SCOPE_MAX && scope != RUNTIME_SCOPE_GLOBAL);
        assert(class >= 0);
        assert(class < _IMAGE_CLASS_MAX);
        assert(images);
 
        _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;
 
                FOREACH_DIRENT_ALL(de, d, return -errno) {
                        _cleanup_free_ char *pretty = NULL, *fname_path = NULL, *chased_path = NULL, *resolved_file = NULL;
                        _cleanup_(image_unrefp) Image *image = NULL;
                        const char *fname = de->d_name;
                        _cleanup_close_ int fd = -EBADF;
 
                        if (dot_or_dot_dot(fname))
                                continue;
 
                        /* Ignore sysupdate temporary files */
                        if (startswith(fname, ".sysupdate."))
                                continue;
 
                        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 (S_ISREG(st.st_mode)) {
                                r = extract_image_basename(
                                                fname,
                                                image_class_suffix_to_string(class),
                                                STRV_MAKE(".raw"),
                                                &pretty,
                                                /* ret_suffix= */ NULL);
                                if (r < 0) {
                                        log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like an image.", fname);
                                        continue;
                                }
                        } else if (S_ISDIR(st.st_mode)) {
                                const char *v;
 
                                v = endswith(fname, ".v");
                                if (v) {
                                        _cleanup_free_ char *suffix = NULL, *nov = NULL;
 
                                        nov = strndup(fname, v - fname); /* Chop off the .v */
                                        if (!nov)
                                                return -ENOMEM;
 
                                        r = extract_image_basename(
                                                        nov,
                                                        image_class_suffix_to_string(class),
                                                        STRV_MAKE(".raw", ".mstack", ""),
                                                        &pretty,
                                                        &suffix);
                                        if (r < 0) {
                                                log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like a versioned image.", fname);
                                                continue;
                                        }
 
                                        PickFilter filter = {
                                                .type_mask = endswith(suffix, ".raw") ? (UINT32_C(1) << DT_REG) | (UINT32_C(1) << DT_BLK) : (UINT32_C(1) << DT_DIR),
                                                .basename = pretty,
                                                .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 {
                                        r = extract_image_basename(
                                                        fname,
                                                        image_class_suffix_to_string(class),
                                                        STRV_MAKE(".mstack", ""),
                                                        &pretty,
                                                        /* ret_suffix= */ NULL);
                                        if (r < 0) {
                                                log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like an image.", fname);
                                                continue;
                                        }
                                }
 
                        } else if (S_ISBLK(st.st_mode)) {
                                r = extract_image_basename(
                                                fname,
                                                /* class_suffix= */ NULL,
                                                /* format_suffix= */ NULL,
                                                &pretty,
                                                /* ret_suffix= */ NULL);
                                if (r < 0) {
                                        log_debug_errno(r, "Skipping directory entry '%s', which doesn't look like an image.", fname);
                                        continue;
                                }
                        } else {
                                log_debug("Skipping directory entry '%s', which is neither regular file, directory nor block device.", fname);
                                continue;
                        }
 
                        if (hashmap_contains(*images, pretty))
                                continue;
 
                        /* Only put resolved paths into the image entry.
                         * Defending against symlink races is not done
                         * and would be a TODO. */
                        r = image_make(class, pretty, fd, resolved_file, &st, &image);
                        if (IN_SET(r, -ENOENT, -EMEDIUMTYPE))
                                continue;
                        if (r < 0)
                                return r;
 
                        image->discoverable = true;
 
                        r = hashmap_ensure_put(images, &image_hash_ops, image->name, image);
                        if (r < 0)
                                return r;
 
                        TAKE_PTR(image);
                }
        }
 
        if (scope == RUNTIME_SCOPE_SYSTEM && class == IMAGE_MACHINE && !hashmap_contains(*images, ".host")) {
                _cleanup_(image_unrefp) Image *image = NULL;
 
                r = image_make(IMAGE_MACHINE,
                               ".host",
                               /* fd= */ -EBADF,
                               /* path= */ empty_to_root(root),
                               /* st= */ NULL,
                               &image);
                if (r < 0)
                        return r;
 
                image->discoverable = true;
 
                r = hashmap_ensure_put(images, &image_hash_ops, image->name, image);
                if (r < 0)
                        return r;
 
                image = NULL;
        }
 
        return 0;
}
 
static int unpriv_remove_cb(
                RecurseDirEvent event,
                const char *path,
                int dir_fd,
                int inode_fd,
                const struct dirent *de,
                const struct statx *sx,
                void *userdata) {
 
        int r, userns_fd = PTR_TO_FD(userdata);
 
        assert(sx);
 
        if (event == RECURSE_DIR_ENTER &&
            S_ISDIR(sx->stx_mode) &&
            uid_is_foreign(sx->stx_uid)) {
 
                /* This is owned by the foreign UID range, and a dir, let's remove it via mountfsd userns
                 * shenanigans. */
 
                _cleanup_close_ int tree_fd = -EBADF;
                r = mountfsd_mount_directory_fd(
                                /* vl= */ NULL,
                                inode_fd,
                                userns_fd,
                                DISSECT_IMAGE_FOREIGN_UID,
                                &tree_fd);
                if (r < 0)
                        return r;
 
                /* Fork off child that moves into userns and does the copying */
                r = pidref_safe_fork_full(
                                "rm-tree",
                                /* stdio_fds= */ NULL,
                                (int[]) { userns_fd, tree_fd, }, 2,
                                FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_WAIT|FORK_REOPEN_LOG,
                                /* ret= */ NULL);
                if (r < 0)
                        log_debug_errno(r, "Process that was supposed to remove subtree '%s' failed, ignoring: %m", empty_to_root(path));
                else if (r == 0) {
                        /* child */
 
                        r = namespace_enter(
                                        /* pidns_fd= */ -EBADF,
                                        /* mntns_fd= */ -EBADF,
                                        /* netns_fd= */ -EBADF,
                                        userns_fd,
                                        /* root_fd= */ -EBADF);
                        if (r < 0) {
                                log_debug_errno(r, "Failed to join user namespace: %m");
                                _exit(EXIT_FAILURE);
                        }
 
                        _cleanup_close_ int dfd = fd_reopen(tree_fd, O_DIRECTORY|O_CLOEXEC);
                        if (dfd < 0) {
                                log_error_errno(dfd, "Failed to reopen tree fd: %m");
                                _exit(EXIT_FAILURE);
                        }
 
                        r = rm_rf_children(dfd, REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_CHMOD, /* root_dev= */ NULL);
                        if (r < 0) {
                                log_error_errno(r, "Failed to empty '%s' directory in foreign UID mode: %m", empty_to_root(path));
                                _exit(EXIT_FAILURE);
                        }
 
                        _exit(EXIT_SUCCESS);
                }
 
                /* Don't descent further into this one, and delete it immediately */
                return RECURSE_DIR_UNLINK_GRACEFUL;
        }
 
        /* Everything else try to remove */
        if (event == RECURSE_DIR_LEAVE)
                return RECURSE_DIR_UNLINK_GRACEFUL;
 
        return RECURSE_DIR_CONTINUE;
}
 
static int unprivileged_remove(Image *i) {
        int r;
 
        assert(i);
 
        /* We want this to work in complex .mstack/ hierarchies, where the main directory (and maybe a .v/
         * directory below or two) might be owned by the user themselves, but some subdirs might be owned by
         * the foreign UID range. We deal with this by recursively descending down the tree, and removing
         * foreign-owned ranges via userns shenanigans, and the rest just like that. */
 
        _cleanup_close_ int userns_fd = nsresource_allocate_userns(
                        /* vl= */ NULL,
                        /* name= */ NULL,
                        /* size= */ NSRESOURCE_UIDS_64K);
        if (userns_fd < 0)
                return log_debug_errno(userns_fd, "Failed to allocate transient user namespace: %m");
 
        r = recurse_dir_at(
                        AT_FDCWD,
                        i->path,
                        /* statx_mask= */ STATX_TYPE|STATX_UID,
                        /* n_depth_max= */ UINT_MAX,
                        RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE|RECURSE_DIR_SAME_MOUNT|RECURSE_DIR_INODE_FD|RECURSE_DIR_TOPLEVEL,
                        unpriv_remove_cb,
                        FD_TO_PTR(userns_fd));
        if (r < 0)
                return r;
 
        return 0;
}
 
int image_remove(Image *i, RuntimeScope scope) {
        _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
        _cleanup_strv_free_ char **settings = NULL;
        int r;
 
        assert(i);
 
        if (image_is_vendor(i) || image_is_host(i))
                return -EROFS;
 
        settings = image_settings_path(i, scope);
        if (!settings)
                return -ENOMEM;
 
        /* Make sure we don't interfere with a running nspawn */
        r = image_path_lock(scope, i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
        if (r < 0)
                return r;
 
        switch (i->type) {
 
        case IMAGE_SUBVOLUME:
 
                /* Let's unlink first, maybe it is a symlink? If that works we are happy. Otherwise, let's get out the
                 * big guns */
                if (unlink(i->path) < 0) {
                        r = btrfs_subvol_remove(i->path, BTRFS_REMOVE_RECURSIVE|BTRFS_REMOVE_QUOTA);
                        if (r < 0)
                                return r;
                }
 
                break;
 
        case IMAGE_DIRECTORY:
                /* Allow deletion of read-only directories */
                (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL);
 
                _fallthrough_;
 
        case IMAGE_MSTACK:
                /* If this is foreign owned, try an unprivileged remove first, but accept if that doesn't work, and do it directly either way, maybe it works */
                if (i->foreign_uid_owned)
                        (void) unprivileged_remove(i);
 
                r = rm_rf(i->path, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
                if (r < 0)
                        return r;
 
                break;
 
        case IMAGE_BLOCK:
 
                /* If this is inside of /dev, then it's a real block device, hence let's not touch the device node
                 * itself (but let's remove the stuff stored alongside it). If it's anywhere else, let's try to unlink
                 * the thing (it's most likely a symlink after all). */
 
                if (path_startswith(i->path, "/dev"))
                        break;
 
                _fallthrough_;
        case IMAGE_RAW:
                if (unlink(i->path) < 0)
                        return -errno;
                break;
 
        default:
                return -EOPNOTSUPP;
        }
 
        STRV_FOREACH(j, settings)
                if (unlink(*j) < 0 && errno != ENOENT)
                        log_debug_errno(errno, "Failed to unlink %s, ignoring: %m", *j);
 
        NULSTR_FOREACH(suffix, auxiliary_suffixes_nulstr) {
                _cleanup_free_ char *aux = NULL;
                r = image_auxiliary_path(i, suffix, &aux);
                if (r < 0)
                        return r;
 
                if (unlink(aux) < 0 && errno != ENOENT)
                        log_debug_errno(errno, "Failed to unlink %s, ignoring: %m", aux);
        }
 
        return 0;
}
 
static int rename_auxiliary_file(const char *path, const char *new_name, const char *suffix) {
        int r;
 
        assert(path);
        assert(new_name);
        assert(suffix);
 
        _cleanup_free_ char *fn = strjoin(new_name, suffix);
        if (!fn)
                return -ENOMEM;
 
        _cleanup_free_ char *rs = NULL;
        r = file_in_same_dir(path, fn, &rs);
        if (r < 0)
                return r;
 
        return rename_noreplace(AT_FDCWD, path, AT_FDCWD, rs);
}
 
int image_rename(Image *i, const char *new_name, RuntimeScope scope) {
        _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT, name_lock = LOCK_FILE_INIT;
        _cleanup_free_ char *new_path = NULL, *nn = NULL;
        _cleanup_strv_free_ char **settings = NULL;
        unsigned file_attr = 0;
        int r, ret = 0;
 
        assert(i);
 
        if (!image_name_is_valid(new_name))
                return -EINVAL;
 
        if (image_is_vendor(i) || image_is_host(i))
                return -EROFS;
 
        settings = image_settings_path(i, scope);
        if (!settings)
                return -ENOMEM;
 
        /* Make sure we don't interfere with a running nspawn */
        r = image_path_lock(scope, i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
        if (r < 0)
                return r;
 
        /* Make sure nobody takes the new name, between the time we
         * checked it is currently unused in all search paths, and the
         * time we take possession of it */
        r = image_name_lock(scope, new_name, LOCK_EX|LOCK_NB, &name_lock);
        if (r < 0)
                return r;
 
        r = image_find(scope, IMAGE_MACHINE, new_name, NULL, NULL);
        if (r >= 0)
                return -EEXIST;
        if (r != -ENOENT)
                return r;
 
        switch (i->type) {
 
        case IMAGE_DIRECTORY:
                /* Turn of the immutable bit while we rename the image, so that we can rename it */
                (void) read_attr_at(AT_FDCWD, i->path, &file_attr);
 
                if (file_attr & FS_IMMUTABLE_FL)
                        (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL);
 
                _fallthrough_;
        case IMAGE_SUBVOLUME:
                r = file_in_same_dir(i->path, new_name, &new_path);
                break;
 
        case IMAGE_BLOCK:
 
                /* Refuse renaming raw block devices in /dev, the names are picked by udev after all. */
                if (path_startswith(i->path, "/dev"))
                        return -EROFS;
 
                r = file_in_same_dir(i->path, new_name, &new_path);
                break;
 
        case IMAGE_RAW: {
                const char *fn;
 
                fn = strjoina(new_name, ".raw");
 
                r = file_in_same_dir(i->path, fn, &new_path);
                break;
        }
 
        default:
                return -EOPNOTSUPP;
        }
        if (r < 0)
                return r;
 
        nn = strdup(new_name);
        if (!nn)
                return -ENOMEM;
 
        r = rename_noreplace(AT_FDCWD, i->path, AT_FDCWD, new_path);
        if (r < 0)
                return r;
 
        /* Restore the immutable bit, if it was set before */
        if (file_attr & FS_IMMUTABLE_FL)
                (void) chattr_path(new_path, FS_IMMUTABLE_FL, FS_IMMUTABLE_FL);
 
        STRV_FOREACH(j, settings) {
                r = rename_auxiliary_file(*j, new_name, ".nspawn");
                if (r < 0 && r != -ENOENT)
                        log_debug_errno(r, "Failed to rename settings file '%s', ignoring: %m", *j);
        }
 
        NULSTR_FOREACH(suffix, auxiliary_suffixes_nulstr) {
                _cleanup_free_ char *aux = NULL;
 
                r = image_auxiliary_path(i, suffix, &aux);
                if (r < 0) {
                        RET_GATHER(ret, log_debug_errno(r, "Failed to generate auxiliary path for image '%s' suffix '%s': %m",
                                                        i->name, suffix));
                        continue;
                }
 
                r = rename_auxiliary_file(aux, new_name, suffix);
                if (r < 0 && r != -ENOENT)
                        log_debug_errno(r, "Failed to rename auxiliary file '%s', ignoring: %m", aux);
        }
 
        free_and_replace(i->path, new_path);
        free_and_replace(i->name, nn);
 
        return ret;
}
 
static int clone_auxiliary_file(const char *path, const char *new_name, const char *suffix) {
        int r;
 
        assert(path);
        assert(new_name);
        assert(suffix);
 
        _cleanup_free_ char *fn = strjoin(new_name, suffix);
        if (!fn)
                return -ENOMEM;
 
        _cleanup_free_ char *rs = NULL;
        r = file_in_same_dir(path, fn, &rs);
        if (r < 0)
                return r;
 
        return copy_file_atomic(path, rs, 0664, /* copy_flags= */ 0);
}
 
static int get_pool_directory(
                RuntimeScope scope,
                ImageClass class,
                const char *fname,
                const char *suffix,
                char **ret) {
 
        int r;
 
        assert(scope >= 0);
        assert(scope < _RUNTIME_SCOPE_MAX);
        assert(class >= 0);
        assert(class < _IMAGE_CLASS_MAX);
        assert(ret);
 
        _cleanup_free_ char *root = NULL;
        switch (scope) {
 
        case RUNTIME_SCOPE_SYSTEM:
                r = sd_path_lookup(SD_PATH_SYSTEM_STATE_PRIVATE, /* suffix= */ NULL, &root);
                break;
 
        case RUNTIME_SCOPE_USER:
                r = sd_path_lookup(SD_PATH_USER_STATE_PRIVATE, /* suffix= */ NULL, &root);
                break;
 
        default:
                return -EOPNOTSUPP;
        }
        if (r < 0)
                return r;
 
        const char *n = image_dirname_to_string(class);
        if (!n)
                return -EOPNOTSUPP;
 
        _cleanup_free_ char *j = NULL;
        const char *fn;
        if (fname && suffix) {
                j = strjoin(fname, suffix);
                if (!j)
                        return -ENOMEM;
                fn = j;
        } else
                fn = fname ?: suffix;
 
        _cleanup_free_ char *p = path_join(root, n, fn);
        if (!p)
                return -ENOMEM;
 
        *ret = TAKE_PTR(p);
        return 0;
}
 
static int unprivileged_clone(Image *i, const char *new_path, bool read_only) {
        int r;
 
        assert(i);
        assert(new_path);
 
        _cleanup_close_ int userns_fd = nsresource_allocate_userns(
                        /* vl= */ NULL,
                        /* name= */ NULL,
                        /* size= */ NSRESOURCE_UIDS_64K);
        if (userns_fd < 0)
                return log_debug_errno(userns_fd, "Failed to allocate transient user namespace: %m");
 
        _cleanup_(sd_varlink_unrefp) sd_varlink *link = NULL;
        r = mountfsd_connect(&link);
        if (r < 0)
                return r;
 
        /* Map original image */
        _cleanup_close_ int tree_fd = -EBADF;
        r = mountfsd_mount_directory(
                        link,
                        i->path,
                        userns_fd,
                        DISSECT_IMAGE_FOREIGN_UID,
                        &tree_fd);
        if (r < 0)
                return r;
 
        /* Make new image */
        _cleanup_close_ int new_fd = -EBADF;
        r = mountfsd_make_directory(
                        link,
                        new_path,
                        MODE_INVALID,
                        /* flags= */ 0,
                        &new_fd);
        if (r < 0)
                return r;
 
        /* Mount new image */
        _cleanup_close_ int target_fd = -EBADF;
        r = mountfsd_mount_directory_fd(
                        link,
                        new_fd,
                        userns_fd,
                        DISSECT_IMAGE_FOREIGN_UID,
                        &target_fd);
        if (r < 0)
                return r;
 
        link = sd_varlink_unref(link);
 
        /* Fork off child that moves into userns and does the copying */
        r = copy_tree_at_foreign(tree_fd, target_fd, userns_fd);
        if (r < 0)
                return r;
 
        /* Match the best-effort immutable bit handling of ordinary directory clones. */
        if (read_only)
                (void) chattr_fd(new_fd, FS_IMMUTABLE_FL, FS_IMMUTABLE_FL);
 
        return 0;
}
 
int image_clone(Image *i, const char *new_name, bool read_only, RuntimeScope scope) {
        _cleanup_(release_lock_file) LockFile name_lock = LOCK_FILE_INIT;
        _cleanup_strv_free_ char **settings = NULL;
        int r;
 
        assert(i);
 
        if (!image_name_is_valid(new_name))
                return -EINVAL;
 
        settings = image_settings_path(i, scope);
        if (!settings)
                return -ENOMEM;
 
        /* Make sure nobody takes the new name, between the time we
         * checked it is currently unused in all search paths, and the
         * time we take possession of it */
        r = image_name_lock(scope, new_name, LOCK_EX|LOCK_NB, &name_lock);
        if (r < 0)
                return r;
 
        r = image_find(scope, i->class, new_name, NULL, NULL);
        if (r >= 0)
                return -EEXIST;
        if (r != -ENOENT)
                return r;
 
        switch (i->type) {
 
        case IMAGE_SUBVOLUME:
        case IMAGE_DIRECTORY: {
                /* If we can we'll always try to create a new btrfs subvolume here, even if the source is a plain
                 * directory. */
 
                _cleanup_free_ char *new_path = NULL;
                r = get_pool_directory(scope, i->class, new_name, /* suffix= */ NULL, &new_path);
                if (r < 0)
                        return r;
 
                if (i->foreign_uid_owned)
                        r = unprivileged_clone(i, new_path, read_only);
                else {
                        r = btrfs_subvol_snapshot_at(
                                        AT_FDCWD, i->path,
                                        AT_FDCWD, new_path,
                                        (read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) |
                                        BTRFS_SNAPSHOT_FALLBACK_COPY |
                                        BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
                                        BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE |
                                        BTRFS_SNAPSHOT_RECURSIVE |
                                        BTRFS_SNAPSHOT_QUOTA);
                        if (r >= 0)
                                /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
                                (void) btrfs_subvol_auto_qgroup(new_path, /* subvol_id= */ 0, /* create_intermediary_qgroup= */ true);
                }
 
                break;
        }
 
        case IMAGE_RAW: {
                _cleanup_free_ char *new_path = NULL;
                r = get_pool_directory(scope, i->class, new_name, ".raw", &new_path);
                if (r < 0)
                        return r;
 
                r = copy_file_atomic(i->path, new_path, read_only ? 0444 : 0644,
                                     COPY_CRTIME|COPY_NOCOW_AFTER);
                break;
        }
 
        case IMAGE_BLOCK:
        default:
                return -EOPNOTSUPP;
        }
        if (r < 0)
                return r;
 
        STRV_FOREACH(j, settings) {
                r = clone_auxiliary_file(*j, new_name, ".nspawn");
                if (r < 0 && r != -ENOENT)
                        log_debug_errno(r, "Failed to clone settings %s, ignoring: %m", *j);
        }
 
        NULSTR_FOREACH(suffix, auxiliary_suffixes_nulstr) {
                _cleanup_free_ char *aux = NULL;
                r = image_auxiliary_path(i, suffix, &aux);
                if (r < 0)
                        return r;
 
                r = clone_auxiliary_file(aux, new_name, suffix);
                if (r < 0 && r != -ENOENT)
                        log_debug_errno(r, "Failed to clone auxiliary file '%s', ignoring: %m", aux);
        }
 
        return 0;
}
 
int image_read_only(Image *i, bool b, RuntimeScope scope) {
        _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
        int r;
 
        assert(i);
 
        if (image_is_vendor(i) || image_is_host(i) || image_is_hidden(i))
                return -EROFS;
 
        /* Make sure we don't interfere with a running nspawn */
        r = image_path_lock(scope, i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
        if (r < 0)
                return r;
 
        switch (i->type) {
 
        case IMAGE_SUBVOLUME:
 
                /* Note that we set the flag only on the top-level
                 * subvolume of the image. */
 
                r = btrfs_subvol_set_read_only(i->path, b);
                if (r < 0)
                        return r;
 
                break;
 
        case IMAGE_DIRECTORY:
                /* For simple directory trees we cannot use the access
                   mode of the top-level directory, since it has an
                   effect on the container itself.  However, we can
                   use the "immutable" flag, to at least make the
                   top-level directory read-only. It's not as good as
                   a read-only subvolume, but at least something, and
                   we can read the value back. */
 
                r = chattr_path(i->path, b ? FS_IMMUTABLE_FL : 0, FS_IMMUTABLE_FL);
                if (r < 0)
                        return r;
 
                break;
 
        case IMAGE_RAW: {
                struct stat st;
 
                if (stat(i->path, &st) < 0)
                        return -errno;
 
                if (chmod(i->path, (st.st_mode & 0444) | (b ? 0000 : 0200)) < 0)
                        return -errno;
 
                /* If the images is now read-only, it's a good time to
                 * defrag it, given that no write patterns will
                 * fragment it again. */
                if (b)
                        (void) btrfs_defrag(i->path);
                break;
        }
 
        case IMAGE_BLOCK: {
                _cleanup_close_ int fd = -EBADF;
                int state = b;
 
                fd = open(i->path, O_CLOEXEC|O_RDONLY|O_NONBLOCK|O_NOCTTY);
                if (fd < 0)
                        return -errno;
 
                r = fd_verify_block(fd);
                if (r < 0)
                        return r;
 
                if (ioctl(fd, BLKROSET, &state) < 0)
                        return -errno;
 
                break;
        }
 
        default:
                return -EOPNOTSUPP;
        }
 
        i->read_only = b;
        return 0;
}
 
static int make_lock_dir(RuntimeScope scope) {
        int r;
 
        _cleanup_free_ char *p = NULL;
        r = runtime_directory_generic(scope, "systemd", &p);
        if (r < 0)
                return r;
 
        _cleanup_close_ int pfd = open_mkdir_at(AT_FDCWD, p, O_CLOEXEC, 0755);
        if (pfd < 0)
                return pfd;
 
        _cleanup_close_ int nfd = open_mkdir_at(pfd, "nspawn", O_CLOEXEC, 0755);
        if (nfd < 0)
                return nfd;
 
        r = RET_NERRNO(mkdirat(nfd, "locks", 0700));
        if (r == -EEXIST)
                return 0;
        if (r < 0)
                return r;
 
        return 1;
}
 
int image_path_lock(
                RuntimeScope scope,
                const char *path,
                int operation,
                LockFile *ret_global,
                LockFile *ret_local) {
 
        _cleanup_free_ char *p = NULL;
        LockFile t = LOCK_FILE_INIT;
        struct stat st;
        bool exclusive;
        int r;
 
        assert(path);
        assert(ret_local);
 
        /* Locks an image path. This actually creates two locks: one "local" one, next to the image path
         * itself, which might be shared via NFS. And another "global" one, in /run/, that uses the
         * device/inode number. This has the benefit that we can even lock a tree that is a mount point,
         * correctly. */
 
        if (!path_is_absolute(path))
                return -EINVAL;
 
        switch (operation & (LOCK_SH|LOCK_EX)) {
        case LOCK_SH:
                exclusive = false;
                break;
        case LOCK_EX:
                exclusive = true;
                break;
        default:
                return -EINVAL;
        }
 
        if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
                *ret_local = LOCK_FILE_INIT;
                if (ret_global)
                        *ret_global = LOCK_FILE_INIT;