HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/mount-util.c

97,047 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: c8f0fd53d4dbb8a72edef75f564df7d9d77bbaae

Lines 1001–2000 of 2,291

        assert(!options || (flags & MOUNT_IN_NAMESPACE_IS_IMAGE));
 
        p = strjoina(propagate_path, "/");
        r = access_nofollow(p, F_OK);
        if (r < 0)
                return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
 
        /* Our goal is to install a new bind mount into the container,
           possibly read-only. This is irritatingly complex
           unfortunately, currently.
 
           First, we start by creating a private playground in /tmp,
           that we can mount MS_SLAVE. (Which is necessary, since
           MS_MOVE cannot be applied to mounts with MS_SHARED parent
           mounts.) */
 
        if (!mkdtemp(mount_slave))
                return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
 
        mount_slave_created = true;
 
        r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
        if (r < 0)
                goto finish;
 
        mount_slave_mounted = true;
 
        r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
        if (r < 0)
                goto finish;
 
        /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
        mount_tmp = strjoina(mount_slave, "/mount");
        r = make_mount_point_inode_from_mode(AT_FDCWD, mount_tmp, (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) ? S_IFDIR : chased_src_st->st_mode, 0700);
        if (r < 0) {
                log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
                goto finish;
        }
 
        mount_tmp_created = true;
 
        if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE)
                r = verity_dissect_and_mount(
                                chased_src_fd,
                                chased_src_path,
                                mount_tmp,
                                options,
                                image_policy,
                                /* image_filter= */ NULL,
                                /* extension_release_data= */ NULL,
                                /* required_class= */ _IMAGE_CLASS_INVALID,
                                /* verity= */ NULL,
                                RUNTIME_SCOPE_SYSTEM,
                                /* ret_image= */ NULL);
        else
                r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(chased_src_fd), mount_tmp, NULL, MS_BIND, NULL);
        if (r < 0)
                goto finish;
 
        mount_tmp_mounted = true;
 
        /* Third, we remount the new bind mount read-only if requested. */
        if (flags & MOUNT_IN_NAMESPACE_READ_ONLY) {
                r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
                if (r < 0)
                        goto finish;
        }
 
        /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
         * right-away. */
 
        mount_outside = strjoina(propagate_path, "/XXXXXX");
        if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
                r = mkdtemp(mount_outside) ? 0 : -errno;
        else {
                r = mkostemp_safe(mount_outside);
                safe_close(r);
        }
        if (r < 0) {
                log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
                goto finish;
        }
 
        mount_outside_created = true;
 
        r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
        if (r < 0)
                goto finish;
 
        mount_outside_mounted = true;
        mount_tmp_mounted = false;
 
        if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
                (void) rmdir(mount_tmp);
        else
                (void) unlink(mount_tmp);
        mount_tmp_created = false;
 
        (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
        mount_slave_mounted = false;
 
        (void) rmdir(mount_slave);
        mount_slave_created = false;
 
        if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
                log_debug_errno(errno, "Failed to create pipe: %m");
                goto finish;
        }
 
        r = namespace_fork(
                        "(sd-bindmnt)",
                        "(sd-bindmnt-inner)",
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
                        pidns_fd,
                        mntns_fd,
                        /* netns_fd= */ -EBADF,
                        /* userns_fd= */ -EBADF,
                        root_fd,
                        &child);
        if (r < 0)
                goto finish;
        if (r == 0) {
                _cleanup_free_ char *mount_outside_fn = NULL, *mount_inside = NULL;
 
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
 
                _cleanup_close_ int dest_fd = -EBADF;
                _cleanup_free_ char *dest_fn = NULL;
                r = chase(dest, /* root= */ NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME|((flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) ? CHASE_MKDIR_0755 : 0), &dest_fn, &dest_fd);
                if (r < 0)
                        log_debug_errno(r, "Failed to pin parent directory of mount '%s', ignoring: %m", dest);
                else if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) {
                        r = make_mount_point_inode_from_mode(dest_fd, dest_fn, (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) ? S_IFDIR : chased_src_st->st_mode, 0700);
                        if (r < 0)
                                log_debug_errno(r, "Failed to make mount point inode of mount '%s', ignoring: %m", dest);
                }
 
                /* Fifth, move the mount to the right place inside */
                r = path_extract_filename(mount_outside, &mount_outside_fn);
                if (r < 0) {
                        log_debug_errno(r, "Failed to extract filename from propagation file or directory '%s': %m", mount_outside);
                        report_errno_and_exit(errno_pipe_fd[1], r);
                }
 
                mount_inside = path_join(incoming_path, mount_outside_fn);
                if (!mount_inside)
                        report_errno_and_exit(errno_pipe_fd[1], log_oom_debug());
 
                r = mount_nofollow_verbose(LOG_DEBUG, mount_inside, dest_fd >= 0 ? FORMAT_PROC_FD_PATH(dest_fd) : dest, /* fstype= */ NULL, MS_MOVE, /* options= */ NULL);
                if (r < 0)
                        report_errno_and_exit(errno_pipe_fd[1], r);
 
                _exit(EXIT_SUCCESS);
        }
 
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
 
        r = pidref_wait_for_terminate_and_check("(sd-bindmnt)", &child, 0);
        if (r < 0) {
                log_debug_errno(r, "Failed to wait for child: %m");
                goto finish;
        }
        if (r != EXIT_SUCCESS) {
                if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
                        log_debug_errno(r, "Failed to mount: %m");
                else
                        log_debug("Child failed.");
                goto finish;
        }
 
