diff --git a/src/libstore/globals.cc b/src/libstore/globals.cc index d22ae4ca02e5..32d39e2d006d 100644 --- a/src/libstore/globals.cc +++ b/src/libstore/globals.cc @@ -415,7 +415,7 @@ void initLibStore() { sshd). This breaks build users because they don't have access to the TMPDIR, in particular in ‘nix-store --serve’. */ #if __APPLE__ - if (hasPrefix(getEnv("TMPDIR").value_or("/tmp"), "/var/folders/")) + if (defaultTempDir(), "/var/folders/")) unsetenv("TMPDIR"); #endif diff --git a/src/libutil/file-system.cc b/src/libutil/file-system.cc index 9dd6a5133cd2..e3660f8e0682 100644 --- a/src/libutil/file-system.cc +++ b/src/libutil/file-system.cc @@ -494,10 +494,16 @@ void AutoDelete::reset(const Path & p, bool recursive) { ////////////////////////////////////////////////////////////////////// +std::string defaultTempDir() { + constexpr auto def = "/tmp"; + auto dir = getEnv("TMPDIR").value_or(def); + return dir.empty() ? def : dir; +} + static Path tempName(Path tmpRoot, const Path & prefix, bool includePid, std::atomic & counter) { - tmpRoot = canonPath(tmpRoot.empty() ? getEnv("TMPDIR").value_or("/tmp") : tmpRoot, true); + tmpRoot = canonPath(tmpRoot.empty() ? defaultTempDir() : tmpRoot, true); if (includePid) return fmt("%1%/%2%-%3%-%4%", tmpRoot, prefix, getpid(), counter++); else @@ -537,7 +543,7 @@ Path createTempDir(const Path & tmpRoot, const Path & prefix, std::pair createTempFile(const Path & prefix) { - Path tmpl(getEnv("TMPDIR").value_or("/tmp") + "/" + prefix + ".XXXXXX"); + Path tmpl(defaultTempDir() + "/" + prefix + ".XXXXXX"); // Strictly speaking, this is UB, but who cares... // FIXME: use O_TMPFILE. AutoCloseFD fd(mkstemp((char *) tmpl.c_str())); diff --git a/src/libutil/file-system.hh b/src/libutil/file-system.hh index 963265e3412b..9d565c881c71 100644 --- a/src/libutil/file-system.hh +++ b/src/libutil/file-system.hh @@ -234,6 +234,10 @@ Path createTempDir(const Path & tmpRoot = "", const Path & prefix = "nix", */ std::pair createTempFile(const Path & prefix = "nix"); +/** + * Return `TMPDIR`, or the default temporary directory if unset or empty. + */ +Path defaultTempDir(); /** * Used in various places. diff --git a/src/nix-build/nix-build.cc b/src/nix-build/nix-build.cc index a372e4b1c7f2..418ee0ddde14 100644 --- a/src/nix-build/nix-build.cc +++ b/src/nix-build/nix-build.cc @@ -476,7 +476,7 @@ static void main_nix_build(int argc, char * * argv) auto env = getEnv(); auto tmp = getEnv("TMPDIR"); - if (!tmp) tmp = getEnv("XDG_RUNTIME_DIR").value_or("/tmp"); + if (!tmp || tmp->empty()) tmp = getEnv("XDG_RUNTIME_DIR").value_or("/tmp"); if (pure) { decltype(env) newEnv;