Skip to content

Commit f5e620b

Browse files
authored
Merge pull request #8483 from edolstra/save-root
restoreMountNamespace(): Restore the original root directory
2 parents 49288d6 + e54538c commit f5e620b

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

src/libutil/util.cc

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1853,17 +1853,19 @@ void setStackSize(size_t stackSize)
18531853

18541854
#if __linux__
18551855
static AutoCloseFD fdSavedMountNamespace;
1856+
static AutoCloseFD fdSavedRoot;
18561857
#endif
18571858

18581859
void saveMountNamespace()
18591860
{
18601861
#if __linux__
18611862
static std::once_flag done;
18621863
std::call_once(done, []() {
1863-
AutoCloseFD fd = open("/proc/self/ns/mnt", O_RDONLY);
1864-
if (!fd)
1864+
fdSavedMountNamespace = open("/proc/self/ns/mnt", O_RDONLY);
1865+
if (!fdSavedMountNamespace)
18651866
throw SysError("saving parent mount namespace");
1866-
fdSavedMountNamespace = std::move(fd);
1867+
1868+
fdSavedRoot = open("/proc/self/root", O_RDONLY);
18671869
});
18681870
#endif
18691871
}
@@ -1876,9 +1878,16 @@ void restoreMountNamespace()
18761878

18771879
if (fdSavedMountNamespace && setns(fdSavedMountNamespace.get(), CLONE_NEWNS) == -1)
18781880
throw SysError("restoring parent mount namespace");
1879-
if (chdir(savedCwd.c_str()) == -1) {
1880-
throw SysError("restoring cwd");
1881+
1882+
if (fdSavedRoot) {
1883+
if (fchdir(fdSavedRoot.get()))
1884+
throw SysError("chdir into saved root");
1885+
if (chroot("."))
1886+
throw SysError("chroot into saved root");
18811887
}
1888+
1889+
if (chdir(savedCwd.c_str()) == -1)
1890+
throw SysError("restoring cwd");
18821891
} catch (Error & e) {
18831892
debug(e.msg());
18841893
}

0 commit comments

Comments
 (0)