finish:
        if (mount_outside_mounted)
                (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
        if (mount_outside_created) {
                if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
                        (void) rmdir(mount_outside);
                else
                        (void) unlink(mount_outside);
        }
 
        if (mount_tmp_mounted)
                (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
        if (mount_tmp_created) {
                if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
                        (void) rmdir(mount_tmp);
                else
                        (void) unlink(mount_tmp);
        }
 
        if (mount_slave_mounted)
                (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
        if (mount_slave_created)
                (void) rmdir(mount_slave);
 
        return r;
}
 
static int mount_in_namespace(
                const PidRef *target,
                const char *propagate_path,
                const char *incoming_path,
                const char *src,
                const char *dest,
                MountInNamespaceFlags flags,
                const MountOptions *options,
                const ImagePolicy *image_policy) {
 
        _cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF, chased_src_fd = -EBADF;
        _cleanup_free_ char *chased_src_path = NULL;
        struct stat st;
        int r;
 
        assert(propagate_path);
        assert(incoming_path);
        assert(src);
        assert(dest);
        assert((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || (!options && !image_policy));
 
        if (!pidref_is_set(target))
                return -ESRCH;
 
        r = pidref_namespace_open(target, &pidns_fd, &mntns_fd, /* ret_netns_fd= */ NULL, /* ret_userns_fd= */ NULL, &root_fd);
        if (r < 0)
                return log_debug_errno(r, "Failed to retrieve FDs of the target process' namespace: %m");
 
        r = is_our_namespace(mntns_fd, NAMESPACE_MOUNT);
        if (r < 0)
                return log_debug_errno(r, "Failed to determine if mount namespaces are equal: %m");
        /* We can't add new mounts at runtime if the process wasn't started in a namespace */
        if (r > 0)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace.");
 
        r = chase(src, NULL, 0, &chased_src_path, &chased_src_fd);
        if (r < 0)
                return log_debug_errno(r, "Failed to resolve source path '%s': %m", src);
        log_debug("Chased source path '%s': %s", src, chased_src_path);
 
        if (fstat(chased_src_fd, &st) < 0)
                return log_debug_errno(errno, "Failed to stat() resolved source path '%s': %m", src);
        if (S_ISLNK(st.st_mode)) /* This shouldn't really happen, given that we just chased the symlinks above, but let's better be safe… */
                return log_debug_errno(SYNTHETIC_ERRNO(ELOOP), "Source path '%s' can't be a symbolic link.", src);
 
        if (!mount_new_api_supported()) /* Fallback if we can't use the new mount API */
                return mount_in_namespace_legacy(
                                chased_src_path,
                                chased_src_fd,
                                &st,
                                propagate_path,
                                incoming_path,
                                dest,
                                pidns_fd,
                                mntns_fd,
                                root_fd,
                                flags,
                                options,
                                image_policy);
 
        _cleanup_(dissected_image_unrefp) DissectedImage *img = NULL;
        _cleanup_close_ int new_mount_fd = -EBADF;
        _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
        _cleanup_(pidref_done) PidRef child = PIDREF_NULL;
 
        if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) {
                r = verity_dissect_and_mount(
                                chased_src_fd,
                                chased_src_path,
                                /* dest= */ NULL,
                                options,
                                image_policy,
                                /* image_filter= */ NULL,
                                /* extension_release_data= */ NULL,
                                /* required_class= */ _IMAGE_CLASS_INVALID,
                                /* verity= */ NULL,
                                RUNTIME_SCOPE_SYSTEM,
                                &img);
                if (r < 0)
                        return log_debug_errno(r,
                                               "Failed to dissect and mount image '%s': %m",
                                               chased_src_path);
        } else {
                new_mount_fd = open_tree(
                                chased_src_fd,
                                "",
                                OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
                if (new_mount_fd < 0)
                        return log_debug_errno(
                                        errno,
                                        "Failed to open mount source '%s': %m",
                                        chased_src_path);
 
                if ((flags & MOUNT_IN_NAMESPACE_READ_ONLY) && mount_setattr(new_mount_fd, "", AT_EMPTY_PATH,
                                               &(struct mount_attr) {
                                                       .attr_set = MOUNT_ATTR_RDONLY,
                                               }, MOUNT_ATTR_SIZE_VER0) < 0)
                        return log_debug_errno(errno,
                                               "Failed to set mount for '%s' to read only: %m",
                                               chased_src_path);
        }
 
        if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0)
                return log_debug_errno(errno, "Failed to create pipe: %m");
 
        r = namespace_fork("(sd-bindmnt)",
                           "(sd-bindmnt-inner)",
                           FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
                           pidns_fd,
                           mntns_fd,
                           /* netns_fd= */ -EBADF,
                           /* userns_fd= */ -EBADF,
                           root_fd,
                           &child);
        if (r < 0)
                return log_debug_errno(r, "Failed to fork off mount helper into namespace: %m");
        if (r == 0) {
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
 
                _cleanup_close_ int dest_fd = -EBADF;
                _cleanup_free_ char *dest_fn = NULL;
                r = chase(dest, /* root= */ NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME|((flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) ? CHASE_MKDIR_0755 : 0), &dest_fn, &dest_fd);
                if (r < 0)
                        report_errno_and_exit(errno_pipe_fd[1], r);
 
                if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
                        (void) make_mount_point_inode_from_mode(dest_fd, dest_fn, img ? S_IFDIR : st.st_mode, 0700);
 
                if (img) {
                        DissectImageFlags f =
                                DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE |
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
 
                        if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
                                f |= DISSECT_IMAGE_MKDIR;
 
                        if (flags & MOUNT_IN_NAMESPACE_READ_ONLY)
                                f |= DISSECT_IMAGE_READ_ONLY;
 
                        r = dissected_image_mount(
                                        img,
                                        dest,
                                        /* uid_shift= */ UID_INVALID,
                                        /* uid_range= */ UID_INVALID,
                                        /* userns_fd= */ -EBADF,
                                        f);
                } else
                        r = mount_exchange_graceful(new_mount_fd, dest, /* mount_beneath= */ true);
 
                report_errno_and_exit(errno_pipe_fd[1], r);
        }
 
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
 
        r = pidref_wait_for_terminate_and_check("(sd-bindmnt)", &child, 0);
        if (r < 0)
                return log_debug_errno(r, "Failed to wait for child: %m");
        if (r != EXIT_SUCCESS) {
                if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
                        return log_debug_errno(r, "Failed to mount into namespace: %m");
 
                return log_debug_errno(SYNTHETIC_ERRNO(EPROTO), "Child failed.");
        }
 
        return 0;
}
 
int bind_mount_in_namespace(
                const PidRef *target,
                const char *propagate_path,
                const char *incoming_path,
                const char *src,
                const char *dest,
                MountInNamespaceFlags flags) {
 
        return mount_in_namespace(target,
                                  propagate_path,
                                  incoming_path,
                                  src,
                                  dest,
                                  flags & ~MOUNT_IN_NAMESPACE_IS_IMAGE,
                                  /* options= */ NULL,
                                  /* image_policy= */ NULL);
}
 
int mount_image_in_namespace(
                const PidRef *target,
                const char *propagate_path,
                const char *incoming_path,
                const char *src,
                const char *dest,
                MountInNamespaceFlags flags,
                const MountOptions *options,
                const ImagePolicy *image_policy) {
 
        return mount_in_namespace(target,
                                  propagate_path,
                                  incoming_path,
                                  src,
                                  dest,
                                  flags | MOUNT_IN_NAMESPACE_IS_IMAGE,
                                  options,
                                  image_policy);
}
 
int make_mount_point(const char *path) {
        int r;
 
        assert(path);
 
        /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
 
        r = path_is_mount_point(path);
        if (r < 0)
                return log_debug_errno(r, "Failed to determine whether '%s' is a mount point: %m", path);
        if (r > 0)
                return 0;
 
        r = mount_nofollow_verbose(LOG_DEBUG, path, path, NULL, MS_BIND|MS_REC, NULL);
        if (r < 0)
                return r;
 
        return 1;
}
 
int fd_make_mount_point(int fd) {
        int r;
 
        assert(fd >= 0);
 
        r = is_mount_point_at(fd, NULL, 0);
        if (r < 0)
                return log_debug_errno(r, "Failed to determine whether file descriptor is a mount point: %m");
        if (r > 0)
                return 0;
 
        r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(fd), FORMAT_PROC_FD_PATH(fd), NULL, MS_BIND|MS_REC, NULL);
        if (r < 0)
                return r;
 
        return 1;
}
 
int mount_fd_clone(int mount_fd, bool recursive, int *replacement_fd) {
        const int flags = OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_EMPTY_PATH|(recursive ? AT_RECURSIVE : 0);
        int r;
 
        assert(mount_fd >= 0);
 
        /* If the input mount fd is supposed to remain cloneable after calling this function, call it as
         * follows: mount_fd_clone(mount_fd, recursive, &mount_fd). */
 
        /* Clone a detached mount (that may be owned by a foreign mountns, e.g. mountfsd's). For this to
         * work on older kernels, we have to jump through some hoops, because the kernel currently doesn't
         * allow us to just call open_tree(OPEN_TREE_CLONE) directly to get a clone of a mount that is
         * detached and owned by another mountns. Hence here's what we do: we clone short-lived child in a
         * new mount namespace owned by our userns. There, we attach the mount (invisible to anyone else).
         * This is sufficient to pass the kernel check, so next we use open_tree(OPEN_TREE_CLONE) to get our
         * own detached mount. This we send back to the parent, which then can use it. */
 
        r = RET_NERRNO(open_tree(mount_fd, "", flags));
        if (r != -EINVAL)
                /* The straightforward path just works? Yay! Don't bother with the complex logic below. No
                 * need to put a replacement fd in replacement_fd as the original fd is still usable. */
                return r;
 
        _cleanup_close_pair_ int transfer_fds[2] = EBADF_PAIR;
        r = socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, transfer_fds);
        if (r < 0)
                return log_debug_errno(errno, "Failed to create socket pair: %m");
 
        _cleanup_close_pair_ int errno_pipe_fds[2] = EBADF_PAIR;
        if (pipe2(errno_pipe_fds, O_CLOEXEC|O_NONBLOCK) < 0)
                return log_debug_errno(errno, "Failed to open pipe: %m");
 
        /* Fork a child. Note that we set FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE here, i.e. get a new mount namespace */
        r = pidref_safe_fork_full(
                        "(sd-clonemnt)",
                        /* stdio_fds= */ NULL,
                        (int[]) { mount_fd, transfer_fds[1], errno_pipe_fds[1] }, 3,
                        FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_REOPEN_LOG|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE,
                        /* ret= */ NULL);
        if (r < 0) {
                errno_pipe_fds[1] = safe_close(errno_pipe_fds[1]);
 
                int q = read_errno(errno_pipe_fds[0]);
                if (q < 0 && q != -EIO)
                        return q;
 
                return r;
        }
        if (r == 0) { /* Child */
 
                /* Attach mount */
                if (move_mount(mount_fd, "", -EBADF, "/", MOVE_MOUNT_F_EMPTY_PATH) < 0) {
                        log_debug_errno(errno, "Failed to move mount file descriptor to '/': %m");
                        report_errno_and_exit(errno_pipe_fds[1], -errno);
                }
 
                /* If requested by the caller, we clone the fd twice. Why? After move_mount(), the input file
                 * descriptor can't be move_mount()'ed again, which means we can't clone it again if it comes
                 * from a different mount namespace. To ensure they can clone the same fd multiple times,
                 * callers can pass a pointer to the input fd which will be replaced with a second clone,
                 * which can be move_mount()'ed and thus can be cloned again. */
 
                for (int i = 0; i < 1 + !!replacement_fd; i++) {
                        /* And now clone the attached mount that is now ours. */
                        _cleanup_close_ int cloned_fd = open_tree(mount_fd, "", flags);
                        if (cloned_fd < 0) {
                                log_debug_errno(errno, "Failed to clone mount file descriptor: %m");
                                report_errno_and_exit(errno_pipe_fds[1], -errno);
                        }
 
                        /* And send it to the parent. */
                        r = send_one_fd(transfer_fds[1], cloned_fd, /* flags= */ 0);
                        if (r < 0)
                                report_errno_and_exit(errno_pipe_fds[1], r);
                }
 
                _exit(EXIT_SUCCESS);
        }
 
        transfer_fds[1] = safe_close(transfer_fds[1]);
 
        /* Accept the new cloned mount */
        _cleanup_close_ int fd1 = receive_one_fd(transfer_fds[0], 0);
        if (fd1 < 0)
                return fd1;
 
        if (replacement_fd) {
                int fd2 = receive_one_fd(transfer_fds[0], 0);
                if (fd2 < 0)
                        return fd2;
 
                close_and_replace(*replacement_fd, fd2);
        }
 
        return TAKE_FD(fd1);
}
 
