diff options
author | Aqua-sama <aqua@iserlohn-fortress.net> | 2020-10-11 18:37:39 +0300 |
---|---|---|
committer | Aqua-sama <aqua@iserlohn-fortress.net> | 2020-10-11 18:37:39 +0300 |
commit | b1e25166433ce93403324a96f129712e4fac944d (patch) | |
tree | 3c168076c6699009ebc85fe1ebd3a65970853481 /src/user.rs | |
parent | Make Prompt more const (diff) | |
download | rshell-b1e25166433ce93403324a96f129712e4fac944d.tar.xz |
Properly read username and hostname
username is read by using libc::getuid, and checking /etc/passwd for the
uid and getting the username from there
hostname is read from /proc/sys/kernel/hostname
Diffstat (limited to 'src/user.rs')
-rw-r--r-- | src/user.rs | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/user.rs b/src/user.rs new file mode 100644 index 0000000..fedf12b --- /dev/null +++ b/src/user.rs @@ -0,0 +1,49 @@ +use std::io::BufRead; + +pub fn hostname() -> std::result::Result<std::string::String, std::io::Error> { + let h = std::fs::read_to_string("/proc/sys/kernel/hostname")?; + Ok(h.trim().to_string()) +} + +#[test] +fn test_hostname() { + let hostname__ = match std::process::Command::new("hostname").output() { + Ok(s) => { + let output = std::string::String::from_utf8(s.stdout).unwrap(); + output.trim().to_string() + } + Err(e) => panic!(e), + }; + + assert_eq!(hostname__, hostname().unwrap()); +} + +pub fn username() -> std::result::Result<std::string::String, std::io::Error> { + let uid = unsafe { libc::getuid().to_string() }; + + let file = std::fs::File::open("/etc/passwd")?; + let reader = std::io::BufReader::new(file); + + for line in reader.lines() { + let l = line?; + let parts: Vec<&str> = l.split(':').collect(); + if uid == parts[2] { + return Ok(parts[0].to_string()); + } + } + + Ok(uid) +} + +#[test] +fn test_username() { + let username__ = match std::process::Command::new("whoami").output() { + Ok(s) => { + let output = std::string::String::from_utf8(s.stdout).unwrap(); + output.trim().to_string() + } + Err(e) => panic!(e), + }; + assert_eq!(username__, username().unwrap()); +} + |