Skip to main content

isothrum_machine/
net.rs

1//! This computer's network, as a caller needs it before it acts: whether a host port is free
2//! ([`port_free`]) and, when it isn't, which process holds it ([`port_holder`]), and its public
3//! IPv4 address, as the internet sees it ([`public_ipv4`]): what a
4//! cloud firewall opens to when it lets this computer alone in. Independent services, run by different
5//! companies, are asked at once (`curl`, through the [`Context`]'s runner), and two must give the
6//! same address: one that is down or blocked fails nothing, and one that answers wrong (a captive
7//! portal's page, a compromised service) can't open a firewall to someone else.
8
9use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream, UdpSocket};
10use std::time::Duration;
11
12use isothrum_runner::{HostPort, PortHolder, ProcessSpec, Protocol};
13use tokio::task::JoinSet;
14
15use crate::context::Context;
16use crate::exec;
17
18/// How long [`port_free`] waits for a listener on the loopback to answer: one there answers at once.
19const LISTENER_ANSWER: Duration = Duration::from_millis(250);
20
21/// How long each of the system's tools [`port_holder`] asks may take.
22pub const HOLDER_LOOKUP: Duration = Duration::from_secs(4);
23
24/// Whether nothing on this computer holds host `port` for `protocol` where a published port goes
25/// (the loopback): a socket bound there and let go at once, nothing kept. A TCP port is also
26/// taken when something answers on it: a listener on every address (`0.0.0.0`) doesn't stop a
27/// loopback bind on every system (macOS lets one through), but it does answer. A free port can
28/// still be taken a moment later: this is a check before acting, not a reservation.
29#[must_use]
30pub fn port_free(port: u16, protocol: Protocol) -> bool {
31    let loopback = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
32    match protocol {
33        Protocol::Tcp => TcpListener::bind(loopback).is_ok() && TcpStream::connect_timeout(&loopback, LISTENER_ANSWER).is_err(),
34        Protocol::Udp => UdpSocket::bind(loopback).is_ok(),
35    }
36}
37
38/// The process holding host `port` for `protocol` on this computer (its program's name and its
39/// pid), when the system's own tools name one: `lsof`, then `ss` (macOS, Linux), `netstat` then
40/// `tasklist` (Windows), each run through the [`Context`]'s runner within [`HOLDER_LOOKUP`]. What
41/// a caller says beside a port [`port_free`] found taken, so the user knows what to stop.
42/// Best-effort: none when no tool answers or names a process (`ss` without root names none).
43pub async fn port_holder(cx: &Context, port: u16, protocol: Protocol) -> Option<PortHolder> {
44    isothrum_runner::port_holder(cx.runner.as_ref(), HostPort::new(port), protocol, HOLDER_LOOKUP).await
45}
46
47/// The services asked by default: each answers a plain-text address over HTTPS.
48pub const RESOLVERS: [&str; 4] = [
49    "https://checkip.amazonaws.com",
50    "https://api.ipify.org",
51    "https://ifconfig.me/ip",
52    "https://icanhazip.com",
53];
54
55/// How long one service may take: one that hangs doesn't hold up the others' answer for long.
56pub const RESOLVER_TIMEOUT: Duration = Duration::from_secs(8);
57
58/// The most an answer may hold: an address is a few bytes, a page (a captive portal's) is no
59/// answer.
60const MAX_ANSWER: usize = 256;
61
62/// Why no public address was agreed on.
63#[derive(Debug, Clone, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum PublicIpFailed {
66    /// The services that answered gave different addresses (a VPN that changes address, two
67    /// internet connections, a service lying): each service with its address.
68    Disagree(Vec<(String, Ipv4Addr)>),
69    /// Fewer than two gave one: each service that gave none, with why.
70    Unconfirmed(Vec<(String, String)>),
71}
72
73impl std::fmt::Display for PublicIpFailed {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        match self {
76            PublicIpFailed::Disagree(seen) => {
77                let said = seen.iter().map(|(url, ip)| format!("{url}: {ip}")).collect::<Vec<_>>().join(", ");
78                write!(f, "the services that tell this computer's public address disagree ({said})")
79            }
80            PublicIpFailed::Unconfirmed(failed) => {
81                let said = failed.iter().map(|(url, why)| format!("{url}: {why}")).collect::<Vec<_>>().join("; ");
82                write!(f, "fewer than two services gave this computer's public address ({said})")
83            }
84        }
85    }
86}
87
88impl std::error::Error for PublicIpFailed {}
89
90/// This computer's public IPv4 address, as `resolvers` ([`RESOLVERS`], unless a caller names its
91/// own) agree on it, all asked at once.
92///
93/// # Errors
94///
95/// [`PublicIpFailed`]: they disagree, or fewer than two gave one ([`agreed`]).
96pub async fn public_ipv4(cx: &Context, resolvers: &[&str]) -> Result<Ipv4Addr, PublicIpFailed> {
97    let mut asked = JoinSet::new();
98    for (i, url) in resolvers.iter().enumerate() {
99        let runner = std::sync::Arc::clone(&cx.runner);
100        let spec = curl(url);
101        asked.spawn(async move { (i, ask(runner.as_ref(), &spec).await) });
102    }
103    let mut answers: Vec<(usize, Result<Ipv4Addr, String>)> = Vec::with_capacity(resolvers.len());
104    while let Some(joined) = asked.join_next().await {
105        // A task panicking is a bug: said as that service's failure, not a hang.
106        answers.push(joined.unwrap_or_else(|e| (usize::MAX, Err(e.to_string()))));
107    }
108    answers.sort_by_key(|(i, _)| *i);
109    agreed(resolvers, &answers.into_iter().map(|(_, a)| a).collect::<Vec<_>>())
110}
111
112/// `curl` asking `url` for the address over IPv4 and HTTPS alone, following no redirect (a
113/// captive portal's), failing on an HTTP error, within [`RESOLVER_TIMEOUT`].
114fn curl(url: &str) -> ProcessSpec {
115    let limit = RESOLVER_TIMEOUT.as_secs().to_string();
116    let max = MAX_ANSWER.to_string();
117    ProcessSpec::new(
118        "curl",
119        [
120            "--ipv4",
121            "--silent",
122            "--show-error",
123            "--fail",
124            "--proto",
125            "=https",
126            "--max-time",
127            &limit,
128            "--max-filesize",
129            &max,
130            url,
131        ],
132    )
133}
134
135/// One service's answer: a public IPv4 address, or why not.
136async fn ask(runner: &dyn isothrum_runner::ProcessRunner, spec: &ProcessSpec) -> Result<Ipv4Addr, String> {
137    // curl ends itself at its `--max-time`; the probe's own limit only catches one that doesn't.
138    let captured = exec::probe_spec(runner, RESOLVER_TIMEOUT + Duration::from_secs(2), spec)
139        .await
140        .map_err(|e| e.to_string())?;
141    let body = captured.output().map_err(|failed| failed.to_string())?;
142    if body.len() > MAX_ANSWER {
143        return Err("an unexpected answer".to_owned());
144    }
145    let ip: Ipv4Addr = body.trim().parse().map_err(|_| "an unexpected answer".to_owned())?;
146    if is_public_ipv4(ip) {
147        Ok(ip)
148    } else {
149        Err(format!("{ip}, not a public address"))
150    }
151}
152
153/// The address `answers` (one per service of `resolvers`, in their order) agree on: at least two
154/// gave it, and none another one.
155///
156/// # Errors
157///
158/// [`PublicIpFailed::Disagree`] when two gave different ones, [`PublicIpFailed::Unconfirmed`]
159/// when fewer than two gave one.
160pub fn agreed(resolvers: &[&str], answers: &[Result<Ipv4Addr, String>]) -> Result<Ipv4Addr, PublicIpFailed> {
161    let seen: Vec<(String, Ipv4Addr)> = resolvers
162        .iter()
163        .zip(answers)
164        .filter_map(|(url, a)| a.as_ref().ok().map(|ip| ((*url).to_owned(), *ip)))
165        .collect();
166    match seen.as_slice() {
167        [(_, first), ..] if seen.iter().any(|(_, ip)| ip != first) => Err(PublicIpFailed::Disagree(seen)),
168        [(_, first), _, ..] => Ok(*first),
169        _ => Err(PublicIpFailed::Unconfirmed(
170            resolvers
171                .iter()
172                .zip(answers)
173                .filter_map(|(url, a)| a.as_ref().err().map(|why| ((*url).to_owned(), why.clone())))
174                .collect(),
175        )),
176    }
177}
178
179/// Whether `ip` is an address on the internet: not private, loopback, link-local, shared
180/// (carrier-grade NAT), documentation, benchmarking, multicast, reserved or broadcast. Anything
181/// else can't be where this computer's traffic comes from, as a cloud firewall sees it.
182#[must_use]
183pub fn is_public_ipv4(ip: Ipv4Addr) -> bool {
184    let [a, b, c, _] = ip.octets();
185    let special = ip.is_private()
186        || ip.is_loopback()
187        || ip.is_link_local()
188        || ip.is_broadcast()
189        || ip.is_documentation()
190        || ip.is_multicast()
191        || a == 0
192        || (a == 100 && (64..128).contains(&b))
193        || (a == 192 && b == 0 && c == 0)
194        || (a == 198 && (b == 18 || b == 19))
195        || a >= 240;
196    !special
197}
198
199#[cfg(test)]
200mod tests {
201    use isothrum_runner::fake::{FakeProcesses, Reply};
202
203    use super::*;
204    use crate::testing::answered_by;
205
206    const ONE: &str = "https://one.example";
207    const TWO: &str = "https://two.example";
208    const THREE: &str = "https://three.example";
209
210    /// Services each answering as `answer` says for its URL.
211    fn services(answer: fn(&str) -> Reply) -> Context {
212        answered_by(FakeProcesses::model(move |call| {
213            assert_eq!(call.program, "curl");
214            assert!(call.args.iter().any(|a| a == "=https") && call.args.iter().any(|a| a == "--ipv4"), "{call:?}");
215            answer(call.args.last().map_or("", String::as_str))
216        }))
217    }
218
219    #[tokio::test]
220    async fn two_services_agreeing_give_the_address_though_one_is_down() {
221        let cx = services(|url| match url {
222            ONE => Reply::fail(28, "curl: (28) Operation timed out"),
223            _ => Reply::ok("1.2.3.4\n"),
224        });
225        assert_eq!(public_ipv4(&cx, &[ONE, TWO, THREE]).await, Ok(Ipv4Addr::new(1, 2, 3, 4)));
226    }
227
228    #[tokio::test]
229    async fn services_that_disagree_give_no_address() {
230        let cx = services(|url| Reply::ok(if url == TWO { "5.6.7.8" } else { "1.2.3.4" }));
231        let Err(PublicIpFailed::Disagree(seen)) = public_ipv4(&cx, &[ONE, TWO, THREE]).await else {
232            panic!()
233        };
234        assert_eq!(seen[1], (TWO.to_owned(), Ipv4Addr::new(5, 6, 7, 8)));
235    }
236
237    #[tokio::test]
238    async fn a_single_answer_a_page_or_a_private_address_is_not_enough() {
239        let cx = services(|url| match url {
240            ONE => Reply::ok("1.2.3.4"),
241            TWO => Reply::ok("<html>Sign in to the network</html>"),
242            _ => Reply::ok("192.168.1.10"),
243        });
244        let Err(PublicIpFailed::Unconfirmed(failed)) = public_ipv4(&cx, &[ONE, TWO, THREE]).await else {
245            panic!()
246        };
247        assert_eq!(
248            failed,
249            [
250                (TWO.to_owned(), "an unexpected answer".to_owned()),
251                (THREE.to_owned(), "192.168.1.10, not a public address".to_owned()),
252            ]
253        );
254        let missing = answered_by(FakeProcesses::script().expect("curl", Reply::missing()).build());
255        assert!(matches!(public_ipv4(&missing, &[ONE, TWO]).await, Err(PublicIpFailed::Unconfirmed(f)) if f.len() == 2));
256    }
257
258    #[test]
259    fn only_internet_addresses_are_public() {
260        for special in [
261            "10.0.0.1",
262            "172.16.0.1",
263            "127.0.0.1",
264            "169.254.1.1",
265            "100.64.0.1",
266            "192.0.0.8",
267            "198.18.0.1",
268            "203.0.113.7",
269            "224.0.0.1",
270            "240.0.0.1",
271            "0.1.2.3",
272        ] {
273            assert!(!is_public_ipv4(special.parse().unwrap()), "{special}");
274        }
275        assert!(is_public_ipv4(Ipv4Addr::new(1, 2, 3, 4)) && is_public_ipv4(Ipv4Addr::new(100, 128, 0, 1)));
276    }
277
278    #[cfg(not(windows))]
279    #[tokio::test]
280    async fn a_taken_port_names_the_process_the_systems_tools_say_holds_it() {
281        let cx = answered_by(
282            FakeProcesses::script()
283                .expect("lsof -nP -iTCP:8000 -sTCP:LISTEN -FpcL", Reply::ok("p4123\ncnginx\nLroot\n"))
284                .build(),
285        );
286        assert_eq!(port_holder(&cx, 8000, Protocol::Tcp).await, Some(PortHolder::new(4123, "nginx")));
287        // Neither tool names anyone (`ss` run without root shows no process): none.
288        let nobody = answered_by(
289            FakeProcesses::script()
290                .expect("lsof -nP -iUDP:53", Reply::ok(""))
291                .expect("ss -H -lunp", Reply::ok("UNCONN 0 0 0.0.0.0:53 0.0.0.0:*"))
292                .build(),
293        );
294        assert_eq!(port_holder(&nobody, 53, Protocol::Udp).await, None);
295    }
296
297    #[test]
298    fn a_port_something_holds_is_not_free_for_its_protocol_alone() {
299        // Each listener is held to the end: a port let go goes to whichever process asks next, so
300        // "free" is shown on a port number held for the other protocol, whose sockets are apart.
301        // TCP: held on the loopback, then on every address (which answers on the loopback too).
302        let held = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("a free port");
303        let port = held.local_addr().expect("its port").port();
304        assert!(!port_free(port, Protocol::Tcp));
305        assert!(port_free(port, Protocol::Udp), "a TCP listener holds no UDP port");
306        let everywhere = TcpListener::bind((Ipv4Addr::UNSPECIFIED, 0)).expect("a free port");
307        let wide = everywhere.local_addr().expect("its port").port();
308        assert!(!port_free(wide, Protocol::Tcp), "a listener on every address holds it");
309        // UDP: its own sockets, apart from TCP's.
310        let udp = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).expect("a free port");
311        let datagrams = udp.local_addr().expect("its port").port();
312        assert!(!port_free(datagrams, Protocol::Udp));
313        assert!(port_free(datagrams, Protocol::Tcp), "a UDP socket holds no TCP port");
314    }
315}