use crate::config::{Interface, Profile, Route};
use crate::net::{Cmd, CommandRunner};
use crate::state::ParentConfig;
use anyhow::{Context, Result};
use ipnet::IpNet;
mod windows;
mod windows_driver_vlan;
pub use windows::{SWITCH_NAME as WINDOWS_SWITCH_NAME, WindowsHyperV};
pub use windows_driver_vlan::WindowsDriverVlan;
pub trait Platform {
fn name(&self) -> &'static str;
fn iface_name(&self, interface: &Interface, device: &str) -> String;
fn bringup_commands(&self, interface: &Interface, device: &str) -> Vec<Cmd>;
fn teardown_commands(&self, iface: &str) -> Vec<Cmd>;
fn route_commands(&self, route: &Route, in_subnet: bool, iface: &str) -> Vec<Cmd>;
fn existing_vlans(
&self,
runner: &mut dyn CommandRunner,
parent: &str,
) -> Result<Vec<(u16, String)>>;
fn is_candidate_device(&self, name: &str) -> bool;
fn reverts_parent_config(&self) -> bool;
fn parent_snapshot(
&self,
_runner: &mut dyn CommandRunner,
_device: &str,
) -> Result<Option<ParentConfig>> {
Ok(None)
}
fn parent_restore_commands(&self, _parent: &ParentConfig) -> Vec<Cmd> {
Vec::new()
}
fn claims_parent_exclusively(&self) -> bool {
false
}
fn teardown_removes_interface(&self) -> bool {
true
}
fn validate_profile(&self, _profile: &Profile) -> Result<()> {
Ok(())
}
fn list_devices(&self, runner: &mut dyn CommandRunner) -> Result<Vec<String>>;
fn addresses_on(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<Vec<IpNet>>;
fn is_wireless(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool>;
fn link_is_active(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool>;
fn records_created_interface(&self, cmd: &Cmd) -> bool;
}
pub struct MacOs;
impl Platform for MacOs {
fn name(&self) -> &'static str {
"macos"
}
fn iface_name(&self, interface: &Interface, device: &str) -> String {
iface_name(interface, device)
}
fn bringup_commands(&self, interface: &Interface, device: &str) -> Vec<Cmd> {
create_address_mtu_commands(interface, device)
}
fn teardown_commands(&self, iface: &str) -> Vec<Cmd> {
teardown_commands(iface)
}
fn route_commands(&self, route: &Route, in_subnet: bool, iface: &str) -> Vec<Cmd> {
let mut cmds = Vec::new();
match &route.gateway {
Some(gateway) => {
let gateway = gateway.to_string();
cmds.push(Cmd::new("route", &["add", &route.destination, &gateway]));
}
None => {
if !in_subnet {
cmds.push(interface_route_command(&route.destination, iface));
}
if let Some(mac) = &route.mac
&& let Ok(net) = route.destination.parse::<IpNet>()
{
let host = net.addr().to_string();
cmds.push(Cmd::new("arp", &["-s", &host, mac]));
}
}
}
cmds
}
fn existing_vlans(
&self,
_runner: &mut dyn CommandRunner,
_parent: &str,
) -> Result<Vec<(u16, String)>> {
Ok(Vec::new())
}
fn is_candidate_device(&self, name: &str) -> bool {
name.starts_with("en") && !name.contains('.')
}
fn reverts_parent_config(&self) -> bool {
false
}
fn list_devices(&self, runner: &mut dyn CommandRunner) -> Result<Vec<String>> {
crate::commands::live_interfaces(runner)
}
fn addresses_on(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<Vec<IpNet>> {
crate::commands::device_inet_addresses(runner, device)
}
fn is_wireless(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool> {
Ok(crate::device::wifi_devices(runner)?
.iter()
.any(|w| w == device))
}
fn link_is_active(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool> {
crate::device::interface_is_active(runner, device)
}
fn records_created_interface(&self, cmd: &Cmd) -> bool {
cmd.program == "ifconfig" && cmd.args.get(1).map(|a| a == "create").unwrap_or(false)
}
}
const LINUX_IFNAMSIZ_MAX: usize = 15;
const LINUX_MAX_VLAN_ID_DIGITS: usize = 4;
const LINUX_MAX_DOTTED_PARENT_LEN: usize = LINUX_IFNAMSIZ_MAX - 1 - LINUX_MAX_VLAN_ID_DIGITS;
pub struct Linux;
impl Platform for Linux {
fn name(&self) -> &'static str {
"linux"
}
fn iface_name(&self, interface: &Interface, device: &str) -> String {
match interface.vlan {
Some(id) => {
if device.len() <= LINUX_MAX_DOTTED_PARENT_LEN {
format!("{device}.{id}")
} else {
format!("vlan{id}")
}
}
None => device.to_string(),
}
}
fn bringup_commands(&self, interface: &Interface, device: &str) -> Vec<Cmd> {
let name = self.iface_name(interface, device);
let addr = interface.address.to_string();
let mut cmds = Vec::new();
cmds.push(Cmd::new("ip", &["link", "set", device, "up"]));
if let Some(id) = interface.vlan {
let id = id.to_string();
cmds.push(Cmd::new(
"ip",
&[
"link", "add", "link", device, "name", &name, "type", "vlan", "id", &id,
],
));
cmds.push(Cmd::new("ip", &["link", "set", &name, "up"]));
}
cmds.push(Cmd::new("ip", &["addr", "add", &addr, "dev", &name]));
if let Some(mtu) = interface.mtu {
cmds.push(Cmd::new(
"ip",
&["link", "set", &name, "mtu", &mtu.to_string()],
));
}
cmds
}
fn teardown_commands(&self, iface: &str) -> Vec<Cmd> {
vec![Cmd::new("ip", &["link", "del", iface])]
}
fn route_commands(&self, route: &Route, _in_subnet: bool, iface: &str) -> Vec<Cmd> {
let mut cmds = Vec::new();
match &route.gateway {
Some(gateway) => {
let gateway = gateway.to_string();
cmds.push(Cmd::new(
"ip",
&[
"route",
"add",
&route.destination,
"via",
&gateway,
"dev",
iface,
],
));
}
None => {
cmds.push(Cmd::new(
"ip",
&["route", "add", &route.destination, "dev", iface],
));
if let Some(mac) = &route.mac
&& let Ok(net) = route.destination.parse::<IpNet>()
{
let host = net.addr().to_string();
cmds.push(Cmd::new(
"ip",
&["neigh", "replace", &host, "lladdr", mac, "dev", iface],
));
}
}
}
cmds
}
fn existing_vlans(
&self,
runner: &mut dyn CommandRunner,
parent: &str,
) -> Result<Vec<(u16, String)>> {
let out = runner.run(&Cmd::new("ip", &["-d", "-json", "link", "show"]))?;
let entries: Vec<serde_json::Value> = serde_json::from_str(&out)?;
let mut found = Vec::new();
for entry in &entries {
if entry.get("link").and_then(|l| l.as_str()) != Some(parent) {
continue;
}
let info = entry.get("linkinfo");
let Some(id) = info
.and_then(|i| i.get("info_data"))
.and_then(|d| d.get("id"))
.and_then(|i| i.as_u64())
else {
continue;
};
let Some(name) = entry.get("ifname").and_then(|n| n.as_str()) else {
continue;
};
found.push((id as u16, name.to_string()));
}
Ok(found)
}
fn is_candidate_device(&self, name: &str) -> bool {
const VIRTUAL: &[&str] = &[
"docker", "veth", "br-", "virbr", "vlan", "tun", "tap", "bond", "wl",
];
name != "lo" && !name.contains('.') && !VIRTUAL.iter().any(|p| name.starts_with(p))
}
fn reverts_parent_config(&self) -> bool {
true
}
fn list_devices(&self, runner: &mut dyn CommandRunner) -> Result<Vec<String>> {
let out = runner.run(&Cmd::new("ip", &["-json", "link", "show"]))?;
let entries: Vec<serde_json::Value> = serde_json::from_str(&out)?;
Ok(entries
.iter()
.filter_map(|e| e.get("ifname")?.as_str().map(str::to_owned))
.collect())
}
fn addresses_on(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<Vec<IpNet>> {
let out = runner.run(&Cmd::new("ip", &["-json", "addr", "show", "dev", device]))?;
let entries: Vec<serde_json::Value> = serde_json::from_str(&out)?;
let mut nets = Vec::new();
for e in &entries {
for a in e
.get("addr_info")
.and_then(|v| v.as_array())
.into_iter()
.flatten()
{
if a.get("family").and_then(|f| f.as_str()) != Some("inet") {
continue;
}
let (Some(local), Some(len)) = (
a.get("local").and_then(|l| l.as_str()),
a.get("prefixlen").and_then(|p| p.as_u64()),
) else {
continue;
};
if let Ok(net) = format!("{local}/{len}").parse::<IpNet>() {
nets.push(net);
}
}
}
Ok(nets)
}
fn is_wireless(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool> {
let out = runner.run(&Cmd::new("ls", &[&format!("/sys/class/net/{device}")]))?;
Ok(out.split_whitespace().any(|entry| entry == "wireless"))
}
fn link_is_active(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool> {
let carrier = runner.run(&Cmd::new(
"cat",
&[&format!("/sys/class/net/{device}/carrier")],
));
if let Ok(s) = &carrier {
return Ok(s.trim() == "1");
}
runner
.run(&Cmd::new(
"cat",
&[&format!("/sys/class/net/{device}/operstate")],
))
.with_context(|| {
format!(
"cannot determine link state for {device}: neither carrier nor \
operstate is readable"
)
})?;
Ok(false)
}
fn records_created_interface(&self, cmd: &Cmd) -> bool {
cmd.program == "ip"
&& cmd.args.first().map(|a| a == "link").unwrap_or(false)
&& cmd.args.get(1).map(|a| a == "add").unwrap_or(false)
}
}
pub fn host_platform() -> Result<Box<dyn Platform>> {
match std::env::consts::OS {
"macos" => Ok(Box::new(MacOs)),
"linux" => Ok(Box::new(Linux)),
"windows" => Ok(Box::new(WindowsHyperV)),
os => Err(no_backend_error(os)),
}
}
fn no_backend_error(os: &str) -> anyhow::Error {
anyhow::anyhow!(
"no Platform implementation for {os}; only '{}', '{}' and '{}' are \
implemented today. Construct a Platform explicitly if you have one \
for this OS.",
MacOs.name(),
Linux.name(),
WindowsHyperV.name(),
)
}
#[must_use]
pub fn preview_platform() -> Box<dyn Platform> {
host_platform().unwrap_or_else(|_| Box::new(MacOs))
}
pub fn host_platform_for(profile: &Profile) -> Result<Box<dyn Platform>> {
match std::env::consts::OS {
"windows" => Ok(windows_platform_for(profile)),
_ => host_platform(),
}
}
#[must_use]
pub fn preview_platform_for(profile: &Profile) -> Box<dyn Platform> {
host_platform_for(profile).unwrap_or_else(|_| Box::new(MacOs))
}
#[must_use]
pub fn windows_platform_for(profile: &Profile) -> Box<dyn Platform> {
if profile.interfaces.len() <= 1 {
Box::new(WindowsDriverVlan)
} else {
Box::new(WindowsHyperV)
}
}
#[must_use]
pub fn platform_named(name: &str) -> Option<Box<dyn Platform>> {
match name {
"macos" => Some(Box::new(MacOs)),
"linux" => Some(Box::new(Linux)),
"windows-hyperv" => Some(Box::new(WindowsHyperV)),
"windows-driver-vlan" => Some(Box::new(WindowsDriverVlan)),
_ => None,
}
}
pub(crate) fn iface_name(interface: &Interface, device: &str) -> String {
match interface.vlan {
Some(id) => format!("vlan{id}"),
None => device.to_string(),
}
}
pub fn bringup_commands_for(
platform: &dyn Platform,
interface: &Interface,
device: &str,
) -> Vec<Cmd> {
let name = platform.iface_name(interface, device);
let mut cmds = platform.bringup_commands(interface, device);
for route in &interface.routes {
let in_subnet = destination_in_subnet(&route.destination, &interface.address);
cmds.extend(platform.route_commands(route, in_subnet, &name));
}
cmds
}
fn create_address_mtu_commands(interface: &Interface, device: &str) -> Vec<Cmd> {
let name = iface_name(interface, device);
let addr = interface.address.addr().to_string();
let netmask = ipv4_netmask(interface.address.prefix_len());
let mut cmds = Vec::new();
match interface.vlan {
Some(id) => {
let id = id.to_string();
cmds.push(Cmd::new("ifconfig", &[&name, "create"]));
cmds.push(Cmd::new(
"ifconfig",
&[&name, "vlan", &id, "vlandev", device],
));
cmds.push(Cmd::new(
"ifconfig",
&[&name, "inet", &addr, "netmask", &netmask],
));
}
None => {
cmds.push(Cmd::new(
"ifconfig",
&[&name, "inet", &addr, "netmask", &netmask, "alias"],
));
}
}
if let Some(mtu) = interface.mtu {
cmds.push(Cmd::new("ifconfig", &[&name, "mtu", &mtu.to_string()]));
}
cmds
}
#[cfg(test)]
fn append_route_commands(cmds: &mut Vec<Cmd>, routes: &[Route], addr: &IpNet, iface: &str) {
for route in routes {
match &route.gateway {
Some(gateway) => {
let gateway = gateway.to_string();
cmds.push(Cmd::new("route", &["add", &route.destination, &gateway]));
}
None => {
let in_subnet = destination_in_subnet(&route.destination, addr);
if !in_subnet {
cmds.push(interface_route_command(&route.destination, iface));
}
if let Some(mac) = &route.mac
&& let Ok(net) = route.destination.parse::<IpNet>()
{
let host = net.addr().to_string();
cmds.push(Cmd::new("arp", &["-s", &host, mac]));
}
}
}
}
}
#[cfg(test)]
pub(crate) fn bringup_commands(interface: &Interface, device: &str) -> Vec<Cmd> {
let name = iface_name(interface, device);
let mut cmds = create_address_mtu_commands(interface, device);
append_route_commands(&mut cmds, &interface.routes, &interface.address, &name);
cmds
}
#[cfg(test)]
fn interface_names(profile: &Profile) -> Vec<String> {
profile
.interfaces
.iter()
.filter_map(|i| i.vlan.map(|id| format!("vlan{id}")))
.collect()
}
fn destination_in_subnet(destination: &str, addr: &IpNet) -> bool {
destination
.parse::<IpNet>()
.map(|dest| addr.contains(&dest))
.unwrap_or(false)
}
fn interface_route_command(destination: &str, iface: &str) -> Cmd {
if destination == "default" {
return Cmd::new("route", &["add", "default", "-interface", iface]);
}
if let Ok(net) = destination.parse::<IpNet>()
&& net.prefix_len() == net.max_prefix_len()
{
let host = net.addr().to_string();
return Cmd::new("route", &["add", "-host", &host, "-interface", iface]);
}
Cmd::new("route", &["add", "-net", destination, "-interface", iface])
}
pub(crate) fn teardown_commands(iface: &str) -> Vec<Cmd> {
vec![Cmd::new("ifconfig", &[iface, "destroy"])]
}
fn ipv4_netmask(prefix: u8) -> String {
let bits: u32 = if prefix == 0 {
0
} else {
u32::MAX << (32 - prefix as u32)
};
format!(
"{}.{}.{}.{}",
(bits >> 24) & 0xff,
(bits >> 16) & 0xff,
(bits >> 8) & 0xff,
bits & 0xff
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{Interface, Route};
use crate::net::RecordingRunner;
use std::net::IpAddr;
#[test]
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn host_platform_refuses_cleanly_with_no_backend() {
let err = host_platform()
.map(|_| ())
.expect_err("no Platform implementation exists for this OS yet");
assert_eq!(
err.to_string(),
no_backend_error(std::env::consts::OS).to_string()
);
}
#[test]
fn no_backend_error_names_supported_platforms_without_phase_labels() {
let msg = no_backend_error("freebsd").to_string();
assert!(msg.contains("freebsd"), "must name the host OS: {msg}");
assert!(
msg.contains("macos") && msg.contains("linux") && msg.contains("windows"),
"expected the error to name the supported platforms: {msg}"
);
assert!(
!msg.contains("1a") && !msg.contains("1b"),
"error text must not leak internal plan-phase labels: {msg}"
);
}
#[test]
#[cfg(target_os = "linux")]
fn host_platform_resolves_to_linux_on_linux() {
let platform = host_platform().expect("Linux backend must be available on Linux");
assert_eq!(platform.name(), "linux");
}
#[test]
fn preview_platform_is_always_available() {
assert!(!preview_platform().name().is_empty());
}
#[test]
fn every_backend_name_resolves_back_to_itself() {
let backends: [Box<dyn Platform>; 4] = [
Box::new(MacOs),
Box::new(Linux),
Box::new(WindowsHyperV),
Box::new(WindowsDriverVlan),
];
for backend in &backends {
let named = platform_named(backend.name())
.unwrap_or_else(|| panic!("{} is not in platform_named", backend.name()));
assert_eq!(named.name(), backend.name());
}
assert!(platform_named("freebsd").is_none());
assert!(platform_named("").is_none());
}
#[test]
fn windows_backend_is_chosen_by_the_profiles_entry_count() {
let one: Profile =
toml::from_str("name=\"live\"\n[[interface]]\nvlan=11\naddress=\"192.168.11.87/24\"\n")
.unwrap();
let two: Profile = toml::from_str(
"name=\"lab\"\n[[interface]]\nvlan=10\naddress=\"192.168.10.90/24\"\n\
[[interface]]\nvlan=11\naddress=\"192.168.11.87/24\"\n",
)
.unwrap();
assert_eq!(windows_platform_for(&one).name(), "windows-driver-vlan");
assert_eq!(windows_platform_for(&two).name(), "windows-hyperv");
if std::env::consts::OS != "windows" {
assert_eq!(
host_platform_for(&one).map(|p| p.name()).ok(),
host_platform().map(|p| p.name()).ok()
);
}
}
#[test]
#[cfg(target_os = "linux")]
fn preview_platform_follows_the_host_backend_on_linux() {
assert_eq!(preview_platform().name(), "linux");
}
#[test]
#[cfg(target_os = "macos")]
fn preview_platform_follows_the_host_backend_on_macos() {
assert_eq!(preview_platform().name(), "macos");
}
#[test]
#[cfg(target_os = "windows")]
fn host_and_preview_platform_resolve_to_windows_on_windows() {
let platform = host_platform().expect("Windows backend must be available on Windows");
assert_eq!(platform.name(), "windows-hyperv");
assert_eq!(preview_platform().name(), "windows-hyperv");
}
#[test]
fn macos_rendering_of_a_tagged_profile_with_routes_is_pinned() {
let i = Interface {
vlan: Some(11),
address: "192.168.11.87/24".parse().unwrap(),
mtu: None,
routes: vec![
Route {
destination: "192.168.11.151/32".to_string(),
gateway: None,
mac: None,
},
Route {
destination: "239.255.0.255/32".to_string(),
gateway: None,
mac: None,
},
],
};
let rendered: Vec<String> = bringup_commands_for(&MacOs, &i, "en7")
.iter()
.map(|c| c.display())
.collect();
assert_eq!(
rendered,
vec![
"ifconfig vlan11 create",
"ifconfig vlan11 vlan 11 vlandev en7",
"ifconfig vlan11 inet 192.168.11.87 netmask 255.255.255.0",
"route add -host 239.255.0.255 -interface vlan11",
],
"macOS rendering changed"
);
}
#[test]
fn macos_rendering_of_an_untagged_profile_with_static_arp_is_pinned() {
let i = Interface {
vlan: None,
address: "192.168.1.100/24".parse().unwrap(),
mtu: None,
routes: vec![Route {
destination: "192.168.10.151/32".to_string(),
gateway: None,
mac: Some("00:00:5e:00:53:01".to_string()),
}],
};
let rendered: Vec<String> = bringup_commands_for(&MacOs, &i, "en7")
.iter()
.map(|c| c.display())
.collect();
assert_eq!(
rendered,
vec![
"ifconfig en7 inet 192.168.1.100 netmask 255.255.255.0 alias",
"route add -host 192.168.10.151 -interface en7",
"arp -s 192.168.10.151 00:00:5e:00:53:01",
],
"macOS rendering changed"
);
}
fn tagged(id: u16, cidr: &str) -> Interface {
Interface {
vlan: Some(id),
address: cidr.parse().unwrap(),
mtu: None,
routes: vec![],
}
}
#[test]
fn netmask_from_prefix() {
assert_eq!(ipv4_netmask(24), "255.255.255.0");
assert_eq!(ipv4_netmask(16), "255.255.0.0");
assert_eq!(ipv4_netmask(8), "255.0.0.0");
}
#[test]
fn tagged_creates_assigns_and_routes() {
let mut v = tagged(100, "192.168.10.2/24");
v.mtu = Some(1500);
v.routes.push(Route {
destination: "192.168.20.0/24".to_string(),
gateway: Some("192.168.10.1".parse::<IpAddr>().unwrap()),
mac: None,
});
let rendered: Vec<String> = bringup_commands(&v, "en10")
.iter()
.map(|c| c.display())
.collect();
assert_eq!(
rendered,
vec![
"ifconfig vlan100 create",
"ifconfig vlan100 vlan 100 vlandev en10",
"ifconfig vlan100 inet 192.168.10.2 netmask 255.255.255.0",
"ifconfig vlan100 mtu 1500",
"route add 192.168.20.0/24 192.168.10.1",
]
);
}
#[test]
fn tagged_routes_without_gateway() {
let mut v = tagged(10, "192.168.10.90/24");
v.routes.push(Route {
destination: "192.168.10.150/32".to_string(),
gateway: None,
mac: None,
});
v.routes.push(Route {
destination: "10.9.9.9/32".to_string(),
gateway: None,
mac: None,
});
v.routes.push(Route {
destination: "239.255.0.0/24".to_string(),
gateway: None,
mac: None,
});
let rendered: Vec<String> = bringup_commands(&v, "en10")
.iter()
.map(|c| c.display())
.collect();
assert!(!rendered.iter().any(|c| c.contains("192.168.10.150"))); assert!(rendered.contains(&"route add -host 10.9.9.9 -interface vlan10".to_string()));
assert!(rendered.contains(&"route add -net 239.255.0.0/24 -interface vlan10".to_string()));
}
#[test]
fn untagged_configures_parent_with_alias_and_routes() {
let mut u = Interface {
vlan: None,
address: "192.168.1.100/24".parse().unwrap(),
mtu: None,
routes: vec![],
};
u.routes.push(Route {
destination: "192.168.10.151/32".to_string(),
gateway: None,
mac: None,
});
let rendered: Vec<String> = bringup_commands(&u, "en16")
.iter()
.map(|c| c.display())
.collect();
assert_eq!(
rendered,
vec![
"ifconfig en16 inet 192.168.1.100 netmask 255.255.255.0 alias",
"route add -host 192.168.10.151 -interface en16",
]
);
}
#[test]
fn untagged_skips_in_subnet_gatewayless_route() {
let mut u = Interface {
vlan: None,
address: "192.168.10.1/24".parse().unwrap(),
mtu: None,
routes: vec![],
};
u.routes.push(Route {
destination: "192.168.10.152/32".to_string(),
gateway: None,
mac: None,
});
let rendered: Vec<String> = bringup_commands(&u, "en16")
.iter()
.map(|c| c.display())
.collect();
assert_eq!(
rendered,
vec!["ifconfig en16 inet 192.168.10.1 netmask 255.255.255.0 alias"]
);
}
#[test]
fn destination_in_subnet_detects_containment() {
let addr: IpNet = "192.168.11.87/24".parse().unwrap();
assert!(destination_in_subnet("192.168.11.151/32", &addr));
assert!(!destination_in_subnet("239.255.0.255/32", &addr));
assert!(!destination_in_subnet("10.0.0.1/32", &addr));
assert!(!destination_in_subnet("default", &addr));
}
#[test]
fn teardown_destroys_interface() {
assert_eq!(
teardown_commands("vlan3")[0].display(),
"ifconfig vlan3 destroy"
);
}
#[test]
fn interface_names_match_vlan_ids() {
let p: Profile = toml::from_str(
"name=\"t\"\n[[interface]]\nvlan=10\naddress=\"1.1.1.1/24\"\n[[interface]]\nvlan=11\naddress=\"2.2.2.2/24\"\n",
)
.unwrap();
p.validate().unwrap();
assert_eq!(interface_names(&p), vec!["vlan10", "vlan11"]);
}
#[test]
fn gatewayless_host_route_with_mac_emits_static_arp() {
let mut u = Interface {
vlan: None,
address: "192.168.1.100/24".parse().unwrap(),
mtu: None,
routes: vec![],
};
u.routes.push(Route {
destination: "192.168.10.151/32".to_string(),
gateway: None,
mac: Some("00:00:5e:00:53:01".to_string()),
});
let cmds = bringup_commands(&u, "en16");
let rendered: Vec<String> = cmds.iter().map(|c| c.display()).collect();
assert_eq!(
rendered,
vec![
"ifconfig en16 inet 192.168.1.100 netmask 255.255.255.0 alias",
"route add -host 192.168.10.151 -interface en16",
"arp -s 192.168.10.151 00:00:5e:00:53:01",
]
);
}
struct Contrarian;
impl Platform for Contrarian {
fn name(&self) -> &'static str {
"contrarian"
}
fn iface_name(&self, interface: &Interface, device: &str) -> String {
match interface.vlan {
Some(id) => format!("{device}.{id}"),
None => device.to_string(),
}
}
fn bringup_commands(&self, _i: &Interface, _d: &str) -> Vec<Cmd> {
vec![Cmd::new("true", &[])]
}
fn teardown_commands(&self, iface: &str) -> Vec<Cmd> {
vec![Cmd::new("false", &[iface])]
}
fn route_commands(&self, route: &Route, in_subnet: bool, iface: &str) -> Vec<Cmd> {
if !in_subnet {
return vec![];
}
vec![Cmd::new(
"contrarian-route",
&["add", &route.destination, "dev", iface],
)]
}
fn existing_vlans(
&self,
_runner: &mut dyn CommandRunner,
_parent: &str,
) -> Result<Vec<(u16, String)>> {
Ok(Vec::new())
}
fn is_candidate_device(&self, name: &str) -> bool {
name.starts_with('x')
}
fn reverts_parent_config(&self) -> bool {
true
}
fn list_devices(&self, runner: &mut dyn CommandRunner) -> Result<Vec<String>> {
let out = runner.run(&Cmd::new("contrarian-list", &[]))?;
Ok(out.split_whitespace().map(|s| s.to_string()).collect())
}
fn addresses_on(
&self,
_runner: &mut dyn CommandRunner,
_device: &str,
) -> Result<Vec<IpNet>> {
Ok(vec![])
}
fn is_wireless(&self, _runner: &mut dyn CommandRunner, _device: &str) -> Result<bool> {
Ok(false)
}
fn link_is_active(&self, _runner: &mut dyn CommandRunner, _device: &str) -> Result<bool> {
Ok(false)
}
fn records_created_interface(&self, cmd: &Cmd) -> bool {
cmd.program == "ip"
&& cmd.args.first().map(|a| a == "link").unwrap_or(false)
&& cmd.args.get(1).map(|a| a == "add").unwrap_or(false)
}
}
#[test]
fn a_platform_controls_interface_naming() {
let i = Interface {
vlan: Some(11),
address: "192.168.11.87/24".parse().unwrap(),
mtu: None,
routes: vec![],
};
assert_eq!(Contrarian.iface_name(&i, "eth0"), "eth0.11");
}
#[test]
fn a_platform_derives_the_onlink_decision_from_in_subnet() {
let route = Route {
destination: "192.168.11.200/32".to_string(),
gateway: None,
mac: None,
};
assert_eq!(
Contrarian
.route_commands(&route, true, "eth0.11")
.iter()
.map(|c| c.display())
.collect::<Vec<_>>(),
vec!["contrarian-route add 192.168.11.200/32 dev eth0.11"]
);
assert!(
Contrarian
.route_commands(&route, false, "eth0.11")
.is_empty()
);
}
#[test]
fn a_platform_controls_reverting_parent_config() {
assert!(Contrarian.reverts_parent_config());
}
#[test]
fn linux_emits_ip_route_and_ip_neigh_not_bsd_route_and_arp() {
let route = Route {
destination: "192.168.11.151/32".to_string(),
gateway: None,
mac: Some("00:00:5e:00:53:01".to_string()),
};
let rendered: Vec<String> = Linux
.route_commands(&route, true, "eth0.11")
.iter()
.map(|c| c.display())
.collect();
assert_eq!(
rendered,
vec![
"ip route add 192.168.11.151/32 dev eth0.11",
"ip neigh replace 192.168.11.151 lladdr 00:00:5e:00:53:01 dev eth0.11",
],
"got {rendered:?}"
);
assert!(!rendered.iter().any(|c| c.contains("arp -s")));
}
#[test]
fn macos_route_emission_is_unchanged_by_the_move() {
let route = Route {
destination: "192.168.11.151/32".to_string(),
gateway: None,
mac: Some("00:00:5e:00:53:01".to_string()),
};
let rendered: Vec<String> = MacOs
.route_commands(&route, true, "vlan11")
.iter()
.map(|c| c.display())
.collect();
assert!(
!rendered.iter().any(|c| c.starts_with("route ")),
"got {rendered:?}"
);
assert!(
rendered
.iter()
.any(|c| c == "arp -s 192.168.11.151 00:00:5e:00:53:01")
);
}
#[test]
fn macos_out_of_subnet_still_emits_host_route_then_arp_in_that_order() {
let route = Route {
destination: "192.168.10.151/32".to_string(),
gateway: None,
mac: Some("00:00:5e:00:53:01".to_string()),
};
let rendered: Vec<String> = MacOs
.route_commands(&route, false, "en7")
.iter()
.map(|c| c.display())
.collect();
assert_eq!(
rendered,
vec![
"route add -host 192.168.10.151 -interface en7",
"arp -s 192.168.10.151 00:00:5e:00:53:01",
],
"order matters: arp -s overwrites the self-MAC entry the route installs, \
and an `arp -d` between them deletes the route"
);
}
#[test]
fn macos_impl_matches_the_free_functions_it_replaces() {
let tagged = Interface {
vlan: Some(11),
address: "192.168.11.87/24".parse().unwrap(),
mtu: Some(1500),
routes: vec![
Route {
destination: "239.255.0.255/32".to_string(),
gateway: None,
mac: None,
},
Route {
destination: "192.168.11.151/32".to_string(),
gateway: None,
mac: None,
},
],
};
let untagged = Interface {
vlan: None,
address: "192.168.1.100/24".parse().unwrap(),
mtu: None,
routes: vec![Route {
destination: "192.168.10.151/32".to_string(),
gateway: None,
mac: Some("00:00:5e:00:53:01".to_string()),
}],
};
for i in [&tagged, &untagged] {
assert_eq!(
bringup_commands_for(&MacOs, i, "en7"),
bringup_commands(i, "en7"),
"routing bring-up through the platform must not change macOS output"
);
assert_eq!(MacOs.iface_name(i, "en7"), iface_name(i, "en7"));
}
assert_eq!(
MacOs.teardown_commands("vlan11"),
teardown_commands("vlan11")
);
}
#[test]
fn macos_skips_an_in_subnet_gatewayless_route_and_keeps_parent_config() {
let route = Route {
destination: "192.168.11.151/32".to_string(),
gateway: None,
mac: None,
};
assert!(
MacOs.route_commands(&route, true, "en7").is_empty(),
"an in-subnet interface-scoped host route self-MACs on macOS"
);
assert!(
!MacOs.route_commands(&route, false, "en7").is_empty(),
"out-of-subnet still needs the route"
);
assert!(
!MacOs.reverts_parent_config(),
"untagged parent config persists by design on macOS"
);
}
#[test]
fn macos_emits_no_route_for_a_gatewayless_in_subnet_destination() {
let i = Interface {
vlan: Some(11),
address: "192.168.11.87/24".parse().unwrap(),
mtu: None,
routes: vec![Route {
destination: "192.168.11.151/32".to_string(),
gateway: None,
mac: None,
}],
};
let rendered: Vec<String> = bringup_commands_for(&MacOs, &i, "en7")
.iter()
.map(|c| c.display())
.collect();
assert!(
!rendered.iter().any(|c| c.starts_with("route ")),
"an in-subnet gatewayless destination must not get an interface-scoped \
host route (it self-MACs and black-holes on macOS): {rendered:?}"
);
let other: Vec<String> = bringup_commands_for(&Contrarian, &i, "eth0")
.iter()
.map(|c| c.display())
.collect();
assert!(
other.iter().any(|c| c.contains("192.168.11.151")),
"sanity check failed: a platform that wants on-link host routes \
must still emit one for the same in-subnet destination: {other:?}"
);
}
#[test]
fn macos_emits_a_route_add_for_a_gatewayed_destination() {
let i = Interface {
vlan: Some(11),
address: "192.168.11.87/24".parse().unwrap(),
mtu: None,
routes: vec![Route {
destination: "192.168.20.0/24".to_string(),
gateway: Some("192.168.11.1".parse().unwrap()),
mac: None,
}],
};
let rendered: Vec<String> = bringup_commands_for(&MacOs, &i, "en7")
.iter()
.map(|c| c.display())
.collect();
assert!(
rendered.contains(&"route add 192.168.20.0/24 192.168.11.1".to_string()),
"expected a route add for the gatewayed destination: {rendered:?}"
);
}
#[test]
fn a_non_ifconfig_platform_still_records_what_it_created() {
let create = Cmd::new(
"ip",
&[
"link", "add", "link", "eth0", "name", "eth0.11", "type", "vlan", "id", "11",
],
);
assert!(
Contrarian.records_created_interface(&create),
"a platform must be able to recognize its own creation command"
);
let not_create = Cmd::new("ip", &["addr", "add", "192.168.11.87/24", "dev", "eth0.11"]);
assert!(!Contrarian.records_created_interface(¬_create));
}
#[test]
fn macos_still_recognizes_ifconfig_create_and_nothing_else() {
assert!(MacOs.records_created_interface(&Cmd::new("ifconfig", &["vlan11", "create"])));
assert!(!MacOs.records_created_interface(&Cmd::new(
"ifconfig",
&[
"vlan11",
"inet",
"192.168.11.87",
"netmask",
"255.255.255.0"
]
)));
}
#[test]
fn the_collision_guard_uses_the_platforms_own_interface_names() {
let p = Profile {
name: "t".to_owned(),
description: None,
device: Some("eth0".to_owned()),
interfaces: vec![tagged(11, "192.168.11.87/24")],
};
let state_path = std::env::temp_dir().join("vlanctl-plan-guard-naming.json");
let _ = std::fs::remove_file(&state_path);
let mut r = RecordingRunner::default();
r.stdout
.insert("contrarian-list".to_owned(), "lo0 eth0 eth0.11".to_owned());
let err = crate::commands::apply(&mut r, &Contrarian, &p, None, &state_path, true)
.expect_err("the platform's own interface name must be refused");
assert!(
err.to_string().contains("eth0.11 already exists"),
"expected the guard to name eth0.11: {err}"
);
let mut r = RecordingRunner::default();
r.stdout
.insert("contrarian-list".to_owned(), "lo0 eth0 vlan11".to_owned());
crate::commands::apply(&mut r, &Contrarian, &p, None, &state_path, true)
.expect("a foreign naming scheme's interface is not a collision");
}
#[test]
fn the_route_decision_comes_from_the_platform_not_hardcoded() {
let i = Interface {
vlan: Some(11),
address: "192.168.11.87/24".parse().unwrap(),
mtu: None,
routes: vec![Route {
destination: "192.168.11.151/32".to_string(),
gateway: None,
mac: None,
}],
};
let mac = bringup_commands_for(&MacOs, &i, "en7");
assert!(
!mac.iter().any(|c| c.display().contains("-host")),
"macOS must not emit an in-subnet host route: {mac:?}"
);
let other = bringup_commands_for(&Contrarian, &i, "eth0");
assert!(
other.iter().any(|c| c.display().contains("192.168.11.151")),
"a platform wanting on-link host routes must emit one: {other:?}"
);
}
#[test]
fn linux_names_vlan_interfaces_after_the_parent() {
let i = Interface {
vlan: Some(11),
address: "192.168.11.87/24".parse().unwrap(),
mtu: None,
routes: vec![],
};
assert_eq!(Linux.iface_name(&i, "eth0"), "eth0.11");
let untagged = Interface {
vlan: None,
address: "192.168.11.87/24".parse().unwrap(),
mtu: None,
routes: vec![],
};
assert_eq!(Linux.iface_name(&untagged, "eth0"), "eth0");
}
#[test]
fn linux_falls_back_to_vlan_id_when_the_dotted_name_would_overflow_ifnamsiz() {
assert_eq!(
Linux.iface_name(&tagged(11, "10.0.0.1/24"), "eth0"),
"eth0.11"
);
assert_eq!(
Linux.iface_name(&tagged(4094, "10.0.0.1/24"), "eth0"),
"eth0.4094"
);
let parent10 = "enp0s31f6a";
assert_eq!(parent10.len(), 10);
assert_eq!(
Linux.iface_name(&tagged(4094, "10.0.0.1/24"), parent10),
"enp0s31f6a.4094"
);
assert_eq!(
Linux.iface_name(&tagged(1, "10.0.0.1/24"), parent10),
"enp0s31f6a.1"
);
let parent11 = "enp0s31f6ab";
assert_eq!(parent11.len(), 11);
let short_id_name = Linux.iface_name(&tagged(999, "10.0.0.1/24"), parent11);
let max_id_name = Linux.iface_name(&tagged(4094, "10.0.0.1/24"), parent11);
assert_eq!(short_id_name, "vlan999");
assert_eq!(max_id_name, "vlan4094");
assert!(!short_id_name.starts_with(parent11));
assert!(!max_id_name.starts_with(parent11));
assert!(short_id_name.starts_with("vlan") && max_id_name.starts_with("vlan"));
let parent15 = "enx001122334455";
assert_eq!(parent15.len(), 15);
assert_eq!(
Linux.iface_name(&tagged(1, "10.0.0.1/24"), parent15),
"vlan1"
);
assert_eq!(
Linux.iface_name(&tagged(4094, "10.0.0.1/24"), parent15),
"vlan4094"
);
assert!(
Linux
.iface_name(&tagged(4094, "10.0.0.1/24"), parent15)
.len()
<= 15
);
let untagged = Interface {
vlan: None,
address: "10.0.0.1/24".parse().unwrap(),
mtu: None,
routes: vec![],
};
assert_eq!(Linux.iface_name(&untagged, parent15), parent15);
}
#[test]
fn linux_bringup_uses_the_fallback_name_consistently() {
let cmds = Linux.bringup_commands(&tagged(11, "192.168.11.87/24"), "enx001122334455");
let rendered: Vec<String> = cmds.iter().map(|c| c.display()).collect();
assert_eq!(
rendered,
vec![
"ip link set enx001122334455 up",
"ip link add link enx001122334455 name vlan11 type vlan id 11",
"ip link set vlan11 up",
"ip addr add 192.168.11.87/24 dev vlan11",
]
);
assert!(
!rendered.iter().any(|c| c.contains("enx001122334455.11")),
"no command may re-derive the dotted name: {rendered:?}"
);
}
#[test]
fn linux_tagged_bringup_raises_the_parent_then_adds_ups_and_addresses() {
let i = Interface {
vlan: Some(11),
address: "192.168.11.87/24".parse().unwrap(),
mtu: Some(9000),
routes: vec![],
};
let rendered: Vec<String> = Linux
.bringup_commands(&i, "eth0")
.iter()
.map(|c| c.display())
.collect();
assert_eq!(
rendered,
vec![
"ip link set eth0 up",
"ip link add link eth0 name eth0.11 type vlan id 11",
"ip link set eth0.11 up",
"ip addr add 192.168.11.87/24 dev eth0.11",
"ip link set eth0.11 mtu 9000",
]
);
}
#[test]
fn linux_untagged_raises_the_parent_and_creates_nothing() {
let i = Interface {
vlan: None,
address: "192.168.1.100/24".parse().unwrap(),
mtu: None,
routes: vec![],
};
let rendered: Vec<String> = Linux
.bringup_commands(&i, "eth0")
.iter()
.map(|c| c.display())
.collect();
assert!(
!rendered.iter().any(|c| c.contains("link add")),
"got {rendered:?}"
);
assert_eq!(
rendered,
vec![
"ip link set eth0 up",
"ip addr add 192.168.1.100/24 dev eth0",
],
"got {rendered:?}"
);
}
#[test]
fn linux_teardown_deletes_the_link() {
assert_eq!(
Linux
.teardown_commands("eth0.11")
.iter()
.map(|c| c.display())
.collect::<Vec<_>>(),
vec!["ip link del eth0.11"]
);
}
#[test]
fn linux_wants_the_onlink_host_route_that_macos_refuses() {
let route = Route {
destination: "192.168.11.151/32".to_string(),
gateway: None,
mac: None,
};
assert!(!Linux.route_commands(&route, true, "eth0.11").is_empty());
assert!(!Linux.route_commands(&route, false, "eth0.11").is_empty());
assert!(MacOs.route_commands(&route, true, "vlan11").is_empty());
}
#[test]
fn linux_reverts_parent_config_because_it_can_delete_one_address() {
assert!(Linux.reverts_parent_config());
}
#[test]
fn linux_recognizes_its_own_creation_command() {
assert!(Linux.records_created_interface(&Cmd::new(
"ip",
&[
"link", "add", "link", "eth0", "name", "eth0.11", "type", "vlan", "id", "11"
]
)));
assert!(!Linux.records_created_interface(&Cmd::new(
"ip",
&["addr", "add", "192.168.11.87/24", "dev", "eth0.11"]
)));
assert!(!Linux.records_created_interface(&Cmd::new("ip", &["link", "set", "eth0", "up"])));
}
#[test]
fn linux_link_is_active_reads_carrier() {
let mut r = RecordingRunner::default();
r.stdout.insert(
"cat /sys/class/net/eth0/carrier".to_string(),
"1\n".to_string(),
);
r.stdout.insert(
"cat /sys/class/net/eth1/carrier".to_string(),
"0\n".to_string(),
);
assert!(Linux.link_is_active(&mut r, "eth0").unwrap());
assert!(!Linux.link_is_active(&mut r, "eth1").unwrap());
}
#[test]
fn linux_link_is_active_treats_an_unreadable_carrier_as_down() {
let mut r = RecordingRunner {
fail_at: Some(0),
..Default::default()
};
assert!(
!Linux
.link_is_active(&mut r, "eth0")
.expect("an unreadable carrier is not an error"),
);
assert_eq!(
r.commands.len(),
2,
"carrier must be attempted, then operstate consulted to tell \
admin-down apart from a device that cannot be asked at all"
);
assert!(
r.commands[1].display().contains("operstate"),
"{:?}",
r.commands
);
}
struct AllFailRunner {
calls: usize,
}
impl CommandRunner for AllFailRunner {
fn run(&mut self, cmd: &Cmd) -> Result<String> {
self.calls += 1;
anyhow::bail!("simulated total failure running `{}`", cmd.display())
}
}
#[test]
fn linux_link_is_active_errors_when_the_device_cannot_be_asked_at_all() {
let mut r = AllFailRunner { calls: 0 };
let err = Linux
.link_is_active(&mut r, "eth0")
.expect_err("a wholly unaskable device must be an Err, not `false`");
assert_eq!(r.calls, 2, "both carrier and operstate must be attempted");
assert!(
err.to_string().contains("eth0"),
"the error should name the device: {err}"
);
}
#[test]
fn linux_is_wireless_looks_for_the_wireless_sysfs_entry() {
let mut r = RecordingRunner::default();
r.stdout.insert(
"ls /sys/class/net/wlan0".to_string(),
"address\ncarrier\nphy80211\nwireless\n".to_string(),
);
r.stdout.insert(
"ls /sys/class/net/eth0".to_string(),
"address\ncarrier\ndevice\n".to_string(),
);
assert!(Linux.is_wireless(&mut r, "wlan0").unwrap());
assert!(!Linux.is_wireless(&mut r, "eth0").unwrap());
}
#[test]
fn linux_is_wireless_defaults_to_wired_for_an_unstubbed_device() {
let mut r = RecordingRunner::default();
assert!(!Linux.is_wireless(&mut r, "eth0").unwrap());
}
#[test]
fn linux_candidate_devices_exclude_loopback_virtual_and_vlan_subinterfaces() {
for ok in ["eth0", "enp0s31f6", "enx00e04c680001", "eno1", "ens5"] {
assert!(Linux.is_candidate_device(ok), "{ok} should be a candidate");
}
for no in [
"lo",
"docker0",
"veth1a2b",
"br-abc123",
"virbr0",
"vlan11",
"tun0",
"tap0",
"bond0",
"wlp0s20f3",
] {
assert!(
!Linux.is_candidate_device(no),
"{no} must not be a candidate"
);
}
assert!(!Linux.is_candidate_device("eth0.11"));
}
#[test]
fn macos_candidates_are_en_prefixed_and_exclude_vlan_subinterfaces() {
assert!(MacOs.is_candidate_device("en7"));
assert!(!MacOs.is_candidate_device("lo0"));
assert!(!MacOs.is_candidate_device("bridge0"));
assert!(
!MacOs.is_candidate_device("en0.100"),
"a vlan sub-interface is not a parent candidate"
);
}
#[test]
fn linux_existing_vlans_reports_ids_with_the_names_holding_them() {
let mut r = RecordingRunner::default();
r.stdout.insert(
"ip -d -json link show".to_string(),
r#"[
{"ifname":"lo"},
{"ifname":"eth0"},
{"ifname":"vlan11","link":"eth0",
"linkinfo":{"info_kind":"vlan","info_data":{"protocol":"802.1Q","id":11}}},
{"ifname":"vlan10","link":"eth0",
"linkinfo":{"info_kind":"vlan","info_data":{"protocol":"802.1Q","id":10}}},
{"ifname":"other.7","link":"eth9",
"linkinfo":{"info_kind":"vlan","info_data":{"protocol":"802.1Q","id":7}}}
]"#
.to_string(),
);
let mut got = Linux.existing_vlans(&mut r, "eth0").unwrap();
got.sort();
assert_eq!(
got,
vec![(10, "vlan10".to_string()), (11, "vlan11".to_string())],
"only VLANs on the named parent count; eth9's id 7 must not appear"
);
}
#[test]
fn macos_reports_no_vlan_id_constraint() {
let mut r = RecordingRunner::default();
assert!(MacOs.existing_vlans(&mut r, "en7").unwrap().is_empty());
assert!(
r.commands.is_empty(),
"macOS must not issue a probe for a constraint it does not enforce"
);
}
#[test]
fn linux_host_state_reads_use_ip_json_not_ifconfig() {
let mut r = RecordingRunner::default();
r.stdout.insert(
"ip -json link show".to_string(),
r#"[{"ifname":"lo"},{"ifname":"eth0"}]"#.to_string(),
);
assert_eq!(Linux.list_devices(&mut r).unwrap(), vec!["lo", "eth0"]);
}
#[test]
fn linux_addresses_on_keeps_only_complete_inet_entries() {
let mut r = RecordingRunner::default();
r.stdout.insert(
"ip -json addr show dev eth0".to_string(),
r#"[{
"ifname": "eth0",
"addr_info": [
{"family": "inet", "local": "192.168.11.87", "prefixlen": 24},
{"family": "inet6", "local": "fe80::1", "prefixlen": 64},
{"family": "inet", "prefixlen": 24},
{"family": "inet", "local": "192.168.11.88"}
]
}]"#
.to_string(),
);
let nets = Linux.addresses_on(&mut r, "eth0").unwrap();
assert_eq!(
nets,
vec!["192.168.11.87/24".parse::<IpNet>().unwrap()],
"expected the inet6 entry excluded and both incomplete inet \
entries (missing local, missing prefixlen) skipped: {nets:?}"
);
}
}