HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/namespace.c

173,584 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: dd15bda3ac6915b01bea339ebbd5f9b2ab083c7e

Lines 3001–4000 of 4,291

                *me = (MountEntry) {
                        .path_const = p->creds_path,
                        .mode = MOUNT_BIND,
                        .read_only = true,
                        .source_const = p->creds_path,
                };
        }
 
        if (!p->creds_path || p->runtime_scope != RUNTIME_SCOPE_SYSTEM) {
                /* If our service has no credentials store configured, or we're running in user scope, then
                 * make the system credentials tree inaccessible wholesale. */
 
                MountEntry *me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = "/run/credentials",
                        .mode = MOUNT_INACCESSIBLE,
                        .ignore = true,
                };
        }
 
        if (p->log_namespace) {
                _cleanup_free_ char *q = NULL;
 
                q = strjoin("/run/systemd/journal.", p->log_namespace);
                if (!q)
                        return log_oom_debug();
 
                MountEntry *me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = "/run/systemd/journal",
                        .mode = MOUNT_BIND_RECURSIVE,
                        .read_only = true,
                        .source_malloc = TAKE_PTR(q),
                };
 
        } else if (p->bind_log_sockets) {
                r = append_bind_mounts(&ml, bind_log_sockets_table, ELEMENTSOF(bind_log_sockets_table));
                if (r < 0)
                        return r;
        }
 
        /* Will be used to add bind mounts at runtime */
        if (setup_propagate) {
                MountEntry *me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .source_const = p->propagate_dir,
                        .path_const = p->incoming_dir,
                        .mode = MOUNT_BIND,
                        .read_only = true,
                };
        }
 
        if (p->notify_socket_path) {
                MountEntry *me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = p->notify_socket_path,
                        .source_const = p->host_notify_socket,
                        .mode = MOUNT_BIND,
                        .read_only = true,
                };
        }
 
        if (p->host_os_release_stage) {
                MountEntry *me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = "/run/host/.os-release-stage/",
                        .source_const = p->host_os_release_stage,
                        .mode = MOUNT_BIND,
                        .read_only = true,
                        .ignore = true, /* Live copy, don't hard-fail if it goes missing */
                };
        }
 
        /* Prepend the root directory where that's necessary */
        r = prefix_where_needed(&ml, root);
        if (r < 0)
                return r;
 
        sort_and_drop_unused_mounts(&ml, root);
 
        /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
 
        if (unshare(CLONE_NEWNS) < 0) {
                r = log_debug_errno(errno, "Failed to unshare the mount namespace: %m");
 
                if (ERRNO_IS_PRIVILEGE(r) ||
                    ERRNO_IS_NOT_SUPPORTED(r))
                        /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter
                         * in place that doesn't allow us to create namespaces (or a missing cap), then
                         * propagate a recognizable error back, which the caller can use to detect this case
                         * (and only this) and optionally continue without namespacing applied. */
                        return -ENOANO;
 
                return r;
        }
 
        /* Create the source directory to allow runtime propagation of mounts */
        if (setup_propagate)
                (void) mkdir_p(p->propagate_dir, 0600);
 
        if (p->n_extension_images > 0 || !strv_isempty(p->extension_directories)) {
                /* ExtensionImages/Directories mountpoint directories will be created while parsing the
                 * mounts to create, so have the parent ready */
                char *extension_dir = strjoina(p->private_namespace_dir, "/unit-extensions");
                (void) mkdir_p(extension_dir, 0600);
        }
 
        /* Remount / as SLAVE so that nothing now mounted in the namespace
         * shows up in the parent */
        r = mount_nofollow_verbose(LOG_DEBUG, /* what= */ NULL, "/", /* fstype= */ NULL, MS_SLAVE|MS_REC, /* options= */ NULL);
        if (r < 0)
                return r;
 
        if (root_mount_fd >= 0) {
                /* If we have root_mount_fd we have a ready-to-use detached mount. Attach it. */
 
                if (move_mount(root_mount_fd, "", AT_FDCWD, root, MOVE_MOUNT_F_EMPTY_PATH) < 0)
                        return log_debug_errno(errno, "Failed to move detached mount to '%s': %m", root);
 
                r = mount_nofollow_verbose(LOG_DEBUG, /* what= */ NULL, root, /* fstype= */ NULL, MS_SLAVE|MS_REC, /* options= */ NULL);
                if (r < 0)
                        return r;
 
        } else if (p->rootfs && p->rootfs->directory) {
 
                /* If we do not have root_mount_fd, but a directory was specified, then we can use it directly. */
 
                /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
                r = path_is_mount_point_full(root, /* root = */ NULL, AT_SYMLINK_FOLLOW);
                if (r < 0)
                        return log_debug_errno(r, "Failed to detect that %s is a mount point or not: %m", root);
                if (r == 0) {
                        r = mount_nofollow_verbose(LOG_DEBUG, root, root, /* fstype= */ NULL, MS_BIND|MS_REC, /* options= */ NULL);
                        if (r < 0)
                                return r;
                }
 
        } else if (dissected_image) {
 
                /* A root image is specified, mount it to the right place */
                r = dissected_image_mount(
                                dissected_image,
                                root,
                                /* uid_shift= */ UID_INVALID,
                                /* uid_range= */ UID_INVALID,
                                userns_fd,
                                dissect_image_flags);
                if (r < 0)
                        return log_debug_errno(r, "Failed to mount root image: %m");
 
                /* Now release the block device lock, so that udevd is free to call BLKRRPART on the device
                 * if it likes. */
                if (loop_device) {
                        r = loop_device_flock(loop_device, LOCK_UN);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to release lock on loopback block device: %m");
                }
 
                r = dissected_image_relinquish(dissected_image);
                if (r < 0)
                        return log_debug_errno(r, "Failed to relinquish dissected image: %m");
 
        } else if (p->rootfs && p->rootfs->mstack_loaded) {
 
                r = mstack_make_mounts(p->rootfs->mstack_loaded, root, mstack_flags);
                if (r < 0)
                        return r;
 
                r = mstack_bind_mounts(p->rootfs->mstack_loaded, root, /* where_fd= */ -EBADF, mstack_flags, /* ret_root_fd= */ NULL);
                if (r < 0)
                        return r;
 
        } else {
                /* Let's mount the main root directory to the root directory to use */
                r = mount_nofollow_verbose(LOG_DEBUG, "/", root, NULL, MS_BIND|MS_REC, NULL);
                if (r < 0)
                        return r;
        }
 
        /* Try to set up the new root directory before mounting anything else there. */
        if (pinned_resource_is_set(p->rootfs))
                (void) base_filesystem_create(root, UID_INVALID, GID_INVALID);
 
        /* Now make the magic happen */
        r = apply_mounts(&ml, root, p, reterr_path);
        if (r < 0)
                return r;
 
        /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
        r = mount_switch_root(root, /* mount_propagation_flag = */ 0);
        if (r == -EINVAL && p->rootfs && p->rootfs->directory) {
                /* If we are using root_directory and we don't have privileges (ie: user manager in a user
                 * namespace) and the root_directory is already a mount point in the parent namespace,
                 * MS_MOVE will fail as we don't have permission to change it (with EINVAL rather than
                 * EPERM). Attempt to bind-mount it over itself (like we do above if it's not already a
                 * mount point) and try again. */
                r = mount_nofollow_verbose(LOG_DEBUG, root, root, NULL, MS_BIND|MS_REC, NULL);
                if (r < 0)
                        return r;
 
                r = mount_switch_root(root, /* mount_propagation_flag= */ 0);
        }
        if (r < 0)
                return log_debug_errno(r, "Failed to mount root with MS_MOVE: %m");
 
        /* Remount / as the desired mode. Note that this will not reestablish propagation from our side to
         * the host, since what's disconnected is disconnected. */
        if (mount(NULL, "/", NULL, mount_propagation_flag | MS_REC, NULL) < 0)
                return log_debug_errno(errno, "Failed to remount '/' with desired mount flags: %m");
 
        /* bind_mount_in_namespace() will MS_MOVE into that directory, and that's only supported for
         * non-shared mounts. This needs to happen after remounting / or it will fail. */
        if (setup_propagate && mount(NULL, p->incoming_dir, NULL, MS_SLAVE, NULL) < 0)
                return log_debug_errno(errno, "Failed to remount %s with MS_SLAVE: %m", p->incoming_dir);
 
        return 0;
}
 
