Skip to main content

isothrum_runner/
net.rs

1//! The host's ports, behind [`HostPorts`]: whether one is taken, a free one to pin, and whether an
2//! address answers. [`LoopbackPorts`] binds real sockets; the `fake` feature's `FakePorts` answers
3//! from a test's setup.
4
5use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, TcpListener, UdpSocket};
6use std::time::Duration;
7
8use isoloom_manifest::Protocol;
9
10use crate::BoxFuture;
11pub(crate) use sealed::HeldPort;
12
13/// The host's ports. Sealed: [`RunnerConfig::new`](crate::RunnerConfig::new) gives the real
14/// host's (sockets on the loopback), and the `fake` feature's `FakePorts` answers from a test's
15/// setup; no other implementation is needed, and only the runner asks them anything.
16pub trait HostPorts: Send + Sync + sealed::Ports {}
17
18impl<T: sealed::Ports> HostPorts for T {}
19
20/// The real host: sockets on the loopback. Never all interfaces: binding 0.0.0.0 made Windows
21/// Firewall ask whether the embedder's app may accept connections from the network.
22#[derive(Debug, Clone, Copy, Default)]
23pub(crate) struct LoopbackPorts;
24
25/// What keeps [`HostPorts`] to this crate's implementations, and its questions to the runner.
26pub(crate) mod sealed {
27    use std::time::Duration;
28
29    use isoloom_manifest::Protocol;
30
31    use crate::BoxFuture;
32
33    /// A free port, held until dropped so it isn't handed out twice while others are picked.
34    pub struct HeldPort {
35        /// The port.
36        pub port: u16,
37        _hold: Box<dyn Send + Sync>,
38    }
39
40    impl std::fmt::Debug for HeldPort {
41        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42            f.debug_struct("HeldPort").field("port", &self.port).finish_non_exhaustive()
43        }
44    }
45
46    impl HeldPort {
47        /// `port`, held by `hold` (a socket, or nothing for a fake).
48        pub(crate) fn new(port: u16, hold: impl Send + Sync + 'static) -> HeldPort {
49            HeldPort { port, _hold: Box::new(hold) }
50        }
51    }
52
53    /// The host's ports, as the runner asks them. Implemented by this crate's ports only.
54    pub trait Ports: Send + Sync {
55        /// Whether `port` is taken over `protocol` on the loopback.
56        fn in_use(&self, port: u16, protocol: Protocol) -> bool;
57        /// A free loopback port over `protocol`, held; none when none is left.
58        ///
59        /// # Errors
60        ///
61        /// The loopback couldn't be bound (no file descriptor left, a loopback that is down).
62        fn pick_free(&self, protocol: Protocol) -> std::io::Result<Option<HeldPort>>;
63        /// Whether `host:port` accepts a TCP connection within `within`.
64        fn reachable<'a>(&'a self, host: &'a str, port: u16, within: Duration) -> BoxFuture<'a, bool>;
65    }
66}
67
68impl sealed::Ports for LoopbackPorts {
69    /// Taken when the IPv4 loopback can't be bound, or the IPv6 one is held (a browser opening
70    /// `localhost` may reach it first); an absent IPv6 loopback doesn't count.
71    fn in_use(&self, port: u16, protocol: Protocol) -> bool {
72        let v4 = bind(Ipv4Addr::LOCALHOST.into(), port, protocol);
73        let v6 = bind(Ipv6Addr::LOCALHOST.into(), port, protocol);
74        v4.is_err() || v6.is_err_and(|e| held_elsewhere(&e))
75    }
76
77    /// A port the OS offers on the IPv4 loopback that [`in_use`](sealed::Ports::in_use) wouldn't call
78    /// taken: one held on the IPv6 loopback is passed over ([`free_on_both`]).
79    fn pick_free(&self, protocol: Protocol) -> std::io::Result<Option<HeldPort>> {
80        free_on_both(protocol, || match protocol {
81            Protocol::Udp => {
82                let s = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
83                Ok(HeldPort::new(s.local_addr()?.port(), s))
84            }
85            Protocol::Tcp => {
86                let l = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
87                Ok(HeldPort::new(l.local_addr()?.port(), l))
88            }
89        })
90    }
91
92    fn reachable<'a>(&'a self, host: &'a str, port: u16, within: Duration) -> BoxFuture<'a, bool> {
93        Box::pin(async move { matches!(tokio::time::timeout(within, tokio::net::TcpStream::connect((host, port))).await, Ok(Ok(_))) })
94    }
95}
96
97/// How many ports the OS may offer a pick before it gives up.
98const PICKS: usize = 16;
99
100/// The first port `next` holds on the IPv4 loopback that the IPv6 one doesn't hold either, as
101/// [`LoopbackPorts`]'s `in_use` counts a port; each one passed over stays held meanwhile, so it
102/// isn't offered again. None after [`PICKS`] offers.
103fn free_on_both(protocol: Protocol, mut next: impl FnMut() -> std::io::Result<HeldPort>) -> std::io::Result<Option<HeldPort>> {
104    let mut passed = Vec::new();
105    for _ in 0..PICKS {
106        let held = next()?;
107        if bind(Ipv6Addr::LOCALHOST.into(), held.port, protocol).is_err_and(|e| held_elsewhere(&e)) {
108            passed.push(held);
109        } else {
110            return Ok(Some(held));
111        }
112    }
113    Ok(None)
114}
115
116/// Binds (then frees) `ip:port` over `protocol`.
117fn bind(ip: IpAddr, port: u16, protocol: Protocol) -> std::io::Result<()> {
118    match protocol {
119        Protocol::Udp => UdpSocket::bind((ip, port)).map(drop),
120        Protocol::Tcp => TcpListener::bind((ip, port)).map(drop),
121    }
122}
123
124/// Whether a failed bind means someone holds the port (or the OS reserved it, as Windows does
125/// for WinNAT and Hyper-V), not that the address doesn't exist here.
126fn held_elsewhere(e: &std::io::Error) -> bool {
127    matches!(e.kind(), std::io::ErrorKind::AddrInUse | std::io::ErrorKind::PermissionDenied)
128}
129
130/// Ports answered from a test's setup (feature `fake`): the free ones handed out in order. An
131/// embedder's tests script those only; the runner's own also mark ports taken, addresses
132/// answering and binds refused.
133#[cfg(any(test, feature = "fake"))]
134#[derive(Debug, Default)]
135pub struct FakePorts {
136    taken: std::sync::Mutex<std::collections::BTreeSet<(u16, Protocol)>>,
137    free: std::sync::Mutex<std::collections::VecDeque<u16>>,
138    answering: std::sync::Mutex<std::collections::BTreeSet<(String, u16)>>,
139    /// What a pick fails with instead of handing out a port, if anything.
140    unbindable: std::sync::Mutex<Option<std::io::ErrorKind>>,
141}
142
143#[cfg(any(test, feature = "fake"))]
144impl FakePorts {
145    /// No port taken; `free` handed out in order.
146    pub fn new(free: impl IntoIterator<Item = u16>) -> FakePorts {
147        FakePorts {
148            free: std::sync::Mutex::new(free.into_iter().collect()),
149            ..FakePorts::default()
150        }
151    }
152
153    /// Marks `port` taken over `protocol`.
154    #[cfg(test)]
155    pub(crate) fn take(&self, port: u16, protocol: Protocol) {
156        self.taken.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((port, protocol));
157    }
158
159    /// Makes every pick of a free port fail as a bind refused with `kind` would.
160    #[cfg(test)]
161    pub(crate) fn refuse_binds(&self, kind: std::io::ErrorKind) {
162        *self.unbindable.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(kind);
163    }
164
165    /// Makes `host:port` answer.
166    #[cfg(test)]
167    pub(crate) fn answer(&self, host: &str, port: u16) {
168        self.answering
169            .lock()
170            .unwrap_or_else(std::sync::PoisonError::into_inner)
171            .insert((host.to_owned(), port));
172    }
173}
174
175#[cfg(any(test, feature = "fake"))]
176impl sealed::Ports for FakePorts {
177    fn in_use(&self, port: u16, protocol: Protocol) -> bool {
178        self.taken.lock().unwrap_or_else(std::sync::PoisonError::into_inner).contains(&(port, protocol))
179    }
180
181    fn pick_free(&self, _protocol: Protocol) -> std::io::Result<Option<HeldPort>> {
182        if let Some(kind) = *self.unbindable.lock().unwrap_or_else(std::sync::PoisonError::into_inner) {
183            return Err(kind.into());
184        }
185        Ok(self
186            .free
187            .lock()
188            .unwrap_or_else(std::sync::PoisonError::into_inner)
189            .pop_front()
190            .map(|p| HeldPort::new(p, ())))
191    }
192
193    fn reachable<'a>(&'a self, host: &'a str, port: u16, within: Duration) -> BoxFuture<'a, bool> {
194        let up = self
195            .answering
196            .lock()
197            .unwrap_or_else(std::sync::PoisonError::into_inner)
198            .contains(&(host.to_owned(), port));
199        Box::pin(async move {
200            if !up {
201                tokio::time::sleep(within).await;
202            }
203            up
204        })
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::sealed::Ports;
211    use super::*;
212
213    /// A port free over both TCP and UDP, below every OS's ephemeral range, so nothing else is
214    /// handed it while the test runs.
215    fn port_free_over_both() -> u16 {
216        let start = 20_000 + u16::try_from(std::process::id() % 10_000).unwrap();
217        (start..32_768)
218            .chain(20_000..start)
219            .find(|&p| !LoopbackPorts.in_use(p, Protocol::Tcp) && !LoopbackPorts.in_use(p, Protocol::Udp))
220            .unwrap()
221    }
222
223    #[test]
224    fn a_held_port_is_in_use_over_its_protocol_only() {
225        let tcp_port = port_free_over_both();
226        let _tcp = TcpListener::bind(("127.0.0.1", tcp_port)).unwrap();
227        assert!(LoopbackPorts.in_use(tcp_port, Protocol::Tcp));
228        assert!(!LoopbackPorts.in_use(tcp_port, Protocol::Udp));
229        let udp_port = port_free_over_both();
230        let _udp = UdpSocket::bind(("127.0.0.1", udp_port)).unwrap();
231        assert!(LoopbackPorts.in_use(udp_port, Protocol::Udp), "a UDP holder (dnsmasq on 53) is caught");
232        assert!(!LoopbackPorts.in_use(udp_port, Protocol::Tcp));
233    }
234
235    #[test]
236    fn only_a_held_or_reserved_address_counts_on_the_ipv6_loopback() {
237        use std::io::{Error, ErrorKind};
238        assert!(held_elsewhere(&Error::from(ErrorKind::AddrInUse)));
239        assert!(held_elsewhere(&Error::from(ErrorKind::PermissionDenied)));
240        assert!(!held_elsewhere(&Error::from(ErrorKind::AddrNotAvailable)), "no IPv6 loopback here");
241    }
242
243    #[test]
244    fn picked_ports_are_held_until_dropped() {
245        let a = LoopbackPorts.pick_free(Protocol::Tcp).unwrap().unwrap();
246        let b = LoopbackPorts.pick_free(Protocol::Tcp).unwrap().unwrap();
247        assert_ne!(a.port, b.port);
248        assert!(LoopbackPorts.in_use(a.port, Protocol::Tcp));
249    }
250
251    /// Regression: a pick bound the IPv4 loopback only, so it could hand out a port held on the
252    /// IPv6 one, which `in_use` calls taken. Such a port is passed over (kept held meanwhile).
253    #[test]
254    fn a_port_held_on_the_ipv6_loopback_is_passed_over() {
255        let Ok(v6) = TcpListener::bind((Ipv6Addr::LOCALHOST, 0)) else {
256            return; // No IPv6 loopback here: nothing can hold a port on it.
257        };
258        let held = v6.local_addr().unwrap().port();
259        let Ok(v4) = TcpListener::bind((Ipv4Addr::LOCALHOST, held)) else {
260            return; // The OS took the IPv4 port too: nothing to pass over.
261        };
262        let mut offers = vec![HeldPort::new(held, v4)].into_iter();
263        let picked = free_on_both(Protocol::Tcp, || {
264            Ok(offers.next().unwrap_or_else(|| {
265                let l = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
266                HeldPort::new(l.local_addr().unwrap().port(), l)
267            }))
268        })
269        .unwrap()
270        .unwrap();
271        assert_ne!(picked.port, held);
272        assert!(LoopbackPorts.in_use(held, Protocol::Tcp), "{held} held on ::1");
273    }
274
275    #[tokio::test]
276    async fn a_listening_address_is_reachable() {
277        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
278        let port = listener.local_addr().unwrap().port();
279        assert!(LoopbackPorts.reachable("127.0.0.1", port, Duration::from_secs(2)).await);
280        drop(listener);
281        assert!(!LoopbackPorts.reachable("127.0.0.1", port, Duration::from_secs(2)).await);
282    }
283}