Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

fix: a port probe never listens (#1241)

iQuantum209dd6d63337
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1d470ec1..29db508b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+- On Linux, checking whether a port is free no longer opens a listener. While another thread was
+ starting a process, such a listener could stay open after the check, so the server then started
+ on that port failed with `Address already in use`, or a client got `Connection reset by peer`
+ (#1239).
- `analyze` no longer reports "Hash iteration order" for a Python set that is tested where it
is written (`c in {'a', 'b'}`, `c not in set(x)`): no code can see its order. A set held by a
name is reported as before (#1235).
diff --git a/Cargo.toml b/Cargo.toml
index c4b932c0..63189035 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -47,7 +47,7 @@ tree-sitter-ruby = "0.23.1"
tree-sitter-swift = "0.7.4"
[target.'cfg(unix)'.dependencies]
-rustix = { version = "1.1.6", default-features = false, features = ["std", "event", "fs"] }
+rustix = { version = "1.1.6", default-features = false, features = ["std", "event", "fs", "net"] }
[lints.rust]
unsafe_code = "forbid"
diff --git a/docs/pitfalls.md b/docs/pitfalls.md
index 15eb8606..d4fb323e 100644
--- a/docs/pitfalls.md
+++ b/docs/pitfalls.md
@@ -354,6 +354,12 @@ to a demo crate, build it and keep the lockfile it writes.
differed once ESLint lived in an install prefix. Replay the original from the same install too:
a run that fails both ways is the path, not the port.
+**A port probe kept listening in another thread's child.** `free_port` and the tests'
+`fixed_port` bound a `TcpListener` and dropped it. A process another thread was spawning held a
+copy until it exec'd, so the port was still taken (`Address already in use`) and a client that
+connected to it got `Connection reset by peer`: with eight threads spawning, 300 of 20,000
+rounds. A probe binds and never listens (`http::probe_bind`).
+
## Language plugins
**A tree-sitter supertype never appears in the tree.** `tree-sitter-kotlin-ng` lists
diff --git a/src/http.rs b/src/http.rs
index 5df99e4a..c36aefa1 100644
--- a/src/http.rs
+++ b/src/http.rs
@@ -3,7 +3,9 @@
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Write};
-use std::net::{Ipv6Addr, SocketAddr, TcpListener, TcpStream};
+#[cfg(any(test, not(target_os = "linux")))]
+use std::net::TcpListener;
+use std::net::{Ipv6Addr, SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
@@ -272,14 +274,43 @@ pub(crate) struct Resp {
pub(crate) body: Vec<u8>,
}
+/// Binds `addr` to learn that the port is free: the socket, held until dropped, and its port (for
+/// port 0, the one the kernel gave). The socket never listens: a child that another thread spawns
+/// holds a copy of it until it execs, and a listening one would keep the port taken, and accept
+/// connections, after the drop.
+#[cfg(target_os = "linux")]
+pub fn probe_bind(addr: SocketAddr) -> std::io::Result<(std::os::fd::OwnedFd, u16)> {
+ use rustix::net::{AddressFamily, SocketFlags, SocketType, sockopt};
+ let family = if addr.is_ipv4() {
+ AddressFamily::INET
+ } else {
+ AddressFamily::INET6
+ };
+ let socket = rustix::net::socket_with(family, SocketType::STREAM, SocketFlags::CLOEXEC, None)?;
+ // As `TcpListener::bind` sets it, and so that a copy still held does not refuse the next bind.
+ sockopt::set_socket_reuseaddr(&socket, true)?;
+ rustix::net::bind(&socket, &addr)?;
+ let port = SocketAddr::try_from(rustix::net::getsockname(&socket)?)?.port();
+ Ok((socket, port))
+}
+
+/// Elsewhere the probe listens: Windows hands a child no such copy, and BSD refuses a bind over
+/// one whether it listens or not.
+#[cfg(not(target_os = "linux"))]
+pub fn probe_bind(addr: SocketAddr) -> std::io::Result<(TcpListener, u16)> {
+ let listener = TcpListener::bind(addr)?;
+ let port = listener.local_addr()?.port();
+ Ok((listener, port))
+}
+
/// Picks an ephemeral port free on IPv4 loopback and not already bound on IPv6 loopback
/// (on dual-stack hosts a port free on `127.0.0.1` can still be bound on `[::1]`, which
/// `listening()` treats as in use).
pub fn free_port() -> Result<u16> {
for _ in 0..16 {
- let v4 = TcpListener::bind("127.0.0.1:0")?;
- let port = v4.local_addr()?.port();
- match TcpListener::bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))) {
+ // Held through the IPv6 check, so that no other port-0 bind is given it meanwhile.
+ let (_v4, port) = probe_bind(SocketAddr::from(([127, 0, 0, 1], 0)))?;
+ match probe_bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))) {
Ok(_) => return Ok(port),
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => continue,
Err(_) => return Ok(port),
@@ -2782,6 +2813,35 @@ fn decode_base64_strict(input: &str) -> Result<Vec<u8>> {
mod tests {
use super::*;
+ /// A child that another thread spawns holds a copy of every socket until it execs, so a probe
+ /// that listened would still accept connections after it returned.
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn a_port_probe_leaves_nothing_listening_while_other_threads_spawn() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ let stop = AtomicBool::new(false);
+ // Below every common ephemeral range, so no other test's port-0 bind is handed it.
+ let addr = (30_000..30_100)
+ .map(|port| SocketAddr::from(([127, 0, 0, 1], port)))
+ .find(|addr| probe_bind(*addr).is_ok())
+ .expect("a free port below the ephemeral range");
+ let answered = std::thread::scope(|scope| {
+ for _ in 0..8 {
+ scope.spawn(|| {
+ while !stop.load(Ordering::Relaxed) {
+ let _ = Command::new("true").status();
+ }
+ });
+ }
+ let answered = (0..500)
+ .filter(|_| probe_bind(addr).is_err() || TcpStream::connect(addr).is_ok())
+ .count();
+ stop.store(true, Ordering::Relaxed);
+ answered
+ });
+ assert_eq!(answered, 0, "the probed port was still listening");
+ }
+
/// `load_spec` reads every field of `HTTP_TEXT_FIELDS` (the list the wildcard sweep walks):
/// a field added to the list without `load_spec` reading it fails this test. The other
/// direction is not held: a text that `load_spec` or `replay` started to read without it
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 5993cc30..7d7b5352 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -142,7 +142,7 @@ impl Drop for Scratch {
/// including a wildcard listener that macOS lets a loopback bind share.
#[allow(dead_code)]
pub fn fixed_port() -> u16 {
- use std::net::{Ipv6Addr, SocketAddr, TcpListener, TcpStream};
+ use std::net::{Ipv6Addr, SocketAddr, TcpStream};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU16, Ordering};
use std::time::Duration;
@@ -162,8 +162,9 @@ pub fn fixed_port() -> u16 {
if answers(&v4) || answers(&v6) {
continue;
}
- let free = TcpListener::bind(v4).is_ok()
- && !matches!(TcpListener::bind(v6), Err(e) if e.kind() == std::io::ErrorKind::AddrInUse);
+ use rust_anything::http::probe_bind;
+ let free = probe_bind(v4).is_ok()
+ && !matches!(probe_bind(v6), Err(e) if e.kind() == std::io::ErrorKind::AddrInUse);
if !free {
continue;
}
diff --git a/tests/http.rs b/tests/http.rs
index 4b74669f..ac21968e 100644
--- a/tests/http.rs
+++ b/tests/http.rs
@@ -2591,9 +2591,9 @@ fn shadow_names_a_request_the_original_did_not_answer() {
"{}",
String::from_utf8_lossy(&recorded.stderr)
);
- let down = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
- let upstream = down.local_addr().unwrap().to_string();
- drop(down);
+ // A fixed port stays this test's: one from port 0 can go to another test's server, which then
+ // answers for the original that should be down.
+ let upstream = format!("127.0.0.1:{}", common::fixed_port());
let port = common::fixed_port();
let build = format!("{python} server.py");
let shadow = {