HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/exec-invoke.c

290,468 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: ff107cc753cf314807216d8e1747fc30661a6ef4

Lines 3001–4000 of 6,799

        if (!params->prefix[type])
                return 0;
 
        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
                if (!uid_is_valid(uid))
                        uid = 0;
                if (!gid_is_valid(gid))
                        gid = 0;
        }
 
        uint32_t exec_dt_proj_id = 0;
        bool quota_already_enforced = false;
 
        FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
                _cleanup_free_ char *p = NULL, *pp = NULL;
 
                p = path_join(params->prefix[type], i->path);
                if (!p) {
                        r = -ENOMEM;
                        goto fail;
                }
 
                r = mkdir_parents_label(p, 0755);
                if (r < 0)
                        goto fail;
 
                if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
 
                        /* If we are in user mode, and a configuration directory exists but a state directory
                         * doesn't exist, then we likely are upgrading from an older systemd version that
                         * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
                         * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
                         * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME it is now
                         * separated. If a service has both dirs configured but only the configuration dir
                         * exists and the state dir does not, we assume we are looking at an update
                         * situation. Hence, create a compatibility symlink, so that all expectations are
                         * met.
                         *
                         * (We also do something similar with the log directory, which still doesn't exist in
                         * the xdg basedir spec. We'll make it a subdir of the state dir.) */
 
                        /* this assumes the state dir is always created before the configuration dir */
                        assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
                        assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
 
                        r = access_nofollow(p, F_OK);
                        if (r == -ENOENT) {
                                _cleanup_free_ char *q = NULL;
 
                                /* OK, we know that the state dir does not exist. Let's see if the dir exists
                                 * under the configuration hierarchy. */
 
                                if (type == EXEC_DIRECTORY_STATE)
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], i->path);
                                else if (type == EXEC_DIRECTORY_LOGS)
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", i->path);
                                else
                                        assert_not_reached();
                                if (!q) {
                                        r = -ENOMEM;
                                        goto fail;
                                }
 
                                r = access_nofollow(q, F_OK);
                                if (r >= 0) {
                                        /* It does exist! This hence looks like an update. Symlink the
                                         * configuration directory into the state directory. */
 
                                        r = symlink_idempotent(q, p, /* make_relative= */ true);
                                        if (r < 0)
                                                goto fail;
 
                                        log_notice("Unit state directory %s missing but matching configuration directory %s exists, assuming update from systemd 253 or older, creating compatibility symlink.", p, q);
                                        continue;
                                } else if (r != -ENOENT)
                                        log_warning_errno(r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
 
                        } else if (r < 0)
                                log_warning_errno(r, "Unable to detect whether unit state directory '%s' is missing, assuming it is: %m", p);
                }
 
                if (exec_directory_is_private(context, type)) {
                        /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
                         * case we want to avoid leaving a directory around fully accessible that is owned by
                         * a dynamic user whose UID is later on reused. To lock this down we use the same
                         * trick used by container managers to prohibit host users to get access to files of
                         * the same UID in containers: we place everything inside a directory that has an
                         * access mode of 0700 and is owned root:root, so that it acts as security boundary
                         * for unprivileged host code. We then use fs namespacing to make this directory
                         * permeable for the service itself.
                         *
                         * Specifically: for a service which wants a special directory "foo/" we first create
                         * a directory "private/" with access mode 0700 owned by root:root. Then we place
                         * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
                         * "private/foo". This way, privileged host users can access "foo/" as usual, but
                         * unprivileged host users can't look into it. Inside of the namespace of the unit
                         * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
                         * "private/foo/" is mounted under the same name, thus disabling the access boundary
                         * for the service and making sure it only gets access to the dirs it needs but no
                         * others. Tricky? Yes, absolutely, but it works!
                         *
                         * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
                         * to be owned by the service itself.
                         *
                         * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
                         * for sharing files or sockets with other services. */
 
                        pp = path_join(params->prefix[type], "private");
                        if (!pp) {
                                r = -ENOMEM;
                                goto fail;
                        }
 
                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
                        if (r < 0)
                                goto fail;
 
                        if (!path_extend(&pp, i->path)) {
                                r = -ENOMEM;
                                goto fail;
                        }
 
                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
                        r = mkdir_parents_label(pp, 0755);
                        if (r < 0)
                                goto fail;
 
                        if (is_dir(p, false) > 0 &&
                            (access_nofollow(pp, F_OK) == -ENOENT)) {
 
                                /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move
                                 * it over. Most likely the service has been upgraded from one that didn't use
                                 * DynamicUser=1, to one that does. */
 
                                log_info("Found pre-existing public %s= directory %s, migrating to %s.\n"
                                         "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
                                         exec_directory_type_to_string(type), p, pp);
 
                                r = RET_NERRNO(rename(p, pp));
                                if (r < 0)
                                        goto fail;
                        } else {
                                /* Otherwise, create the actual directory for the service */
 
                                r = mkdir_label(pp, context->directories[type].mode);
                                if (r < 0 && r != -EEXIST)
                                        goto fail;
                        }
 
                        if (!FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE)) {
                                /* And link it up from the original place.
                                 * Notes
                                 * 1) If a mount namespace is going to be used, then this symlink remains on
                                 *    the host, and a new one for the child namespace will be created later.
                                 * 2) It is not necessary to create this symlink when one of its parent
                                 *    directories is specified and already created. E.g.
                                 *        StateDirectory=foo foo/bar
                                 *    In that case, the inode points to pp and p for "foo/bar" are the same:
                                 *        pp = "/var/lib/private/foo/bar"
                                 *        p = "/var/lib/foo/bar"
                                 *    and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
                                 *    we do not need to create the symlink, but we cannot create the symlink.
                                 *    See issue #24783. */
                                r = symlink_idempotent(pp, p, true);
                                if (r < 0)
                                        goto fail;
                        }
 
                } else {
                        _cleanup_free_ char *target = NULL;
 
                        if (EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type) &&
                            readlink_and_make_absolute(p, &target) >= 0) {
                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
 
                                /* This already exists and is a symlink? Interesting. Maybe it's one created
                                 * by DynamicUser=1 (see above)?
                                 *
                                 * We do this for all directory types except for ConfigurationDirectory=,
                                 * since they all support the private/ symlink logic at least in some
                                 * configurations, see above. */
 
                                r = chase(target, NULL, 0, &target_resolved, NULL);
                                if (r < 0)
                                        goto fail;
 
                                q = path_join(params->prefix[type], "private", i->path);
                                if (!q) {
                                        r = -ENOMEM;
                                        goto fail;
                                }
 
                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
                                if (r < 0)
                                        goto fail;
 
                                if (path_equal(q_resolved, target_resolved)) {
 
                                        /* Hmm, apparently DynamicUser= was once turned on for this service,
                                         * but is no longer. Let's move the directory back up. */
 
                                        log_info("Found pre-existing private %s= directory %s, migrating to %s.\n"
                                                 "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
                                                 exec_directory_type_to_string(type), q, p);
 
                                        r = RET_NERRNO(unlink(p));
                                        if (r < 0)
                                                goto fail;
 
                                        r = RET_NERRNO(rename(q, p));
                                        if (r < 0)
                                                goto fail;
                                }
                        }
 
                        r = mkdir_label(p, context->directories[type].mode);
                        if (r < 0) {
                                if (r != -EEXIST)
                                        goto fail;
 
                                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type)) {
                                        struct stat st;
 
                                        /* Don't change the owner/access mode of the configuration directory,
                                         * as in the common case it is not written to by a service, and shall
                                         * not be writable. */
 
                                        r = RET_NERRNO(stat(p, &st));
                                        if (r < 0)
                                                goto fail;
 
                                        /* Still complain if the access mode doesn't match */
                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
                                                log_warning("%s \'%s\' already exists but the mode is different. "
                                                            "(File system: %o %sMode: %o)",
                                                            exec_directory_type_to_string(type), i->path,
                                                            st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
 
                                        continue;
                                }
                        }
                }
 
                /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
                 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
                 * current UID/GID ownership.) */
                const char *target_dir = pp ?: p;
                r = chmod_and_chown(target_dir, context->directories[type].mode, UID_INVALID, GID_INVALID);
                if (r < 0)
                        goto fail;
 
                /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
                 * available to user code anyway */
                if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
                        continue;
 
                int idmapping_supported = is_idmapping_supported(target_dir);
                if (idmapping_supported < 0) {
                        r = log_debug_errno(idmapping_supported, "Unable to determine if ID mapping is supported on mount '%s': %m", target_dir);
                        goto fail;
                }
 
                log_debug("ID-mapping is%ssupported for exec directory %s", idmapping_supported ? " " : " not ", target_dir);
 
                /* Change the ownership of the whole tree, if necessary. When dynamic users are used we
                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
                 * assignments to exist. */
                uid_t chown_uid = uid;
                gid_t chown_gid = gid;
                bool do_chown = false;
 
                if (uid == 0 || gid == 0 || !idmapping_supported) {
                        do_chown = true;
                        i->idmapped = false;
                } else {
                        /* Use 'nobody' uid/gid for exec directories if ID-mapping is supported. For backward compatibility,
                         * continue doing chmod/chown if the directory was chmod/chowned before (if uid/gid is not 'nobody') */
                        struct stat st;
                        r = RET_NERRNO(stat(target_dir, &st));
                        if (r < 0)
                                goto fail;
 
                        if (st.st_uid == UID_NOBODY && st.st_gid == GID_NOBODY) {
                                do_chown = false;
                                i->idmapped = true;
                       } else if (exec_directory_is_private(context, type) && st.st_uid == 0 && st.st_gid == 0) {
                                chown_uid = UID_NOBODY;
                                chown_gid = GID_NOBODY;
                                do_chown = true;
                                i->idmapped = true;
                        } else {
                                do_chown = true;
                                i->idmapped = false;
                        }
                }
 
                if (do_chown) {
                        r = path_chown_recursive(target_dir, chown_uid, chown_gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
                        if (r < 0)
                                goto fail;
                }
 
                /* Apply storage quotas and accounting */
                r = apply_exec_quotas(target_dir, params->cgroup_path, type, &context->directories[type].exec_quota, &exec_dt_proj_id, &quota_already_enforced);
                if (r < 0)
                        goto fail;
        }
 
        /* If we are not going to run in a namespace, set up the symlinks - otherwise
         * they are set up later, to allow configuring empty var/run/etc. */
        if (!needs_mount_namespace)
                FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
                        r = create_many_symlinks(params->prefix[type], i->path, i->symlinks);
                        if (r < 0)
                                goto fail;
                }
 
        return 0;
 
