arks_server/daemon/
platform.rs1use std::net::ToSocketAddrs;
11use std::path::PathBuf;
12
13#[derive(Debug, Clone, PartialEq, Eq, Default)]
15pub struct HostInfo {
16 pub canonical: String,
18 pub ip: String,
20}
21
22pub trait DaemonPlatform: Send + Sync {
24 fn home_dir(&self, user: &str) -> Option<PathBuf>;
26 fn lookup_host(&self, host: &str) -> Option<HostInfo>;
28}
29
30#[derive(Debug, Clone, Copy, Default)]
32pub struct StdPlatform;
33
34impl DaemonPlatform for StdPlatform {
35 fn home_dir(&self, user: &str) -> Option<PathBuf> {
36 if cfg!(windows) {
37 return None;
39 }
40 let text = std::fs::read_to_string("/etc/passwd").ok()?;
41 passwd_home(&text, user)
42 }
43
44 fn lookup_host(&self, host: &str) -> Option<HostInfo> {
45 if host.is_empty() {
46 return None;
47 }
48 let addr = (host, 0u16).to_socket_addrs().ok()?.next()?;
49 Some(HostInfo {
50 canonical: host.to_string(),
51 ip: addr.ip().to_string(),
52 })
53 }
54}
55
56pub(super) fn passwd_home(text: &str, user: &str) -> Option<PathBuf> {
58 text.lines().find_map(|line| {
59 let fields: Vec<&str> = line.split(':').collect();
60 (fields.len() >= 7 && fields[0] == user).then(|| PathBuf::from(fields[5]))
61 })
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 #[test]
69 fn passwd_home_reads_sixth_field() {
70 let text = "root:x:0:0:root:/root:/bin/sh\nalice:x:1000:1000::/srv/users/alice:/bin/sh\n";
71 assert_eq!(
72 passwd_home(text, "alice"),
73 Some(PathBuf::from("/srv/users/alice"))
74 );
75 assert_eq!(passwd_home(text, "bob"), None);
76 }
77
78 #[test]
79 fn std_lookup_resolves_numeric_hosts() {
80 let info = StdPlatform.lookup_host("127.0.0.1").unwrap();
81 assert_eq!(info.ip, "127.0.0.1");
82 assert!(StdPlatform.lookup_host("").is_none());
83 }
84}