From 1b046378e1748fbe4b740ade0e0a420251025455 Mon Sep 17 00:00:00 2001 From: Allison Karlitskaya Date: Thu, 19 Dec 2024 14:29:03 +0100 Subject: [PATCH] mount: factor open_tree_from_pidns() We might also want to open mount objects in our own mount namespace. This is particularly useful when recursive is set to `false`. For example, we can use this to perform operations directly on the root filesystem of the container, rather than having to deal with all of the bind mounts added by the container runtime. Factor the actual code for calling open_tree() into its own wrapper function with the same name. Signed-off-by: Allison Karlitskaya --- lib/src/mount.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/lib/src/mount.rs b/lib/src/mount.rs index a1ad00e6..f924332e 100644 --- a/lib/src/mount.rs +++ b/lib/src/mount.rs @@ -146,6 +146,23 @@ pub(crate) fn is_same_as_host(path: &Utf8Path) -> Result { Ok(devstat.f_fsid == hostdevstat.f_fsid) } +/// Open the named path as a new mount attached to an fd. +#[context("Opening mount tree from pid")] +pub(crate) fn open_tree(path: &Utf8Path, recursive: bool) -> Result { + // Open the target mount path as a file descriptor. + let recursive = if recursive { + OpenTreeFlags::AT_RECURSIVE + } else { + OpenTreeFlags::empty() + }; + rustix::mount::open_tree( + rustix::fs::CWD, + path.as_std_path(), + OpenTreeFlags::OPEN_TREE_CLOEXEC | OpenTreeFlags::OPEN_TREE_CLONE | recursive, + ) + .context("open_tree") +} + /// Given a pid, enter its mount namespace and acquire a file descriptor /// for a mount from that namespace. #[allow(unsafe_code)] @@ -179,18 +196,7 @@ pub(crate) fn open_tree_from_pidns( ) .context("setns")?; - // Open the target mount path as a file descriptor. - let recursive = if recursive { - OpenTreeFlags::AT_RECURSIVE - } else { - OpenTreeFlags::empty() - }; - let fd = rustix::mount::open_tree( - rustix::fs::CWD, - path.as_std_path(), - OpenTreeFlags::OPEN_TREE_CLOEXEC | OpenTreeFlags::OPEN_TREE_CLONE | recursive, - ) - .context("open_tree")?; + let fd = open_tree(path, recursive)?; // And send that file descriptor via fd passing over the socketpair. let fd = fd.as_fd();