Skip to content

Commit 8e167c7

Browse files
bors[bot]magicant
andauthored
Merge #1815
1815: Handle unacceptable name gracefully in {User,Group}::from_name r=asomers a=magicant 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. Co-authored-by: WATANABE Yuki <magicant@wonderwand.net>
2 parents adca7fd + 4d38456 commit 8e167c7

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ This project adheres to [Semantic Versioning](https://semver.org/).
2020

2121
- Fix microsecond calculation for `TimeSpec`.
2222
([#1801](https://github.com/nix-rust/nix/pull/1801))
23+
- Fix `User::from_name` and `Group::from_name` panicking
24+
when given a name containing a nul.
25+
([#1815](https://github.com/nix-rust/nix/pull/1815))
2326

2427
### Removed
2528

src/unistd.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3143,7 +3143,10 @@ impl User {
31433143
/// assert_eq!(res.name, "root");
31443144
/// ```
31453145
pub fn from_name(name: &str) -> Result<Option<Self>> {
3146-
let name = CString::new(name).unwrap();
3146+
let name = match CString::new(name) {
3147+
Ok(c_str) => c_str,
3148+
Err(_nul_error) => return Ok(None),
3149+
};
31473150
User::from_anything(|pwd, cbuf, cap, res| {
31483151
unsafe { libc::getpwnam_r(name.as_ptr(), pwd, cbuf, cap, res) }
31493152
})
@@ -3268,7 +3271,10 @@ impl Group {
32683271
/// assert!(res.name == "root");
32693272
/// ```
32703273
pub fn from_name(name: &str) -> Result<Option<Self>> {
3271-
let name = CString::new(name).unwrap();
3274+
let name = match CString::new(name) {
3275+
Ok(c_str) => c_str,
3276+
Err(_nul_error) => return Ok(None),
3277+
};
32723278
Group::from_anything(|grp, cbuf, cap, res| {
32733279
unsafe { libc::getgrnam_r(name.as_ptr(), grp, cbuf, cap, res) }
32743280
})

0 commit comments

Comments
 (0)