nstool: Enter holder's cwd when changing mount ns with nstool exec

If we enter a mount namespace with nstool exec our working directory will
be changed to / in the new mount ns.  This is surprising if we haven't
actually altered any mounts yet in the new ns.  Instead, change the working
directory to match that of the holder process in this situation.

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Signed-off-by: Stefano Brivio <sbrivio@redhat.com>
This commit is contained in:
David Gibson 2023-04-06 13:28:19 +10:00 committed by Stefano Brivio
parent 98031bee73
commit 1a3ade9037

View file

@ -420,6 +420,7 @@ static void cmd_exec(int argc, char *argv[])
const struct ns_type *nst; const struct ns_type *nst;
int ctlfd, flags, opt, rc; int ctlfd, flags, opt, rc;
const char *const *xargs; const char *const *xargs;
struct holder_info info;
bool keepcaps = false; bool keepcaps = false;
struct ucred peercred; struct ucred peercred;
const char *exe; const char *exe;
@ -444,7 +445,7 @@ static void cmd_exec(int argc, char *argv[])
sockpath = argv[optind]; sockpath = argv[optind];
ctlfd = connect_ctl(sockpath, false, NULL, &peercred); ctlfd = connect_ctl(sockpath, false, &info, &peercred);
flags = detect_namespaces(peercred.pid); flags = detect_namespaces(peercred.pid);
@ -475,6 +476,15 @@ static void cmd_exec(int argc, char *argv[])
nst->name, strerror(errno)); nst->name, strerror(errno));
} }
/* If we've entered a mount ns, our cwd has changed to /.
* Switch to the cwd of the holder, which is probably less
* surprising. */
if (flags & CLONE_NEWNS) {
rc = chdir(info.cwd);
if (rc < 0)
die("chdir(\"%s\"): %s\n", info.cwd, strerror(errno));
}
/* Fork to properly enter PID namespace */ /* Fork to properly enter PID namespace */
xpid = fork(); xpid = fork();
if (xpid < 0) if (xpid < 0)