From 4d38456cab60843d212a62af7066ceac7bc6011e Mon Sep 17 00:00:00 2001 From: WATANABE Yuki Date: Sun, 11 Sep 2022 23:01:08 +0900 Subject: Handle unacceptable name gracefully in {User,Group}::from_name Calling `unwrap` on the result of `CString::new` may cause the current thread to panic, which is a bit surprising undocumented behavior. It would be more reasonable to treat the erroneous name as a non-existing user or group. --- src/unistd.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'src/unistd.rs') diff --git a/src/unistd.rs b/src/unistd.rs index 02fe4ff6..63795cac 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -3143,7 +3143,10 @@ impl User { /// assert_eq!(res.name, "root"); /// ``` pub fn from_name(name: &str) -> Result> { - let name = CString::new(name).unwrap(); + let name = match CString::new(name) { + Ok(c_str) => c_str, + Err(_nul_error) => return Ok(None), + }; User::from_anything(|pwd, cbuf, cap, res| { unsafe { libc::getpwnam_r(name.as_ptr(), pwd, cbuf, cap, res) } }) @@ -3268,7 +3271,10 @@ impl Group { /// assert!(res.name == "root"); /// ``` pub fn from_name(name: &str) -> Result> { - let name = CString::new(name).unwrap(); + let name = match CString::new(name) { + Ok(c_str) => c_str, + Err(_nul_error) => return Ok(None), + }; Group::from_anything(|grp, cbuf, cap, res| { unsafe { libc::getgrnam_r(name.as_ptr(), grp, cbuf, cap, res) } }) -- cgit v1.2.3