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
5mod reservations;
6pub(crate) use reservations::PortReservations;
7
8use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, TcpListener, UdpSocket};
9use std::time::Duration;
10
11use crate::project::platform::Protocol;
12
13use crate::BoxFuture;
14use crate::port::HostPort;
15pub(crate) use sealed::HeldPort;
16
17/// The host's ports. Sealed: [`RunnerConfig::new`](crate::RunnerConfig::new) gives the real
18/// host's (sockets on the loopback), and the `fake` feature's `FakePorts` answers from a test's
19/// setup; no other implementation is needed, and only the runner asks them anything.
20pub trait HostPorts: Send + Sync + sealed::Ports {}
21
22impl<T: sealed::Ports> HostPorts for T {}
23
24/// The real host: sockets on the loopback. Nothing listens on all interfaces: binding 0.0.0.0
25/// made Windows Firewall ask whether the embedder's app may accept connections from the network
26/// ([`held_on_all`] only binds there, and not on Windows).
27#[derive(Debug, Clone, Copy, Default)]
28pub(crate) struct LoopbackPorts;
29
30/// What keeps [`HostPorts`] to this crate's implementations, and its questions to the runner.
31pub(crate) mod sealed {
32    use std::time::Duration;
33
34    use crate::project::platform::Protocol;
35
36    use crate::BoxFuture;
37    use crate::port::HostPort;
38
39    /// A free port, held until dropped so it isn't handed out twice while others are picked.
40    pub struct HeldPort {
41        /// The port.
42        pub port: HostPort,
43        _hold: Box<dyn Send + Sync>,
44    }
45
46    impl std::fmt::Debug for HeldPort {
47        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48            f.debug_struct("HeldPort").field("port", &self.port).finish_non_exhaustive()
49        }
50    }
51
52    impl HeldPort {
53        /// `port`, held by `hold` (a socket, or nothing for a fake).
54        pub(crate) fn new(port: HostPort, hold: impl Send + Sync + 'static) -> HeldPort {
55            HeldPort { port, _hold: Box::new(hold) }
56        }
57    }
58
59    /// The host's ports, as the runner asks them. Implemented by this crate's ports only.
60    pub trait Ports: Send + Sync {
61        /// Whether `port` is taken over `protocol` on the loopback.
62        fn in_use(&self, port: HostPort, protocol: Protocol) -> bool;
63        /// A free loopback port over `protocol`, held; none when none is left.
64        ///
65        /// # Errors
66        ///
67        /// The loopback couldn't be bound (no file descriptor left, a loopback that is down).
68        fn pick_free(&self, protocol: Protocol) -> std::io::Result<Option<HeldPort>>;
69        /// Whether `host:port` accepts a TCP connection within `within` and keeps it: a port
70        /// forwarded by a proxy (Docker's, a hypervisor's NAT) accepts every connection and
71        /// closes it at once when nothing listens behind, which is not a service ready.
72        fn reachable<'a>(&'a self, host: &'a str, port: u16, within: Duration) -> BoxFuture<'a, bool>;
73    }
74}
75
76impl sealed::Ports for LoopbackPorts {
77    /// Taken when the IPv4 loopback can't be bound, or the IPv6 one is held (a browser opening
78    /// `localhost` may reach it first), or a program holds it on all interfaces
79    /// ([`held_on_all`]); an absent IPv6 loopback doesn't count.
80    fn in_use(&self, port: HostPort, protocol: Protocol) -> bool {
81        let port = port.get();
82        let v4 = bind(Ipv4Addr::LOCALHOST.into(), port, protocol);
83        let v6 = bind(Ipv6Addr::LOCALHOST.into(), port, protocol);
84        v4.is_err() || v6.is_err_and(|e| held_elsewhere(&e)) || held_on_all(port, protocol)
85    }
86
87    /// A port the OS offers on the IPv4 loopback that [`in_use`](sealed::Ports::in_use) wouldn't call
88    /// taken: one held on the IPv6 loopback is passed over ([`free_on_both`]).
89    fn pick_free(&self, protocol: Protocol) -> std::io::Result<Option<HeldPort>> {
90        free_on_both(protocol, || match protocol {
91            Protocol::Udp => {
92                let s = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
93                Ok(HeldPort::new(HostPort::new(s.local_addr()?.port()), s))
94            }
95            Protocol::Tcp => {
96                let l = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
97                Ok(HeldPort::new(HostPort::new(l.local_addr()?.port()), l))
98            }
99        })
100    }
101
102    fn reachable<'a>(&'a self, host: &'a str, port: u16, within: Duration) -> BoxFuture<'a, bool> {
103        Box::pin(async move {
104            match tokio::time::timeout(within, tokio::net::TcpStream::connect((host, port))).await {
105                Ok(Ok(stream)) => kept_open(stream).await,
106                _ => false,
107            }
108        })
109    }
110}
111
112/// How long an accepted connection is watched for the peer closing it: a proxy with nothing
113/// behind closes within milliseconds; a service that waits for the client's first bytes keeps it.
114const HOLD: Duration = Duration::from_millis(500);
115
116/// Whether the peer keeps `stream` open for [`HOLD`] (or speaks first): closed at once is a
117/// proxy's accept with nothing listening behind.
118async fn kept_open(stream: tokio::net::TcpStream) -> bool {
119    let mut first = [0u8; 1];
120    match tokio::time::timeout(HOLD, stream.peek(&mut first)).await {
121        Ok(Ok(0) | Err(_)) => false,
122        Ok(Ok(_)) | Err(_) => true,
123    }
124}
125
126/// How many ports the OS may offer a pick before it gives up.
127const PICKS: usize = 16;
128
129/// The first port `next` holds on the IPv4 loopback that the IPv6 one doesn't hold either, as
130/// [`LoopbackPorts`]'s `in_use` counts a port; each one passed over stays held meanwhile, so it
131/// isn't offered again. None after [`PICKS`] offers.
132fn free_on_both(protocol: Protocol, mut next: impl FnMut() -> std::io::Result<HeldPort>) -> std::io::Result<Option<HeldPort>> {
133    let mut passed = Vec::new();
134    for _ in 0..PICKS {
135        let held = next()?;
136        if bind(Ipv6Addr::LOCALHOST.into(), held.port.get(), protocol).is_err_and(|e| held_elsewhere(&e)) {
137            passed.push(held);
138        } else {
139            return Ok(Some(held));
140        }
141    }
142    Ok(None)
143}
144
145/// Binds (then frees) `ip:port` over `protocol`.
146fn bind(ip: IpAddr, port: u16, protocol: Protocol) -> std::io::Result<()> {
147    match protocol {
148        Protocol::Udp => UdpSocket::bind((ip, port)).map(drop),
149        Protocol::Tcp => TcpListener::bind((ip, port)).map(drop),
150    }
151}
152
153/// Whether a program holds `port` over `protocol` on all interfaces (`0.0.0.0`, `::`), as an
154/// engine publishing a port for the network does. macOS lets the loopback be bound with address
155/// reuse (which std's listeners set) while another socket listens on all interfaces, and Windows
156/// lets a more specific address be bound beside such a socket without it, so the loopback alone
157/// read such a port free, and the start failed later with the engine's bind error. Bound, never
158/// listened on, so no firewall asks about it; an absent IPv6 doesn't count.
159fn held_on_all(port: u16, protocol: Protocol) -> bool {
160    [IpAddr::from(Ipv4Addr::UNSPECIFIED), IpAddr::from(Ipv6Addr::UNSPECIFIED)]
161        .into_iter()
162        .any(|ip| bind_only(ip, port, protocol).is_err_and(|e| held_elsewhere(&e)))
163}
164
165/// Binds (then frees) `ip:port` over `protocol` without listening, `::` for IPv6 alone. Elsewhere
166/// than Windows with address reuse, as std's TCP listeners set it (a port only left in
167/// `TIME_WAIT` is free); on Windows without it, where it would let the bind take a port another
168/// socket holds.
169fn bind_only(ip: IpAddr, port: u16, protocol: Protocol) -> std::io::Result<()> {
170    use socket2::{Domain, Socket, Type};
171    let address = std::net::SocketAddr::new(ip, port);
172    let kind = match protocol {
173        Protocol::Tcp => Type::STREAM,
174        Protocol::Udp => Type::DGRAM,
175    };
176    let socket = Socket::new(Domain::for_address(address), kind, None)?;
177    if cfg!(not(windows)) && matches!(protocol, Protocol::Tcp) {
178        socket.set_reuse_address(true)?;
179    }
180    if ip.is_ipv6() {
181        socket.set_only_v6(true)?;
182    }
183    socket.bind(&address.into())
184}
185
186/// Whether a failed bind means someone holds the port (or the OS reserved it, as Windows does
187/// for WinNAT and Hyper-V), not that the address doesn't exist here.
188fn held_elsewhere(e: &std::io::Error) -> bool {
189    matches!(e.kind(), std::io::ErrorKind::AddrInUse | std::io::ErrorKind::PermissionDenied)
190}
191
192/// Ports answered from a test's setup (feature `fake`): the free ones handed out in order. An
193/// embedder's tests script those only; the runner's own also mark ports taken, addresses
194/// answering and binds refused.
195#[cfg(any(test, feature = "fake"))]
196#[derive(Debug, Default)]
197pub struct FakePorts {
198    taken: std::sync::Mutex<std::collections::BTreeSet<(u16, Protocol)>>,
199    free: std::sync::Mutex<std::collections::VecDeque<u16>>,
200    answering: std::sync::Mutex<std::collections::BTreeSet<(String, u16)>>,
201    /// What a pick fails with instead of handing out a port, if anything.
202    unbindable: std::sync::Mutex<Option<std::io::ErrorKind>>,
203}
204
205#[cfg(any(test, feature = "fake"))]
206impl FakePorts {
207    /// No port taken; `free` handed out in order.
208    pub fn new(free: impl IntoIterator<Item = u16>) -> FakePorts {
209        FakePorts {
210            free: std::sync::Mutex::new(free.into_iter().collect()),
211            ..FakePorts::default()
212        }
213    }
214
215    /// `port` taken over `protocol`, as one something else on this computer binds.
216    #[must_use]
217    pub fn taken(self, port: u16, protocol: Protocol) -> FakePorts {
218        self.taken.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((port, protocol));
219        self
220    }
221}
222
223#[cfg(any(test, feature = "fake"))]
224impl sealed::Ports for FakePorts {
225    fn in_use(&self, port: HostPort, protocol: Protocol) -> bool {
226        self.taken
227            .lock()
228            .unwrap_or_else(std::sync::PoisonError::into_inner)
229            .contains(&(port.get(), protocol))
230    }
231
232    fn pick_free(&self, _protocol: Protocol) -> std::io::Result<Option<HeldPort>> {
233        if let Some(kind) = *self.unbindable.lock().unwrap_or_else(std::sync::PoisonError::into_inner) {
234            return Err(kind.into());
235        }
236        Ok(self
237            .free
238            .lock()
239            .unwrap_or_else(std::sync::PoisonError::into_inner)
240            .pop_front()
241            .map(|p| HeldPort::new(HostPort::new(p), ())))
242    }
243
244    fn reachable<'a>(&'a self, host: &'a str, port: u16, within: Duration) -> BoxFuture<'a, bool> {
245        let up = self
246            .answering
247            .lock()
248            .unwrap_or_else(std::sync::PoisonError::into_inner)
249            .contains(&(host.to_owned(), port));
250        Box::pin(async move {
251            if !up {
252                tokio::time::sleep(within).await;
253            }
254            up
255        })
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    /// The probe reads a port that answers as reachable, whether it greets or waits for the
262    /// client; one nobody listens on, one let go, or a proxy's accept closed at once, isn't.
263    #[tokio::test]
264    async fn a_port_that_accepts_and_closes_at_once_isnt_reachable_one_that_holds_is() {
265        use tokio::io::AsyncWriteExt as _;
266        let ports = super::LoopbackPorts;
267        let within = Duration::from_secs(5);
268        // Nothing listening.
269        let free = ports.pick_free(Protocol::Tcp).unwrap().unwrap().port;
270        assert!(!ports.reachable("127.0.0.1", free.get(), within).await);
271        // A listener let go.
272        let gone = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
273        let gone_port = gone.local_addr().unwrap().port();
274        drop(gone);
275        assert!(!ports.reachable("127.0.0.1", gone_port, within).await, "let go");
276        // A proxy's accept: closed at once.
277        let closing = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
278        let closing_port = closing.local_addr().unwrap().port();
279        drop(tokio::spawn(async move {
280            let (s, _) = closing.accept().await.unwrap();
281            drop(s);
282        }));
283        assert!(!ports.reachable("127.0.0.1", closing_port, within).await);
284        // A service that greets, then holds the connection for as long as the test runs.
285        let greeting = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
286        let greeting_port = greeting.local_addr().unwrap().port();
287        drop(tokio::spawn(async move {
288            let (mut s, _) = greeting.accept().await.unwrap();
289            s.write_all(b"220 ready\r\n").await.unwrap();
290            std::future::pending::<()>().await;
291        }));
292        assert!(ports.reachable("127.0.0.1", greeting_port, within).await);
293        // A service that waits for the client's first bytes, as long as the test runs.
294        let silent = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
295        let silent_port = silent.local_addr().unwrap().port();
296        drop(tokio::spawn(async move {
297            let (_held, _) = silent.accept().await.unwrap();
298            std::future::pending::<()>().await;
299        }));
300        assert!(ports.reachable("127.0.0.1", silent_port, within).await);
301    }
302
303    use super::sealed::Ports;
304    use super::*;
305
306    /// A TCP port the OS gives on `at`, held, whose number is free over UDP too: another, while
307    /// it isn't. Never a port probed first and bound after, which another test process picking
308    /// at once may take in between.
309    fn held_tcp(at: std::net::IpAddr) -> (TcpListener, u16) {
310        for _ in 0..100 {
311            let held = TcpListener::bind((at, 0)).unwrap();
312            let port = held.local_addr().unwrap().port();
313            if !LoopbackPorts.in_use(HostPort::new(port), Protocol::Udp) {
314                return (held, port);
315            }
316        }
317        panic!("no port the OS gave was free over UDP too");
318    }
319
320    /// [`held_tcp`] over UDP: a UDP port the OS gives on `at`, held, free over TCP too.
321    fn held_udp(at: std::net::IpAddr) -> (UdpSocket, u16) {
322        for _ in 0..100 {
323            let held = UdpSocket::bind((at, 0)).unwrap();
324            let port = held.local_addr().unwrap().port();
325            if !LoopbackPorts.in_use(HostPort::new(port), Protocol::Tcp) {
326                return (held, port);
327            }
328        }
329        panic!("no port the OS gave was free over TCP too");
330    }
331
332    #[test]
333    fn a_held_port_is_in_use_over_its_protocol_only() {
334        let (_tcp, tcp_port) = held_tcp(Ipv4Addr::LOCALHOST.into());
335        assert!(LoopbackPorts.in_use(HostPort::new(tcp_port), Protocol::Tcp));
336        assert!(!LoopbackPorts.in_use(HostPort::new(tcp_port), Protocol::Udp));
337        let (_udp, udp_port) = held_udp(Ipv4Addr::LOCALHOST.into());
338        assert!(
339            LoopbackPorts.in_use(HostPort::new(udp_port), Protocol::Udp),
340            "a UDP holder (dnsmasq on 53) is caught"
341        );
342        assert!(!LoopbackPorts.in_use(HostPort::new(udp_port), Protocol::Tcp));
343    }
344
345    /// Regression: only the loopback was bound, which macOS and Windows allow while another program
346    /// listens on all interfaces, so such a port read free. (Linux refuses that bind already: there
347    /// this holds either way.)
348    #[test]
349    fn a_port_held_on_all_interfaces_is_in_use() {
350        // Once let go, the port reads free, unless another process took it at once (a busy host
351        // hands its ports on): then another port is tried, and one of them must read free.
352        let freed = (0..20).any(|_| {
353            let (tcp, tcp_port) = held_tcp(Ipv4Addr::UNSPECIFIED.into());
354            assert!(LoopbackPorts.in_use(HostPort::new(tcp_port), Protocol::Tcp));
355            assert!(held_on_all(tcp_port, Protocol::Tcp), "{tcp_port} held on 0.0.0.0");
356            drop(tcp);
357            !held_on_all(tcp_port, Protocol::Tcp)
358        });
359        assert!(freed, "a port let go never read free");
360        let (_udp, udp_port) = held_udp(Ipv4Addr::UNSPECIFIED.into());
361        assert!(LoopbackPorts.in_use(HostPort::new(udp_port), Protocol::Udp));
362        assert!(held_on_all(udp_port, Protocol::Udp), "{udp_port} held on 0.0.0.0");
363        if let Ok(v6) = TcpListener::bind((Ipv6Addr::UNSPECIFIED, 0)) {
364            let port = v6.local_addr().unwrap().port();
365            assert!(LoopbackPorts.in_use(HostPort::new(port), Protocol::Tcp), "{port} held on ::");
366        }
367    }
368
369    /// A port a closed connection left in `TIME_WAIT` stays free: the check on all interfaces
370    /// reuses the address as a listener would. The port is an ephemeral one, which a connection
371    /// of a test running meanwhile can also be given: one of three ports reading free proves it,
372    /// where `TIME_WAIT` holding them would leave all three held.
373    #[cfg(not(windows))]
374    #[test]
375    fn a_port_left_in_time_wait_is_free() {
376        let left_in_time_wait = || {
377            let listener = TcpListener::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
378            let port = listener.local_addr().unwrap().port();
379            let client = std::net::TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap();
380            let (served, _) = listener.accept().unwrap();
381            drop(served); // The server closes first: its side waits in TIME_WAIT.
382            drop(client);
383            drop(listener);
384            port
385        };
386        let ports: Vec<u16> = (0..3).map(|_| left_in_time_wait()).collect();
387        assert!(ports.iter().any(|p| !held_on_all(*p, Protocol::Tcp)), "{ports:?}");
388    }
389
390    #[test]
391    fn only_a_held_or_reserved_address_counts_on_the_ipv6_loopback() {
392        use std::io::{Error, ErrorKind};
393        assert!(held_elsewhere(&Error::from(ErrorKind::AddrInUse)));
394        assert!(held_elsewhere(&Error::from(ErrorKind::PermissionDenied)));
395        assert!(!held_elsewhere(&Error::from(ErrorKind::AddrNotAvailable)), "no IPv6 loopback here");
396    }
397
398    #[test]
399    fn picked_ports_are_held_until_dropped() {
400        let a = LoopbackPorts.pick_free(Protocol::Tcp).unwrap().unwrap();
401        let b = LoopbackPorts.pick_free(Protocol::Tcp).unwrap().unwrap();
402        assert_ne!(a.port, b.port);
403        assert!(LoopbackPorts.in_use(a.port, Protocol::Tcp));
404    }
405
406    /// Regression: a pick bound the IPv4 loopback only, so it could hand out a port held on the
407    /// IPv6 one, which `in_use` calls taken. Such a port is passed over (kept held meanwhile).
408    #[test]
409    fn a_port_held_on_the_ipv6_loopback_is_passed_over() {
410        let Ok(v6) = TcpListener::bind((Ipv6Addr::LOCALHOST, 0)) else {
411            return; // No IPv6 loopback here: nothing can hold a port on it.
412        };
413        let held = v6.local_addr().unwrap().port();
414        let Ok(v4) = TcpListener::bind((Ipv4Addr::LOCALHOST, held)) else {
415            return; // The OS took the IPv4 port too: nothing to pass over.
416        };
417        let mut offers = vec![HeldPort::new(HostPort::new(held), v4)].into_iter();
418        let picked = free_on_both(Protocol::Tcp, || {
419            Ok(offers.next().unwrap_or_else(|| {
420                let l = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
421                HeldPort::new(HostPort::new(l.local_addr().unwrap().port()), l)
422            }))
423        })
424        .unwrap()
425        .unwrap();
426        assert_ne!(picked.port, HostPort::new(held));
427        assert!(LoopbackPorts.in_use(HostPort::new(held), Protocol::Tcp), "{held} held on ::1");
428    }
429}