void bind_mount_free_many(BindMount *b, size_t n) {
        assert(b || n == 0);
 
        FOREACH_ARRAY(i, b, n) {
                free(i->source);
                free(i->destination);
        }
 
        free(b);
}
 
int bind_mount_add(BindMount **b, size_t *n, const BindMount *item) {
        _cleanup_free_ char *s = NULL, *d = NULL;
 
        assert(b);
        assert(n);
        assert(item);
 
        s = strdup(item->source);
        if (!s)
                return -ENOMEM;
 
        d = strdup(item->destination);
        if (!d)
                return -ENOMEM;
 
        if (!GREEDY_REALLOC(*b, *n + 1))
                return -ENOMEM;
 
        (*b)[(*n)++] = (BindMount) {
                .source = TAKE_PTR(s),
                .destination = TAKE_PTR(d),
                .read_only = item->read_only,
                .nodev = item->nodev,
                .nosuid = item->nosuid,
                .noexec = item->noexec,
                .recursive = item->recursive,
                .ignore_enoent = item->ignore_enoent,
        };
 
        return 0;
}
 
static void mount_image_done(MountImage *m) {
        assert(m);
        m->source = mfree(m->source);
        m->destination = mfree(m->destination);
        m->mount_options = mount_options_free_all(m->mount_options);
}
 
