diff --git a/src/env.cpp b/src/env.cpp index 0d5917fde..108fbab4c 100644 --- a/src/env.cpp +++ b/src/env.cpp @@ -840,16 +840,19 @@ void env_init(const struct config_paths_t *paths /* or NULL */) { if (env_get_string(L"HOME").missing_or_empty()) { const env_var_t unam = env_get_string(L"USER"); char *unam_narrow = wcs2str(unam.c_str()); - struct passwd *pw = getpwnam(unam_narrow); - if (pw == NULL) { + struct passwd userinfo; + struct passwd *result; + char buf[8192]; + int retval = getpwnam_r(unam_narrow, &userinfo, buf, sizeof(buf), &result); + if (retval || !result) { // Maybe USER is set but it's bogus. Reset USER from the db and try again. setup_user(true); const env_var_t unam = env_get_string(L"USER"); unam_narrow = wcs2str(unam.c_str()); - pw = getpwnam(unam_narrow); + retval = getpwnam_r(unam_narrow, &userinfo, buf, sizeof(buf), &result); } - if (pw && pw->pw_dir) { - const wcstring dir = str2wcstring(pw->pw_dir); + if (!retval && result && userinfo.pw_dir) { + const wcstring dir = str2wcstring(userinfo.pw_dir); env_set(L"HOME", dir.c_str(), ENV_GLOBAL | ENV_EXPORT); } free(unam_narrow); diff --git a/src/expand.cpp b/src/expand.cpp index 1c60d506c..74e0f8008 100644 --- a/src/expand.cpp +++ b/src/expand.cpp @@ -1178,11 +1178,14 @@ static void expand_home_directory(wcstring &input) { } else { // Some other users home directory. std::string name_cstr = wcs2string(username); - struct passwd *userinfo = getpwnam(name_cstr.c_str()); - if (userinfo == NULL) { + struct passwd userinfo; + struct passwd *result; + char buf[8192]; + int retval = getpwnam_r(name_cstr.c_str(), &userinfo, buf, sizeof(buf), &result); + if (retval || !result) { tilde_error = true; } else { - home = str2wcstring(userinfo->pw_dir); + home = str2wcstring(userinfo.pw_dir); } }