use std::net::IpAddr;
#[derive(Debug, thiserror::Error)]
pub enum HostRouteError {
#[error("a host route requires a non-empty name")]
BlankName,
#[error("the unspecified address {0} would expose a host listener on every interface")]
Unspecified(IpAddr),
#[error("the multicast address {0} cannot serve a host listener")]
Multicast(IpAddr),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostRoute {
name: String,
address: IpAddr,
}
impl HostRoute {
pub fn new(name: impl Into<String>, address: IpAddr) -> Result<Self, HostRouteError> {
let name = name.into();
if name.trim().is_empty() {
return Err(HostRouteError::BlankName);
}
if address.is_unspecified() {
return Err(HostRouteError::Unspecified(address));
}
if address.is_multicast() {
return Err(HostRouteError::Multicast(address));
}
Ok(Self { name, address })
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub const fn address(&self) -> IpAddr {
self.address
}
}
#[cfg(test)]
mod tests {
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use super::*;
#[test]
fn a_route_rejects_the_unspecified_and_multicast_addresses() {
for address in [
IpAddr::V4(Ipv4Addr::UNSPECIFIED),
IpAddr::V6(Ipv6Addr::UNSPECIFIED),
] {
assert!(matches!(
HostRoute::new("host.docker.internal", address),
Err(HostRouteError::Unspecified(_))
));
}
for address in [
IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1)),
IpAddr::V6(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1)),
] {
assert!(matches!(
HostRoute::new("host.docker.internal", address),
Err(HostRouteError::Multicast(_))
));
}
}
#[test]
fn a_route_needs_a_name() {
assert!(matches!(
HostRoute::new(" ", IpAddr::V4(Ipv4Addr::LOCALHOST)),
Err(HostRouteError::BlankName)
));
}
#[test]
fn a_route_names_what_the_container_dials_and_the_host_binds() {
let route =
HostRoute::new("host.docker.internal", IpAddr::V4(Ipv4Addr::LOCALHOST)).unwrap();
assert_eq!(route.name(), "host.docker.internal");
assert_eq!(route.address(), IpAddr::V4(Ipv4Addr::LOCALHOST));
}
#[test]
fn loopback_and_gateway_addresses_are_accepted() {
for address in [
IpAddr::V4(Ipv4Addr::LOCALHOST),
IpAddr::V6(Ipv6Addr::LOCALHOST),
IpAddr::V4(Ipv4Addr::new(172, 17, 0, 1)),
] {
HostRoute::new("host.docker.internal", address).unwrap();
}
}
}