fail:
        *exit_status = exit_status_table[type];
        return r;
}
 
#if ENABLE_SMACK
static int setup_smack(
                const ExecContext *context,
                const ExecParameters *params,
                int executable_fd) {
        int r;
 
        assert(context);
        assert(params);
        assert(executable_fd >= 0);
 
        if (context->smack_process_label) {
                r = mac_smack_apply_pid(0, context->smack_process_label);
                if (r < 0)
                        return r;
        } else if (params->fallback_smack_process_label) {
                _cleanup_free_ char *exec_label = NULL;
 
                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
                        return r;
 
                r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
#endif
 
static int compile_bind_mounts(
                const ExecContext *context,
                const ExecParameters *params,
                uid_t exec_directory_uid, /* only used for id-mapped mounts Exec directories */
                gid_t exec_directory_gid, /* only used for id-mapped mounts Exec directories */
                BindMount **ret_bind_mounts,
                size_t *ret_n_bind_mounts,
                char ***ret_empty_directories) {
 
        _cleanup_strv_free_ char **empty_directories = NULL;
        BindMount *bind_mounts = NULL;
        size_t n, h = 0;
        int r;
 
        assert(context);
        assert(params);
        assert(ret_bind_mounts);
        assert(ret_n_bind_mounts);
        assert(ret_empty_directories);
 
        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
 
        n = context->n_bind_mounts;
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
                if (!params->prefix[t])
                        continue;
 
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items)
                        n += !FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) || FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY);
        }
 
        if (n <= 0) {
                *ret_bind_mounts = NULL;
                *ret_n_bind_mounts = 0;
                *ret_empty_directories = NULL;
                return 0;
        }
 
        bind_mounts = new(BindMount, n);
        if (!bind_mounts)
                return -ENOMEM;
 
        FOREACH_ARRAY(item, context->bind_mounts, context->n_bind_mounts) {
                r = bind_mount_add(&bind_mounts, &h, item);
                if (r < 0)
                        return r;
        }
 
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
                if (!params->prefix[t])
                        continue;
 
                if (context->directories[t].n_items == 0)
                        continue;
 
                if (exec_directory_is_private(context, t) &&
                    !exec_context_with_rootfs(context)) {
                        char *private_root;
 
                        /* So this is for a dynamic user, and we need to make sure the process can access its own
                         * directory. For that we overmount the usually inaccessible "private" subdirectory with a
                         * tmpfs that makes it accessible and is empty except for the submounts we do this for. */
 
                        private_root = path_join(params->prefix[t], "private");
                        if (!private_root)
                                return -ENOMEM;
 
                        r = strv_consume(&empty_directories, private_root);
                        if (r < 0)
                                return r;
                }
 
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items) {
                        _cleanup_free_ char *s = NULL, *d = NULL;
 
                        /* When one of the parent directories is in the list, we cannot create the symlink
                         * for the child directory. See also the comments in setup_exec_directory().
                         * But if it needs to be read only, then we have to create a bind mount anyway to
                         * make it so. */
                        if (FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) && !FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY))
                                continue;
 
                        if (exec_directory_is_private(context, t))
                                s = path_join(params->prefix[t], "private", i->path);
                        else
                                s = path_join(params->prefix[t], i->path);
                        if (!s)
                                return -ENOMEM;
 
                        if (exec_directory_is_private(context, t) &&
                            exec_context_with_rootfs(context))
                                /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
                                 * directory is not created on the root directory. So, let's bind-mount the directory
                                 * on the 'non-private' place. */
                                d = path_join(params->prefix[t], i->path);
                        else
                                d = strdup(s);
                        if (!d)
                                return -ENOMEM;
 
                        bind_mounts[h++] = (BindMount) {
                                .source = TAKE_PTR(s),
                                .destination = TAKE_PTR(d),
                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
                                .recursive = true,
                                .read_only = FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY),
                                .idmapped = i->idmapped,
                                .uid = exec_directory_uid,
                                .gid = exec_directory_gid,
                        };
                }
        }
 
        assert(h == n);
 
        *ret_bind_mounts = TAKE_PTR(bind_mounts);
        *ret_n_bind_mounts = n;
        *ret_empty_directories = TAKE_PTR(empty_directories);
 
        return (int) n;
}
 