DEFINE_ARRAY_FREE_FUNC(mount_image_free_array, MountImage, mount_image_done);
 
int mount_image_add(MountImage **m, size_t *n, const MountImage *item) {
        _cleanup_free_ char *s = NULL, *d = NULL;
        _cleanup_(mount_options_free_allp) MountOptions *o = NULL;
        int r;
 
        assert(m);
        assert(n);
        assert(item);
 
        s = strdup(item->source);
        if (!s)
                return -ENOMEM;
 
        if (item->destination) {
                d = strdup(item->destination);
                if (!d)
                        return -ENOMEM;
        }
 
        if (item->mount_options) {
                r = mount_options_dup(item->mount_options, &o);
                if (r < 0)
                        return r;
        }
 
        if (!GREEDY_REALLOC(*m, *n + 1))
                return -ENOMEM;
 
        (*m)[(*n)++] = (MountImage) {
                .source = TAKE_PTR(s),
                .destination = TAKE_PTR(d),
                .mount_options = TAKE_PTR(o),
                .ignore_enoent = item->ignore_enoent,
                .type = item->type,
        };
 
        return 0;
}
 
void temporary_filesystem_free_many(TemporaryFileSystem *t, size_t n) {
        assert(t || n == 0);
 
        for (size_t i = 0; i < n; i++) {
                free(t[i].path);
                free(t[i].options);
        }
 
        free(t);
}
 
int temporary_filesystem_add(
                TemporaryFileSystem **t,
                size_t *n,
                const char *path,
                const char *options) {
 
        _cleanup_free_ char *p = NULL, *o = NULL;
 
        assert(t);
        assert(n);
        assert(path);
 
        p = strdup(path);
        if (!p)
                return -ENOMEM;
 
        if (!isempty(options)) {
                o = strdup(options);
                if (!o)
                        return -ENOMEM;
        }
 
        if (!GREEDY_REALLOC(*t, *n + 1))
                return -ENOMEM;
 
        (*t)[(*n)++] = (TemporaryFileSystem) {
                .path = TAKE_PTR(p),
                .options = TAKE_PTR(o),
        };
 
        return 0;
}
 
char* namespace_cleanup_tmpdir(char *p) {
        if (!p)
                return NULL;
 
        if (!streq(p, RUN_SYSTEMD_EMPTY)) {
                _cleanup_free_ char *child = path_join(p, "tmp");
                if (!child)
                        log_oom_debug();
                else
                        (void) rmdir(child);
 
                (void) rmdir(p);
        }
 
        return mfree(p);
}
 
static int make_tmp_prefix(const char *prefix) {
        _cleanup_free_ char *t = NULL;
        _cleanup_close_ int fd = -EBADF;
        int r;
 
        assert(prefix);
 
        /* Don't do anything unless we know the dir is actually missing */
        r = access(prefix, F_OK);
        if (r >= 0)
                return 0;
        if (errno != ENOENT)
                return -errno;
 
        WITH_UMASK(000)
                r = mkdir_parents(prefix, 0755);
        if (r < 0)
                return r;
 
        r = tempfn_random(prefix, NULL, &t);
        if (r < 0)
                return r;
 
        /* umask will corrupt this access mode, but that doesn't matter, we need to call chmod() anyway for
         * the suid bit, below. */
        fd = open_mkdir(t, O_EXCL|O_CLOEXEC, 0777);
        if (fd < 0)
                return fd;
 
        r = RET_NERRNO(fchmod(fd, 01777));
        if (r < 0) {
                (void) rmdir(t);
                return r;
        }
 
        r = RET_NERRNO(rename(t, prefix));
        if (r < 0) {
                (void) rmdir(t);
                return IN_SET(r, -EEXIST, -ENOTEMPTY) ? 0 : r; /* it's fine if someone else created the dir by now */
        }
 
        return 0;
}
 
