Skip to main content

fritz_core/diagnose/
network.rs

1//! What a diagnosis does from this machine, outside the device: resolve a
2//! name with the resolver of the operating system and connect to a TCP
3//! port. Behind a trait, so that tests use a fake resolver and loopback.
4
5use std::collections::BTreeSet;
6use std::io;
7use std::net::{IpAddr, SocketAddr};
8use std::time::Duration;
9
10use serde::Serialize;
11
12/// How long a TCP connect may take before the port counts as filtered.
13pub const PROBE_TIMEOUT: Duration = Duration::from_secs(1);
14
15/// How long the resolver may take.
16pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(5);
17
18/// The state of a TCP port.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "lowercase")]
21pub enum Port {
22    /// The connection was made.
23    Open,
24    /// The host refused it.
25    Closed,
26    /// No answer in time, or the host cannot be reached.
27    Filtered,
28}
29
30/// The network as this machine sees it.
31pub trait Network {
32    /// The addresses of `name`, by the resolver of the operating system.
33    fn resolve(&self, name: &str) -> impl Future<Output = io::Result<Vec<IpAddr>>> + Send;
34
35    /// Connects to `address` and closes the connection right away.
36    fn connect(&self, address: SocketAddr) -> impl Future<Output = Port> + Send;
37}
38
39/// The network of the operating system.
40#[derive(Debug, Clone, Copy)]
41pub struct System {
42    /// How long a TCP connect may take.
43    pub timeout: Duration,
44}
45
46impl Default for System {
47    fn default() -> Self {
48        Self {
49            timeout: PROBE_TIMEOUT,
50        }
51    }
52}
53
54impl Network for System {
55    async fn resolve(&self, name: &str) -> io::Result<Vec<IpAddr>> {
56        let lookup = tokio::net::lookup_host((name, 0));
57        let found = tokio::time::timeout(RESOLVE_TIMEOUT, lookup).await;
58        let found = found.unwrap_or_else(|_| Err(io::ErrorKind::TimedOut.into()))?;
59        let addresses: BTreeSet<IpAddr> = found.map(|a| a.ip()).collect();
60        Ok(addresses.into_iter().collect())
61    }
62
63    async fn connect(&self, address: SocketAddr) -> Port {
64        let connect = tokio::net::TcpStream::connect(address);
65        let result = tokio::time::timeout(self.timeout, connect).await.ok();
66        state(result.map(|r| r.map(drop)))
67    }
68}
69
70/// The state of a port after a connect, `None` if it timed out.
71fn state(result: Option<io::Result<()>>) -> Port {
72    match result {
73        Some(Ok(())) => Port::Open,
74        Some(Err(e)) if e.kind() == io::ErrorKind::ConnectionRefused => Port::Closed,
75        _ => Port::Filtered,
76    }
77}
78
79/// A network with fixed answers, for tests: the names resolve to their
80/// addresses, others not at all; the ports have their states, others are
81/// filtered.
82#[derive(Debug, Clone, Default)]
83pub struct Fixed {
84    pub names: Vec<(String, Vec<IpAddr>)>,
85    pub ports: Vec<(SocketAddr, Port)>,
86}
87
88impl Network for Fixed {
89    fn resolve(&self, name: &str) -> impl Future<Output = io::Result<Vec<IpAddr>>> + Send {
90        let found = self
91            .names
92            .iter()
93            .find(|(n, _)| n == name)
94            .map(|(_, addresses)| addresses.clone())
95            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "unknown name"));
96        std::future::ready(found)
97    }
98
99    fn connect(&self, address: SocketAddr) -> impl Future<Output = Port> + Send {
100        let port = self
101            .ports
102            .iter()
103            .find(|(a, _)| *a == address)
104            .map_or(Port::Filtered, |(_, port)| *port);
105        std::future::ready(port)
106    }
107}
108
109/// Whether an address is only used inside a home network or on this
110/// machine: private, link-local or loopback, and unique local for IPv6.
111#[must_use]
112pub fn is_private(address: IpAddr) -> bool {
113    match address {
114        IpAddr::V4(v4) => v4.is_private() || v4.is_link_local() || v4.is_loopback(),
115        IpAddr::V6(v6) => {
116            let first = v6.segments()[0];
117            v6.is_loopback() || (first & 0xFE00) == 0xFC00 || (first & 0xFFC0) == 0xFE80
118        }
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn knows_private_addresses() {
128        for private in [
129            "192.168.178.1",
130            "10.0.0.1",
131            "169.254.1.1",
132            "127.0.0.1",
133            "fd00::1",
134            "fe80::1",
135            "::1",
136        ] {
137            assert!(is_private(private.parse().unwrap()), "{private}");
138        }
139        for public in ["192.0.2.1", "8.8.8.8", "2001:db8::1"] {
140            assert!(!is_private(public.parse().unwrap()), "{public}");
141        }
142    }
143
144    #[tokio::test]
145    async fn probes_ports_on_loopback() {
146        let system = System::default();
147        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
148        let open = listener.local_addr().unwrap();
149        assert_eq!(system.connect(open).await, Port::Open);
150        drop(listener);
151        assert_eq!(system.connect(open).await, Port::Closed);
152        assert_eq!(state(None), Port::Filtered);
153        let unreachable = io::Error::from(io::ErrorKind::HostUnreachable);
154        assert_eq!(state(Some(Err(unreachable))), Port::Filtered);
155    }
156
157    #[tokio::test]
158    async fn resolves_names() {
159        let system = System::default();
160        let addresses = system.resolve("localhost").await.unwrap();
161        assert!(addresses.iter().all(IpAddr::is_loopback), "{addresses:?}");
162        assert_ne!(addresses, Vec::<IpAddr>::new());
163    }
164}