//! Networks: canonical CIDRs, host networks, overlap, and what `internet` means. use ipnet::IpNet; use std::fmt; use std::net::IpAddr; use std::str::FromStr; /// A canonical network (host bits zero), serialised as its text in every format. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Net(IpNet); impl Net { /// Parses `a.b.c.d/n` or `x::/n`; `Err(true)` when it parses but has host bits set. pub fn parse_canonical(s: &str) -> Result { let n = IpNet::from_str(s).map_err(|_| false)?; if n.trunc() != n || n.to_string() != s { return Err(true); } Ok(Net(n)) } /// The `/32` or `/128` of one address. pub fn host(addr: IpAddr) -> Net { Net(IpNet::from(addr)) } pub fn v4_default() -> Net { Net(IpNet::from_str("0.0.0.0/0").expect("literal")) } pub fn v6_default() -> Net { Net(IpNet::from_str("::/0").expect("literal")) } pub fn inner(&self) -> IpNet { self.0 } pub fn prefix_len(&self) -> u8 { self.0.prefix_len() } pub fn contains(&self, other: &Net) -> bool { self.0.contains(&other.0) } pub fn contains_addr(&self, addr: &IpAddr) -> bool { self.0.contains(addr) } pub fn overlaps(&self, other: &Net) -> bool { self.contains(other) || other.contains(self) } /// Whether any part of this network is on the internet: it is not wholly inside one of [`NOT_INTERNET`]. pub fn reaches_internet(&self) -> bool { !NOT_INTERNET .iter() .any(|s| Net::parse_canonical(s).expect("literal").contains(self)) } /// An IPv6 network that carries IPv4 addresses inside it (mapped, compatible, NAT64, 6to4). Refused /// everywhere: write the IPv4 network, so the two families are never compared apart (QA R-07). pub fn embeds_ipv4(&self) -> bool { matches!(self.0, IpNet::V6(_)) && EMBEDS_IPV4 .iter() .any(|s| Net::parse_canonical(s).expect("literal").contains(self)) } /// Loopback, link-local (cloud metadata lives there), multicast, broadcast and "this network": never a /// place to reach or route (QA R-08). pub fn is_special(&self) -> bool { SPECIAL .iter() .any(|s| self.overlaps(&Net::parse_canonical(s).expect("literal"))) } } const EMBEDS_IPV4: &[&str] = &[ "::/96", "::ffff:0.0.0.0/96", "64:ff9b::/96", "64:ff9b:1::/48", "2002::/16", ]; const SPECIAL: &[&str] = &[ "0.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16", "224.0.0.0/4", "240.0.0.0/4", "::1/128", "fe80::/10", "ff00::/8", ]; /// What `internet` excludes (docs/FORMATS.md, "The plan"). pub const NOT_INTERNET: &[&str] = &[ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "::1/128", "fc00::/7", "fe80::/10", ]; impl fmt::Display for Net { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl fmt::Debug for Net { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Net({})", self.0) } } impl serde::Serialize for Net { fn serialize(&self, s: S) -> Result { s.collect_str(&self.0) } } impl<'de> serde::Deserialize<'de> for Net { fn deserialize>(d: D) -> Result { let s = String::deserialize(d)?; Net::parse_canonical(&s) .map_err(|_| serde::de::Error::custom(format!("`{s}` is not a canonical network"))) } } /// A mesh address, serialised as text in every format. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub struct Addr(pub IpAddr); impl fmt::Display for Addr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl serde::Serialize for Addr { fn serialize(&self, s: S) -> Result { s.collect_str(&self.0) } } impl<'de> serde::Deserialize<'de> for Addr { fn deserialize>(d: D) -> Result { let s = String::deserialize(d)?; match s.parse::() { Ok(a) if a.to_string() == s => Ok(Addr(a)), _ => Err(serde::de::Error::custom(format!( "`{s}` is not an IP address in its usual form" ))), } } } #[cfg(test)] mod tests { use super::*; #[test] fn canonical_networks() { assert!(Net::parse_canonical("192.168.100.0/24").is_ok()); assert_eq!(Net::parse_canonical("192.168.100.7/24"), Err(true)); assert_eq!( Net::parse_canonical("fd00:0::/64"), Err(true), "not the usual text form" ); assert!(Net::parse_canonical("fd00::/64").is_ok()); assert_eq!(Net::parse_canonical("192.168.100.0"), Err(false)); assert_eq!(Net::parse_canonical("nonsense"), Err(false)); } #[test] fn internet() { assert!( Net::parse_canonical("8.8.8.0/24") .unwrap() .reaches_internet() ); assert!(Net::v4_default().reaches_internet()); assert!( !Net::parse_canonical("192.168.100.0/24") .unwrap() .reaches_internet() ); assert!( !Net::parse_canonical("100.96.0.0/16") .unwrap() .reaches_internet() ); } #[test] fn embedded_ipv4_and_special_ranges() { let n = |s: &str| Net::parse_canonical(s).unwrap(); assert!(n("::ffff:10.0.0.0/120").embeds_ipv4()); assert!(n("64:ff9b::/96").embeds_ipv4()); assert!(n("2002::/16").embeds_ipv4()); assert!(n("::1/128").embeds_ipv4()); assert!(!n("2000::/3").embeds_ipv4()); assert!(!n("::/0").embeds_ipv4()); assert!(!n("fd00::/64").embeds_ipv4()); for s in [ "127.0.0.0/8", "169.254.169.254/32", "224.0.0.0/4", "255.255.255.255/32", "fe80::/10", "ff02::1/128", "0.0.0.0/1", ] { assert!(n(s).is_special(), "{s}"); } assert!(!n("192.168.100.0/24").is_special()); } }