HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/sysext/sysext.c

132,720 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: e31d38d83f0ebe3c4643975d7ec98aa1f9102715

Lines 1001–2000 of 3,321

                if (chmod_fd < 0)
                        return log_error_errno(chmod_fd, "Failed to reopen '%s/%s': %m", strempty(root), skip_leading_slash(path));
 
                if (fchmod(chmod_fd, hierarchy_mode) < 0)
                        return log_error_errno(errno, "Failed to chmod directory '%s/%s': %m", strempty(root), skip_leading_slash(path));
 
                r = mac_selinux_fix_full(chmod_fd, /* inode_path= */ NULL, hierarchy, /* flags= */ 0, /* label_context= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to fix SELinux label for '%s/%s': %m", strempty(root), skip_leading_slash(path));
        }
 
        r = chase(path, root, CHASE_PREFIX_ROOT, &resolved_path, NULL);
        if (r < 0 && r != -ENOENT)
                return log_error_errno(r, "Failed to resolve mutable directory '%s': %m", path);
 
        *ret_resolved_mutable_directory = TAKE_PTR(resolved_path);
        return 0;
}
 
static int overlayfs_paths_new(const Context *c, const char *hierarchy, const char *workspace_path, OverlayFSPaths **ret_op) {
        _cleanup_free_ char *hierarchy_copy = NULL, *resolved_hierarchy = NULL, *resolved_mutable_directory = NULL;
        mode_t hierarchy_mode;
 
        int r;
 
        assert(c);
        assert(hierarchy);
        assert(ret_op);
 
        hierarchy_copy = strdup(hierarchy);
        if (!hierarchy_copy)
                return log_oom();
 
        r = resolve_hierarchy(c, hierarchy, &resolved_hierarchy);
        if (r < 0)
                return r;
 
        if (resolved_hierarchy) {
                struct stat st;
 
                if (stat(resolved_hierarchy, &st) < 0)
                        return log_error_errno(errno, "Failed to stat '%s': %m", resolved_hierarchy);
                hierarchy_mode = st.st_mode & 0777;
        } else
                hierarchy_mode = 0755;
 
        r = resolve_mutable_directory(c, hierarchy, hierarchy_mode, workspace_path, &resolved_mutable_directory);
        if (r < 0)
                return r;
 
        OverlayFSPaths *op;
        op = new(OverlayFSPaths, 1);
        if (!op)
                return log_oom();
 
        *op = (OverlayFSPaths) {
                .hierarchy = TAKE_PTR(hierarchy_copy),
                .hierarchy_mode = hierarchy_mode,
                .resolved_hierarchy = TAKE_PTR(resolved_hierarchy),
                .resolved_mutable_directory = TAKE_PTR(resolved_mutable_directory),
        };
 
        *ret_op = TAKE_PTR(op);
        return 0;
}
 
static int determine_used_extensions(const char *hierarchy, char **paths, char ***ret_used_paths, size_t *ret_extensions_used) {
        _cleanup_strv_free_ char **used_paths = NULL;
        size_t n = 0;
        int r;
 
        assert(hierarchy);
        assert(paths);
        assert(ret_used_paths);
        assert(ret_extensions_used);
 
        STRV_FOREACH(p, paths) {
                _cleanup_free_ char *resolved = NULL;
 
                r = chase(hierarchy, *p, CHASE_PREFIX_ROOT, &resolved, NULL);
                if (r == -ENOENT) {
                        log_debug_errno(r, "Hierarchy '%s' in extension '%s' doesn't exist, not merging.", hierarchy, *p);
                        continue;
                }
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve hierarchy '%s' in extension '%s': %m", hierarchy, *p);
 
                r = dir_is_empty(resolved, /* ignore_hidden_or_backup= */ false);
                if (r < 0)
                        return log_error_errno(r, "Failed to check if hierarchy '%s' in extension '%s' is empty: %m", resolved, *p);
                if (r > 0) {
                        log_debug("Hierarchy '%s' in extension '%s' is empty, not merging.", hierarchy, *p);
                        continue;
                }
 
                r = strv_consume_with_size(&used_paths, &n, TAKE_PTR(resolved));
                if (r < 0)
                        return log_oom();
        }
 
        *ret_used_paths = TAKE_PTR(used_paths);
        *ret_extensions_used = n;
        return 0;
}
 