/* ret_symlinks will contain a list of pairs src:dest that describes
 * the symlinks to create later on. For example, the symlinks needed
 * to safely give private directories to DynamicUser=1 users. */
static int compile_symlinks(
                const ExecContext *context,
                const ExecParameters *params,
                bool setup_os_release_symlink,
                char ***ret_symlinks) {
 
        _cleanup_strv_free_ char **symlinks = NULL;
        int r;
 
        assert(context);
        assert(params);
        assert(ret_symlinks);
 
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
                FOREACH_ARRAY(i, context->directories[dt].items, context->directories[dt].n_items) {
                        _cleanup_free_ char *private_path = NULL, *path = NULL;
 
                        STRV_FOREACH(symlink, i->symlinks) {
                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
 
                                src_abs = path_join(params->prefix[dt], i->path);
                                dst_abs = path_join(params->prefix[dt], *symlink);
                                if (!src_abs || !dst_abs)
                                        return -ENOMEM;
 
                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
                                if (r < 0)
                                        return r;
                        }
 
                        if (!exec_directory_is_private(context, dt) ||
                            exec_context_with_rootfs(context) ||
                            FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE))
                                continue;
 
                        private_path = path_join(params->prefix[dt], "private", i->path);
                        if (!private_path)
                                return -ENOMEM;
 
                        path = path_join(params->prefix[dt], i->path);
                        if (!path)
                                return -ENOMEM;
 
                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
                        if (r < 0)
                                return r;
                }
 
        /* We make the host's os-release available via a symlink, so that we can copy it atomically
         * and readers will never get a half-written version. Note that, while the paths specified here are
         * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
         * 'os-release -> .os-release-stage/os-release' is what will be created. */
        if (setup_os_release_symlink) {
                r = strv_extend_many(
                                &symlinks,
                                "/run/host/.os-release-stage/os-release",
                                "/run/host/os-release");
                if (r < 0)
                        return r;
        }
 
        *ret_symlinks = TAKE_PTR(symlinks);
 
        return 0;
}
 
