use crate::info;
use crate::system::interface::source::viable_interfaces;
use crate::system::interface::{Link, LinkAddress};
use std::net::Ipv6Addr;
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ViabilityError {
IsDown,
NotPhysical,
NoMacAddress,
NotBroadcast,
IsPointToPoint,
NoValidLanIp,
}
#[derive(Debug, Clone)]
pub struct LanLink {
pub link: Link,
pub ipv4: Option<LinkAddress>,
pub ipv6: Vec<LinkAddress>,
}
impl LanLink {
pub fn link_local(&self) -> Option<Ipv6Addr> {
self.ipv6
.iter()
.filter_map(|held| match held.address() {
std::net::IpAddr::V6(v6) => Some(v6),
std::net::IpAddr::V4(_) => None,
})
.find(Ipv6Addr::is_unicast_link_local)
}
}
pub fn prioritized_interfaces(limit: usize) -> Vec<Link> {
prioritized_interfaces_with(limit, viable_interfaces())
}
pub(crate) fn prioritized_interfaces_with(limit: usize, mut links: Vec<Link>) -> Vec<Link> {
links.sort_by_key(|link| if link.is_wireless() { 1 } else { 0 });
links.into_iter().take(limit).collect()
}
pub fn lan_link() -> Option<LanLink> {
lan_link_with(crate::system::interface::interfaces())
}
pub fn lan_network() -> Option<LinkAddress> {
lan_link()?.ipv4
}
pub(crate) fn lan_link_with(interfaces: Vec<Link>) -> Option<LanLink> {
let interfaces_str: &str = match interfaces.len() {
1 => "interface",
_ => "interfaces",
};
info!(
verbosity = 3,
"identified {} network {}, picking the best one",
interfaces.len(),
interfaces_str
);
let viable: Vec<Link> = interfaces
.into_iter()
.filter(|link| lan_viability(link).is_ok())
.collect();
let link = select_best_lan_interface(viable)?;
info!(
verbosity = 3,
"performing LAN scan on interface {}",
link.name()
);
let ipv4 = link
.addresses()
.iter()
.copied()
.find(|held| matches!(held.address(), std::net::IpAddr::V4(v4) if v4.is_private()));
let ipv6 = link
.addresses()
.iter()
.copied()
.filter(|held| held.address().is_ipv6())
.collect();
Some(LanLink { link, ipv4, ipv6 })
}
pub fn lan_viability(link: &Link) -> Result<(), ViabilityError> {
if !link.is_up() {
return Err(ViabilityError::IsDown);
}
if !link.is_physical() || link.is_loopback() {
return Err(ViabilityError::NotPhysical);
}
if link.mac().is_none() {
return Err(ViabilityError::NoMacAddress);
}
if !link.is_broadcast() {
return Err(ViabilityError::NotBroadcast);
}
if link.is_point_to_point() {
return Err(ViabilityError::IsPointToPoint);
}
let has_valid_ip = link.addresses().iter().any(|held| match held.address() {
std::net::IpAddr::V4(v4) => v4.is_private(),
std::net::IpAddr::V6(v6) => v6.is_unicast_link_local(),
});
if !has_valid_ip {
return Err(ViabilityError::NoValidLanIp);
}
Ok(())
}
fn select_best_lan_interface(links: Vec<Link>) -> Option<Link> {
if let Some(routed) = links.iter().find(|link| link.carries_default_route()) {
return Some(routed.clone());
}
links
.iter()
.find(|link| link.has_gateway() && has_private_ipv4(link))
.or_else(|| {
links
.iter()
.find(|link| link.is_wired() && has_private_ipv4(link))
})
.or_else(|| links.iter().find(|link| has_private_ipv4(link)))
.or_else(|| links.iter().find(|link| link.is_wired()))
.or_else(|| links.first())
.cloned()
}
fn has_private_ipv4(link: &Link) -> bool {
link.ipv4().any(|(address, _)| address.is_private())
}
#[cfg(test)]
mod tests {
use crate::model::mac::MacAddr;
fn of_kind(name: &str, kind: LinkKind) -> Link {
Link::new(name, 1)
.with_kind(kind)
.with_mac(MacAddr::new(1, 2, 3, 4, 5, 6))
}
#[test]
fn a_wired_link_is_preferred_however_the_platform_names_it() {
let ordered = prioritized_interfaces_with(
10,
vec![
of_kind("en1", LinkKind::Wireless),
of_kind("{3F2504E0-4F89}", LinkKind::Wired),
],
);
assert_eq!(ordered[0].name(), "{3F2504E0-4F89}");
assert_eq!(ordered[1].name(), "en1");
}
#[test]
fn no_more_links_than_were_asked_for() {
let links = vec![
of_kind("en0", LinkKind::Wired),
of_kind("en1", LinkKind::Wired),
of_kind("en2", LinkKind::Wired),
];
assert_eq!(prioritized_interfaces_with(2, links.clone()).len(), 2);
assert_eq!(prioritized_interfaces_with(0, links).len(), 0);
}
use super::*;
use crate::system::interface::Addressing;
use crate::system::interface::LinkKind;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
fn mock_interface(
up: bool,
mac: bool,
broadcast: bool,
p2p: bool,
loopback: bool,
ip: bool,
) -> Link {
let mut link = Link::new("test0", 0)
.with_link_up(up)
.with_addressing(Addressing::of(broadcast, p2p))
.with_physical(!loopback)
.with_kind(if loopback {
LinkKind::Loopback
} else {
LinkKind::Wired
});
if mac {
link = link.with_mac(crate::model::mac::MacAddr::new(1, 2, 3, 4, 5, 6));
}
if ip {
link = link.with_addresses(vec![LinkAddress::new(
IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)),
24,
)]);
}
link
}
#[test]
fn a_link_with_only_ipv6_is_still_a_lan_link() {
let intf = mock_interface(true, true, true, false, false, false).with_addresses(vec![
LinkAddress::new(IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)), 64),
]);
assert_eq!(lan_viability(&intf), Ok(()));
let link = lan_link_with(vec![intf]).expect("a viable link is selected");
assert!(
link.ipv4.is_none(),
"there is no private IPv4 network here, and saying so is the point"
);
assert_eq!(
link.link_local(),
Some(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)),
"the address probes would leave from has to survive selection"
);
assert_eq!(link.link.name(), "test0");
}
#[test]
fn a_dual_stack_link_carries_both_families() {
let mut held = mock_interface(true, true, true, false, false, true)
.addresses()
.to_vec();
held.push(LinkAddress::new(
IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)),
64,
));
let intf = mock_interface(true, true, true, false, false, true).with_addresses(held);
let link = lan_link_with(vec![intf]).expect("a viable link is selected");
assert_eq!(
link.ipv4.map(|held| held.address()),
Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)))
);
assert_eq!(link.ipv6.len(), 1);
}
#[test]
fn the_ipv4_view_of_a_link_is_unchanged() {
let intf = mock_interface(true, true, true, false, false, true);
let link = lan_link_with(vec![intf]).expect("a viable link is selected");
let held = link.ipv4.expect("the link has a private IPv4 network");
assert_eq!(held.address(), IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)));
assert_eq!(held.prefix(), 24);
}
#[test]
fn the_link_carrying_the_default_route_is_the_lan() {
let wifi = mock_interface(true, true, true, false, false, true)
.with_kind(LinkKind::Wireless)
.with_default_route(true);
let airdrop = Link::new("awdl0", 17)
.with_link_up(true)
.with_physical(true)
.with_addressing(Addressing::Broadcast)
.with_kind(LinkKind::Wired)
.with_mac(crate::model::mac::MacAddr::new(1, 2, 3, 4, 5, 6))
.with_addresses(vec![LinkAddress::new(
IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)),
64,
)]);
let chosen =
select_best_lan_interface(vec![airdrop, wifi]).expect("one of them is the LAN");
assert_eq!(
chosen.name(),
"test0",
"the wired-looking link with no network won over the one carrying the route"
);
}
#[test]
fn a_virtualisation_bridge_does_not_outrank_the_default_route() {
let wifi = mock_interface(true, true, true, false, false, true)
.with_kind(LinkKind::Wireless)
.with_default_route(true);
let bridge = Link::new("bridge100", 20)
.with_link_up(true)
.with_physical(true)
.with_addressing(Addressing::Broadcast)
.with_kind(LinkKind::Wired)
.with_mac(crate::model::mac::MacAddr::new(1, 2, 3, 4, 5, 7))
.with_addresses(vec![LinkAddress::new(
IpAddr::V4(Ipv4Addr::new(192, 168, 64, 1)),
24,
)]);
let chosen = select_best_lan_interface(vec![bridge, wifi]).expect("one of them is the LAN");
assert_eq!(chosen.name(), "test0");
}
#[test]
fn a_gateway_beats_a_wired_bridge_when_a_vpn_holds_the_default_route() {
let wifi = mock_interface(true, true, true, false, false, true)
.with_kind(LinkKind::Wireless)
.with_gateway(true);
let bridge = Link::new("bridge100", 20)
.with_link_up(true)
.with_physical(true)
.with_addressing(Addressing::Broadcast)
.with_kind(LinkKind::Wired)
.with_mac(crate::model::mac::MacAddr::new(1, 2, 3, 4, 5, 7))
.with_addresses(vec![LinkAddress::new(
IpAddr::V4(Ipv4Addr::new(192, 168, 64, 1)),
24,
)]);
let chosen = select_best_lan_interface(vec![bridge, wifi]).expect("one of them is the LAN");
assert_eq!(chosen.name(), "test0", "the link with a router is the LAN");
}
#[test]
fn with_no_route_a_sweepable_link_beats_one_with_nothing_to_sweep() {
let addressed = mock_interface(true, true, true, false, false, true);
let bare = Link::new("awdl0", 17)
.with_link_up(true)
.with_physical(true)
.with_addressing(Addressing::Broadcast)
.with_kind(LinkKind::Wired)
.with_mac(crate::model::mac::MacAddr::new(1, 2, 3, 4, 5, 6));
let chosen =
select_best_lan_interface(vec![bare, addressed]).expect("one of them is picked");
assert_eq!(chosen.name(), "test0");
}
#[test]
fn is_viable_down() {
let intf = mock_interface(false, true, true, false, false, true);
assert_eq!(lan_viability(&intf), Err(ViabilityError::IsDown));
}
#[test]
fn is_viable_not_physical() {
let intf = mock_interface(true, true, true, false, false, true).with_physical(false);
assert_eq!(lan_viability(&intf), Err(ViabilityError::NotPhysical));
}
#[test]
fn is_viable_no_mac() {
let intf = mock_interface(true, false, true, false, false, true);
assert_eq!(lan_viability(&intf), Err(ViabilityError::NoMacAddress));
}
#[test]
fn is_viable_success() {
let intf = mock_interface(true, true, true, false, false, true);
assert_eq!(lan_viability(&intf), Ok(()));
}
}