From 64d92432eddbc66002e9ccd07911d4ff20b70f28 Mon Sep 17 00:00:00 2001 From: eric Date: Wed, 9 Sep 2026 13:45:51 +0800 Subject: [PATCH] fix(net): close inbound connections gracefully by default Every accepted inbound socket was given SO_LINGER = 0, so closing it sent a reset. That discards whatever is still queued for the peer: a response whose end is marked by the close itself -- HTTP/1.0, a body with no length, anything read to EOF -- can be truncated, and a peer that has received every byte but not yet read them can still see the transfer fail with a reset. What it bought was the socket back at once, with no TIME_WAIT. But TIME_WAIT falls on whoever closes first, and on the common paths that is the client: leaf is the passive closer and has no TIME_WAIT to avoid. The reclaim is only ever paid for on the paths where leaf closes first -- the idle timeouts and the error teardowns -- and those are the paths where a reset is the right answer anyway. So it is now off by default and available as TCP_INBOUND_ABORT_ON_CLOSE, for devices that cannot afford the sockets. Sessions are still bounded by the existing uplink and downlink idle timeouts. --- leaf/src/option/mod.rs | 21 +++++++++++++++++ leaf/src/proxy/mod.rs | 51 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/leaf/src/option/mod.rs b/leaf/src/option/mod.rs index 0a546cc..59aa333 100644 --- a/leaf/src/option/mod.rs +++ b/leaf/src/option/mod.rs @@ -152,6 +152,27 @@ lazy_static! { get_env_var_or("TCP_DOWNLINK_TIMEOUT", 10) }; + /// Whether to abort inbound TCP connections instead of closing them + /// gracefully. + /// + /// With this on, every accepted socket gets `SO_LINGER = 0`, so closing it + /// sends a reset: no TIME_WAIT, nothing left waiting on a peer that has + /// gone away, and the socket reclaimed at once. It also discards whatever + /// is still queued for that peer, which is why it is off by default. A + /// response whose end is marked by the close itself -- HTTP/1.0, a body + /// with no length, anything read to EOF -- can be truncated, and a peer + /// that has received every byte but not yet read them can still see the + /// transfer fail. + /// + /// The reclaim is only ever paid for on the paths where leaf closes first, + /// which are the idle timeouts and the error teardowns. When the peer + /// closes first, leaf is the passive closer and has no TIME_WAIT to avoid. + /// So turn this on where a device cannot afford the sockets, not as a + /// matter of course. + pub static ref TCP_INBOUND_ABORT_ON_CLOSE: bool = { + get_env_var_or("TCP_INBOUND_ABORT_ON_CLOSE", false) + }; + /// Buffer size for uplink and downlink connections, in KB. pub static ref LINK_BUFFER_SIZE: usize = { get_env_var_or("LINK_BUFFER_SIZE", 2) diff --git a/leaf/src/proxy/mod.rs b/leaf/src/proxy/mod.rs index 5d2827a..8baf7da 100644 --- a/leaf/src/proxy/mod.rs +++ b/leaf/src/proxy/mod.rs @@ -200,7 +200,12 @@ impl TcpListener { pub async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { let (stream, addr) = self.inner.accept().await?; apply_socket_opts(&stream)?; - SockRef::from(&stream).set_linger(Some(Duration::ZERO))?; + if *option::TCP_INBOUND_ABORT_ON_CLOSE { + // Reclaims the socket the moment it is closed, and discards + // anything still queued for the peer along with it. See the + // option's own documentation for when that trade is the right one. + SockRef::from(&stream).set_linger(Some(Duration::ZERO))?; + } Ok((stream, addr)) } } @@ -765,3 +770,47 @@ pub async fn peek_tcp_one_off(lhs: Option<&mut AnyStream>) -> Vec { } Vec::new() } + +#[cfg(test)] +mod tests { + use super::*; + + fn runtime() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + } + + /// An accepted connection is closed gracefully unless the option asks for + /// the aggressive reclaim: a reset discards whatever is still queued for + /// the peer, including the tail of a response whose end is the close. + #[test] + fn accepted_socket_linger_follows_the_option() { + runtime().block_on(async { + let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()) + .await + .unwrap(); + let addr = listener.io().local_addr().unwrap(); + let connecting = tokio::spawn(TcpStream::connect(addr)); + let (accepted, _) = listener.accept().await.unwrap(); + let _client = connecting.await.unwrap().unwrap(); + + let linger = SockRef::from(&accepted).linger().unwrap(); + if *option::TCP_INBOUND_ABORT_ON_CLOSE { + assert_eq!(linger, Some(Duration::ZERO)); + } else { + assert_eq!(linger, None); + } + }); + } + + #[test] + fn abort_on_close_is_off_unless_asked_for() { + if std::env::var("TCP_INBOUND_ABORT_ON_CLOSE").is_ok() { + // The environment chose; the case above covers the wiring. + return; + } + assert!(!*option::TCP_INBOUND_ABORT_ON_CLOSE); + } +}