Skip to content

Commit

Permalink
Improve home retrieving home directory. Fixes #2149.
Browse files Browse the repository at this point in the history
  • Loading branch information
antonsviridenko committed Apr 21, 2024
1 parent ffd1bbc commit 39732fa
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
29 changes: 27 additions & 2 deletions src/common/file-utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
#include "str-utils.h"
#include <algorithm>
#ifdef _WIN32
#include <Shlobj.h>
#include <random> // for rnp_mkstemp
#define CATCH_AND_RETURN(v) \
catch (...) \
Expand All @@ -51,6 +52,7 @@
}
#else
#include <string.h>
#include <pwd.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
Expand Down Expand Up @@ -329,10 +331,33 @@ empty(const std::string &path)
std::string
HOME(const std::string &sdir)
{
const char *home = getenv("HOME");
const char *home;
#ifdef _WIN32
wchar_t wcsidlprf[MAX_PATH];
wchar_t *wuserprf;

wuserprf = _wgetenv(L"USERPROFILE");

if (wuserprf != NULL) {
home = wstr_to_utf8(wuserprf).c_str();
} else if (SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, wcsidlprf) ==
S_OK) {
home = wstr_to_utf8(wcsidlprf).c_str();
} else {
home = "";
}
#else
home = getenv("HOME");
if (!home) {
return "";
struct passwd *pwd;
pwd = getpwuid(getuid());
if (pwd != NULL) {
home = pwd->pw_dir;
} else {
home = "";

Check warning on line 357 in src/common/file-utils.cpp

View check run for this annotation

Codecov / codecov/patch

src/common/file-utils.cpp#L357

Added line #L357 was not covered by tests
}
}
#endif
return sdir.empty() ? home : append(home, sdir);
}

Expand Down
5 changes: 2 additions & 3 deletions src/tests/cli_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2725,9 +2725,8 @@ def test_no_home_dir(self):
del os.environ['HOME']
ret, _, err = run_proc(RNP, ['-v', 'non-existing.pgp'])
os.environ['HOME'] = home
self.assertEqual(ret, 2, 'failed to run without HOME env variable')
self.assertRegex(err, r'(?s)^.*Home directory .* does not exist or is not writable!')
self.assertRegex(err, RE_KEYSTORE_INFO)
self.assertEqual(ret, 1, 'failed to run without HOME env variable')
self.assertRegex(err, r'(?s)^.*can\'t stat \'non-existing.pgp\'')

def test_exit_codes(self):
ret, _, _ = run_proc(RNP, ['--homedir', RNPDIR, '--help'])
Expand Down

0 comments on commit 39732fa

Please sign in to comment.