From 8c93a481af2ce8fbcdb9e2bbcc9559d52703112f Mon Sep 17 00:00:00 2001 From: Eelco Dolstra Date: Tue, 16 Nov 2021 14:23:05 +0100 Subject: [PATCH] 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. --- src/libutil/util.cc | 14 ++++++++++---- src/nix/main.cc | 8 +++++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/libutil/util.cc b/src/libutil/util.cc index a6552ebca..8ae3445c6 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -1631,6 +1631,7 @@ void setStackSize(size_t stackSize) } #endif } + static AutoCloseFD fdSavedMountNamespace; void saveMountNamespace() @@ -1638,9 +1639,10 @@ void saveMountNamespace() #if __linux__ static std::once_flag done; std::call_once(done, []() { - fdSavedMountNamespace = open("/proc/self/ns/mnt", O_RDONLY); - if (!fdSavedMountNamespace) + AutoCloseFD fd = open("/proc/self/ns/mnt", O_RDONLY); + if (!fd) throw SysError("saving parent mount namespace"); + fdSavedMountNamespace = std::move(fd); }); #endif } @@ -1648,8 +1650,12 @@ void saveMountNamespace() void restoreMountNamespace() { #if __linux__ - if (fdSavedMountNamespace && setns(fdSavedMountNamespace.get(), CLONE_NEWNS) == -1) - throw SysError("restoring parent mount namespace"); + try { + if (fdSavedMountNamespace && setns(fdSavedMountNamespace.get(), CLONE_NEWNS) == -1) + throw SysError("restoring parent mount namespace"); + } catch (Error & e) { + debug(e.msg()); + } #endif } diff --git a/src/nix/main.cc b/src/nix/main.cc index 01889a71f..60b0aa410 100644 --- a/src/nix/main.cc +++ b/src/nix/main.cc @@ -257,9 +257,11 @@ void mainWrapped(int argc, char * * argv) #if __linux__ if (getuid() == 0) { - saveMountNamespace(); - if (unshare(CLONE_NEWNS) == -1) - throw SysError("setting up a private mount namespace"); + try { + saveMountNamespace(); + if (unshare(CLONE_NEWNS) == -1) + throw SysError("setting up a private mount namespace"); + } catch (Error & e) { } } #endif