use crate::system::interface::Link;
use crate::model::ip::scoped::Zone;
use crate::model::parse::ip::Keyword;
use crate::system::interface;
const ZONE_SIGIL: char = '%';
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum LinkError {
#[error("a link expression cannot be empty")]
Empty,
#[error("'{expression}' is not an interface on this machine (it has: {})", .available.join(", "))]
Unknown {
expression: String,
available: Vec<String>,
},
#[error("no local segment was found to listen on")]
NoLan,
#[error("this machine has no interface that is up, so there is nothing to listen to")]
NoLinks,
}
pub fn for_listening<S: AsRef<str>>(exprs: &[S]) -> Result<Vec<Zone>, LinkError> {
for_listening_on(exprs, &crate::system::interface::interfaces())
}
pub fn for_listening_on<S: AsRef<str>>(
exprs: &[S],
interfaces: &[Link],
) -> Result<Vec<Zone>, LinkError> {
if exprs.is_empty() {
let links: Vec<Zone> = interfaces
.iter()
.filter(|link| link.is_up())
.map(Link::zone)
.collect();
return if links.is_empty() {
Err(LinkError::NoLinks)
} else {
Ok(links)
};
}
let mut links: Vec<Zone> = Vec::with_capacity(exprs.len());
for expr in exprs {
let written = expr.as_ref().trim();
let name = written.strip_prefix(ZONE_SIGIL).unwrap_or(written);
if name.is_empty() {
return Err(LinkError::Empty);
}
let link = if Keyword::from_token(name) == Some(Keyword::Lan) {
interface::lan_link_with(interfaces.to_vec())
.map(|lan| lan.link.zone())
.ok_or(LinkError::NoLan)?
} else {
interfaces
.iter()
.find(|link| link.name() == name)
.map(Link::zone)
.ok_or_else(|| LinkError::Unknown {
expression: written.to_owned(),
available: interfaces
.iter()
.map(|link| link.name().to_owned())
.collect(),
})?
};
if !links.contains(&link) {
links.push(link);
}
}
Ok(links)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::system::interface::Link;
fn table() -> Vec<Link> {
let up = |name: &str, index: u32, up: bool| Link::new(name, index).with_link_up(up);
vec![
up("en0", 4, true),
up("en1", 5, true),
up("awdl0", 9, false),
]
}
fn lan_capable(name: &str, index: u32) -> Link {
Link::new(name, index)
.with_link_up(true)
.with_physical(true)
.with_addressing(crate::system::interface::Addressing::Broadcast)
.with_kind(crate::system::interface::LinkKind::Wired)
.with_mac(crate::model::mac::MacAddr::new(2, 0, 0, 0, 0, 1))
.with_addresses(vec![crate::system::interface::LinkAddress::new(
std::net::IpAddr::V4(std::net::Ipv4Addr::new(192, 168, 1, 10)),
24,
)])
.with_default_route(true)
}
#[test]
fn lan_is_answered_from_the_table_this_was_given() {
let table = vec![lan_capable("lab0", 42)];
let links = for_listening_on(&["lan"], &table).expect("the table has a lan");
assert_eq!(links.len(), 1);
assert_eq!(
links[0].name(),
"lab0",
"`lan` was answered from the machine rather than from the table"
);
}
#[test]
fn a_table_with_no_lan_refuses_rather_than_asking_the_machine() {
assert!(matches!(
for_listening_on(&["lan"], &table()),
Err(LinkError::NoLan)
));
assert!(matches!(
for_listening_on(&["lan"], &[]),
Err(LinkError::NoLan)
));
}
#[test]
fn a_link_is_named_by_its_interface_name() {
let links = for_listening_on(&["en1"], &table()).expect("en1 is on the machine");
assert_eq!(links.len(), 1);
assert_eq!(links[0].name(), "en1");
assert_eq!(
links[0].index(),
Some(5),
"the index is what a link-local address needs to be usable"
);
}
#[test]
fn the_zone_sigil_names_the_same_link_as_the_bare_name() {
let with = for_listening_on(&["%en0"], &table()).expect("the sigil is accepted");
let without = for_listening_on(&["en0"], &table()).expect("so is the bare name");
assert_eq!(with, without);
}
#[test]
fn a_link_named_twice_is_one_link() {
let links = for_listening_on(&["en0", "%en0", "en1"], &table()).expect("all are real");
assert_eq!(
links.iter().map(Zone::name).collect::<Vec<_>>(),
vec!["en0", "en1"],
"deduplicated, and in the order they were written"
);
}
#[test]
fn nothing_written_means_every_link_that_is_up() {
let links = for_listening_on::<&str>(&[], &table()).expect("the machine has links");
assert_eq!(
links.iter().map(Zone::name).collect::<Vec<_>>(),
vec!["en0", "en1"],
"a link that is down carries nothing to hear"
);
}
#[test]
fn an_unknown_link_names_what_the_machine_has_instead() {
let error = for_listening_on(&["eth0"], &table()).expect_err("eth0 is not on this machine");
let LinkError::Unknown {
expression,
available,
} = &error
else {
panic!("expected an unknown link, got {error:?}");
};
assert_eq!(expression, "eth0");
assert!(available.contains(&"en0".to_owned()));
assert!(
error.to_string().contains("en0"),
"and it says so out loud: {error}"
);
}
#[test]
fn an_empty_expression_is_refused_rather_than_read_as_every_link() {
assert!(matches!(
for_listening_on(&[" "], &table()),
Err(LinkError::Empty)
));
assert!(matches!(
for_listening_on(&["%"], &table()),
Err(LinkError::Empty)
));
}
#[test]
fn a_machine_with_nothing_up_has_nothing_to_listen_to() {
assert!(matches!(
for_listening_on::<&str>(&[], &[]),
Err(LinkError::NoLinks)
));
}
}