165 lines
5.2 KiB
Rust
165 lines
5.2 KiB
Rust
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
//! Ports, temporary directories, external binaries and child processes.
|
|
|
|
use std::net::SocketAddr;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::Child;
|
|
use std::sync::atomic::{AtomicU32, Ordering};
|
|
use std::time::{Duration, Instant};
|
|
|
|
/// The kernel's ephemeral port range (ports it hands to `bind(:0)` and outgoing connections).
|
|
fn ephemeral_range() -> (u16, u16) {
|
|
std::fs::read_to_string("/proc/sys/net/ipv4/ip_local_port_range")
|
|
.ok()
|
|
.and_then(|s| {
|
|
let mut it = s.split_whitespace().filter_map(|x| x.parse::<u16>().ok());
|
|
Some((it.next()?, it.next()?))
|
|
})
|
|
.unwrap_or((32768, 60999))
|
|
}
|
|
|
|
/// A port on 127.0.0.1 that is free now, never handed out before by this process, and (where
|
|
/// possible) outside the ephemeral range, so the kernel does not give it to another socket
|
|
/// between this call and the server binding it, or while a server restarts on it.
|
|
pub fn free_port() -> u16 {
|
|
static GIVEN: std::sync::Mutex<Vec<u16>> = std::sync::Mutex::new(Vec::new());
|
|
let (low, high) = ephemeral_range();
|
|
let (from, to) = if low > 12_000 {
|
|
(10_000u32, u32::from(low))
|
|
} else {
|
|
(u32::from(high) + 1, 65_000)
|
|
};
|
|
let seed = std::process::id().wrapping_mul(2_654_435_761)
|
|
^ std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.map(|d| d.subsec_nanos())
|
|
.unwrap_or(0);
|
|
let span = to.saturating_sub(from).max(1);
|
|
let mut given = GIVEN.lock().unwrap();
|
|
for k in 0..span {
|
|
let port = (from + (seed.wrapping_add(k.wrapping_mul(7919))) % span) as u16;
|
|
if given.contains(&port) {
|
|
continue;
|
|
}
|
|
if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() {
|
|
given.push(port);
|
|
return port;
|
|
}
|
|
}
|
|
// Everything outside the ephemeral range is taken: fall back to the kernel's choice.
|
|
loop {
|
|
let port = std::net::TcpListener::bind("127.0.0.1:0")
|
|
.unwrap()
|
|
.local_addr()
|
|
.unwrap()
|
|
.port();
|
|
if !given.contains(&port) {
|
|
given.push(port);
|
|
return port;
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn local(port: u16) -> SocketAddr {
|
|
SocketAddr::from(([127, 0, 0, 1], port))
|
|
}
|
|
|
|
/// Wait until something accepts TCP connections on `addr`.
|
|
pub fn wait_for_port(addr: SocketAddr, timeout: Duration) -> bool {
|
|
let deadline = Instant::now() + timeout;
|
|
while Instant::now() < deadline {
|
|
if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
|
|
return true;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
false
|
|
}
|
|
|
|
/// A directory removed on drop (kept when `IANITOR_KEEP_TMP` is set, for debugging).
|
|
pub struct TempDir(PathBuf);
|
|
|
|
impl TempDir {
|
|
pub fn new(label: &str) -> TempDir {
|
|
static N: AtomicU32 = AtomicU32::new(0);
|
|
let p = std::env::temp_dir().join(format!(
|
|
"ianitor-{label}-{}-{}",
|
|
std::process::id(),
|
|
N.fetch_add(1, Ordering::SeqCst)
|
|
));
|
|
let _ = std::fs::remove_dir_all(&p);
|
|
std::fs::create_dir_all(&p).unwrap();
|
|
TempDir(p)
|
|
}
|
|
|
|
pub fn path(&self) -> &Path {
|
|
&self.0
|
|
}
|
|
|
|
pub fn join(&self, p: &str) -> PathBuf {
|
|
self.0.join(p)
|
|
}
|
|
|
|
pub fn str(&self, p: &str) -> String {
|
|
self.join(p).to_string_lossy().into_owned()
|
|
}
|
|
}
|
|
|
|
impl Drop for TempDir {
|
|
fn drop(&mut self) {
|
|
if std::env::var_os("IANITOR_KEEP_TMP").is_none() {
|
|
let _ = std::fs::remove_dir_all(&self.0);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Locate an external tool: `$IANITOR_<NAME>_BIN`, then `$PATH`.
|
|
pub fn find_binary(name: &str) -> Option<PathBuf> {
|
|
let var = format!(
|
|
"IANITOR_{}_BIN",
|
|
name.to_ascii_uppercase().replace('-', "_")
|
|
);
|
|
if let Some(p) = std::env::var_os(&var) {
|
|
return Some(PathBuf::from(p));
|
|
}
|
|
let path = std::env::var_os("PATH")?;
|
|
std::env::split_paths(&path)
|
|
.map(|d| d.join(name))
|
|
.find(|p| p.is_file())
|
|
}
|
|
|
|
/// Like [`find_binary`], but a missing tool fails the test, unless `IANITOR_ALLOW_SKIP=1`,
|
|
/// in which case the test prints SKIPPED and the caller returns early.
|
|
pub fn require_binary(name: &str) -> Option<PathBuf> {
|
|
match find_binary(name) {
|
|
Some(p) => Some(p),
|
|
None if std::env::var("IANITOR_ALLOW_SKIP").as_deref() == Ok("1") => {
|
|
eprintln!("SKIPPED: `{name}` not found (IANITOR_ALLOW_SKIP=1)");
|
|
None
|
|
}
|
|
None => {
|
|
let var = format!(
|
|
"IANITOR_{}_BIN",
|
|
name.to_ascii_uppercase().replace('-', "_")
|
|
);
|
|
panic!(
|
|
"`{name}` is needed for this test but was not found on PATH (or ${var}). \
|
|
In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead."
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Kills the child on drop.
|
|
pub struct ChildGuard(pub Child);
|
|
|
|
impl Drop for ChildGuard {
|
|
fn drop(&mut self) {
|
|
let _ = self.0.kill();
|
|
let _ = self.0.wait();
|
|
}
|
|
}
|