int make_userns(uid_t uid_shift,
                uid_t uid_range,
                uid_t source_owner,
                uid_t dest_owner,
                RemountIdmapping idmapping) {
 
        _cleanup_close_ int userns_fd = -EBADF;
        _cleanup_free_ char *line = NULL;
        uid_t source_base = 0;
 
        /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
         * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
 
        if (!userns_shift_range_valid(uid_shift, uid_range))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid UID range for user namespace.");
 
        switch (idmapping) {
 
        case REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT:
                source_base = FOREIGN_UID_BASE;
                _fallthrough_;
 
        case REMOUNT_IDMAPPING_NONE:
        case REMOUNT_IDMAPPING_HOST_ROOT:
 
                if (asprintf(&line,
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
                             source_base, uid_shift, uid_range) < 0)
                        return log_oom_debug();
 
                /* If requested we'll include an entry in the mapping so that the host root user can make
                 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
                 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
                 * to create various missing inodes in the OS tree before booting into it, and this becomes
                 * very easy and straightforward to do if it can just do it under its own regular UID. Note
                 * that in that case the container's runtime uidmap (i.e. the one the container payload
                 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
                 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
                 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
                 * to the container's own UID range, but it's good to have a safety net, in case we
                 * forget it.) */
                if (idmapping == REMOUNT_IDMAPPING_HOST_ROOT)
                        if (strextendf(&line,
                                       UID_FMT " " UID_FMT " " UID_FMT "\n",
                                       UID_MAPPED_ROOT, (uid_t) 0u, (uid_t) 1u) < 0)
                                return log_oom_debug();
 
                break;
 
        case REMOUNT_IDMAPPING_HOST_OWNER:
                /* Remap the owner of the bind mounted directory to the root user within the container. This
                 * way every file written by root within the container to the bind-mounted directory will
                 * be owned by the original user from the host. All other users will remain unmapped. */
                if (asprintf(&line,
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
                             source_owner, uid_shift, (uid_t) 1u) < 0)
                        return log_oom_debug();
                break;
 
        case REMOUNT_IDMAPPING_HOST_OWNER_TO_TARGET_OWNER:
                /* Remap the owner of the bind mounted directory to the owner of the target directory
                 * within the container. This way every file written by target directory owner within the
                 * container to the bind-mounted directory will be owned by the original host user.
                 * All other users will remain unmapped. */
                if (asprintf(&line,
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
                             source_owner, dest_owner, (uid_t) 1u) < 0)
                        return log_oom_debug();
                break;
 
        default:
                assert_not_reached();
        }
 
        /* We always assign the same UID and GID ranges */
        userns_fd = userns_acquire(line, line, /* setgroups_deny= */ true);
        if (userns_fd < 0)
                return log_debug_errno(userns_fd, "Failed to acquire new userns: %m");
 
        return TAKE_FD(userns_fd);
}
 