int setup_tmp_dir_one(const char *id, const char *prefix, char **ret_path) {
        _cleanup_free_ char *d = NULL;
        sd_id128_t boot_id;
        bool rw = true;
        int r;
 
        assert(id);
        assert(prefix);
        assert(ret_path);
 
        /* We include the boot id in the directory so that after a
         * reboot we can easily identify obsolete directories. */
 
        r = sd_id128_get_boot(&boot_id);
        if (r < 0)
                return r;
 
        d = strjoin(prefix, "/systemd-private-", SD_ID128_TO_STRING(boot_id), "-", id, "-XXXXXX");
        if (!d)
                return -ENOMEM;
 
        r = make_tmp_prefix(prefix);
        if (r < 0)
                return r;
 
        WITH_UMASK(0077)
                if (!mkdtemp(d)) {
                        if (errno == EROFS || ERRNO_IS_DISK_SPACE(errno))
                                rw = false;
                        else
                                return -errno;
                }
 
        if (rw) {
                _cleanup_free_ char *inner_dir = path_join(d, "tmp");
                if (!inner_dir) {
                        (void) rmdir(d);
                        return -ENOMEM;
                }
 
                WITH_UMASK(0000)
                        r = RET_NERRNO(mkdir(inner_dir, 0777 | S_ISVTX));
                if (r < 0) {
                        (void) rmdir(d);
                        return r;
                }
 
                r = label_fix_full(AT_FDCWD, inner_dir, prefix, /* flags= */ 0, /* label_context= */ NULL);
                if (r < 0) {
                        (void) rmdir(inner_dir);
                        (void) rmdir(d);
                        return r;
                }
        } else {
                /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
                 * read-only. This way the service will get the EROFS result as if it was writing to the real
                 * file system. */
                WITH_UMASK(0000)
                        r = mkdir_p(RUN_SYSTEMD_EMPTY, 0500);
                if (r < 0)
                        return r;
 
                r = free_and_strdup(&d, RUN_SYSTEMD_EMPTY);
                if (r < 0)
                        return r;
        }
 
        *ret_path = TAKE_PTR(d);
        return 0;
}
 
