From a8aedb8cd6283229da72ccb0d062f6e609bdba0c Mon Sep 17 00:00:00 2001 From: David Gibson Date: Thu, 20 Aug 2026 15:30:32 +1000 Subject: isolation: Create helper function to enter user namespace Currently, isolate_user() open codes the steps needed to open and join an existing user namespace. Upcoming changes are going to want to re-use these steps, so move this logic into a helper function, Signed-off-by: David Gibson Signed-off-by: Stefano Brivio --- isolation.c | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/isolation.c b/isolation.c index a30b329..024c26a 100644 --- a/isolation.c +++ b/isolation.c @@ -292,6 +292,24 @@ int isolate_fds(int argc, char **argv) return fd; } +/** + * enter_userns() - Enter a named user namespace + * @userns: userns path to enter + */ +static void enter_userns(const char *userns) +{ + int ufd; + + ufd = open(userns, O_RDONLY | O_CLOEXEC); + if (ufd < 0) + die_perror("Couldn't open user namespace %s", userns); + + if (setns(ufd, CLONE_NEWUSER) != 0) + die_perror("Couldn't enter user namespace %s", userns); + + close(ufd); +} + /** * isolate_user() - Switch to final UID/GID and move into userns * @c: Execution context @@ -325,17 +343,7 @@ void isolate_user(const struct ctx *c, uid_t uid, gid_t gid, bool use_userns, die_perror("Can't set UID to %u", uid); if (*userns) { /* If given a userns, join it */ - int ufd; - - ufd = open(userns, O_RDONLY | O_CLOEXEC); - if (ufd < 0) - die_perror("Couldn't open user namespace %s", userns); - - if (setns(ufd, CLONE_NEWUSER) != 0) - die_perror("Couldn't enter user namespace %s", userns); - - close(ufd); - + enter_userns(userns); } else if (use_userns) { /* Create and join a new userns */ if (unshare(CLONE_NEWUSER) != 0) die_perror("Couldn't create user namespace"); -- cgit v1.2.3