int open_tree_attr_with_fallback(int dir_fd, const char *path, unsigned flags, struct mount_attr *attr) {
        _cleanup_close_ int fd = -EBADF;
 
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
        assert(attr);
 
        if (isempty(path)) {
                path = "";
                flags |= AT_EMPTY_PATH;
        }
 
        fd = open_tree_attr(dir_fd, path, flags, attr, sizeof(struct mount_attr));
        if (fd >= 0)
                return TAKE_FD(fd);
        if (!ERRNO_IS_NOT_SUPPORTED(errno))
                return log_debug_errno(errno, "Failed to open tree and set mount attributes: %m");
 
        if (attr->attr_clr & MOUNT_ATTR_IDMAP)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Cannot clear idmap from mount without open_tree_attr()");
 
        fd = open_tree(dir_fd, path, flags);
        if (fd < 0)
                return log_debug_errno(errno, "Failed to open tree: %m");
 
        if (mount_setattr(fd, "", AT_EMPTY_PATH | (flags & AT_RECURSIVE), attr, sizeof(struct mount_attr)) < 0)
                return log_debug_errno(errno, "Failed to change mount attributes: %m");
 
        return TAKE_FD(fd);
}
 
int open_tree_try_drop_idmap(int dir_fd, const char *path, unsigned flags) {
        /* Tries to drop MOUNT_ATTR_IDMAP while calling open_tree_attr(), but if that doesn't work just uses
         * a regular open_tree() */
 
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
 
        if (isempty(path)) {
                path = "";
                flags |= AT_EMPTY_PATH;
        }
 
        _cleanup_close_ int fd = open_tree_attr_with_fallback(
                        dir_fd,
                        path,
                        flags,
                        &(struct mount_attr) {
                                .attr_clr = MOUNT_ATTR_IDMAP,
                        });
        if (fd < 0) {
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(fd))
                        return log_debug_errno(fd, "Failed to clear idmap of directory with open_tree_attr(): %m");
 
                log_debug_errno(fd, "Failed to clear idmap with open_tree_attr(), retrying open_tree() without clearing idmap: %m");
 
                fd = RET_NERRNO(open_tree(dir_fd, path, flags));
                if (fd < 0)
                        return log_debug_errno(fd, "Both open_tree() and open_tree_attr() failed, giving up: %m");
 
                log_debug("open_tree() without clearing idmap worked.");
                return TAKE_FD(fd);
        }
 
        log_debug("Successfully acquired mount fd with cleared idmap.");
        return TAKE_FD(fd);
}
 
