Skip to content

Commit

Permalink
Swap order of attempts in getHome() to check syscall first and `$HO…
Browse files Browse the repository at this point in the history
…ME` second if necessary

Useful because a default `sudo` on darwin doesn't clear `$HOME`, so things like `sudo nix-channel --list`
will surprisingly return the USER'S channels, rather than `root`'s.

Other counterintuitive outcomes can be seen in this PR description:
  #6622
  • Loading branch information
virusdave committed Jun 15, 2022
1 parent 9f58df4 commit d0a110d
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/libutil/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -573,16 +573,22 @@ Path getHome()
{
static Path homeDir = []()
{
auto homeDir = getEnv("HOME");
if (!homeDir) {
std::vector<char> buf(16384);
struct passwd pwbuf;
struct passwd * pw;
if (getpwuid_r(geteuid(), &pwbuf, buf.data(), buf.size(), &pw) != 0
|| !pw || !pw->pw_dir || !pw->pw_dir[0])
throw Error("cannot determine user's home directory");
std::vector<char> buf(16384);
struct passwd pwbuf;
struct passwd * pw;

std::optional<std::string> homeDir = {};

if (getpwuid_r(geteuid(), &pwbuf, buf.data(), buf.size(), &pw) == 0
&& pw && pw->pw_dir && pw->pw_dir[0])
homeDir = pw->pw_dir;
}

if (!homeDir)
homeDir = getEnv("HOME");

if (!homeDir || !(*homeDir)[0])
throw Error("cannot determine user's home directory");

return *homeDir;
}();
return homeDir;
Expand Down

0 comments on commit d0a110d

Please sign in to comment.