Skip to content

Commit f994a91

Browse files
Improve home retrieving home directory. Fixes #2149.
1 parent e9021c4 commit f994a91

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

src/common/file-utils.cpp

+27-2
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
#include "str-utils.h"
4343
#include <algorithm>
4444
#ifdef _WIN32
45+
#include <Shlobj.h>
4546
#include <random> // for rnp_mkstemp
4647
#define CATCH_AND_RETURN(v) \
4748
catch (...) \
@@ -51,6 +52,7 @@
5152
}
5253
#else
5354
#include <string.h>
55+
#include <pwd.h>
5456
#endif
5557
#ifdef HAVE_FCNTL_H
5658
#include <fcntl.h>
@@ -329,10 +331,33 @@ empty(const std::string &path)
329331
std::string
330332
HOME(const std::string &sdir)
331333
{
332-
const char *home = getenv("HOME");
334+
const char *home;
335+
#ifdef _WIN32
336+
wchar_t wcsidlprf[MAX_PATH];
337+
wchar_t *wuserprf;
338+
339+
wuserprf = _wgetenv(L"USERPROFILE");
340+
341+
if (wuserprf != NULL) {
342+
home = wstr_to_utf8(wuserprf).c_str();
343+
} else if (SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, wcsidlprf) ==
344+
S_OK) {
345+
home = wstr_to_utf8(wcsidlprf).c_str();
346+
} else {
347+
home = "";
348+
}
349+
#else
350+
home = getenv("HOME");
333351
if (!home) {
334-
return "";
352+
struct passwd *pwd;
353+
pwd = getpwuid(getuid());
354+
if (pwd != NULL) {
355+
home = pwd->pw_dir;
356+
} else {
357+
home = "";
358+
}
335359
}
360+
#endif
336361
return sdir.empty() ? home : append(home, sdir);
337362
}
338363

src/tests/cli_tests.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -2678,9 +2678,8 @@ def test_no_home_dir(self):
26782678
del os.environ['HOME']
26792679
ret, _, err = run_proc(RNP, ['-v', 'non-existing.pgp'])
26802680
os.environ['HOME'] = home
2681-
self.assertEqual(ret, 2, 'failed to run without HOME env variable')
2682-
self.assertRegex(err, r'(?s)^.*Home directory .* does not exist or is not writable!')
2683-
self.assertRegex(err, RE_KEYSTORE_INFO)
2681+
self.assertEqual(ret, 1, 'failed to run without HOME env variable')
2682+
self.assertRegex(err, r'(?s)^.*can\'t stat \'non-existing.pgp\'')
26842683

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

0 commit comments

Comments
 (0)