int setup_shareable_ns(int ns_storage_socket[static 2], unsigned long nsflag) {
        _cleanup_close_ int ns = -EBADF;
        const char *ns_name, *ns_path;
        int r;
 
        assert(ns_storage_socket);
        assert(ns_storage_socket[0] >= 0);
        assert(ns_storage_socket[1] >= 0);
 
        ns_name = ASSERT_PTR(namespace_single_flag_to_string(nsflag));
 
        /* We use the passed socketpair as a storage buffer for our namespace reference fd. Whatever process
         * runs this first shall create a new namespace, all others should just join it. To serialize that we
         * use a file lock on the socket pair.
         *
         * It's a bit crazy, but hey, works great! */
 
        r = posix_lock(ns_storage_socket[0], LOCK_EX);
        if (r < 0)
                return r;
 
        CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
 
        ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
        if (ns >= 0) {
                /* Yay, found something, so let's join the namespace */
                r = RET_NERRNO(setns(ns, nsflag));
                if (r < 0)
                        return r;
 
                return 0;
        }
 
        if (ns != -EAGAIN)
                return ns;
 
        /* Nothing stored yet, so let's create a new namespace. */
 
        if (unshare(nsflag) < 0)
                return -errno;
 
        if (nsflag == CLONE_NEWNET)
                (void) loopback_setup();
 
        ns_path = strjoina("/proc/self/ns/", ns_name);
        ns = open(ns_path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
        if (ns < 0)
                return -errno;
 
        r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
        if (r < 0)
                return r;
 
        return 1;
}
 
int open_shareable_ns_path(int ns_storage_socket[static 2], const char *path, unsigned long nsflag) {
        _cleanup_close_ int ns = -EBADF;
        NamespaceType type;
        int r;
 
        assert(ns_storage_socket);
        assert(ns_storage_socket[0] >= 0);
        assert(ns_storage_socket[1] >= 0);
        assert(path);
 
        /* If the storage socket doesn't contain a ns fd yet, open one via the file system and store it in
         * it. This is supposed to be called ahead of time, i.e. before setup_shareable_ns() which will
         * allocate a new anonymous ns if needed. */
 
        type = clone_flag_to_namespace_type(nsflag);
        assert(type >= 0);
 
        r = posix_lock(ns_storage_socket[0], LOCK_EX);
        if (r < 0)
                return r;
 
        CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
 
        ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
        if (ns >= 0)
                return 0;
        if (ns != -EAGAIN)
                return ns;
 
        /* Nothing stored yet. Open the file from the file system. */
 
        ns = open(path, O_RDONLY|O_NOCTTY|O_CLOEXEC);
        if (ns < 0)
                return -errno;
 
        r = fd_is_namespace(ns, type);
        if (r < 0)
                return r;
        if (r == 0)
                return -EINVAL;
 
        r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
        if (r < 0)
                return r;
 
        return 1;
}
 
static int is_extension_overlay(const char *path, int fd) {
        _cleanup_free_ char *source = NULL;
        _cleanup_close_ int dfd = -EBADF;
        int r;
 
        assert(path);
 
        if (fd < 0) {
                r = chase(path, /* root= */ NULL, CHASE_TRAIL_SLASH|CHASE_MUST_BE_DIRECTORY|CHASE_TRIGGER_AUTOFS, /* ret_path= */ NULL, &dfd);
                if (r < 0)
                        return r;
                fd = dfd;
        }
 
        r = is_mount_point_at(fd, /* path= */ NULL, /* flags= */ 0);
        if (r < 0)
                return log_debug_errno(r, "Unable to determine whether '%s' is a mount point: %m", path);
        if (r == 0)
                return 0;
 
        r = fd_is_fs_type(fd, OVERLAYFS_SUPER_MAGIC);
        if (r < 0)
                return log_debug_errno(r, "Failed to check if %s is an overlayfs: %m", path);
        if (r == 0)
                return 0;
 
        /* Check the 'source' field of the mount on mount_path */
        r = path_get_mount_info_at(fd, /* path= */ NULL, /* ret_fstype= */ NULL, /* ret_options= */ NULL, &source);
        if (r < 0)
                return log_debug_errno(r, "Failed to get mount info for %s: %m", path);
        if (!streq_ptr(source, "systemd-extensions"))
                return 0;
 
        return 1;
}
 
static int unpeel_get_fd(const char *mount_path, int *ret_fd) {
        _cleanup_close_pair_ int pipe_fds[2] = EBADF_PAIR;
        _cleanup_close_ int fs_fd = -EBADF;
        int r;
 
        assert(mount_path);
        assert(ret_fd);
 
        r = socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pipe_fds);
        if (r < 0)
                return log_debug_errno(errno, "Failed to create socket pair: %m");
 
        /* Clone mount namespace here to unpeel without affecting live process */
        r = pidref_safe_fork("(sd-ns-unpeel)", FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, /* ret= */ NULL);
        if (r < 0)
                return r;
        if (r == 0) {
                _cleanup_close_ int dir_fd = -EBADF;
 
                pipe_fds[0] = safe_close(pipe_fds[0]);
 
                /* Opportunistically unmount any overlay at this path */
                r = is_extension_overlay(mount_path, /* fd= */ -EBADF);
                if (r < 0) {
                        log_debug_errno(r, "Unable to determine whether '%s' is an extension overlay: %m", mount_path);
                        _exit(EXIT_FAILURE);
                }
                if (r > 0) {
                        r = umount_recursive(mount_path, MNT_DETACH);
                        if (r < 0)
                                _exit(EXIT_FAILURE);
                        if (r == 0) /* no umounts done, possible if a previous reload deleted all extensions */
                                log_debug("No overlay layer unmountable from %s", mount_path);
                }
 
                /* Now that /mount_path is exposed, get an FD for it and pass back */
                dir_fd = open_tree(-EBADF, mount_path, AT_SYMLINK_NOFOLLOW|OPEN_TREE_CLONE);
                if (dir_fd < 0) {
                        log_debug_errno(errno, "Failed to clone mount %s: %m", mount_path);
                        _exit(EXIT_FAILURE);
                }
 
                r = fd_is_fs_type(dir_fd, OVERLAYFS_SUPER_MAGIC);
                if (r < 0) {
                        log_debug_errno(r, "Unable to determine whether '%s' is an overlay after opening mount tree: %m", mount_path);
                        _exit(EXIT_FAILURE);
                }
                if (r > 0) {
                        log_debug("'%s' is still an overlay after opening mount tree", mount_path);
                        _exit(EXIT_FAILURE);
                }
 
                r = send_one_fd(pipe_fds[1], dir_fd, 0);
                if (r < 0) {
                        log_debug_errno(r, "Failed to send mount fd: %m");
                        _exit(EXIT_FAILURE);
                }
 
                _exit(EXIT_SUCCESS);
        }
 
        pipe_fds[1] = safe_close(pipe_fds[1]);
 
        r = receive_one_fd(pipe_fds[0], 0);
        if (r < 0)
                return log_debug_errno(r, "Failed to receive mount fd: %m");
        fs_fd = r;
 
        r = fd_is_fs_type(fs_fd, OVERLAYFS_SUPER_MAGIC);
        if (r < 0)
                return log_debug_errno(r, "Unable to determine if unpeeled directory refers to overlayfs: %m");
        if (r > 0)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Unpeeled mount is still an overlayfs, something is weird, refusing.");
 
        *ret_fd = TAKE_FD(fs_fd);
        return 0;
}
 