int remount_idmap_fd(
                char **paths,
                int userns_fd,
                uint64_t extra_mount_attr_set) {
 
        int r;
 
        assert(userns_fd >= 0);
 
        /* This remounts all specified paths with the specified userns as idmap. It will do so in the
         * order specified in the strv: the expectation is that the top-level directories are at the
         * beginning, and nested directories in the right, so that the tree can be built correctly from left
         * to right. */
 
        size_t n = strv_length(paths);
        if (n == 0) /* Nothing to do? */
                return 0;
 
        int *mount_fds = NULL;
        size_t n_mounts_fds = 0;
 
        mount_fds = new(int, n);
        if (!mount_fds)
                return log_oom_debug();
 
        CLEANUP_ARRAY(mount_fds, n_mounts_fds, close_many_and_free);
 
        for (size_t i = 0; i < n; i++) {
                /* Clone the mount point and et the user namespace mapping attribute on the cloned mount point. */
                mount_fds[n_mounts_fds] = open_tree_attr_with_fallback(
                                AT_FDCWD,
                                paths[i],
                                OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC,
                                &(struct mount_attr) {
                                          .attr_set = MOUNT_ATTR_IDMAP | extra_mount_attr_set,
                                          .userns_fd = userns_fd,
                                });
                if (mount_fds[n_mounts_fds] < 0)
                        return mount_fds[n_mounts_fds];
 
                n_mounts_fds++;
        }
 
        for (size_t i = n; i > 0; i--) { /* Unmount the paths right-to-left */
                /* Remove the old mount points now that we have a idmapped mounts as replacement for all of them */
                r = umount_verbose(LOG_DEBUG, paths[i-1], UMOUNT_NOFOLLOW);
                if (r < 0)
                        return r;
        }
 
        for (size_t i = 0; i < n; i++) { /* Mount the replacement mounts left-to-right */
                /* And place the cloned version in its place */
                log_debug("Mounting idmapped fs to '%s'", paths[i]);
                if (move_mount(mount_fds[i], "", -EBADF, paths[i], MOVE_MOUNT_F_EMPTY_PATH) < 0)
                        return log_debug_errno(errno, "Failed to attach UID mapped mount to '%s': %m", paths[i]);
        }
 
        return 0;
}
 
