1use 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
18const LISTENER_ANSWER: Duration = Duration::from_millis(250);
20
21pub const HOLDER_LOOKUP: Duration = Duration::from_secs(4);
23
24#[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
38pub 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
47pub 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
55pub const RESOLVER_TIMEOUT: Duration = Duration::from_secs(8);
57
58const MAX_ANSWER: usize = 256;
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum PublicIpFailed {
66 Disagree(Vec<(String, Ipv4Addr)>),
69 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
90pub 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 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
112fn 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
135async fn ask(runner: &dyn isothrum_runner::ProcessRunner, spec: &ProcessSpec) -> Result<Ipv4Addr, String> {
137 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
153pub 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#[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 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 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 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 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}