/* In target namespace, unmounts an existing overlayfs at mount_path (if one exists), grabs FD from the
 * underlying directory, and sets up a new overlayfs mount. Coordinates with parent process over pair_fd:
 * 1. Creates and sends new overlay fs fd to parent
 * 2. Fake-unmounts overlay at mount_path to obtain underlying directory fd to build new overlay
 * 3. Waits for parent to configure layers
 * 4. Performs final mount at mount_path
 *
 * This is used by refresh_extensions_in_namespace() to peel back any existing overlays and reapply them.
 */
static int unpeel_mount_and_setup_overlay(int pair_fd, const char *mount_path) {
        _cleanup_close_ int dir_unpeeled_fd = -EBADF, overlay_fs_fd = -EBADF, mount_fd = -EBADF;
        int r;
 
        assert(pair_fd >= 0);
        assert(mount_path);
 
        /* Create new OverlayFS and send to parent */
        overlay_fs_fd = fsopen("overlay", FSOPEN_CLOEXEC);
        if (overlay_fs_fd < 0)
                return log_debug_errno(errno, "Failed to create overlay fs for %s: %m", mount_path);
 
        r = send_one_fd(pair_fd, overlay_fs_fd, /* flags= */ 0);
        if (r < 0)
                return log_debug_errno(r, "Failed to send overlay fs fd to parent: %m");
 
        /* Unpeel in cloned mount namespace to get underlying directory fd */
        r = unpeel_get_fd(mount_path, &dir_unpeeled_fd);
        if (r < 0)
                return log_debug_errno(r, "Failed to unpeel mount %s: %m", mount_path);
 
        /* Send the fd to the parent */
        r = send_one_fd(pair_fd, dir_unpeeled_fd, /* flags= */ 0);
        if (r < 0)
                return log_debug_errno(r, "Failed to send %s fd to parent: %m", mount_path);
 
        /* Wait for parent to signal overlay configuration completion */
        log_debug("Waiting for configured overlay fs for %s", mount_path);
        r = receive_one_fd(pair_fd, 0);
        if (r < 0)
                return log_debug_errno(r, "Failed to receive configured overlay: %m");
 
        /* Create the mount */
        mount_fd = fsmount(overlay_fs_fd, FSMOUNT_CLOEXEC, /* flags= */ 0);
        if (mount_fd < 0)
                return log_debug_errno(errno, "Failed to create overlay mount: %m");
 
        /* Move mount to final location */
        r = mount_exchange_graceful(mount_fd, mount_path, /* mount_beneath= */ true);
        if (r < 0)
                return log_debug_errno(r, "Failed to move overlay to %s: %m", mount_path);
 
        return 0;
}
 