int remount_idmap(
                char **p,
                uid_t uid_shift,
                uid_t uid_range,
                uid_t source_owner,
                uid_t dest_owner,
                RemountIdmapping idmapping) {
 
        _cleanup_close_ int userns_fd = -EBADF;
 
        userns_fd = make_userns(uid_shift, uid_range, source_owner, dest_owner, idmapping);
        if (userns_fd < 0)
                return userns_fd;
 
        return remount_idmap_fd(p, userns_fd, /* extra_mount_attr_set= */ 0);
}
 
static void sub_mount_clear(SubMount *s) {
        assert(s);
 
        s->path = mfree(s->path);
        s->mount_fd = safe_close(s->mount_fd);
}
 
DEFINE_ARRAY_FREE_FUNC(sub_mount_array_free, SubMount, sub_mount_clear);
 
#if HAVE_LIBMOUNT
static int sub_mount_compare(const SubMount *a, const SubMount *b) {
        assert(a);
        assert(b);
 
        /* sub_mount_drop() creates NULL paths which we order to the end so that after the sort we can
         * truncate the array. Done manually because path_compare() orders NULL before non-NULL. */
        if (!a->path || !b->path)
                return CMP(!a->path, !b->path);
 
        return path_compare(a->path, b->path);
}
 
static void sub_mount_drop(SubMount *s, size_t *n) {
        assert(n);
        assert(s || *n == 0);
 
        /* Works on a sorted array. Drops mounts that are covered by the preceding entry's recursive
         * open_tree() clone, clearing the slot in place. Then sorts again for the NULL paths to be shifted
         * past the kept count. */
 
        size_t kept = *n > 0;
        for (size_t m = 0, i = 1; i < *n; i++)
                if (path_startswith(s[i].path, s[m].path))
                        sub_mount_clear(s + i);
                else {
                        m = i;
                        kept++;
                }
 
        if (kept < *n)
                typesafe_qsort(s, *n, sub_mount_compare);
 
        *n = kept;
}
#endif
 