static bool insist_on_sandboxing(
                const ExecContext *context,
                const PinnedResource *rootfs,
                const BindMount *bind_mounts,
                size_t n_bind_mounts) {
 
        assert(context);
        assert(rootfs);
        assert(n_bind_mounts == 0 || bind_mounts);
 
        /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
         * would alter the view on the file system beyond making things read-only or invisible, i.e. would
         * rearrange stuff in a way we cannot ignore gracefully. */
 
        if (context->n_temporary_filesystems > 0)
                return true;
 
        if (pinned_resource_is_set(rootfs))
                return true;
 
        if (context->n_mount_images > 0)
                return true;
 
        if (context->dynamic_user)
                return true;
 
        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
                return true;
 
        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
         * essential. */
        FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
                if (!path_equal(i->source, i->destination))
                        return true;
 
        if (context->log_namespace)
                return true;
 
        return false;
}
 
static int setup_ephemeral(
                const ExecContext *context,
                ExecRuntime *runtime,
                PinnedResource *rootfs,  /* both input and output! modified if ephemeral logic enabled */
                char **reterr_path) {
 
        _cleanup_close_ int fd = -EBADF;
        _cleanup_free_ char *new_root = NULL;
        int r;
 
        assert(context);
        assert(runtime);
        assert(rootfs);
        assert(reterr_path);
 
        if (!rootfs->image && !rootfs->directory)
                return 0;
 
        if (!runtime->ephemeral_copy)
                return 0;
 
        assert(runtime->ephemeral_storage_socket[0] >= 0);
        assert(runtime->ephemeral_storage_socket[1] >= 0);
 
        new_root = strdup(runtime->ephemeral_copy);
        if (!new_root)
                return log_oom_debug();
 
        r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
        if (r < 0)
                return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
 
        CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
 
        fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
        if (fd >= 0)
                /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
                return 0;
        if (fd != -EAGAIN)
                return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
 
        if (rootfs->image) {
                log_debug("Making ephemeral copy of %s to %s", rootfs->image, new_root);
 
                fd = copy_file(rootfs->image, new_root, O_EXCL, 0600,
                               COPY_LOCK_BSD|COPY_CRTIME|COPY_NOCOW_AFTER);
                if (fd < 0) {
                        *reterr_path = strdup(rootfs->image);
                        return log_debug_errno(fd, "Failed to copy image %s to %s: %m",
                                               rootfs->image, new_root);
                }
        } else {
                assert(rootfs->directory);
 
                log_debug("Making ephemeral snapshot of %s to %s", rootfs->directory, new_root);
 
                fd = btrfs_subvol_snapshot_at(
                                AT_FDCWD, rootfs->directory,
                                AT_FDCWD, new_root,
                                BTRFS_SNAPSHOT_FALLBACK_COPY |
                                BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
                                BTRFS_SNAPSHOT_RECURSIVE |
                                BTRFS_SNAPSHOT_LOCK_BSD);
                if (fd < 0) {
                        *reterr_path = strdup(rootfs->directory);
                        return log_debug_errno(fd, "Failed to snapshot directory %s to %s: %m",
                                               rootfs->directory, new_root);
                }
        }
 
        r = send_one_fd(runtime->ephemeral_storage_socket[1], fd, MSG_DONTWAIT);
        if (r < 0)
                return log_debug_errno(r, "Failed to queue file descriptor on ephemeral storage socket: %m");
 
        if (rootfs->image) {
                free_and_replace(rootfs->image, new_root);
                close_and_replace(rootfs->image_fd, fd);
        } else {
                assert(rootfs->directory);
 
                free_and_replace(rootfs->directory, new_root);
                close_and_replace(rootfs->directory_fd, fd);
        }
 
        return 1;
}
 