static int maybe_import_mutable_directory(const Context *c, OverlayFSPaths *op) {
        int r;
 
        assert(c);
        assert(op);
 
        /* If importing mutable layer and it actually exists and is not a hierarchy itself, add it just below
         * the meta path */
 
        if (c->mutable != MUTABLE_IMPORT || !op->resolved_mutable_directory)
                return 0;
 
        r = path_equal_or_inode_same_full(op->resolved_hierarchy, op->resolved_mutable_directory, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to check equality of hierarchy %s and its mutable directory %s: %m", op->resolved_hierarchy, op->resolved_mutable_directory);
        if (r > 0)
                return log_error_errno(SYNTHETIC_ERRNO(ELOOP), "Not importing mutable directory for hierarchy %s as a lower dir, because it points to the hierarchy itself", op->hierarchy);
 
        r = strv_extend(&op->lower_dirs, op->resolved_mutable_directory);
        if (r < 0)
                return log_oom();
 
        return 0;
}
 
static int maybe_import_ignored_mutable_directory(const Context *c, OverlayFSPaths *op) {
        _cleanup_free_ char *dir_name = NULL, *path = NULL, *resolved_path = NULL;
        int r;
 
        assert(c);
        assert(op);
 
        /* If importing the ignored mutable layer and it actually exists and is not a hierarchy itself, add
         * it just below the meta path */
        if (c->mutable != MUTABLE_EPHEMERAL_IMPORT)
                return 0;
 
        dir_name = hierarchy_as_single_path_component(op->hierarchy);
        if (!dir_name)
                return log_oom();
 
        path = path_join(MUTABLE_EXTENSIONS_BASE_DIR, dir_name);
        if (!path)
                return log_oom();
 
        r = chase(path, c->root, CHASE_PREFIX_ROOT, &resolved_path, NULL);
        if (r == -ENOENT) {
                log_debug("Mutable directory for %s does not exist, not importing", op->hierarchy);
                return 0;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to resolve mutable directory '%s': %m", path);
 
        r = path_equal_or_inode_same_full(op->resolved_hierarchy, resolved_path, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to check equality of hierarchy %s and its mutable directory %s: %m", op->resolved_hierarchy, op->resolved_mutable_directory);
 
        if (r > 0)
                return log_error_errno(SYNTHETIC_ERRNO(ELOOP), "Not importing mutable directory for hierarchy %s as a lower dir, because it points to the hierarchy itself", op->hierarchy);
 
        r = strv_consume(&op->lower_dirs, TAKE_PTR(resolved_path));
        if (r < 0)
                return log_oom();
 
        return 0;
}
 
static int determine_top_lower_dirs(const Context *c, OverlayFSPaths *op, const char *meta_path) {
        int r;
 
        assert(c);
        assert(op);
        assert(meta_path);
 
        /* Put the meta path (i.e. our synthesized stuff) at the top of the layer stack */
        r = strv_extend(&op->lower_dirs, meta_path);
        if (r < 0)
                return log_oom();
 
        r = maybe_import_mutable_directory(c, op);
        if (r < 0)
                return r;
 
        r = maybe_import_ignored_mutable_directory(c, op);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int determine_middle_lower_dirs(OverlayFSPaths *op, char **paths) {
        assert(op);
 
        /* The paths were already determined in determine_used_extensions, so we just take them as is. */
        if (strv_extend_strv(&op->lower_dirs, paths, /* filter_duplicates= */ false) < 0)
                return log_oom();
 
        return 0;
}
 
static int hierarchy_as_lower_dir(const Context *c, OverlayFSPaths *op) {
        int r;
 
        /* return 0 if hierarchy should be used as lower dir, >0, if not */
 
        assert(c);
        assert(op);
 
        if (!op->resolved_hierarchy) {
                log_debug("Host hierarchy '%s' does not exist, will not be used as lowerdir", op->hierarchy);
                return 1;
        }
 
        r = dir_is_empty(op->resolved_hierarchy, /* ignore_hidden_or_backup= */ false);
        if (r < 0)
                return log_error_errno(r, "Failed to check if host hierarchy '%s' is empty: %m", op->resolved_hierarchy);
        if (r > 0) {
                log_debug("Host hierarchy '%s' is empty, will not be used as lower dir.", op->resolved_hierarchy);
                return 1;
        }
 
        if (c->mutable == MUTABLE_IMPORT) {
                log_debug("Mutability for host hierarchy '%s' is disabled, so host hierarchy will be a lowerdir", op->resolved_hierarchy);
                return 0;
        }
 
        if (c->mutable == MUTABLE_EPHEMERAL_IMPORT) {
                log_debug("Mutability for host hierarchy '%s' is ephemeral, so host hierarchy will be a lowerdir", op->resolved_hierarchy);
                return 0;
        }
 
        if (!op->resolved_mutable_directory) {
                log_debug("No mutable directory found, so host hierarchy '%s' will be used as lowerdir", op->resolved_hierarchy);
                return 0;
        }
 
        r = path_equal_or_inode_same_full(op->resolved_hierarchy, op->resolved_mutable_directory, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to check equality of hierarchy %s and its mutable directory %s: %m", op->resolved_hierarchy, op->resolved_mutable_directory);
        if (r > 0) {
                log_debug("Host hierarchy '%s' will serve as upperdir.", op->resolved_hierarchy);
                return 1;
        }
 
        return 0;
}
 
static int determine_bottom_lower_dirs(const Context *c, OverlayFSPaths *op, dev_t *ret_backing_devnum) {
        int r;
 
        assert(c);
        assert(op);
        assert(ret_backing_devnum);
 
        r = hierarchy_as_lower_dir(c, op);
        if (r < 0)
                return r;
        if (!r) {
                if (strv_extend(&op->lower_dirs, op->resolved_hierarchy) < 0)
                        return log_oom();
 
                r = get_block_device(op->resolved_hierarchy, ret_backing_devnum);
                if (r < 0)
                        return log_error_errno(r, "Failed to get block device of '%s': %m", op->resolved_hierarchy);
        } else
                *ret_backing_devnum = 0;
 
        return 0;
}
 
static int determine_lower_dirs(
                const Context *c,
                OverlayFSPaths *op,
                char **paths,
                const char *meta_path,
                dev_t *ret_backing_devnum) {
 
        int r;
 
        assert(c);
        assert(op);
        assert(meta_path);
        assert(ret_backing_devnum);
 
        r = determine_top_lower_dirs(c, op, meta_path);
        if (r < 0)
                return r;
 
        r = determine_middle_lower_dirs(op, paths);
        if (r < 0)
                return r;
 
        r = determine_bottom_lower_dirs(c, op, ret_backing_devnum);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int determine_upper_dir(const Context *c, OverlayFSPaths *op) {
        int r;
 
        assert(c);
        assert(op);
        assert(!op->upper_dir);
 
        if (c->mutable == MUTABLE_IMPORT) {
                log_debug("Mutability is disabled, there will be no upperdir for host hierarchy '%s'", op->hierarchy);
                return 0;
        }
 
        if (!op->resolved_mutable_directory) {
                log_debug("No mutable directory found for host hierarchy '%s', there will be no upperdir", op->hierarchy);
                return 0;
        }
 
        /* Require upper dir to be on writable filesystem if it's going to be used as an actual overlayfs
         * upperdir, instead of a lowerdir as an imported path. */
        r = path_is_read_only_fs(op->resolved_mutable_directory);
        if (r < 0)
                return log_error_errno(r, "Failed to determine if mutable directory '%s' is on read-only filesystem: %m", op->resolved_mutable_directory);
        if (r > 0)
                return log_error_errno(SYNTHETIC_ERRNO(EROFS), "Can't use '%s' as an upperdir as it is read-only.", op->resolved_mutable_directory);
 
        op->upper_dir = strdup(op->resolved_mutable_directory);
        if (!op->upper_dir)
                return log_oom();
 
        return 0;
}
 
static int determine_work_dir(const Context *c, OverlayFSPaths *op) {
        _cleanup_free_ char *work_dir = NULL;
        int r;
 
        assert(c);
        assert(op);
        assert(!op->work_dir);
 
        if (!op->upper_dir)
                return 0;
 
        if (c->mutable == MUTABLE_IMPORT)
                return 0;
 
        r = work_dir_for_hierarchy(op->hierarchy, op->upper_dir, &work_dir);
        if (r < 0)
                return r;
 
        op->work_dir = TAKE_PTR(work_dir);
        return 0;
}
 
static int mount_overlayfs_with_op(
                OverlayFSPaths *op,
                ImageClass image_class,
                int noexec,
                const char *overlay_path,
                const char *meta_path,
                const char *mount_options) {
 
        int r;
        const char *top_layer = NULL;
 
        assert(op);
        assert(overlay_path);
 
        r = mkdir_p(overlay_path, 0700);
        if (r < 0)
                return log_error_errno(r, "Failed to make directory '%s': %m", overlay_path);
 
        r = mkdir_p(meta_path, 0700);
        if (r < 0)
                return log_error_errno(r, "Failed to make directory '%s': %m", meta_path);
 
        _cleanup_close_ int atfd = open(meta_path, O_DIRECTORY|O_CLOEXEC);
        if (atfd < 0)
                return log_error_errno(errno, "Failed to open directory '%s': %m", meta_path);
 
        r = mac_selinux_fix_full(atfd, /* inode_path= */ NULL, op->hierarchy, /* flags= */ 0, /* label_context= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to fix SELinux label for '%s': %m", meta_path);
 
        if (op->upper_dir && op->work_dir) {
                r = mkdir_p(op->work_dir, 0700);
                if (r < 0)
                        return log_error_errno(r, "Failed to make directory '%s': %m", op->work_dir);
 
                _cleanup_close_ int dfd = open(op->work_dir, O_DIRECTORY|O_CLOEXEC);
                if (dfd < 0)
                        return log_error_errno(errno, "Failed to open directory '%s': %m", op->work_dir);
 
                r = mac_selinux_fix_full(dfd, /* inode_path= */ NULL, op->hierarchy, /* flags= */ 0, /* label_context= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to fix SELinux label for '%s': %m", op->work_dir);
 
                top_layer = op->upper_dir;
        } else {
                assert(!strv_isempty(op->lower_dirs));
                top_layer = op->lower_dirs[0];
        }
 
        /* Overlayfs merged directory has the same mode as the top layer (either first lowerdir in options in
         * read-only case, or upperdir for mutable case. Set up top overlayfs layer to the same mode as the
         * unmerged hierarchy, otherwise we might end up with merged hierarchy owned by root and with mode
         * being 0700. */
        if (chmod(top_layer, op->hierarchy_mode) < 0)
                return log_error_errno(errno, "Failed to set permissions of '%s' to %04o: %m", top_layer, op->hierarchy_mode);
 
        r = mount_overlayfs(image_class, noexec, overlay_path, op->lower_dirs, op->upper_dir, op->work_dir, mount_options);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int write_extensions_file(ImageClass image_class, char **extensions, const char *meta_path, const char *hierarchy) {
        _cleanup_free_ char *f = NULL, *buf = NULL;
        int r;
 
        assert(meta_path);
 
        /* Let's generate a metadata file that lists all extensions we took into account for this
         * hierarchy. We include this in the final fs, to make things nicely discoverable and
         * recognizable. */
        f = path_join(meta_path, image_class_info[image_class].dot_directory_name, image_class_info[image_class].short_identifier_plural);
        if (!f)
                return log_oom();
 
        if (!strv_isempty(extensions)) {
                buf = strv_join(extensions, "\n");
                if (!buf)
                        return log_oom();
 
                if (!strextend(&buf, "\n")) /* manually append newline since we want to suppress newline if zero extensions are applied */
                        return log_oom();
        }
 
        _cleanup_free_ char *hierarchy_path = path_join(hierarchy, image_class_info[image_class].dot_directory_name, image_class_info[image_class].short_identifier_plural);
        if (!hierarchy_path)
                return log_oom();
 
        r = write_string_file_full(AT_FDCWD, f, strempty(buf), WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MKDIR_0755|WRITE_STRING_FILE_LABEL|WRITE_STRING_FILE_AVOID_NEWLINE, /* ts= */ NULL, hierarchy_path);
        if (r < 0)
                return log_error_errno(r, "Failed to write extension meta file '%s': %m", f);
 
        return 0;
}
 
static int write_origin_file(ImageClass image_class, const char *origin_content, const char *meta_path, const char *hierarchy) {
        _cleanup_free_ char *f = NULL;
        int r;
 
        assert(meta_path);
 
        /* The origin file is compared to know if a refresh can be skipped (opt-in, used at service startup). */
        f = path_join(meta_path, image_class_info[image_class].dot_directory_name, "origin");
        if (!f)
                return log_oom();
 
        _cleanup_free_ char *hierarchy_path = path_join(hierarchy, image_class_info[image_class].dot_directory_name, image_class_info[image_class].short_identifier_plural);
        if (!hierarchy_path)
                return log_oom();
 
        r = write_string_file_full(AT_FDCWD, f, strempty(origin_content),
                                   WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MKDIR_0755|WRITE_STRING_FILE_LABEL|WRITE_STRING_FILE_AVOID_NEWLINE,
                                   /* ts= */ NULL, hierarchy_path);
        if (r < 0)
                return log_error_errno(r, "Failed to write origin meta file '%s': %m", f);
 
        return 0;
}
 
static int write_dev_file(ImageClass image_class, const char *meta_path, const char *overlay_path, const char *hierarchy) {
        _cleanup_free_ char *f = NULL;
        struct stat st;
        int r;
 
        assert(meta_path);
        assert(overlay_path);
 
        /* Now we have mounted the new file system. Let's now figure out its .st_dev field, and make that
         * available in the metadata directory. This is useful to detect whether the metadata dir actually
         * belongs to the fs it is found on: if .st_dev of the top-level mount matches it, it's pretty likely
         * we are looking at a live tree, and not an unpacked tar or so of one. */
        if (stat(overlay_path, &st) < 0)
                return log_error_errno(errno, "Failed to stat mount '%s': %m", overlay_path);
 
        f = path_join(meta_path, image_class_info[image_class].dot_directory_name, "dev");
        if (!f)
                return log_oom();
 
        /* Modifying the underlying layers while the overlayfs is mounted is technically undefined, but at
         * least it won't crash or deadlock, as per the kernel docs about overlayfs:
         * https://www.kernel.org/doc/html/latest/filesystems/overlayfs.html#changes-to-underlying-filesystems */
        _cleanup_free_ char *hierarchy_path = path_join(hierarchy, image_class_info[image_class].dot_directory_name, image_class_info[image_class].short_identifier_plural);
        if (!hierarchy_path)
                return log_oom();
 
        r = write_string_file_full(AT_FDCWD, f, FORMAT_DEVNUM(st.st_dev), WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_LABEL, /* ts= */ NULL, hierarchy_path);
        if (r < 0)
                return log_error_errno(r, "Failed to write '%s': %m", f);
 
        return 0;
}
 
static int write_backing_file(ImageClass image_class, const char *meta_path, const char *overlay_path, const char *hierarchy, dev_t backing) {
        int r;
 
        assert(meta_path);
        assert(overlay_path);
        assert(hierarchy);
 
        if (backing == 0)
                return 0;
 
        /* Let's also store away the backing file system dev_t, so that applications can trace back what they are looking at here */
        _cleanup_free_ char *f = path_join(meta_path, image_class_info[image_class].dot_directory_name, "backing");
        if (!f)
                return log_oom();
 
        /* Modifying the underlying layers while the overlayfs is mounted is technically undefined, but at
         * least it won't crash or deadlock, as per the kernel docs about overlayfs:
         * https://www.kernel.org/doc/html/latest/filesystems/overlayfs.html#changes-to-underlying-filesystems */
        _cleanup_free_ char *hierarchy_path = path_join(hierarchy, image_class_info[image_class].dot_directory_name, image_class_info[image_class].short_identifier_plural);
        if (!hierarchy_path)
                return log_oom();
 
        r = write_string_file_full(AT_FDCWD, f, FORMAT_DEVNUM(backing), WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_LABEL, /* ts= */ NULL, hierarchy_path);
        if (r < 0)
                return log_error_errno(r, "Failed to write '%s': %m", f);
 
        return 0;
}
 
static int write_work_dir_file(const Context *c, const char *meta_path, const char *work_dir, const char* hierarchy) {
        _cleanup_free_ char *escaped_work_dir_in_root = NULL, *f = NULL;
        char *work_dir_in_root = NULL;
        int r;
 
        assert(c);
        assert(meta_path);
 
        if (!work_dir)
                return 0;
 
        /* Do not store work dir path for ephemeral mode, it will be gone once this process is done. */
        if (IN_SET(c->mutable, MUTABLE_EPHEMERAL, MUTABLE_EPHEMERAL_IMPORT))
                return 0;
 
        work_dir_in_root = path_startswith(work_dir, empty_to_root(c->root));
        if (!work_dir_in_root)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Workdir '%s' must not be outside root '%s'", work_dir, empty_to_root(c->root));
 
        f = path_join(meta_path, image_class_info[c->image_class].dot_directory_name, "work_dir");
        if (!f)
                return log_oom();
 
        /* Paths can have newlines for whatever reason, so better escape them to really get a single
         * line file. */
        escaped_work_dir_in_root = cescape(work_dir_in_root);
        if (!escaped_work_dir_in_root)
                return log_oom();
 
        _cleanup_free_ char *hierarchy_path = path_join(hierarchy, image_class_info[c->image_class].dot_directory_name, "work_dir");
        if (!hierarchy_path)
                return log_oom();
 
        r = write_string_file_full(AT_FDCWD, f, escaped_work_dir_in_root, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_LABEL, /* ts= */ NULL, hierarchy_path);
        if (r < 0)
                return log_error_errno(r, "Failed to write '%s': %m", f);
 
        return 0;
}
 
static int store_info_in_meta(
                const Context *c,
                char **extensions,
                const char *origin_content,
                const char *meta_path,
                const char *overlay_path,
                const char *work_dir,
                const char *hierarchy,
                dev_t backing) {
 
        int r;
 
        assert(c);
        assert(meta_path);
        assert(overlay_path);
        /* work_dir may be NULL */
 
        _cleanup_free_ char *f = path_join(meta_path, image_class_info[c->image_class].dot_directory_name);
        if (!f)
                return log_oom();
 
        r = mkdir_p(f, 0755);
        if (r < 0)
                return log_error_errno(r, "Failed to create directory '%s': %m", f);
 
        _cleanup_close_ int atfd = open(f, O_DIRECTORY|O_CLOEXEC);
        if (atfd < 0)
                return log_error_errno(errno, "Failed to open directory '%s': %m", f);
 
        r = mac_selinux_fix_full(atfd, /* inode_path= */ NULL, hierarchy, /* flags= */ 0, /* label_context= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to fix SELinux label for '%s': %m", hierarchy);
 
        r = write_extensions_file(c->image_class, extensions, meta_path, hierarchy);
        if (r < 0)
                return r;
 
        r = write_origin_file(c->image_class, origin_content, meta_path, hierarchy);
        if (r < 0)
                return r;
 
        r = write_dev_file(c->image_class, meta_path, overlay_path, hierarchy);
        if (r < 0)
                return r;
 
        r = write_work_dir_file(c, meta_path, work_dir, hierarchy);
        if (r < 0)
                return r;
 
        r = write_backing_file(c->image_class, meta_path, overlay_path, hierarchy, backing);
        if (r < 0)
                return r;
 
        /* Make sure the top-level dir has an mtime marking the point we established the merge */
        if (utimensat(AT_FDCWD, meta_path, NULL, AT_SYMLINK_NOFOLLOW) < 0)
                return log_error_errno(errno, "Failed to fix mtime of '%s': %m", meta_path);
 
        return 0;
}
 
static int make_mounts_read_only(ImageClass image_class, const char *overlay_path, bool mutable) {
        int r;
 
        assert(overlay_path);
 
        if (mutable) {
                /* Bind mount the meta path as read-only on mutable overlays to avoid accidental
                 * modifications of the contents of meta directory, which could lead to systemd thinking that
                 * this hierarchy is not our mount. */
                _cleanup_free_ char *f = NULL;
 
                f = path_join(overlay_path, image_class_info[image_class].dot_directory_name);
                if (!f)
                        return log_oom();
 
                r = mount_nofollow_verbose(LOG_ERR, f, f, NULL, MS_BIND, NULL);
                if (r < 0)
                        return r;
 
                r = bind_remount_one(f, MS_RDONLY, MS_RDONLY);
                if (r < 0)
                        return log_error_errno(r, "Failed to remount '%s' as read-only: %m", f);
        } else {
                /* The overlayfs superblock is read-only. Let's also mark the bind mount read-only. Extra
                 * turbo safety 😎 */
                r = bind_remount_recursive(overlay_path, MS_RDONLY, MS_RDONLY, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to make bind mount '%s' read-only: %m", overlay_path);
        }
 
        return 0;
}
 
static int merge_hierarchy(
                const Context *c,
                const char *hierarchy,
                char **extensions,
                char **paths,
                const char *origin_content,
                const char *meta_path,
                const char *overlay_path,
                const char *workspace_path) {
 
        _cleanup_(overlayfs_paths_freep) OverlayFSPaths *op = NULL;
        _cleanup_strv_free_ char **used_paths = NULL;
        size_t extensions_used = 0;
        int r;
 
        assert(c);
        assert(hierarchy);
        assert(paths);
        assert(meta_path);
        assert(overlay_path);
        assert(workspace_path);
 
        mac_selinux_init();
 
        r = determine_used_extensions(hierarchy, paths, &used_paths, &extensions_used);
        if (r < 0)
                return r;
 
        if (extensions_used == 0 && c->mutable == MUTABLE_NO) /* No extension with files in this hierarchy? Then don't do anything. */
                return 0;
 
        r = overlayfs_paths_new(c, hierarchy, workspace_path, &op);
        if (r < 0)
                return r;
 
        dev_t backing;
        r = determine_lower_dirs(c, op, used_paths, meta_path, &backing);
        if (r < 0)
                return r;
 
        r = determine_upper_dir(c, op);
        if (r < 0)
                return r;
 
        r = determine_work_dir(c, op);
        if (r < 0)
                return r;
 
        r = mount_overlayfs_with_op(op, c->image_class, c->noexec, overlay_path, meta_path, c->overlayfs_mount_options);
        if (r < 0)
                return r;
 
        r = store_info_in_meta(c, extensions, origin_content, meta_path, overlay_path, op->work_dir, op->hierarchy, backing);
        if (r < 0)
                return r;
 
        r = make_mounts_read_only(c->image_class, overlay_path, op->upper_dir && op->work_dir);
        if (r < 0)
                return r;
 
        return 1;
}
 
static int strverscmp_improvedp(char *const* a, char *const* b) {
        assert(a);
        assert(b);
 
        /* usable in qsort() for sorting a string array with strverscmp_improved() */
        return strverscmp_improved(*a, *b);
}
 
static const ImagePolicy* pick_image_policy(const Context *c, const Image *img) {
        assert(c);
        assert(img);
        assert(img->path);
 
        /* Explicitly specified policy always wins */
        if (c->image_policy)
                return c->image_policy;
 
        /* If located in /.extra/ in the initrd, then it was placed there by systemd-stub, and was
         * picked up from an untrusted ESP. Thus, require a stricter policy by default for them. (For the
         * other directories we assume the appropriate level of trust was already established.)
         * With --root= we default to the regular policy, though. (To change that, the check would need
         * to prepend (or cut away) c->root.) */
 
        if (in_initrd() && !c->root) {
                if (path_startswith(img->path, "/.extra/sysext/"))
                        return &image_policy_sysext_strict;
                if (path_startswith(img->path, "/.extra/global_sysext/"))
                        return &image_policy_sysext_strict;
                if (path_startswith(img->path, "/.extra/confext/"))
                        return &image_policy_confext_strict;
                if (path_startswith(img->path, "/.extra/global_confext/"))
                        return &image_policy_confext_strict;
 
                /* Better safe than sorry, refuse everything else passed in via the untrusted /.extra/ dir */
                if (path_startswith(img->path, "/.extra/"))
                        return &image_policy_deny;
        }
 
        return image_class_info[img->class].default_image_policy;
}
 
static int unmerge_hierarchy(const Context *c, const char *p, const char *submounts_path) {
        _cleanup_free_ char *dot_dir = NULL, *work_dir_info_file = NULL;
        int n_unmerged = 0;
        int r;
 
        assert(c);
        assert(p);
 
        dot_dir = path_join(p, image_class_info[c->image_class].dot_directory_name);
        if (!dot_dir)
                return log_oom();
 
        work_dir_info_file = path_join(dot_dir, "work_dir");
        if (!work_dir_info_file)
                return log_oom();
 
        for (;;) {
                _cleanup_free_ char *escaped_work_dir_in_root = NULL, *work_dir = NULL;
 
                /* We only unmount /usr/ if it is a mount point and really one of ours, in order not to break
                 * systems where /usr/ is a mount point of its own already. */
 
                r = is_our_mount_point(c->image_class, p);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                r = read_one_line_file(work_dir_info_file, &escaped_work_dir_in_root);
                if (r < 0) {
                        if (r != -ENOENT)
                                return log_error_errno(r, "Failed to read '%s': %m", work_dir_info_file);
                } else {
                        _cleanup_free_ char *work_dir_in_root = NULL;
                        ssize_t l;
 
                        l = cunescape_length(escaped_work_dir_in_root, r, 0, &work_dir_in_root);
                        if (l < 0)
                                return log_error_errno(l, "Failed to unescape work directory path: %m");
                        if (path_is_absolute(work_dir_in_root) || !path_is_normalized(work_dir_in_root))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Invalid work directory path '%s'.", work_dir_in_root);
 
                        work_dir = path_join(c->root, work_dir_in_root);
                        if (!work_dir)
                                return log_oom();
                }
 
                r = umount_verbose(LOG_DEBUG, dot_dir, MNT_DETACH|UMOUNT_NOFOLLOW);
                if (r < 0) {
                        /* EINVAL is possibly "not a mount point". Let it slide as it's expected to occur if
                         * the whole hierarchy was read-only, so the dot directory inside it was not
                         * bind-mounted as read-only. */
                        if (r != -EINVAL)
                                return log_error_errno(r, "Failed to unmount '%s': %m", dot_dir);
                }
 
                /* After we've unmounted the metadata directory, save all other submounts so we can restore
                 * them after unmerging the hierarchy. */
                r = move_submounts(p, submounts_path);
                if (r < 0)
                        return r;
 
                r = umount_verbose(LOG_ERR, p, MNT_DETACH|UMOUNT_NOFOLLOW);
                if (r < 0)
                        return r;
 
                if (work_dir) {
                        r = rm_rf(work_dir, REMOVE_ROOT | REMOVE_MISSING_OK | REMOVE_PHYSICAL);
                        if (r < 0)
                                return log_error_errno(r, "Failed to remove '%s': %m", work_dir);
                }
 
                log_info("Unmerged '%s'.", p);
                n_unmerged++;
        }
 
        return n_unmerged;
}
 
static int unmerge_subprocess(
                const Context *c,
                const char *workspace) {
 
        int r, ret = 0;
 
        assert(c);
        assert(workspace);
        assert(path_startswith(workspace, "/run/"));
 
        /* Mark the whole of /run as MS_SLAVE, so that we can mount stuff below it that doesn't show up on
         * the host otherwise. */
        r = mount_nofollow_verbose(LOG_ERR, NULL, "/run", NULL, MS_SLAVE|MS_REC, NULL);
        if (r < 0)
                return r;
 
        /* Let's create the workspace if it's missing */
        r = mkdir_p(workspace, 0700);
        if (r < 0)
                return log_error_errno(r, "Failed to create '%s': %m", workspace);
 
        STRV_FOREACH(h, c->hierarchies) {
                _cleanup_free_ char *submounts_path = NULL, *resolved = NULL;
 
                submounts_path = path_join(workspace, "submounts", *h);
                if (!submounts_path)
                        return log_oom();
 
                r = chase(*h, c->root, CHASE_PREFIX_ROOT, &resolved, NULL);
                if (r == -ENOENT) {
                        log_debug_errno(r, "Hierarchy '%s%s' does not exist, ignoring.", strempty(c->root), *h);
                        continue;
                }
                if (r < 0) {
                        RET_GATHER(ret, log_error_errno(r, "Failed to resolve path to hierarchy '%s%s': %m", strempty(c->root), *h));
                        continue;
                }
 
                r = unmerge_hierarchy(c, resolved, submounts_path);
                if (r < 0) {
                        RET_GATHER(ret, r);
                        continue;
                }
                if (r == 0)
                        continue;
 
                /* If we unmerged something, then we have to move the submounts from the hierarchy back into
                 * place in the host's original hierarchy. */
 
                r = move_submounts(submounts_path, resolved);
                if (r < 0)
                        return r;
        }
 
        return ret;
}
 
static int unmerge(const Context *c) {
 
        _cleanup_set_free_ Set *units_to_restart = NULL, *units_to_reload_or_restart = NULL;
        bool need_to_reload;
        int r;
 
        assert(c);
 
        (void) dlopen_libmount(LOG_DEBUG);
 
        r = get_extension_release_metadata(c, &need_to_reload, &units_to_restart, &units_to_reload_or_restart);
        if (r < 0)
                return r;
 
        r = pidref_safe_fork(
                        "(sd-unmerge)",
                        FORK_WAIT|FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_NEW_MOUNTNS,
                        /* ret= */ NULL);
        if (r < 0)
                return r;
        if (r == 0) {
                /* Child with its own mount namespace */
 
                r = unmerge_subprocess(c, "/run/systemd/sysext");
 
                /* Our namespace ceases to exist here, also implicitly detaching all temporary mounts we
                 * created below /run. Nice! */
 
                _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
        }
 
        if (need_to_reload) {
                r = daemon_reload();
                if (r < 0)
                        return r;
        }
 
        /* The sets will be empty when opted out */
        r = restart_units(units_to_restart, units_to_reload_or_restart);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int merge_subprocess(
                const Context *c,
                Hashmap *images,
                const char *workspace) {
 
        _cleanup_free_ char *host_os_release_id = NULL, *host_os_release_id_like = NULL,
                        *host_os_release_version_id = NULL, *host_os_release_api_level = NULL,
                        *filename = NULL, *old_origin_content = NULL,
                        *extensions_origin_content = NULL, *root_resolved = NULL;
        _cleanup_strv_free_ char **extensions = NULL, **extensions_v = NULL, **paths = NULL;
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *extensions_origin_entries = NULL,
                        *extensions_origin_json = NULL, *mutable_dir_entries = NULL;
        size_t n_extensions = 0;
        unsigned n_ignored = 0;
        Image *img;
        int r;
 
        assert(c);
 
        if (!isempty(c->root)) {
                r = chase(c->root, /* root= */ NULL, CHASE_MUST_BE_DIRECTORY, &root_resolved, /* ret_fd= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve --root='%s': %m", strempty(c->root));
        }
 
        assert(path_startswith(workspace, "/run/"));
 
        /* Mark the whole of /run as MS_SLAVE, so that we can mount stuff below it that doesn't show up on
         * the host otherwise. */
        r = mount_nofollow_verbose(LOG_ERR, NULL, "/run", NULL, MS_SLAVE|MS_REC, NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to remount /run/ MS_SLAVE: %m");
 
        /* Let's create the workspace if it's missing */
        r = mkdir_p(workspace, 0700);
        if (r < 0)
                return log_error_errno(r, "Failed to create '%s': %m", workspace);
 
        /* Let's mount a tmpfs to our workspace. This way we don't need to clean up the inodes we mount over,
         * but let the kernel do that entirely automatically, once our namespace dies. Note that this file
         * system won't be visible to anyone but us, since we opened our own namespace and then made the