static int refresh_grandchild_proc(
                const PidRef *target,
                MountList *ml,
                const char *overlay_prefix,
                int pidns_fd,
                int mntns_fd,
                int root_fd,
                int pipe_fd) {
 
        int r;
 
        assert(pidref_is_set(target));
        assert(ml);
        assert(overlay_prefix);
        assert(pidns_fd >= 0);
        assert(mntns_fd >= 0);
        assert(root_fd >= 0);
        assert(pipe_fd >= 0);
 
        r = namespace_enter(pidns_fd, mntns_fd, /* netns_fd= */ -EBADF, /* userns_fd= */ -EBADF, root_fd);
        if (r < 0)
                return log_debug_errno(r, "Failed to enter namespace: %m");
 
        /* Handle each overlay mount path */
        FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
                if (m->mode != MOUNT_OVERLAY)
                        continue;
 
                /* Need an absolute path under the child namespace, rather than the root's */
                _cleanup_free_ char *mount_path = NULL;
                mount_path = path_join("/",
                                       path_startswith(mount_entry_unprefixed_path(m), overlay_prefix) ?:
                                            mount_entry_unprefixed_path(m));
                if (!mount_path)
                        return log_oom_debug();
 
                /* If there are no extensions mounted for this overlay layer, instead of setting everything
                 * up, the correct behavior is to unmount the existing overlay in the target namespace to
                 * expose the original files. */
                if (strv_isempty(m->overlay_layers)) {
                        r = is_extension_overlay(mount_path, /* fd= */ -EBADF);
                        if (r < 0)
                                return log_debug_errno(r, "Unable to determine whether '%s' is an extension overlay: %m", mount_path);
                        if (r == 0)
                                continue;
 
                        log_debug("No extensions for %s, undoing existing mount", mount_path);
                        (void) umount_recursive(mount_path, MNT_DETACH);
 
                        continue;
                }
 
                r = unpeel_mount_and_setup_overlay(pipe_fd, mount_path);
                if (r < 0)
                        return log_debug_errno(r, "Failed to setup overlay mount for %s: %m", mount_path);
        }
 
        return 0;
}
 