static int verity_settings_prepare(
                VeritySettings *verity,
                const char *root_image,
                const struct iovec *root_hash,     /* may be NULL */
                const char *root_hash_path,        /* may be NULL */
                const struct iovec *root_hash_sig, /* may be NULL */
                const char *root_hash_sig_path,    /* may be NULL */
                const char *verity_data_path) {    /* may be NULL */
 
        int r;
 
        assert(verity);
        assert(root_image);
 
        if (root_hash) {
                iovec_done(&verity->root_hash);
 
                if (!iovec_memdup(root_hash, &verity->root_hash))
                        return -ENOMEM;
 
                verity->designator = PARTITION_ROOT;
        }
 
        if (root_hash_sig) {
                iovec_done(&verity->root_hash_sig);
 
                if (!iovec_memdup(root_hash_sig, &verity->root_hash_sig))
                        return -ENOMEM;
 
                verity->designator = PARTITION_ROOT;
        }
 
        if (verity_data_path) {
                r = free_and_strdup(&verity->data_path, verity_data_path);
                if (r < 0)
                        return r;
        }
 
        r = verity_settings_load(
                        verity,
                        root_image,
                        root_hash_path,
                        root_hash_sig_path);
        if (r < 0)
                return log_debug_errno(r, "Failed to load root hash: %m");
 
        return 0;
}
 
