Skip to content

An open-source cross-platform alternative to AirDrop

fix: keep accepting connections after a failed accept (#3262)

Azadd1075458e378
diff --git a/Cargo.lock b/Cargo.lock
index a7351993..1db71260 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2202,6 +2202,7 @@ dependencies = [
"hyper",
"hyper-util",
"if-addrs",
+ "libc",
"lru",
"pem 4.0.0",
"percent-encoding",
diff --git a/packages/core/Cargo.toml b/packages/core/Cargo.toml
index 3affce83..3f270ca6 100644
--- a/packages/core/Cargo.toml
+++ b/packages/core/Cargo.toml
@@ -41,6 +41,12 @@ uuid = { version = "1.24.0", features = ["serde", "v4"] }
webrtc = { version = "0.14.0", optional = true }
x509-parser = { version = "0.18.1", features = ["verify"], optional = true }
+[dev-dependencies]
+# Lowers this process' descriptor limit in `accept_resilience`, to reproduce
+# the exhaustion the accept loop has to survive. Already in the tree as a
+# transitive dependency, so it costs no extra compilation.
+libc = "0.2"
+
[[example]]
name = "stress_send"
required-features = ["http"]
diff --git a/packages/core/src/http/server/mod.rs b/packages/core/src/http/server/mod.rs
index a8b39be9..0d969dc0 100644
--- a/packages/core/src/http/server/mod.rs
+++ b/packages/core/src/http/server/mod.rs
@@ -308,6 +308,22 @@ pub struct TlsConfig {
pub private_key: String,
}
+/// How long the accept loop waits after a failure that would repeat
+/// immediately, doubling up to [`ACCEPT_BACKOFF_MAX`].
+const ACCEPT_BACKOFF_MIN: std::time::Duration = std::time::Duration::from_millis(50);
+const ACCEPT_BACKOFF_MAX: std::time::Duration = std::time::Duration::from_secs(1);
+
+/// Whether the failed accept concerned only the connection being accepted, so
+/// the next one can be attempted right away.
+fn is_transient_accept_error(err: &std::io::Error) -> bool {
+ matches!(
+ err.kind(),
+ std::io::ErrorKind::ConnectionAborted
+ | std::io::ErrorKind::ConnectionReset
+ | std::io::ErrorKind::Interrupted
+ )
+}
+
async fn start_server_with_listener(
incoming: tokio::net::TcpListener,
tls_config: Option<TlsConfig>,
@@ -336,8 +352,33 @@ async fn start_server_with_listener(
tls_acceptor.is_some()
);
+ let mut accept_backoff = ACCEPT_BACKOFF_MIN;
loop {
- let (tcp_stream, remote_addr) = incoming.accept().await?;
+ let (tcp_stream, remote_addr) = match incoming.accept().await {
+ Ok(accepted) => {
+ accept_backoff = ACCEPT_BACKOFF_MIN;
+ accepted
+ }
+ // Accepting fails for reasons that say nothing about the listener:
+ // the peer went away before the handshake completed, or the process
+ // momentarily ran out of file descriptors (a subnet scan opens a
+ // few hundred sockets). Giving up here would stop the server for
+ // good and the application would never learn that it can no longer
+ // receive anything, so keep accepting.
+ //
+ // Descriptor exhaustion would otherwise spin: the pending
+ // connection stays in the backlog and fails again immediately, so
+ // back off before retrying.
+ Err(err) => {
+ tracing::warn!("Could not accept a connection: {err:#}");
+ if is_transient_accept_error(&err) {
+ continue;
+ }
+ tokio::time::sleep(accept_backoff).await;
+ accept_backoff = (accept_backoff * 2).min(ACCEPT_BACKOFF_MAX);
+ continue;
+ }
+ };
let tls_acceptor = tls_acceptor.clone();
let app_state = app_state.clone();
diff --git a/packages/core/tests/accept_resilience.rs b/packages/core/tests/accept_resilience.rs
new file mode 100644
index 00000000..68f6cce0
--- /dev/null
+++ b/packages/core/tests/accept_resilience.rs
@@ -0,0 +1,142 @@
+#![cfg(all(feature = "http", unix))]
+
+//! Accepting a connection fails for reasons that say nothing about the
+//! listener: the peer can go away before the handshake completes, or the
+//! process can momentarily run out of file descriptors. The server has to keep
+//! accepting afterwards — nothing tells the application that it stopped, so a
+//! device would silently stop receiving files until the app is restarted.
+//!
+//! This test lowers the descriptor limit of its own process, which is why it
+//! is the only test in this binary.
+
+use localsend::http::server::v2::ServerEventV2;
+use localsend::http::server::{start_with_port, ServerConfigV2};
+use localsend::http::state::ClientInfo;
+use std::time::Duration;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::sync::{mpsc, oneshot};
+
+/// Descriptors this process is allowed to hold while the test runs. Low enough
+/// to be exhausted quickly, high enough for the runtime and the listeners.
+const DESCRIPTOR_LIMIT: u64 = 256;
+
+/// Lowers the soft limit on open descriptors. Only ever lowers it, which needs
+/// no privileges.
+fn limit_descriptors() -> bool {
+ // SAFETY: `getrlimit`/`setrlimit` only read and write the `rlimit` below.
+ unsafe {
+ let mut limit = std::mem::zeroed::<libc::rlimit>();
+ if libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) != 0 {
+ return false;
+ }
+ if limit.rlim_cur <= DESCRIPTOR_LIMIT as libc::rlim_t {
+ return true;
+ }
+ limit.rlim_cur = DESCRIPTOR_LIMIT as libc::rlim_t;
+ libc::setrlimit(libc::RLIMIT_NOFILE, &limit) == 0
+ }
+}
+
+/// Requests `/info` and returns the status line.
+async fn info_status(port: u16) -> std::io::Result<String> {
+ let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port)).await?;
+ stream
+ .write_all(
+ b"GET /api/localsend/v2/info HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
+ )
+ .await?;
+ let mut buf = Vec::new();
+ tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut buf))
+ .await
+ .map_err(|_| std::io::Error::other("timed out"))??;
+ Ok(String::from_utf8_lossy(&buf)
+ .lines()
+ .next()
+ .unwrap_or_default()
+ .to_string())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn server_survives_descriptor_exhaustion() {
+ if !limit_descriptors() {
+ eprintln!("skipping: could not lower the descriptor limit");
+ return;
+ }
+
+ let port = 41777;
+ let (event_tx, _event_rx) = mpsc::channel::<ServerEventV2>(16);
+ let (_stop_tx, stop_rx) = oneshot::channel();
+
+ start_with_port(
+ port,
+ None, // plain HTTP
+ ClientInfo {
+ alias: "Target".to_string(),
+ version: "2.2".to_string(),
+ device_model: None,
+ device_type: None,
+ token: "target-fingerprint".to_string(),
+ },
+ None,
+ Some(ServerConfigV2 {
+ pin: None,
+ verify_checksums: true,
+ event_tx,
+ }),
+ None,
+ stop_rx,
+ )
+ .await
+ .expect("Failed to start server");
+
+ for _ in 0..100 {
+ if info_status(port).await.is_ok() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ assert!(
+ info_status(port).await.unwrap_or_default().contains("200"),
+ "the server did not answer before the test started"
+ );
+
+ // A client in another process, so its sockets do not come out of the
+ // budget this process is about to exhaust. Started first: spawning needs
+ // descriptors too.
+ let mut knocker = std::process::Command::new("bash")
+ .arg("-c")
+ .arg(format!(
+ // `/dev/tcp` is a bash feature; dash does not have it.
+ "for i in $(seq 1 400); do (exec 3<>/dev/tcp/127.0.0.1/{port}) 2>/dev/null; sleep 0.02; done"
+ ))
+ .spawn()
+ .expect("failed to spawn the connecting process");
+ tokio::time::sleep(Duration::from_millis(300)).await;
+
+ // Exhaust the descriptors, so the pending connections cannot be accepted.
+ let mut held: Vec<std::fs::File> = Vec::new();
+ while held.len() < DESCRIPTOR_LIMIT as usize * 2 {
+ match std::fs::File::open("/dev/null") {
+ Ok(file) => held.push(file),
+ Err(_) => break,
+ }
+ }
+ assert!(
+ !held.is_empty(),
+ "no descriptor could be held, the limit is not what the test assumes"
+ );
+
+ // Let the accept loop run into them.
+ tokio::time::sleep(Duration::from_secs(2)).await;
+
+ // Give the descriptors back: the process is healthy again.
+ drop(held);
+ let _ = knocker.wait();
+ tokio::time::sleep(Duration::from_millis(500)).await;
+
+ let status = info_status(port).await;
+ assert!(
+ status.as_deref().unwrap_or_default().contains("200"),
+ "the server stopped accepting after running out of descriptors: {status:?}"
+ );
+}