use std::fmt;
use std::net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6};
use std::str::FromStr;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Zone {
index: Option<u32>,
name: Arc<str>,
}
impl Zone {
pub fn new(index: u32, name: impl Into<Arc<str>>) -> Self {
Self {
index: Some(index),
name: name.into(),
}
}
pub fn unresolved(name: impl Into<Arc<str>>) -> Self {
Self {
index: None,
name: name.into(),
}
}
pub fn index(&self) -> Option<u32> {
self.index
}
pub fn name(&self) -> &str {
&self.name
}
fn identity(&self) -> (Option<u32>, Option<&str>) {
match self.index {
Some(index) => (Some(index), None),
None => (None, Some(&*self.name)),
}
}
}
impl PartialEq for Zone {
fn eq(&self, other: &Self) -> bool {
self.identity() == other.identity()
}
}
impl Eq for Zone {}
impl std::hash::Hash for Zone {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.identity().hash(state);
}
}
impl PartialOrd for Zone {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Zone {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.identity().cmp(&other.identity())
}
}
impl fmt::Display for Zone {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.name)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ScopedIp {
addr: IpAddr,
zone: Option<Zone>,
}
impl ScopedIp {
pub fn unscoped(addr: IpAddr) -> Self {
Self { addr, zone: None }
}
pub fn scoped(addr: IpAddr, zone: Zone) -> Self {
Self {
addr,
zone: Self::needs_zone(&addr).then_some(zone),
}
}
pub fn needs_zone(addr: &IpAddr) -> bool {
matches!(addr, IpAddr::V6(v6) if v6.is_unicast_link_local())
}
pub fn addr(&self) -> IpAddr {
self.addr
}
pub fn zone(&self) -> Option<&Zone> {
self.zone.as_ref()
}
pub fn is_unusable(&self) -> bool {
Self::needs_zone(&self.addr) && self.zone.as_ref().and_then(Zone::index).is_none()
}
pub fn to_socket_addr(&self, port: u16) -> Option<SocketAddr> {
if self.is_unusable() {
return None;
}
match (self.addr, self.zone.as_ref().and_then(Zone::index)) {
(IpAddr::V6(v6), Some(scope_id)) => {
Some(SocketAddr::V6(SocketAddrV6::new(v6, port, 0, scope_id)))
}
(addr, _) => Some(SocketAddr::new(addr, port)),
}
}
}
impl From<IpAddr> for ScopedIp {
fn from(addr: IpAddr) -> Self {
Self::unscoped(addr)
}
}
impl fmt::Display for ScopedIp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.zone {
Some(zone) => write!(f, "{}%{}", self.addr, zone),
None => self.addr.fmt(f),
}
}
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ScopedIpError {
#[error("not an IP address: {0}")]
NotAnAddress(String),
#[error("{0} is not a link-local address, so `%{1}` means nothing")]
ZoneOnUnscopedAddress(IpAddr, String),
#[error("`%` with no interface after it")]
EmptyZone,
}
impl FromStr for ScopedIp {
type Err = ScopedIpError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let Some((addr, zone)) = s.split_once('%') else {
return s
.parse::<IpAddr>()
.map(Self::unscoped)
.map_err(|_| ScopedIpError::NotAnAddress(s.to_string()));
};
if zone.is_empty() {
return Err(ScopedIpError::EmptyZone);
}
let addr: IpAddr = addr
.parse()
.map_err(|_| ScopedIpError::NotAnAddress(s.to_string()))?;
if !Self::needs_zone(&addr) {
return Err(ScopedIpError::ZoneOnUnscopedAddress(addr, zone.to_string()));
}
Ok(Self {
addr,
zone: Some(Zone::unresolved(zone)),
})
}
}
impl Default for ScopedIp {
fn default() -> Self {
Self::unscoped(IpAddr::V6(Ipv6Addr::UNSPECIFIED))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::Ipv4Addr;
fn link_local() -> IpAddr {
IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1))
}
fn global() -> IpAddr {
IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1))
}
fn en0() -> Zone {
Zone::new(4, "en0")
}
fn en1() -> Zone {
Zone::new(5, "en1")
}
#[test]
fn the_same_link_local_on_two_interfaces_is_two_addresses() {
assert_ne!(
ScopedIp::scoped(link_local(), en0()),
ScopedIp::scoped(link_local(), en1())
);
}
#[test]
fn a_global_address_is_the_same_address_through_any_interface() {
assert_eq!(
ScopedIp::scoped(global(), en0()),
ScopedIp::scoped(global(), en1())
);
assert_eq!(
ScopedIp::scoped(global(), en0()),
ScopedIp::unscoped(global())
);
assert!(ScopedIp::scoped(global(), en0()).zone().is_none());
}
#[test]
fn ipv4_never_carries_a_zone() {
let v4 = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
assert!(!ScopedIp::needs_zone(&v4));
assert!(ScopedIp::scoped(v4, en0()).zone().is_none());
}
#[test]
fn a_zone_is_its_index_not_its_name() {
assert_eq!(Zone::new(4, "en0"), Zone::new(4, "utun4"));
assert_ne!(Zone::new(4, "en0"), Zone::new(5, "en0"));
}
#[test]
fn an_unresolved_zone_is_identified_by_the_name_it_was_written_under() {
let en0: ScopedIp = "fe80::1%en0".parse().expect("parses");
let en1: ScopedIp = "fe80::1%en1".parse().expect("parses");
assert_ne!(en0, en1, "two interfaces, two addresses");
assert_eq!(en0, "fe80::1%en0".parse().expect("parses"));
assert!(en0.is_unusable());
assert_eq!(en0.to_socket_addr(22), None);
}
#[test]
fn a_scoped_address_produces_a_socket_address_with_its_scope_id() {
let socket = ScopedIp::scoped(link_local(), en0())
.to_socket_addr(443)
.expect("a scoped link-local is usable");
match socket {
SocketAddr::V6(v6) => assert_eq!(v6.scope_id(), 4),
SocketAddr::V4(_) => panic!("an IPv6 address produced a V4 socket address"),
}
}
#[test]
fn an_unzoned_link_local_is_not_usable() {
let bare = ScopedIp::unscoped(link_local());
assert!(bare.is_unusable());
assert_eq!(bare.to_socket_addr(443), None);
}
#[test]
fn an_ordinary_address_is_usable_without_a_zone() {
let host = ScopedIp::unscoped(global());
assert!(!host.is_unusable());
assert_eq!(
host.to_socket_addr(443),
Some(SocketAddr::new(global(), 443))
);
}
#[test]
fn a_scoped_address_renders_and_parses_the_way_the_operating_system_writes_it() {
let scoped = ScopedIp::scoped(link_local(), en0());
assert_eq!(scoped.to_string(), "fe80::1%en0");
let parsed: ScopedIp = "fe80::1%en0".parse().unwrap();
assert_eq!(parsed.addr(), link_local());
assert_eq!(parsed.zone().map(Zone::name), Some("en0"));
}
#[test]
fn addresses_sort_by_address_with_the_zone_breaking_ties() {
let mut addresses = vec![
ScopedIp::scoped(link_local(), en1()),
ScopedIp::unscoped(global()),
ScopedIp::scoped(link_local(), en0()),
];
addresses.sort();
assert_eq!(
addresses,
vec![
ScopedIp::unscoped(global()),
ScopedIp::scoped(link_local(), en0()),
ScopedIp::scoped(link_local(), en1()),
]
);
}
#[test]
fn an_unscoped_address_renders_bare() {
assert_eq!(ScopedIp::unscoped(global()).to_string(), "2001:db8::1");
}
#[test]
fn a_zone_on_an_address_that_cannot_use_one_is_rejected() {
assert!(matches!(
"2001:db8::1%en0".parse::<ScopedIp>(),
Err(ScopedIpError::ZoneOnUnscopedAddress(_, _))
));
assert_eq!(
"fe80::1%".parse::<ScopedIp>(),
Err(ScopedIpError::EmptyZone)
);
assert!(matches!(
"not-an-address%en0".parse::<ScopedIp>(),
Err(ScopedIpError::NotAnAddress(_))
));
}
}