fritz_core/diagnose/
network.rs1use std::collections::BTreeSet;
6use std::io;
7use std::net::{IpAddr, SocketAddr};
8use std::time::Duration;
9
10use serde::Serialize;
11
12pub const PROBE_TIMEOUT: Duration = Duration::from_secs(1);
14
15pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(5);
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "lowercase")]
21pub enum Port {
22 Open,
24 Closed,
26 Filtered,
28}
29
30pub trait Network {
32 fn resolve(&self, name: &str) -> impl Future<Output = io::Result<Vec<IpAddr>>> + Send;
34
35 fn connect(&self, address: SocketAddr) -> impl Future<Output = Port> + Send;
37}
38
39#[derive(Debug, Clone, Copy)]
41pub struct System {
42 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
70fn 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#[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#[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}