int get_sub_mounts(const char *prefix, SubMount **ret_mounts, size_t *ret_n_mounts) {
#if HAVE_LIBMOUNT
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
        SubMount *mounts = NULL;
        size_t n = 0;
        int r;
 
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
 
        assert(prefix);
        assert(ret_mounts);
        assert(ret_n_mounts);
 
        r = libmount_parse_mountinfo(/* source= */ NULL, &table, &iter);
        if (r < 0)
                return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
 
        for (;;) {
                _cleanup_close_ int mount_fd = -EBADF;
                _cleanup_free_ char *p = NULL;
                struct libmnt_fs *fs;
                const char *path;
 
                r = sym_mnt_table_next_fs(table, iter, &fs);
                if (r == 1)
                        break; /* EOF */
                if (r < 0)
                        return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
 
                path = sym_mnt_fs_get_target(fs);
                if (!path)
                        continue;
 
                if (isempty(path_startswith(path, prefix)))
                        continue;
 
                /* The path may be hidden by another over-mount or already remounted; skip it in that case
                 * (libmount_fs_id_matches_path() already logs the details at debug level). */
                r = libmount_fs_id_matches_path(fs, path);
                if (r <= 0)
                        continue;
 
                /* If possible on a newer kernel, use MS_PRIVATE to decouple it from the original mount.
                 * Otherwise MNT_DETACH of the source path could propagate through and unmount the
                 * just-moved nested children at the destination (relevant for preserving nested mounts
                 * under sysext hierarchies).
                 *
                 * Also, pass AT_NO_AUTOMOUNT so that we clone automount points (i.e. autofs mounts) as
                 * they are, instead of triggering them. OPEN_TREE_CLONE would otherwise force them to be
                 * mounted, and — worse — block until the automount request has been served. If the
                 * automount point is managed by PID 1 itself (as is the case for systemd's own
                 * /proc/sys/fs/binfmt_misc automount point, which is cloned whenever a private /proc is
                 * set up for a service) this can take a long time during boot, since the resulting mount
                 * job competes with the ongoing boot transaction. */
                static bool mount_attr_unsupported = false;
 
                if (!mount_attr_unsupported) {
                        mount_fd = open_tree_attr_with_fallback(
                                        AT_FDCWD, path,
                                        OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_RECURSIVE|AT_NO_AUTOMOUNT,
                                        &(struct mount_attr) { .propagation = MS_PRIVATE });
                        if (mount_fd == -ENOENT) /* The path may be hidden by another over-mount or already unmounted. */
                                continue;
                        if (mount_fd < 0 && ERRNO_IS_NEG_NOT_SUPPORTED(mount_fd)) {
                                /* On a kernel older than 5.12 without mount_setattr() we do the regular
                                 * clone. Nested mounts under sysext and similar cases may get lost. */
                                log_debug_errno(mount_fd, "mount_setattr() not supported, falling back to plain open_tree() without MS_PRIVATE: %m");
                                mount_attr_unsupported = true;
                        } else if (mount_fd < 0)
                                return log_debug_errno(mount_fd, "Failed to open subtree of mounted filesystem '%s': %m", path);
                }
 
                if (mount_attr_unsupported) {
                        mount_fd = RET_NERRNO(open_tree(AT_FDCWD, path, OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_RECURSIVE|AT_NO_AUTOMOUNT));
                        if (mount_fd == -ENOENT)
                                continue;
                        if (mount_fd < 0)
                                return log_debug_errno(mount_fd, "Failed to open subtree of mounted filesystem '%s': %m", path);
                }
 
                p = strdup(path);
                if (!p)
                        return log_oom_debug();
 
                if (!GREEDY_REALLOC(mounts, n + 1))
                        return log_oom_debug();
 
                mounts[n++] = (SubMount) {
                        .path = TAKE_PTR(p),
                        .mount_fd = TAKE_FD(mount_fd),
                };
        }
 
        typesafe_qsort(mounts, n, sub_mount_compare);
        sub_mount_drop(mounts, &n);
 
        *ret_mounts = TAKE_PTR(mounts);
        *ret_n_mounts = n;
        return 0;
#else
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "libmount support not compiled in");
#endif
}
 