static int pin_rootfs(
                const ExecContext *context,
                const ExecParameters *params,
                PinnedResource *ret,
                char **reterr_path) {
 
        int r;
 
        assert(context);
        assert(params);
        assert(ret);
        assert(reterr_path);
 
        if (!FLAGS_SET(params->flags, EXEC_APPLY_CHROOT)) {
                *ret = PINNED_RESOURCE_NULL;
                return 0;
        }
 
        if (context->root_directory_as_fd) {
                _cleanup_close_ int fd = fcntl(params->root_directory_fd, F_DUPFD_CLOEXEC, 3);
                if (fd < 0)
                        return log_debug_errno(errno, "Failed to duplicate root directory fd: %m");
 
                *ret = (PinnedResource) {
                        .directory_fd = TAKE_FD(fd),
                        .image_fd = -EBADF,
                };
 
                return 1;
        }
 
        if (context->root_image) {
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
 
                r = path_pick(/* root_path= */ NULL,
                              /* root_fd= */ AT_FDCWD,
                              /* dir_fd= */ AT_FDCWD,
                              context->root_image,
                              pick_filter_image_raw,
                              ELEMENTSOF(pick_filter_image_raw),
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
                              &result);
                if (r < 0) {
                        *reterr_path = strdup(context->root_image);
                        return r;
                }
 
                if (!result.path) {
                        *reterr_path = strdup(context->root_image);
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_image);
                }
 
                /* path_pick() returns us an O_PATH fd, let's turn this into a fully opened file, because
                 * mountfsd will want this later, and it wants a fully opened fd, so that security checks
                 * have been passed */
                _cleanup_close_ int reopened_fd = -EBADF;
                reopened_fd = fd_reopen(result.fd, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_RDWR);
                if (ERRNO_IS_NEG_FS_WRITE_REFUSED(reopened_fd))
                        reopened_fd = fd_reopen(result.fd, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_RDONLY);
                if (reopened_fd < 0) {
                        *reterr_path = strdup(context->root_image);
                        return log_debug_errno(reopened_fd, "Failed to open image '%s': %m", context->root_image);
                }
 
                *ret = (PinnedResource) {
                        .image = TAKE_PTR(result.path),
                        .image_fd = TAKE_FD(reopened_fd),
                        .directory_fd = -EBADF,
                };
 
                return r;
        }
 
        if (context->root_directory) {
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
 
                r = path_pick(/* root_path= */ NULL,
                              /* root_fd= */ AT_FDCWD,
                              /* dir_fd= */ AT_FDCWD,
                              context->root_directory,
                              pick_filter_image_dir,
                              ELEMENTSOF(pick_filter_image_dir),
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
                              &result);
                if (r < 0) {
                        *reterr_path = strdup(context->root_directory);
                        return r;
                }
 
                if (!result.path) {
                        *reterr_path = strdup(context->root_directory);
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_directory);
                }
 
                *ret = (PinnedResource) {
                        .directory = TAKE_PTR(result.path),
                        .directory_fd = TAKE_FD(result.fd),
                        .image_fd = -EBADF,
                };
 
                return r;
        }
 
        if (context->root_mstack) {
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
 
                r = path_pick(/* root_path= */ NULL,
                              /* root_fd= */ AT_FDCWD,
                              /* dir_fd= */ AT_FDCWD,
                              context->root_mstack,
                              pick_filter_image_mstack,
                              /* n_filters= */ 1,
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
                              &result);
                if (r < 0) {
                        *reterr_path = strdup(context->root_mstack);
                        return r;
                }
 
                if (!result.path) {
                        *reterr_path = strdup(context->root_mstack);
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_mstack);
                }
 
                _cleanup_(mstack_freep) MStack *mstack = NULL;
                r = mstack_load(result.path, result.fd, &mstack);
                if (r < 0) {
                        *reterr_path = TAKE_PTR(result.path);
                        return r;
                }
 
                *ret = (PinnedResource) {
                        .mstack = TAKE_PTR(result.path),
                        .mstack_loaded = TAKE_PTR(mstack),
                        .image_fd = -EBADF,
                        .directory_fd = -EBADF,
                };
 
                return r;
        }
 
        *ret = PINNED_RESOURCE_NULL;
        return 0;
}
 
