aither_sandbox/spawn/
route.rs1use std::net::IpAddr;
4
5#[derive(Debug, thiserror::Error)]
7pub enum HostRouteError {
8 #[error("a host route requires a non-empty name")]
10 BlankName,
11 #[error("the unspecified address {0} would expose a host listener on every interface")]
13 Unspecified(IpAddr),
14 #[error("the multicast address {0} cannot serve a host listener")]
16 Multicast(IpAddr),
17}
18
19#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct HostRoute {
36 name: String,
37 address: IpAddr,
38}
39
40impl HostRoute {
41 pub fn new(name: impl Into<String>, address: IpAddr) -> Result<Self, HostRouteError> {
47 let name = name.into();
48 if name.trim().is_empty() {
49 return Err(HostRouteError::BlankName);
50 }
51 if address.is_unspecified() {
52 return Err(HostRouteError::Unspecified(address));
53 }
54 if address.is_multicast() {
55 return Err(HostRouteError::Multicast(address));
56 }
57 Ok(Self { name, address })
58 }
59
60 #[must_use]
62 pub fn name(&self) -> &str {
63 &self.name
64 }
65
66 #[must_use]
68 pub const fn address(&self) -> IpAddr {
69 self.address
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
76
77 use super::*;
78
79 #[test]
80 fn a_route_rejects_the_unspecified_and_multicast_addresses() {
81 for address in [
82 IpAddr::V4(Ipv4Addr::UNSPECIFIED),
83 IpAddr::V6(Ipv6Addr::UNSPECIFIED),
84 ] {
85 assert!(matches!(
86 HostRoute::new("host.docker.internal", address),
87 Err(HostRouteError::Unspecified(_))
88 ));
89 }
90 for address in [
91 IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1)),
92 IpAddr::V6(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1)),
93 ] {
94 assert!(matches!(
95 HostRoute::new("host.docker.internal", address),
96 Err(HostRouteError::Multicast(_))
97 ));
98 }
99 }
100
101 #[test]
102 fn a_route_needs_a_name() {
103 assert!(matches!(
104 HostRoute::new(" ", IpAddr::V4(Ipv4Addr::LOCALHOST)),
105 Err(HostRouteError::BlankName)
106 ));
107 }
108
109 #[test]
110 fn a_route_names_what_the_container_dials_and_the_host_binds() {
111 let route =
112 HostRoute::new("host.docker.internal", IpAddr::V4(Ipv4Addr::LOCALHOST)).unwrap();
113 assert_eq!(route.name(), "host.docker.internal");
114 assert_eq!(route.address(), IpAddr::V4(Ipv4Addr::LOCALHOST));
115 }
116
117 #[test]
118 fn loopback_and_gateway_addresses_are_accepted() {
119 for address in [
120 IpAddr::V4(Ipv4Addr::LOCALHOST),
121 IpAddr::V6(Ipv6Addr::LOCALHOST),
122 IpAddr::V4(Ipv4Addr::new(172, 17, 0, 1)),
123 ] {
124 HostRoute::new("host.docker.internal", address).unwrap();
125 }
126 }
127}