Ignore errors unsharing/restoring the mount namespace

This prevents Nix from barfing when run in a container where it
doesn't have the appropriate privileges.
This commit is contained in:
Eelco Dolstra 2021-11-16 14:23:05 +01:00
parent 51ffc19f02
commit 8c93a481af
2 changed files with 15 additions and 7 deletions

View file

@ -1631,6 +1631,7 @@ void setStackSize(size_t stackSize)
} }
#endif #endif
} }
static AutoCloseFD fdSavedMountNamespace; static AutoCloseFD fdSavedMountNamespace;
void saveMountNamespace() void saveMountNamespace()
@ -1638,9 +1639,10 @@ void saveMountNamespace()
#if __linux__ #if __linux__
static std::once_flag done; static std::once_flag done;
std::call_once(done, []() { std::call_once(done, []() {
fdSavedMountNamespace = open("/proc/self/ns/mnt", O_RDONLY); AutoCloseFD fd = open("/proc/self/ns/mnt", O_RDONLY);
if (!fdSavedMountNamespace) if (!fd)
throw SysError("saving parent mount namespace"); throw SysError("saving parent mount namespace");
fdSavedMountNamespace = std::move(fd);
}); });
#endif #endif
} }
@ -1648,8 +1650,12 @@ void saveMountNamespace()
void restoreMountNamespace() void restoreMountNamespace()
{ {
#if __linux__ #if __linux__
try {
if (fdSavedMountNamespace && setns(fdSavedMountNamespace.get(), CLONE_NEWNS) == -1) if (fdSavedMountNamespace && setns(fdSavedMountNamespace.get(), CLONE_NEWNS) == -1)
throw SysError("restoring parent mount namespace"); throw SysError("restoring parent mount namespace");
} catch (Error & e) {
debug(e.msg());
}
#endif #endif
} }

View file

@ -257,9 +257,11 @@ void mainWrapped(int argc, char * * argv)
#if __linux__ #if __linux__
if (getuid() == 0) { if (getuid() == 0) {
try {
saveMountNamespace(); saveMountNamespace();
if (unshare(CLONE_NEWNS) == -1) if (unshare(CLONE_NEWNS) == -1)
throw SysError("setting up a private mount namespace"); throw SysError("setting up a private mount namespace");
} catch (Error & e) { }
} }
#endif #endif