static int apply_mount_namespace(
                ExecCommandFlags command_flags,
                const ExecContext *context,
                const ExecParameters *params,
                const ExecRuntime *runtime,
                const PinnedResource *rootfs,
                char *const *pressure_path,
                bool needs_sandboxing,
                uid_t exec_directory_uid,
                gid_t exec_directory_gid,
                PidRef *bpffs_pidref,
                int bpffs_socket_fd,
                int bpffs_errno_pipe,
                sd_varlink *mountfsd_link, /* may be NULL */
                char **reterr_path) {
 
        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
                        **read_write_paths_cleanup = NULL;
        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
                *private_namespace_dir = NULL, *host_os_release_stage = NULL;
        const char *tmp_dir = NULL, *var_tmp_dir = NULL;
        char **read_write_paths;
        bool setup_os_release_symlink;
        BindMount *bind_mounts = NULL;
        size_t n_bind_mounts = 0;
        int r;
 
        assert(context);
        assert(params);
        assert(runtime);
        assert(rootfs);
        assert(pressure_path);
        assert(bpffs_pidref);
        assert(reterr_path);
 
        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
 
        r = compile_bind_mounts(context, params, exec_directory_uid, exec_directory_gid, &bind_mounts, &n_bind_mounts, &empty_directories);
        if (r < 0)
                return r;
 
        /* We need to make the pressure paths writable even if /sys/fs/cgroups is made read-only, as the
         * service will need to write to them in order to start the notifications. */
        bool need_pressure_rw = false;
        for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++)
                if (pressure_path[t] && !streq(pressure_path[t], "/dev/null")) {
                        need_pressure_rw = true;
                        break;
                }
 
        if (exec_is_cgroup_mount_read_only(context) && need_pressure_rw) {
                read_write_paths_cleanup = strv_copy(context->read_write_paths);
                if (!read_write_paths_cleanup)
                        return -ENOMEM;
 
                for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++) {
                        if (!pressure_path[t] || streq(pressure_path[t], "/dev/null"))
                                continue;
 
                        r = strv_extend(&read_write_paths_cleanup, pressure_path[t]);
                        if (r < 0)
                                return r;
                }
 
                read_write_paths = read_write_paths_cleanup;
        } else
                read_write_paths = context->read_write_paths;
 
        if (needs_sandboxing) {
                /* The runtime struct only contains the parent of the private /tmp, which is non-accessible
                 * to world users. Inside of it there's a /tmp that is sticky, and that's the one we want to
                 * use here. This does not apply when we are using /run/systemd/empty as fallback. */
 
                if (context->private_tmp == PRIVATE_TMP_CONNECTED && runtime->shared) {
                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
                                tmp_dir = runtime->shared->tmp_dir;
                        else if (runtime->shared->tmp_dir)
                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
                }
 
                if (context->private_var_tmp == PRIVATE_TMP_CONNECTED && runtime->shared) {
                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
                                var_tmp_dir = runtime->shared->var_tmp_dir;
                        else if (runtime->shared->var_tmp_dir)
                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
                }
        }
 
        /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
        setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && pinned_resource_is_set(rootfs);
        r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
        if (r < 0)
                return r;
 
        if (context->mount_propagation_flag == MS_SHARED)
                log_debug("shared mount propagation hidden by other fs namespacing unit settings: ignoring");
 
        r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
        if (r < 0)
                return r;
 
        if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
                if (!mount_new_api_supported()) {
                        propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
                        if (!propagate_dir)
                                return -ENOMEM;
 
                        incoming_dir = strdup("/run/systemd/incoming");
                        if (!incoming_dir)
                                return -ENOMEM;
                }
 
                private_namespace_dir = strdup("/run/systemd");
                if (!private_namespace_dir)
                        return -ENOMEM;
 
                /* If running under a different root filesystem, propagate the host's os-release. We make a
                 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
                if (setup_os_release_symlink) {
                        host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
                        if (!host_os_release_stage)
                                return -ENOMEM;
                }
        } else {
                assert(params->runtime_scope == RUNTIME_SCOPE_USER);
 
                if (asprintf(&private_namespace_dir, "/run/user/" UID_FMT "/systemd", geteuid()) < 0)
                        return -ENOMEM;