int bind_mount_submounts(
                const char *source,
                const char *target) {
 
        SubMount *mounts = NULL;
        size_t n = 0;
        int ret = 0, r;
 
        /* Bind mounts all child mounts of 'source' to 'target'. Useful when setting up a new procfs instance
         * with new mount options to copy the original submounts over. */
 
        assert(source);
        assert(target);
 
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
 
        r = get_sub_mounts(source, &mounts, &n);
        if (r < 0)
                return r;
 
        FOREACH_ARRAY(m, mounts, n) {
                _cleanup_free_ char *t = NULL;
                const char *suffix;
 
                if (isempty(m->path))
                        continue;
 
                assert_se(suffix = path_startswith(m->path, source));
 
                t = path_join(target, suffix);
                if (!t)
                        return -ENOMEM;
 
                r = path_is_mount_point(t);
                if (r < 0) {
                        log_debug_errno(r, "Failed to detect if '%s' already is a mount point, ignoring: %m", t);
                        continue;
                }
                if (r > 0) {
                        log_debug("Not bind mounting '%s' from '%s' to '%s', since there's already a mountpoint.", suffix, source, target);
                        continue;
                }
 
                RET_GATHER(ret, RET_NERRNO(move_mount(m->mount_fd, "", AT_FDCWD, t, MOVE_MOUNT_F_EMPTY_PATH)));
        }
 
        return ret;
}
 
int make_mount_point_inode_from_mode(int dir_fd, const char *dest, mode_t source_mode, mode_t target_mode) {
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
        assert(dest);
 
        if (S_ISDIR(source_mode))
                return mkdirat_label(dir_fd, dest, target_mode & 07777, /* label_context= */ NULL);
        else
                return RET_NERRNO(mknodat(dir_fd, dest, S_IFREG|(target_mode & 07666), 0)); /* Mask off X bit */
}
 
int make_mount_point_inode_from_path(const char *source, const char *dest, mode_t access_mode) {
        struct stat st;
 
        assert(source);
        assert(dest);
 
        if (stat(source, &st) < 0)
                return -errno;
 
        return make_mount_point_inode_from_mode(AT_FDCWD, dest, st.st_mode, access_mode);
}
 
int trigger_automount_at(int dir_fd, const char *path) {
        _cleanup_free_ char *nested = NULL;
 
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
 
        nested = path_join(path, "a");
        if (!nested)
                return -ENOMEM;
 
        (void) faccessat(dir_fd, nested, F_OK, 0);
 
        return 0;
}
 
unsigned long credentials_fs_mount_flags(bool ro) {
        /* A tight set of mount flags for credentials mounts */