From 39732fab9f85e4e4e2e4149c17b125550e519100 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 11 Dec 2023 02:08:04 +0400 Subject: [PATCH] Improve home retrieving home directory. Fixes #2149. --- src/common/file-utils.cpp | 29 +++++++++++++++++++++++++++-- src/tests/cli_tests.py | 5 ++--- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/common/file-utils.cpp b/src/common/file-utils.cpp index d9cdb402dc..944514c98c 100644 --- a/src/common/file-utils.cpp +++ b/src/common/file-utils.cpp @@ -42,6 +42,7 @@ #include "str-utils.h" #include #ifdef _WIN32 +#include #include // for rnp_mkstemp #define CATCH_AND_RETURN(v) \ catch (...) \ @@ -51,6 +52,7 @@ } #else #include +#include #endif #ifdef HAVE_FCNTL_H #include @@ -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 = ""; + } } +#endif return sdir.empty() ? home : append(home, sdir); } diff --git a/src/tests/cli_tests.py b/src/tests/cli_tests.py index 634c88504e..f694e1e934 100755 --- a/src/tests/cli_tests.py +++ b/src/tests/cli_tests.py @@ -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'])