about summary refs log tree commit diff
path: root/src/libstore/local-store.cc
diff options
context:
space:
mode:
Diffstat (limited to 'src/libstore/local-store.cc')
-rw-r--r--src/libstore/local-store.cc39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/libstore/local-store.cc b/src/libstore/local-store.cc
index 085e662edd74..bb755b8211ac 100644
--- a/src/libstore/local-store.cc
+++ b/src/libstore/local-store.cc
@@ -20,6 +20,11 @@
 #include <stdio.h>
 #include <time.h>
 
+#if HAVE_UNSHARE
+#include <sched.h>
+#include <sys/mount.h>
+#endif
+
 #include <sqlite3.h>
 
 
@@ -292,6 +297,8 @@ LocalStore::LocalStore(bool reserveSpace)
     }
 
     else openDB(false);
+
+    makeStoreWritable();
 }
 
 
@@ -411,6 +418,38 @@ void LocalStore::openDB(bool create)
 }
 
 
+/* To improve purity, users may want to make the Nix store a read-only
+   bind mount.  So make the Nix store writable for this process. */
+void LocalStore::makeStoreWritable()
+{
+#if HAVE_UNSHARE
+    if (getuid() != 0) return;
+
+    if (!pathExists("/proc/self/mountinfo")) return;
+
+    /* Check if /nix/store is a read-only bind mount. */
+    bool found = false;
+    Strings mounts = tokenizeString<Strings>(readFile("/proc/self/mountinfo", true), "\n");
+    foreach (Strings::iterator, i, mounts) {
+        vector<string> fields = tokenizeString<vector<string> >(*i, " ");
+        if (fields.at(3) == "/" || fields.at(4) != settings.nixStore) continue;
+        Strings options = tokenizeString<Strings>(fields.at(5), ",");
+        if (std::find(options.begin(), options.end(), "ro") == options.end()) continue;
+        found = true;
+        break;
+    }
+
+    if (!found) return;
+
+    if (unshare(CLONE_NEWNS) == -1)
+        throw SysError("setting up a private mount namespace");
+
+    if (mount(0, settings.nixStore.c_str(), 0, MS_REMOUNT | MS_BIND, 0) == -1)
+        throw SysError(format("remounting %1% writable") % settings.nixStore);
+#endif
+}
+
+
 const time_t mtimeStore = 1; /* 1 second into the epoch */