1use std::net::IpAddr;
10
11use serde::{Deserialize, Serialize};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
15#[serde(rename_all = "kebab-case")]
16#[non_exhaustive]
17pub enum AddrClass {
18 Loopback,
19 LinkLocal,
21 Private,
23 Cgnat,
25 Public,
26}
27
28impl AddrClass {
29 pub fn of(ip: IpAddr) -> Self {
30 match ip {
31 IpAddr::V4(v4) => {
32 let o = v4.octets();
33 if v4.is_loopback() {
34 Self::Loopback
35 } else if v4.is_link_local() {
36 Self::LinkLocal
37 } else if v4.is_private() {
38 Self::Private
39 } else if o[0] == 100 && (o[1] & 0xc0) == 64 {
40 Self::Cgnat
41 } else {
42 Self::Public
43 }
44 }
45 IpAddr::V6(v6) => {
46 if let Some(v4) = v6.to_ipv4_mapped() {
47 return Self::of(IpAddr::V4(v4));
48 }
49 let s = v6.segments();
50 if v6.is_loopback() {
51 Self::Loopback
52 } else if (s[0] & 0xffc0) == 0xfe80 {
53 Self::LinkLocal
54 } else if (s[0] & 0xfe00) == 0xfc00 {
55 Self::Private
56 } else {
57 Self::Public
58 }
59 }
60 }
61 }
62
63 pub fn advertised(self) -> bool {
65 matches!(self, Self::Loopback | Self::LinkLocal | Self::Private)
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
71#[non_exhaustive]
72pub struct LinkMeasure {
73 pub peer: String,
74 pub gbps: f32,
75 pub rtt_us: u32,
76 pub at_ms: i64,
77}
78
79impl LinkMeasure {
80 pub fn new(peer: impl Into<String>, gbps: f32, rtt_us: u32, at_ms: i64) -> Self {
81 Self { peer: peer.into(), gbps, rtt_us, at_ms }
82 }
83}
84
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87#[non_exhaustive]
88pub struct LinkInfo {
89 pub addr: String,
91 pub class: AddrClass,
92 #[serde(default)]
93 pub iface: Option<String>,
94 #[serde(default)]
96 pub nominal_gbps: Option<f32>,
97 #[serde(default)]
99 pub declared_gbps: Option<f32>,
100 #[serde(default)]
101 pub measured: Vec<LinkMeasure>,
102}
103
104impl LinkInfo {
105 pub fn new(addr: IpAddr) -> Self {
107 Self { addr: addr.to_string(), class: AddrClass::of(addr), iface: None, nominal_gbps: None, declared_gbps: None, measured: Vec::new() }
108 }
109
110 pub fn with_iface(mut self, iface: impl Into<String>) -> Self {
111 self.iface = Some(iface.into());
112 self
113 }
114
115 pub fn with_nominal_gbps(mut self, gbps: Option<f32>) -> Self {
116 self.nominal_gbps = gbps;
117 self
118 }
119
120 pub fn with_declared_gbps(mut self, gbps: Option<f32>) -> Self {
121 self.declared_gbps = gbps;
122 self
123 }
124
125 pub fn best_gbps(&self) -> Option<f32> {
127 self.measured.iter().map(|m| m.gbps).reduce(f32::max).or(self.declared_gbps).or(self.nominal_gbps)
128 }
129}
130
131pub fn advertised(links: impl IntoIterator<Item = LinkInfo>) -> Vec<LinkInfo> {
133 links
134 .into_iter()
135 .filter(|l| l.class.advertised() && l.addr.parse::<IpAddr>().is_ok_and(|ip| AddrClass::of(ip) == l.class))
136 .take(MAX_LINKS)
137 .collect()
138}
139
140pub const MAX_LINKS: usize = 16;
142
143pub fn local_links() -> Vec<LinkInfo> {
146 let mut out: Vec<LinkInfo> = interfaces()
147 .into_iter()
148 .filter(|(_, ip)| AddrClass::of(*ip).advertised() && !ip.is_loopback())
149 .map(|(iface, ip)| {
150 let speed = nominal_gbps(&iface);
151 LinkInfo::new(ip).with_iface(iface).with_nominal_gbps(speed)
152 })
153 .collect();
154 out.sort_by(|a, b| (&a.iface, &a.addr).cmp(&(&b.iface, &b.addr)));
155 out.dedup_by(|a, b| a.addr == b.addr);
156 out.truncate(MAX_LINKS);
157 out
158}
159
160#[cfg(target_os = "linux")]
161fn nominal_gbps(iface: &str) -> Option<f32> {
162 if iface.contains('/') || iface.contains("..") {
163 return None;
164 }
165 let mbps: i64 = std::fs::read_to_string(format!("/sys/class/net/{iface}/speed")).ok()?.trim().parse().ok()?;
166 (mbps > 0).then(|| mbps as f32 / 1000.0)
167}
168
169#[cfg(not(target_os = "linux"))]
170fn nominal_gbps(_iface: &str) -> Option<f32> {
171 None
172}
173
174#[cfg(unix)]
175fn interfaces() -> Vec<(String, IpAddr)> {
176 use std::ffi::CStr;
177 use std::net::{Ipv4Addr, Ipv6Addr};
178 let mut out = Vec::new();
179 let mut head: *mut libc::ifaddrs = std::ptr::null_mut();
180 if unsafe { libc::getifaddrs(&mut head) } != 0 {
182 return out;
183 }
184 let mut cur = head;
185 while !cur.is_null() {
186 let ifa = unsafe { &*cur };
188 cur = ifa.ifa_next;
189 if ifa.ifa_addr.is_null() || ifa.ifa_name.is_null() {
190 continue;
191 }
192 let name = unsafe { CStr::from_ptr(ifa.ifa_name) }.to_string_lossy().into_owned();
194 let ip = match i32::from(unsafe { (*ifa.ifa_addr).sa_family }) {
196 libc::AF_INET => {
197 let sa = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in) };
198 IpAddr::V4(Ipv4Addr::from(u32::from_be(sa.sin_addr.s_addr)))
199 }
200 libc::AF_INET6 => {
201 let sa = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in6) };
202 IpAddr::V6(Ipv6Addr::from(sa.sin6_addr.s6_addr))
203 }
204 _ => continue,
205 };
206 out.push((name, ip));
207 }
208 unsafe { libc::freeifaddrs(head) };
210 out
211}
212
213#[cfg(not(unix))]
214fn interfaces() -> Vec<(String, IpAddr)> {
215 Vec::new()
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 fn ip(s: &str) -> IpAddr {
223 s.parse().unwrap()
224 }
225
226 #[test]
227 fn addresses_are_classed_and_only_private_ones_advertised() {
228 for (a, c) in [
229 ("127.0.0.1", AddrClass::Loopback),
230 ("::1", AddrClass::Loopback),
231 ("169.254.3.4", AddrClass::LinkLocal),
232 ("fe80::1", AddrClass::LinkLocal),
233 ("10.0.0.2", AddrClass::Private),
234 ("172.16.5.5", AddrClass::Private),
235 ("192.168.1.5", AddrClass::Private),
236 ("fd12:3456::1", AddrClass::Private),
237 ("::ffff:192.168.1.5", AddrClass::Private),
238 ("100.64.0.1", AddrClass::Cgnat),
239 ("100.127.255.1", AddrClass::Cgnat),
240 ("100.128.0.1", AddrClass::Public),
241 ("8.8.8.8", AddrClass::Public),
242 ("2001:db8::1", AddrClass::Public),
243 ] {
244 assert_eq!(AddrClass::of(ip(a)), c, "{a}");
245 }
246 let links = vec![LinkInfo::new(ip("10.0.0.2")), LinkInfo::new(ip("8.8.8.8")), LinkInfo::new(ip("100.100.1.1")), LinkInfo::new(ip("fe80::1"))];
247 let kept: Vec<_> = advertised(links).into_iter().map(|l| l.addr).collect();
248 assert_eq!(kept, ["10.0.0.2", "fe80::1"]);
249 let mut forged = LinkInfo::new(ip("8.8.8.8"));
251 forged.class = AddrClass::Private;
252 assert!(advertised([forged]).is_empty());
253 }
254
255 #[test]
256 fn measured_beats_declared_beats_nominal() {
257 let mut l = LinkInfo::new(ip("10.0.0.2")).with_nominal_gbps(Some(10.0));
258 assert_eq!(l.best_gbps(), Some(10.0));
259 l = l.with_declared_gbps(Some(25.0));
260 assert_eq!(l.best_gbps(), Some(25.0));
261 l.measured.push(LinkMeasure::new("p", 18.5, 40, 1));
262 assert_eq!(l.best_gbps(), Some(18.5));
263 }
264
265 #[test]
266 fn local_links_are_never_public() {
267 for l in local_links() {
268 assert!(l.class.advertised() && l.class != AddrClass::Loopback, "{l:?}");
269 }
270 }
271}