Skip to content

Commit

Permalink
Add a new config to set TCP_USER_TIMEOUT
Browse files Browse the repository at this point in the history
Setting TCP keepalive is not enough to prevent dead TCP connections.

See https://blog.cloudflare.com/when-tcp-sockets-refuse-to-die/
  • Loading branch information
guillaumebort committed Oct 1, 2024
1 parent fcb8565 commit 736bd7f
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/client/legacy/connect/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ struct Config {
recv_buffer_size: Option<usize>,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
interface: Option<String>,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
tcp_user_timeout: Option<Duration>,
}

#[derive(Default, Debug, Clone, Copy)]
Expand Down Expand Up @@ -182,6 +184,8 @@ impl<R> HttpConnector<R> {
recv_buffer_size: None,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
interface: None,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
tcp_user_timeout: None,
}),
resolver,
}
Expand Down Expand Up @@ -324,6 +328,13 @@ impl<R> HttpConnector<R> {
self
}

/// Sets the value of the TCP_USER_TIMEOUT option on the socket.
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[inline]
pub fn set_tcp_user_timeout(&mut self, time: Option<Duration>) {
self.config_mut().set_tcp_user_timeout = time;
}

// private

fn config_mut(&mut self) -> &mut Config {
Expand Down Expand Up @@ -728,6 +739,13 @@ fn connect(
.map_err(ConnectError::m("tcp bind interface error"))?;
}

#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
if let Some(tcp_user_timeout) = &config.tcp_user_timeout_config.into_tcpkeepalive() {
if let Err(e) = socket.set_tcp_user_timeout(tcp_user_timeout) {
warn!("tcp set_tcp_user_timeout error: {}", e);
}
}

bind_local_address(
&socket,
addr,
Expand Down

0 comments on commit 736bd7f

Please sign in to comment.