Skip to content

home: Handle empty HOME on unix #12023

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions crates/home/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,8 @@ readme = "README.md"
repository = "https://github.com/rust-lang/cargo"
description = "Shared definitions of home directories."

[target.'cfg(unix)'.dependencies]
libc = "0.2"

[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.48.0", features = ["Win32_Foundation", "Win32_UI_Shell"] }
15 changes: 10 additions & 5 deletions crates/home/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
//! incorrect because it considers the `HOME` environment variable on
//! Windows. This causes surprising situations where a Rust program
//! will behave differently depending on whether it is run under a
//! Unix emulation environment like Cygwin or MinGW. Neither Cargo nor
//! rustup use the standard libraries definition - they use the
//! definition here.
//! Unix emulation environment like Cygwin or MinGW. Additionally, on Unix,
//! if the `HOME` environment variable is set but empty, an empty path is
//! returned. Neither Cargo nor rustup use the standard libraries definition
//! - they use the definition here.
//!
//! This crate further provides two functions, `cargo_home` and
//! `rustup_home`, which are the canonical way to determine the
Expand All @@ -30,7 +31,9 @@

pub mod env;

#[cfg(target_os = "windows")]
#[cfg(unix)]
mod unix;
#[cfg(windows)]
mod windows;

use std::io;
Expand Down Expand Up @@ -65,10 +68,12 @@ pub fn home_dir() -> Option<PathBuf> {
env::home_dir_with_env(&env::OS_ENV)
}

#[cfg(unix)]
use unix::home_dir_inner;
#[cfg(windows)]
use windows::home_dir_inner;

#[cfg(any(unix, target_os = "redox"))]
#[cfg(target_os = "redox")]
fn home_dir_inner() -> Option<PathBuf> {
#[allow(deprecated)]
std::env::home_dir()
Expand Down
92 changes: 92 additions & 0 deletions crates/home/src/unix.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
use std::env;
use std::ffi::{CStr, OsString};
use std::mem;
use std::os::unix::prelude::OsStringExt;
use std::path::PathBuf;
use std::ptr;

pub fn home_dir_inner() -> Option<PathBuf> {
return env::var_os("HOME")
.filter(|s| !s.is_empty())
.or_else(|| unsafe { fallback() })
.map(PathBuf::from);

#[cfg(any(
target_os = "android",
target_os = "ios",
target_os = "watchos",
target_os = "emscripten",
target_os = "redox",
target_os = "vxworks",
target_os = "espidf",
target_os = "horizon"
))]
unsafe fn fallback() -> Option<OsString> {
None
}
#[cfg(not(any(
target_os = "android",
target_os = "ios",
target_os = "watchos",
target_os = "emscripten",
target_os = "redox",
target_os = "vxworks",
target_os = "espidf",
target_os = "horizon"
)))]
unsafe fn fallback() -> Option<OsString> {
let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
n if n < 0 => 512_usize,
n => n as usize,
};
let mut buf = Vec::with_capacity(amt);
let mut passwd: libc::passwd = mem::zeroed();
let mut result = ptr::null_mut();
match libc::getpwuid_r(
libc::getuid(),
&mut passwd,
buf.as_mut_ptr(),
buf.capacity(),
&mut result,
) {
0 if !result.is_null() => {
let ptr = passwd.pw_dir as *const _;
let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
Some(OsStringExt::from_vec(bytes))
}
_ => None,
}
}
}

#[cfg(not(any(
target_os = "android",
target_os = "ios",
target_os = "watchos",
target_os = "emscripten",
target_os = "redox",
target_os = "vxworks",
target_os = "espidf",
target_os = "horizon"
)))]
#[cfg(test)]
mod tests {
use super::home_dir_inner;
use std::env;
use std::path::{Path, PathBuf};

#[test]
fn test_with_without() {
let oldhome: Option<PathBuf> = Some(env::var_os("HOME").unwrap().into());
env::remove_var("HOME");
assert_eq!(home_dir_inner(), oldhome);

let home = Path::new("");
env::set_var("HOME", home.as_os_str());
assert_eq!(home_dir_inner(), oldhome);

let home = Path::new("/home/foobarbaz");
env::set_var("HOME", home.as_os_str());
assert_eq!(home_dir_inner().as_deref(), Some(home));
}
}
2 changes: 1 addition & 1 deletion crates/home/src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ mod tests {

assert_eq!(home_dir_inner(), Some(PathBuf::from(olduserprofile)));

let home = Path::new(r"C:\Users\foo tar baz");
let home = Path::new(r"C:\Users\foo bar baz");

env::set_var("HOME", home.as_os_str());
assert_ne!(home_dir_inner().as_ref().map(Deref::deref), Some(home));
Expand Down