use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use crate::model::ip::range::{IpRange, cidr_range};
use crate::model::ip::scoped::Zone;
use crate::model::ip::set::IpSet;
use crate::model::mac::MacAddr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LinkAddress {
address: IpAddr,
prefix: u8,
}
impl LinkAddress {
pub fn new(address: IpAddr, prefix: u8) -> Self {
let ceiling = if address.is_ipv4() { 32 } else { 128 };
Self {
address,
prefix: prefix.min(ceiling),
}
}
pub fn address(&self) -> IpAddr {
self.address
}
pub fn prefix(&self) -> u8 {
self.prefix
}
pub fn network(&self) -> IpRange {
cidr_range(self.address, self.prefix).expect("a prefix clamped to its family")
}
pub fn contains(&self, ip: &IpAddr) -> bool {
self.network().contains(ip)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LinkKind {
Wired,
Wireless,
Loopback,
Virtual,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Link {
name: String,
friendly_name: Option<String>,
index: u32,
mac: Option<MacAddr>,
addresses: Vec<LinkAddress>,
kind: LinkKind,
up: bool,
addressing: Addressing,
physical: bool,
default_route: bool,
gateway: bool,
}
impl Link {
pub fn new(name: impl Into<String>, index: u32) -> Self {
Self {
name: name.into(),
friendly_name: None,
index,
mac: None,
addresses: Vec::new(),
kind: LinkKind::Virtual,
up: false,
addressing: Addressing::Neither,
physical: false,
default_route: false,
gateway: false,
}
}
#[must_use]
pub fn with_mac(mut self, mac: MacAddr) -> Self {
self.mac = Some(mac);
self
}
#[must_use]
pub fn with_addresses(mut self, addresses: Vec<LinkAddress>) -> Self {
self.addresses = addresses;
self
}
#[must_use]
pub fn with_kind(mut self, kind: LinkKind) -> Self {
self.kind = kind;
self
}
#[must_use]
pub fn with_link_up(mut self, up: bool) -> Self {
self.up = up;
self
}
#[must_use]
pub fn with_addressing(mut self, addressing: Addressing) -> Self {
self.addressing = addressing;
self
}
#[must_use]
pub fn with_physical(mut self, physical: bool) -> Self {
self.physical = physical;
self
}
#[must_use]
pub fn with_default_route(mut self, carries: bool) -> Self {
self.default_route = carries;
self
}
#[must_use]
pub fn with_gateway(mut self, has: bool) -> Self {
self.gateway = has;
self
}
pub fn name(&self) -> &str {
&self.name
}
pub(crate) fn display_name(&self) -> &str {
self.friendly_name.as_deref().unwrap_or(&self.name)
}
pub fn index(&self) -> u32 {
self.index
}
pub fn mac(&self) -> Option<MacAddr> {
self.mac
}
pub fn addresses(&self) -> &[LinkAddress] {
&self.addresses
}
pub fn ipv4(&self) -> impl Iterator<Item = (Ipv4Addr, u8)> + '_ {
self.addresses.iter().filter_map(|held| match held.address {
IpAddr::V4(v4) => Some((v4, held.prefix)),
IpAddr::V6(_) => None,
})
}
pub fn ipv6(&self) -> impl Iterator<Item = (Ipv6Addr, u8)> + '_ {
self.addresses.iter().filter_map(|held| match held.address {
IpAddr::V6(v6) => Some((v6, held.prefix)),
IpAddr::V4(_) => None,
})
}
pub fn zone(&self) -> Zone {
Zone::new(self.index, self.name.clone())
}
pub fn kind(&self) -> LinkKind {
self.kind
}
pub fn is_up(&self) -> bool {
self.up
}
pub fn is_loopback(&self) -> bool {
self.kind == LinkKind::Loopback
}
pub fn is_wireless(&self) -> bool {
self.kind == LinkKind::Wireless
}
pub fn is_physical(&self) -> bool {
self.physical
}
pub fn is_broadcast(&self) -> bool {
self.addressing == Addressing::Broadcast
}
pub fn is_point_to_point(&self) -> bool {
self.addressing == Addressing::PointToPoint
}
pub fn carries_default_route(&self) -> bool {
self.default_route
}
pub fn has_gateway(&self) -> bool {
self.gateway
}
pub fn is_wired(&self) -> bool {
self.kind == LinkKind::Wired
}
pub fn carries_frames(&self) -> bool {
!self.is_point_to_point() && !self.is_loopback() && self.mac.is_some()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Addressing {
Broadcast,
PointToPoint,
Neither,
}
impl Addressing {
pub(crate) fn of(broadcast: bool, point_to_point: bool) -> Self {
match (broadcast, point_to_point) {
(_, true) => Self::PointToPoint,
(true, false) => Self::Broadcast,
(false, false) => Self::Neither,
}
}
}
pub fn interfaces() -> Vec<Link> {
host_table().into_iter().map(Link::from_netdev).collect()
}
pub(crate) fn host_table() -> Vec<netdev::Interface> {
let mut table = netdev::get_interfaces();
let peers = point_to_point_peers();
if !peers.is_empty() {
for interface in &mut table {
own_addresses_for_peers(interface, &peers);
}
}
table
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct PeerAddress {
link: String,
peer: IpAddr,
local: IpAddr,
}
fn own_addresses_for_peers(interface: &mut netdev::Interface, peers: &[PeerAddress]) {
let local_for = |peer: IpAddr| {
peers
.iter()
.find(|pair| pair.link == interface.name && pair.peer == peer)
.map(|pair| pair.local)
};
let replaced_v4: Vec<_> = interface
.ipv4
.iter()
.map(|net| match local_for(IpAddr::V4(net.addr())) {
Some(IpAddr::V4(local)) => {
netdev::ipnet::Ipv4Net::new(local, net.prefix_len()).unwrap_or(*net)
}
_ => *net,
})
.collect();
let replaced_v6: Vec<_> = interface
.ipv6
.iter()
.map(|net| match local_for(IpAddr::V6(net.addr())) {
Some(IpAddr::V6(local)) => {
netdev::ipnet::Ipv6Net::new(local, net.prefix_len()).unwrap_or(*net)
}
_ => *net,
})
.collect();
interface.ipv4 = replaced_v4;
interface.ipv6 = replaced_v6;
}
#[cfg(target_os = "linux")]
fn point_to_point_peers() -> Vec<PeerAddress> {
let mut head: *mut libc::ifaddrs = std::ptr::null_mut();
if unsafe { libc::getifaddrs(&mut head) } != 0 {
return Vec::new();
}
let mut pairs = Vec::new();
let mut entry = head;
while !entry.is_null() {
let node = unsafe { &*entry };
entry = node.ifa_next;
if node.ifa_flags & libc::IFF_POINTOPOINT as u32 == 0 {
continue;
}
let (Some(local), Some(peer)) = (unsafe { ip_of(node.ifa_addr) }, unsafe {
ip_of(node.ifa_ifu)
}) else {
continue;
};
if local == peer {
continue;
}
let link = unsafe { std::ffi::CStr::from_ptr(node.ifa_name) }
.to_string_lossy()
.into_owned();
pairs.push(PeerAddress { link, peer, local });
}
unsafe { libc::freeifaddrs(head) };
pairs
}
#[cfg(not(target_os = "linux"))]
fn point_to_point_peers() -> Vec<PeerAddress> {
Vec::new()
}
#[cfg(target_os = "linux")]
unsafe fn ip_of(address: *const libc::sockaddr) -> Option<IpAddr> {
if address.is_null() {
return None;
}
match i32::from(unsafe { (*address).sa_family }) {
libc::AF_INET => {
let v4 = unsafe { &*address.cast::<libc::sockaddr_in>() };
Some(IpAddr::V4(Ipv4Addr::from(u32::from_be(v4.sin_addr.s_addr))))
}
libc::AF_INET6 => {
let v6 = unsafe { &*address.cast::<libc::sockaddr_in6>() };
Some(IpAddr::V6(Ipv6Addr::from(v6.sin6_addr.s6_addr)))
}
_ => None,
}
}
impl Link {
pub fn from_netdev(interface: netdev::Interface) -> Self {
use netdev::interface::types::InterfaceType;
let kind = if interface.is_loopback() {
LinkKind::Loopback
} else if interface.if_type == InterfaceType::Wireless80211 {
LinkKind::Wireless
} else if interface.is_physical() {
LinkKind::Wired
} else {
LinkKind::Virtual
};
let addresses = interface
.ipv4
.iter()
.map(|net| LinkAddress::new(IpAddr::V4(net.addr()), net.prefix_len()))
.chain(
interface
.ipv6
.iter()
.map(|net| LinkAddress::new(IpAddr::V6(net.addr()), net.prefix_len())),
)
.collect();
Self {
mac: interface.mac_addr.map(|mac| MacAddr::from(mac.octets())),
addresses,
kind,
up: carries_traffic(
interface.is_up(),
interface.oper_state(),
interface.is_running(),
),
addressing: Addressing::of(interface.is_broadcast(), interface.is_point_to_point()),
physical: interface.is_physical(),
default_route: interface.default,
gateway: interface
.gateway
.as_ref()
.is_some_and(|g| !g.ipv4.is_empty() || !g.ipv6.is_empty()),
friendly_name: interface
.friendly_name
.filter(|friendly| !friendly.is_empty() && *friendly != interface.name),
name: interface.name,
index: interface.index,
}
}
}
pub fn is_layer_2_capable(link: &Link) -> bool {
link.carries_frames()
}
pub fn is_on_link(link: &Link, ips: &IpSet) -> bool {
let within = |start: IpAddr, end: IpAddr| {
link.addresses()
.iter()
.any(|held| held.contains(&start) && held.contains(&end))
};
ips.v4()
.iter()
.all(|range| within(range.start_addr().into(), range.end_addr().into()))
&& ips
.v6()
.iter()
.all(|range| within(range.start_addr().into(), range.end_addr().into()))
}
fn carries_traffic(
admin_up: bool,
oper: netdev::interface::state::OperState,
running: bool,
) -> bool {
use netdev::interface::state::OperState;
admin_up
&& match oper {
OperState::Up => true,
OperState::Unknown => running,
OperState::NotPresent
| OperState::Down
| OperState::LowerLayerDown
| OperState::Testing
| OperState::Dormant => false,
}
}
#[cfg(test)]
mod tests {
use crate::model::ip::range::IpRange;
fn misread_ppp() -> netdev::Interface {
let mut interface = netdev::Interface::dummy();
interface.name = "ppp0".to_string();
interface.ipv4 = vec![
"203.0.113.2/32".parse().expect("a network"),
"198.51.100.9/24".parse().expect("a network"),
];
interface.ipv6 = vec!["2001:db8::2/128".parse().expect("a network")];
interface
}
fn peer(link: &str, peer: &str, local: &str) -> PeerAddress {
PeerAddress {
link: link.to_string(),
peer: peer.parse().expect("an address"),
local: local.parse().expect("an address"),
}
}
#[test]
fn a_point_to_point_link_holds_its_own_address_and_not_its_peers() {
let mut interface = misread_ppp();
own_addresses_for_peers(
&mut interface,
&[
peer("ppp0", "203.0.113.2", "203.0.113.1"),
peer("ppp0", "2001:db8::2", "2001:db8::1"),
],
);
let held: Vec<String> = Link::from_netdev(interface)
.addresses()
.iter()
.map(|held| format!("{}/{}", held.address(), held.prefix()))
.collect();
assert_eq!(
held,
["203.0.113.1/32", "198.51.100.9/24", "2001:db8::1/128"]
);
}
#[test]
fn a_peer_is_corrected_on_its_own_link_only() {
let mut interface = misread_ppp();
interface.name = "eth0".to_string();
own_addresses_for_peers(
&mut interface,
&[peer("ppp0", "203.0.113.2", "203.0.113.1")],
);
assert_eq!(
interface.ipv4[0],
"203.0.113.2/32".parse::<netdev::ipnet::Ipv4Net>().unwrap()
);
}
fn link(name: &str, kind: LinkKind) -> Link {
Link::new(name, 1)
.with_kind(kind)
.with_mac(MacAddr::new(1, 2, 3, 4, 5, 6))
}
fn holding(name: &str, address: &str, prefix: u8) -> Link {
link(name, LinkKind::Wired).with_addresses(vec![LinkAddress::new(
address.parse::<IpAddr>().expect("an address"),
prefix,
)])
}
fn targets(written: &str) -> IpSet {
let mut set = IpSet::new();
set.insert_range(written.parse::<IpRange>().expect("a range"));
set
}
#[test]
fn a_range_is_on_link_only_if_all_of_it_is() {
let link = holding("en0", "198.51.100.7", 25);
assert!(is_on_link(&link, &targets("198.51.100.1-198.51.100.50")));
assert!(is_on_link(&link, &targets("198.51.100.0/25")), "the whole");
assert!(
!is_on_link(&link, &targets("198.51.100.130-198.51.100.135")),
"past"
);
assert!(
!is_on_link(&link, &targets("198.51.100.100-198.51.100.140")),
"a range that starts on the link and leaves it is not on the link"
);
}
#[test]
fn a_link_with_no_addressing_has_nothing_on_it() {
let bare = link("en0", LinkKind::Wired);
assert!(!is_on_link(&bare, &targets("198.51.100.1-198.51.100.50")));
}
#[test]
fn an_ipv6_prefix_does_not_answer_for_an_ipv4_range() {
let v6_only = link("en0", LinkKind::Wired).with_addresses(vec![LinkAddress::new(
"fe80::1".parse::<IpAddr>().expect("an address"),
64,
)]);
assert!(!is_on_link(
&v6_only,
&targets("198.51.100.1-198.51.100.50")
));
}
use super::*;
#[test]
fn an_interface_of_unknown_state_carries_traffic_while_it_runs() {
use netdev::interface::state::OperState;
assert!(carries_traffic(true, OperState::Up, true));
assert!(
carries_traffic(true, OperState::Unknown, true),
"a tunnel in use"
);
assert!(
!carries_traffic(true, OperState::Unknown, false),
"a tunnel nothing is attached to"
);
assert!(
!carries_traffic(false, OperState::Unknown, true),
"brought down"
);
for down in [
OperState::Down,
OperState::LowerLayerDown,
OperState::Dormant,
OperState::Testing,
OperState::NotPresent,
] {
assert!(!carries_traffic(true, down, true), "{down:?}");
}
}
fn v4(address: &str, prefix: u8) -> LinkAddress {
LinkAddress::new(IpAddr::V4(address.parse().expect("an address")), prefix)
}
#[test]
fn a_network_covers_every_address_its_prefix_names() {
let held = v4("198.51.100.7", 25);
let network = held.network();
assert_eq!(
network.start_addr(),
"198.51.100.0".parse::<IpAddr>().unwrap()
);
assert_eq!(
network.end_addr(),
"198.51.100.127".parse::<IpAddr>().unwrap()
);
assert!(
held.contains(&"198.51.100.0".parse().unwrap()),
"the network"
);
assert!(
held.contains(&"198.51.100.127".parse().unwrap()),
"the broadcast"
);
assert!(
!held.contains(&"198.51.100.128".parse().unwrap()),
"the next one"
);
}
#[test]
fn the_ends_of_the_prefix_range_are_both_networks() {
let single = v4("192.0.2.1", 32);
assert_eq!(single.network().len(), 1);
assert!(single.contains(&"192.0.2.1".parse().unwrap()));
let everything = v4("192.0.2.1", 0);
assert!(everything.contains(&"8.8.8.8".parse().unwrap()));
}
#[test]
fn a_prefix_past_its_family_is_clamped_and_the_address_survives() {
let absurd = v4("198.51.100.7", 200);
assert_eq!(absurd.prefix(), 32, "clamped to what IPv4 has");
assert_eq!(absurd.address(), "198.51.100.7".parse::<IpAddr>().unwrap());
assert_eq!(absurd.network().len(), 1);
let v6 = LinkAddress::new(IpAddr::V6("fe80::1".parse().unwrap()), 255);
assert_eq!(v6.prefix(), 128, "and to what IPv6 has");
}
#[test]
fn a_link_carries_frames_only_with_a_segment_and_an_address_to_send_from() {
let mac = MacAddr::new(2, 0, 0, 0, 0, 1);
let wired = Link::new("en0", 1).with_kind(LinkKind::Wired).with_mac(mac);
assert!(wired.carries_frames());
assert!(
!Link::new("en0", 1)
.with_kind(LinkKind::Wired)
.carries_frames(),
"no hardware address to send from"
);
assert!(
!Link::new("lo0", 1)
.with_kind(LinkKind::Loopback)
.with_mac(mac)
.carries_frames(),
"nobody else on it"
);
assert!(
!Link::new("utun0", 1)
.with_kind(LinkKind::Wired)
.with_mac(mac)
.with_addressing(Addressing::PointToPoint)
.carries_frames(),
"a peer rather than a segment"
);
}
#[test]
fn a_links_addresses_are_readable_by_family() {
let link = Link::new("en0", 1).with_addresses(vec![
v4("198.51.100.7", 24),
LinkAddress::new(IpAddr::V6("fe80::1".parse().unwrap()), 64),
v4("192.0.2.5", 25),
]);
let v4s: Vec<_> = link.ipv4().collect();
assert_eq!(v4s.len(), 2);
assert_eq!(v4s[0], ("198.51.100.7".parse().unwrap(), 24));
assert_eq!(v4s[1], ("192.0.2.5".parse().unwrap(), 25));
let v6s: Vec<_> = link.ipv6().collect();
assert_eq!(v6s.len(), 1);
assert_eq!(v6s[0], ("fe80::1".parse().unwrap(), 64));
}
#[test]
fn a_link_is_its_own_zone() {
let zone = Link::new("en0", 7).zone();
assert_eq!(zone.name(), "en0");
assert_eq!(zone.index(), Some(7));
}
#[test]
fn an_interface_is_called_what_a_person_calls_it() {
let guid = "{4D36E972-E325-11CE-BFC1-08002BE10318}";
let read = |friendly: Option<&str>| {
let mut interface = netdev::Interface::dummy();
interface.name = guid.to_owned();
interface.friendly_name = friendly.map(str::to_owned);
Link::from_netdev(interface)
};
assert_eq!(
read(Some("vEthernet (WSL)")).display_name(),
"vEthernet (WSL)"
);
assert_eq!(read(None).display_name(), guid);
assert_eq!(read(Some("")).display_name(), guid);
}
#[test]
fn every_interface_this_machine_has_reads_back_consistently() {
for link in interfaces() {
assert!(!link.name().is_empty(), "an interface with no name");
if link.is_loopback() {
assert!(
!link.carries_frames(),
"{} is loopback and claims a segment",
link.name()
);
}
for held in link.addresses() {
let ceiling = if held.address().is_ipv4() { 32 } else { 128 };
assert!(
held.prefix() <= ceiling,
"{} holds {} with a /{} its family cannot express",
link.name(),
held.address(),
held.prefix()
);
assert!(
held.contains(&held.address()),
"{} holds {} on a network that excludes it",
link.name(),
held.address()
);
}
}
}
}