Skip to main content

arks_server/daemon/
platform.rs

1//! OS lookups the daemon needs: `~user` home directories (`--user-path`) and
2//! client host names (`%CH` / `%IP` for `--interpolated-path` and
3//! `--access-hook`).
4//!
5//! This crate forbids `unsafe`, so the default [`StdPlatform`] uses only the
6//! standard library (`/etc/passwd`, `ToSocketAddrs`); the CLI may inject a
7//! platform backed by `getpwnam(3)` / `getaddrinfo(3)` for NSS and canonical
8//! names.
9
10use std::net::ToSocketAddrs;
11use std::path::PathBuf;
12
13/// Result of resolving the host name a client sent with `host=`.
14#[derive(Debug, Clone, PartialEq, Eq, Default)]
15pub struct HostInfo {
16    /// `%CH`: canonical host name.
17    pub canonical: String,
18    /// `%IP`: first address the name resolves to.
19    pub ip: String,
20}
21
22/// OS services used while resolving a request.
23pub trait DaemonPlatform: Send + Sync {
24    /// Home directory of `user` (`~user` expansion).
25    fn home_dir(&self, user: &str) -> Option<PathBuf>;
26    /// Resolve a client-supplied host name; `None` when it does not resolve.
27    fn lookup_host(&self, host: &str) -> Option<HostInfo>;
28}
29
30/// Standard-library implementation.
31#[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            // No passwd database (matrix SoT §Windows rule 7).
38            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
56/// Home directory of `user` in `passwd(5)` text.
57pub(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}