static int handle_mount_from_grandchild(
                MountEntry *m,
                const char *overlay_prefix,
                int **fd_layers,
                size_t *n_fd_layers,
                int pipe_fd) {
 
        _cleanup_free_ char *layers = NULL, *options = NULL, *hierarchy_path_moved_mount = NULL;
        _cleanup_close_ int hierarchy_path_fd = -EBADF, overlay_fs_fd = -EBADF;
        _cleanup_strv_free_ char **new_layers = NULL;
        int r;
 
        assert(m);
        assert(overlay_prefix);
        assert(fd_layers);
        assert(n_fd_layers);
        assert(pipe_fd >= 0);
 
        if (m->mode != MOUNT_OVERLAY)
                return 0;
 
        const char *mount_path = path_startswith(mount_entry_unprefixed_path(m), overlay_prefix);
        if (!mount_path)
                mount_path = mount_entry_unprefixed_path(m);
 
        /* If there are no extensions mounted for this overlay layer, we only need to
        * unmount the existing overlay (this is handled in the grandchild process) and
        * would skip the usual cooperative processing here.
        */
        if (strv_isempty(m->overlay_layers)) {
                log_debug("No layers for %s, skip setting up overlay", mount_path);
                return 0;
        }
 
        /* Receive the fds from grandchild */
        overlay_fs_fd = receive_one_fd(pipe_fd, 0);
        if (overlay_fs_fd < 0)
                return log_debug_errno(overlay_fs_fd, "Failed to receive overlay fs fd from grandchild: %m");
 
        hierarchy_path_fd = receive_one_fd(pipe_fd, 0);
        if (hierarchy_path_fd < 0)
                return log_debug_errno(hierarchy_path_fd, "Failed to receive fd from grandchild for %s: %m", mount_path);
 
        /* move_mount so that it is visible on our end. */
        hierarchy_path_moved_mount = path_join(overlay_prefix, mount_path);
        if (!hierarchy_path_moved_mount)
                return log_oom_debug();
 
        (void) mkdir_p_label(hierarchy_path_moved_mount, 0555);
        r = move_mount(hierarchy_path_fd, "", AT_FDCWD, hierarchy_path_moved_mount, MOVE_MOUNT_F_EMPTY_PATH);
        if (r < 0)
                return log_debug_errno(r, "Failed to move mount for %s: %m", mount_path);
 
        /* Turn all overlay layer directories into FD-based references */
        if (!GREEDY_REALLOC(*fd_layers, *n_fd_layers + strv_length(m->overlay_layers)))
                return log_oom_debug();
 
        STRV_FOREACH(ol, m->overlay_layers) {
                _cleanup_close_ int tree_fd = -EBADF;
 
                tree_fd = open_tree(-EBADF, *ol, /* flags= */ 0);
                if (tree_fd < 0)
                        return log_debug_errno(errno, "Failed to open_tree overlay layer '%s': %m", *ol);
 
                r = strv_extend(&new_layers, FORMAT_PROC_FD_PATH(tree_fd));
                if (r < 0)
                        return log_oom_debug();
 
                (*fd_layers)[(*n_fd_layers)++] = TAKE_FD(tree_fd);
        }
        m->overlay_layers = strv_free(m->overlay_layers);
        m->overlay_layers = TAKE_PTR(new_layers);
 
        layers = strv_join(m->overlay_layers, ":");
        if (!layers)
                return log_oom_debug();
 
        /* Append the underlying hierarchy path as the last lowerdir */
        options = strjoin(layers, ":", FORMAT_PROC_FD_PATH(hierarchy_path_fd));
        if (!options)
                return log_oom_debug();
 
        if (fsconfig(overlay_fs_fd, FSCONFIG_SET_STRING, "lowerdir", options, 0) < 0)
                return log_debug_errno(errno, "Failed to set lowerdir=%s: %m", options);
 
        if (fsconfig(overlay_fs_fd, FSCONFIG_SET_STRING, "source", "systemd-extensions", 0) < 0)
                return log_debug_errno(errno, "Failed to set source=systemd-extensions: %m");
 
        /* Create the superblock */
        if (fsconfig(overlay_fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0)
                return log_debug_errno(errno, "Failed to create overlay superblock: %m");
 
        /* Signal completion to grandchild */
        r = send_one_fd(pipe_fd, overlay_fs_fd, 0);
        if (r < 0)
                return log_debug_errno(r, "Failed to signal overlay configuration complete for %s: %m", mount_path);
 
        return 0;
}
 
static int refresh_apply_and_prune(const NamespaceParameters *p, MountList *ml) {
        int r;
 
        assert(p);
        assert(ml);
 
        /* Open all extensions on the host, drop all sysexts since they won't have /etc/. The list of
         * overlays also need to be updated, so that if it's empty after a confext has been removed, the
         * child process can correctly undo the overlay in the target namespace, rather than attempting to
         * mount an empty overlay which the kernel does not allow, so this pruning has to be done here and
         * not later (nor earlier, as we don't know if an image is a confext until this point). */
        MountEntry *f, *t;
        for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
                if (IN_SET(f->mode, MOUNT_EXTENSION_DIRECTORY, MOUNT_EXTENSION_IMAGE)) {
                        f->filter_class = IMAGE_CONFEXT;
 
                        r = apply_one_mount("/", f, p);
                        if (r < 0)
                                return r;
                        /* Nothing happened? Then it is not a confext, prune it from the lists */
                        if (r == 0) {
                                FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
                                        if (m->mode != MOUNT_OVERLAY)
                                                continue;
 
                                        _cleanup_strv_free_ char **pruned = NULL;
 
                                        STRV_FOREACH(ol, m->overlay_layers)
                                                if (!path_startswith(*ol, mount_entry_path(f))) {
                                                        r = strv_extend(&pruned, *ol);
                                                        if (r < 0)
                                                                return log_oom_debug();
                                                }
                                        strv_free(m->overlay_layers);
                                        m->overlay_layers = TAKE_PTR(pruned);
                                }
                                mount_entry_done(f);
                                continue;
                        }
                }
 
                *t = *f;
                t++;
        }
 
        ml->n_mounts = t - ml->mounts;
 
        return 0;
}
 
int refresh_extensions_in_namespace(
                const PidRef *target,
                const char *hierarchy_env,
                const NamespaceParameters *p) {
 
        _cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF;
        const char *overlay_prefix = "/run/systemd/mount-rootfs";
        _cleanup_(mount_list_done) MountList ml = {};
        _cleanup_free_ char *extension_dir = NULL;
        _cleanup_strv_free_ char **hierarchies = NULL;
        int r;
 
        assert(pidref_is_set(target));
        assert(hierarchy_env);
        assert(p);
 
        log_debug("Refreshing extensions in-namespace for hierarchy '%s'", hierarchy_env);