pwd/unix.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
use libc::{c_char, endpwent, getpwent, getpwnam, getpwuid, getuid, passwd, setpwent};
use std::ffi::{CStr, CString};
use crate::errors::{PwdError, Result};
/// The main struct for the library, a safe version
/// of the POSIX `struct passwd`
///
/// There are 2 ways to construct a `Passwd` instance (other
/// than assigning fields by hand). You can look up a user account
/// by username with `Passwd::from_name(String)`, or by uid with
/// `Passwd::from_uid(u32)`.
///
/// There is a shortcut function, `Passwd::current_user()`, which is just
/// short for `Passwd::from_uid(unsafe { libc::getuid() } as u32)`.
#[derive(Debug, Clone, PartialEq)]
pub struct Passwd {
pub name: String,
pub passwd: Option<String>,
pub uid: u32,
pub gid: u32,
pub gecos: Option<String>,
pub dir: String,
pub shell: String,
}
// has to be public so it can be used, but we don't want people actually using it directly
#[derive(Debug, Clone, PartialEq)]
#[doc(hidden)]
pub struct PasswdIter {
inited: bool,
}
impl PasswdIter {
fn new() -> PasswdIter {
PasswdIter { inited: false }
}
}
impl Iterator for PasswdIter {
type Item = Passwd;
fn next(&mut self) -> Option<Self::Item> {
if !self.inited {
unsafe {
setpwent();
};
self.inited = true;
}
let next = unsafe { getpwent() };
if next.is_null() {
unsafe {
endpwent();
};
return None;
}
if let Ok(passwd) = Passwd::from_unsafe(next) {
Some(passwd)
} else {
None
}
}
}
fn cstr_to_string(cstr: *const c_char) -> Result<String> {
let cstr = unsafe { CStr::from_ptr(cstr) };
Ok(cstr
.to_str()
.map_err(|e| PwdError::StringConvError(format!("{:?}", e)))?
.to_string())
}
impl Passwd {
fn from_unsafe(pwd: *mut passwd) -> Result<Passwd> {
if pwd.is_null() {
return Err(PwdError::NullPtr);
}
// take ownership, since this shouldn't be null if we get here
let pwd = unsafe { *pwd };
let password = if pwd.pw_passwd.is_null() {
None
} else {
Some(cstr_to_string(pwd.pw_passwd)?)
};
let gecos = if pwd.pw_gecos.is_null() {
None
} else {
Some(cstr_to_string(pwd.pw_gecos)?)
};
Ok(Passwd {
name: cstr_to_string(pwd.pw_name)?,
passwd: password,
uid: pwd.pw_uid as u32,
gid: pwd.pw_gid as u32,
gecos,
dir: cstr_to_string(pwd.pw_dir)?,
shell: cstr_to_string(pwd.pw_shell)?,
})
}
/// Looks up the username and returns a Passwd with the user's values, if the user is found
///
/// This is `Result<Option<>>` because the operation to convert a rust String to a cstring could fail
///
/// # Example
///
/// ```rust
/// # extern crate pwd;
/// # use pwd::Result;
/// use pwd::Passwd;
///
/// # fn run() -> Result<()> {
/// let pwd = Passwd::from_name("bob")?;
///
/// if let Some(passwd) = pwd {
/// println!("uid is {}", passwd.uid);
/// }
/// # Ok(())
/// # }
/// #
/// # fn main() {
/// # if let Err(_) = run() {
/// # eprintln!("error running example");
/// # }
/// # }
/// ```
pub fn from_name(name: &str) -> Result<Option<Passwd>> {
let cname =
CString::new(name).map_err(|e| PwdError::StringConvError(format!("{:?}", e)))?;
let pwd = unsafe { getpwnam(cname.as_ptr()) };
if pwd.is_null() {
Ok(None)
} else {
Ok(Some(Passwd::from_unsafe(pwd)?))
}
}
/// Looks up the uid and returns a Passwd with the user's values, if the user is found
///
/// # Example
///
/// ```rust
/// # extern crate pwd;
/// # extern crate libc;
/// # use pwd::Result;
/// use libc::getuid;
/// use pwd::Passwd;
///
/// # fn run() -> Result<()> {
/// let uid = unsafe { getuid() };
/// let pwd = Passwd::from_uid(uid as u32);
///
/// if let Some(passwd) = pwd {
/// println!("username is {}", passwd.name);
/// }
/// # Ok(())
/// # }
/// #
/// # fn main() {
/// # if let Err(_) = run() {
/// # eprintln!("error running example");
/// # }
/// # }
/// ```
pub fn from_uid(uid: u32) -> Option<Passwd> {
let pwd = unsafe { getpwuid(uid) };
Passwd::from_unsafe(pwd).ok()
}
/// Shortcut for `Passwd::from_uid(libc::getuid() as u32)`, so see the docs for that constructor
///
/// # Example
///
/// ```rust
/// # extern crate pwd;
/// # use pwd::Result;
/// use pwd::Passwd;
///
/// # fn run() -> Result<()> {
/// let pwd = Passwd::current_user();
///
/// if let Some(passwd) = pwd {
/// println!("username is {}", passwd.name);
/// }
/// # Ok(())
/// # }
/// #
/// # fn main() {
/// # if let Err(_) = run() {
/// # eprintln!("error running example");
/// # }
/// # }
/// ```
pub fn current_user() -> Option<Passwd> {
let uid = unsafe { getuid() };
Passwd::from_uid(uid as u32)
}
/// Returns an iterator over all entries in the /etc/passwd file
///
/// # Example
///
/// ```rust
/// # extern crate pwd;
/// # use pwd::Result;
/// use pwd::Passwd;
///
/// # fn run() -> Result<()> {
/// let passwds = Passwd::iter();
///
/// for passwd in passwds {
/// println!("username is {}", passwd.name);
/// }
/// # Ok(())
/// # }
/// #
/// # fn main() {
/// # if let Err(_) = run() {
/// # eprintln!("error running example");
/// # }
/// # }
/// ```
pub fn iter() -> PasswdIter {
PasswdIter::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::u32;
#[test]
fn test_null_pwd_from_uid() {
let should_be_none = Passwd::from_uid(u32::MAX);
assert_eq!(should_be_none, None);
}
}