Skip to content

An open-source cross-platform alternative to AirDrop

feat: limit incoming requests by IP

Tien Do Nam612aeef2bca4
diff --git a/packages/core/Cargo.toml b/packages/core/Cargo.toml
index c02f2305..0fa34482 100644
--- a/packages/core/Cargo.toml
+++ b/packages/core/Cargo.toml
@@ -12,7 +12,7 @@ flate2 = { version = "1.1.9", optional = true }
form_urlencoded = { version = "1.2.2", optional = true }
futures-util = { version = "0.3.33", features = ["sink"] }
http-body-util = { version = "0.1.4", optional = true }
-hyper = { version = "1.11.0", optional = true }
+hyper = { version = "1.11.0", features = ["http1", "server"], optional = true }
if-addrs = { version = "0.15.0", optional = true }
hyper-util = { version = "0.1.20", features = ["server"], optional = true }
lru = "0.18.1"
diff --git a/packages/core/src/http/server/connection_limit.rs b/packages/core/src/http/server/connection_limit.rs
new file mode 100644
index 00000000..893fb4c9
--- /dev/null
+++ b/packages/core/src/http/server/connection_limit.rs
@@ -0,0 +1,168 @@
+//! Limits on the connections being served, in total and per peer.
+
+use std::collections::HashMap;
+use std::net::IpAddr;
+use std::sync::{Arc, Mutex};
+
+/// How many connections are served at once. Protects the descriptors of the
+/// process (which the application shares) against many peers together.
+pub(crate) const MAX_CONNECTIONS: usize = 64;
+
+/// How many connections a single peer may hold, so that one peer cannot take
+/// every slot. Real peers use a few: a sender uploads two files in parallel
+/// and browsers open up to six connections per host.
+pub(crate) const MAX_CONNECTIONS_PER_IP: usize = 8;
+
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) enum LimitReached {
+ Total,
+ PerIp,
+}
+
+pub(crate) struct ConnectionLimiter {
+ max_total: usize,
+ max_per_ip: usize,
+ counts: Mutex<Counts>,
+}
+
+#[derive(Default)]
+struct Counts {
+ total: usize,
+ per_ip: HashMap<IpAddr, usize>,
+}
+
+impl ConnectionLimiter {
+ pub(crate) fn new(max_total: usize, max_per_ip: usize) -> Arc<Self> {
+ Arc::new(Self {
+ max_total,
+ max_per_ip,
+ counts: Mutex::new(Counts::default()),
+ })
+ }
+
+ /// Reserves a slot for a connection from `ip`, released when the permit is dropped.
+ ///
+ /// Loopback peers only count towards the total: they are on this device
+ /// anyway, and tests and tools connect from there many times at once.
+ pub(crate) fn try_acquire(
+ self: &Arc<Self>,
+ ip: IpAddr,
+ ) -> Result<ConnectionPermit, LimitReached> {
+ let ip = ip.to_canonical();
+ let ip = (!ip.is_loopback()).then_some(ip);
+
+ let mut counts = self.counts.lock().unwrap();
+ if counts.total >= self.max_total {
+ return Err(LimitReached::Total);
+ }
+ if let Some(ip) = ip {
+ let count = counts.per_ip.entry(ip).or_default();
+ if *count >= self.max_per_ip {
+ return Err(LimitReached::PerIp);
+ }
+ *count += 1;
+ }
+ counts.total += 1;
+
+ Ok(ConnectionPermit {
+ limiter: self.clone(),
+ ip,
+ })
+ }
+
+ #[cfg(test)]
+ pub(crate) fn total(&self) -> usize {
+ self.counts.lock().unwrap().total
+ }
+}
+
+pub(crate) struct ConnectionPermit {
+ limiter: Arc<ConnectionLimiter>,
+
+ /// `None` when the connection is not limited per peer.
+ ip: Option<IpAddr>,
+}
+
+impl Drop for ConnectionPermit {
+ fn drop(&mut self) {
+ let mut counts = self.limiter.counts.lock().unwrap();
+ counts.total -= 1;
+ if let Some(ip) = self.ip {
+ if let Some(count) = counts.per_ip.get_mut(&ip) {
+ *count -= 1;
+ if *count == 0 {
+ counts.per_ip.remove(&ip);
+ }
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ip(s: &str) -> IpAddr {
+ s.parse().unwrap()
+ }
+
+ #[test]
+ fn limits_connections_per_ip() {
+ let limiter = ConnectionLimiter::new(10, 2);
+ let _a1 = limiter.try_acquire(ip("192.168.1.2")).unwrap();
+ let a2 = limiter.try_acquire(ip("192.168.1.2")).unwrap();
+ assert_eq!(
+ limiter.try_acquire(ip("192.168.1.2")).err(),
+ Some(LimitReached::PerIp)
+ );
+
+ // Other peers are not affected.
+ let _b = limiter.try_acquire(ip("192.168.1.3")).unwrap();
+
+ // A closed connection frees its slot.
+ drop(a2);
+ let _a3 = limiter.try_acquire(ip("192.168.1.2")).unwrap();
+ }
+
+ #[test]
+ fn ipv4_mapped_addresses_count_as_the_ipv4_peer() {
+ let limiter = ConnectionLimiter::new(10, 1);
+ let _a = limiter.try_acquire(ip("192.168.1.2")).unwrap();
+ assert_eq!(
+ limiter.try_acquire(ip("::ffff:192.168.1.2")).err(),
+ Some(LimitReached::PerIp)
+ );
+ }
+
+ #[test]
+ fn limits_connections_in_total() {
+ let limiter = ConnectionLimiter::new(2, 2);
+ let a = limiter.try_acquire(ip("192.168.1.2")).unwrap();
+ let _b = limiter.try_acquire(ip("fe80::1")).unwrap();
+ assert_eq!(
+ limiter.try_acquire(ip("192.168.1.4")).err(),
+ Some(LimitReached::Total)
+ );
+
+ drop(a);
+ let _c = limiter.try_acquire(ip("192.168.1.4")).unwrap();
+ assert_eq!(limiter.total(), 2);
+ }
+
+ #[test]
+ fn loopback_peers_only_count_towards_the_total() {
+ let limiter = ConnectionLimiter::new(3, 1);
+ let permits: Vec<_> = ["127.0.0.1", "127.0.0.1", "::1"]
+ .into_iter()
+ .map(|peer| limiter.try_acquire(ip(peer)).unwrap())
+ .collect();
+ assert_eq!(
+ limiter.try_acquire(ip("127.0.0.1")).err(),
+ Some(LimitReached::Total)
+ );
+
+ drop(permits);
+ assert_eq!(limiter.total(), 0);
+ assert!(limiter.counts.lock().unwrap().per_ip.is_empty());
+ }
+}
diff --git a/packages/core/src/http/server/mod.rs b/packages/core/src/http/server/mod.rs
index 40bcebaa..a4981698 100644
--- a/packages/core/src/http/server/mod.rs
+++ b/packages/core/src/http/server/mod.rs
@@ -1,4 +1,5 @@
pub mod common;
+mod connection_limit;
pub mod internal;
mod peer_ip;
pub mod v2;
@@ -17,10 +18,10 @@ use common::error::AppError;
use common::response;
use common::response::BoxedBody;
use common::session::SessionStateV2;
+use connection_limit::{ConnectionLimiter, LimitReached, MAX_CONNECTIONS, MAX_CONNECTIONS_PER_IP};
use hyper::body::Incoming;
use hyper::{Method, Request, Response, StatusCode};
-use hyper_util::rt::{TokioExecutor, TokioIo};
-use hyper_util::server::conn::auto::Builder;
+use hyper_util::rt::TokioIo;
use lru::LruCache;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
@@ -29,6 +30,7 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::num::NonZeroUsize;
use std::ops::Deref;
use std::sync::Arc;
+use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{mpsc, oneshot, Mutex};
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
@@ -85,6 +87,9 @@ pub struct AppState {
/// State of the v2 protocol endpoints. `None` disables the v2 routes.
v2: Option<Arc<V2State>>,
+
+ /// Limits the connections being served, shared by the IPv4 and IPv6 listeners.
+ connection_limiter: Arc<ConnectionLimiter>,
}
impl AppState {
@@ -117,6 +122,7 @@ impl AppState {
NonZeroUsize::new(200).unwrap(),
))),
v2,
+ connection_limiter: ConnectionLimiter::new(MAX_CONNECTIONS, MAX_CONNECTIONS_PER_IP),
}
}
}
@@ -329,6 +335,13 @@ const ACCEPT_BACKOFF_MAX: std::time::Duration = std::time::Duration::from_secs(1
/// OS-specific) produces them in an endless, immediate sequence.
const ACCEPT_FAILURE_LIMIT: u32 = 100;
+/// Detects peers that vanished without closing their connections (e.g. left
+/// the network mid-transfer), which would otherwise count towards the
+/// connection limits forever.
+const TCP_KEEPALIVE: socket2::TcpKeepalive = socket2::TcpKeepalive::new()
+ .with_time(std::time::Duration::from_secs(60))
+ .with_interval(std::time::Duration::from_secs(10));
+
/// 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 {
@@ -389,6 +402,7 @@ async fn start_server_with_listener(
let mut accept_backoff = ACCEPT_BACKOFF_MIN;
let mut accept_failures = 0u32;
+ let mut at_connection_limit = false;
loop {
let (tcp_stream, remote_addr) = match incoming.accept().await {
Ok(accepted) => {
@@ -396,6 +410,7 @@ async fn start_server_with_listener(
accept_failures = 0;
// Disable Nagle: it delays small responses (reqwest already does this on the client side).
let _ = accepted.0.set_nodelay(true);
+ let _ = socket2::SockRef::from(&accepted.0).set_tcp_keepalive(&TCP_KEEPALIVE);
accepted
}
// Accepting fails for two kinds of reasons that say nothing about
@@ -431,10 +446,34 @@ async fn start_server_with_listener(
}
};
+ // Dropping the stream closes the connection.
+ let permit = match app_state.connection_limiter.try_acquire(remote_addr.ip()) {
+ Ok(permit) => permit,
+ Err(LimitReached::Total) => {
+ if !at_connection_limit {
+ tracing::warn!(
+ "Refusing connections: {MAX_CONNECTIONS} connections are being served"
+ );
+ at_connection_limit = true;
+ }
+ continue;
+ }
+ // Debug only: the peer decides how often this happens.
+ Err(LimitReached::PerIp) => {
+ tracing::debug!(
+ "Refusing connection from {}: {MAX_CONNECTIONS_PER_IP} of its connections are being served",
+ remote_addr.ip()
+ );
+ continue;
+ }
+ };
+ at_connection_limit = false;
+
let tls_acceptor = tls_acceptor.clone();
let app_state = app_state.clone();
let cancel = cancel.clone();
connections.spawn(async move {
+ let _permit = permit;
let serve = serve_connection(tcp_stream, remote_addr, tls_acceptor, app_state);
tokio::select! {
_ = serve => {}
@@ -475,33 +514,14 @@ async fn serve_connection(
}
};
- Builder::new(TokioExecutor::new())
- .serve_connection(
- TokioIo::new(tls_stream),
- hyper::service::service_fn(move |mut req: Request<Incoming>| {
- req.extensions_mut()
- .insert::<RequestClientInfo>(client_info.clone());
- req.extensions_mut().insert::<AppState>(app_state.clone());
- handle_request(req)
- }),
- )
- .await
+ serve_http(tls_stream, client_info, app_state).await
}
None => {
- Builder::new(TokioExecutor::new())
- .serve_connection(
- TokioIo::new(tcp_stream),
- hyper::service::service_fn(move |mut req: Request<Incoming>| {
- req.extensions_mut()
- .insert::<RequestClientInfo>(RequestClientInfo {
- ip: PeerIp::from_remote_addr(&remote_addr),
- cert: None,
- });
- req.extensions_mut().insert::<AppState>(app_state.clone());
- handle_request(req)
- }),
- )
- .await
+ let client_info = RequestClientInfo {
+ ip: PeerIp::from_remote_addr(&remote_addr),
+ cert: None,
+ };
+ serve_http(tcp_stream, client_info, app_state).await
}
};
@@ -510,6 +530,29 @@ async fn serve_connection(
}
}
+/// Serves HTTP/1.1 only: HTTP/2 multiplexes many requests over one connection,
+/// so the connection limits would no longer bound the requests of a peer.
+async fn serve_http<I>(
+ io: I,
+ client_info: RequestClientInfo,
+ app_state: AppState,
+) -> hyper::Result<()>
+where
+ I: AsyncRead + AsyncWrite + Unpin + Send + 'static,
+{
+ hyper::server::conn::http1::Builder::new()
+ .serve_connection(
+ TokioIo::new(io),
+ hyper::service::service_fn(move |mut req: Request<Incoming>| {
+ req.extensions_mut()
+ .insert::<RequestClientInfo>(client_info.clone());
+ req.extensions_mut().insert::<AppState>(app_state.clone());
+ handle_request(req)
+ }),
+ )
+ .await
+}
+
fn create_tls_config(
tls_config: &TlsConfig,
mandatory_client_auth: bool,
diff --git a/packages/core/tests/connections.rs b/packages/core/tests/connections.rs
new file mode 100644
index 00000000..cf772bb3
--- /dev/null
+++ b/packages/core/tests/connections.rs
@@ -0,0 +1,114 @@
+#![cfg(feature = "http")]
+//! How the server admits connections and which protocol they may speak.
+
+use localsend::http::server::start_with_port;
+use localsend::http::server::web::WebConfig;
+use localsend::http::state::ClientInfo;
+use std::time::Duration;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpStream;
+use tokio::sync::oneshot;
+
+/// `MAX_CONNECTIONS` of the server. Loopback peers are not limited per IP,
+/// so only this limit applies here.
+const MAX_CONNECTIONS: usize = 64;
+
+async fn start_test_server() -> (u16, oneshot::Sender<()>) {
+ let _ = tracing_subscriber::fmt().with_test_writer().try_init();
+ let (stop_tx, stop_rx) = oneshot::channel::<()>();
+
+ // Port 0 lets the OS pick a free port, avoiding collisions between tests.
+ let handle = start_with_port(
+ 0,
+ None,
+ ClientInfo {
+ alias: "Test Server".to_string(),
+ version: "2.2".to_string(),
+ device_model: None,
+ device_type: None,
+ token: "server-fingerprint".to_string(),
+ },
+ None,
+ None,
+ WebConfig::default(),
+ stop_rx,
+ )
+ .await
+ .expect("Failed to start server");
+
+ (handle.port(), stop_tx)
+}
+
+async fn connect(port: u16) -> TcpStream {
+ TcpStream::connect(("127.0.0.1", port)).await.unwrap()
+}
+
+/// Reads until the server closes the connection.
+async fn read_until_closed(stream: &mut TcpStream) -> Vec<u8> {
+ let mut buf = Vec::new();
+ tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut buf))
+ .await
+ .expect("the server did not close the connection")
+ // A reset counts as closed as well.
+ .ok();
+ buf
+}
+
+#[tokio::test]
+async fn http2_is_refused() {
+ let (port, _stop_tx) = start_test_server().await;
+
+ let mut stream = connect(port).await;
+ stream
+ .write_all(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
+ .await
+ .unwrap();
+
+ // An HTTP/2 server would answer with its SETTINGS frame.
+ let response = read_until_closed(&mut stream).await;
+ assert!(
+ response.is_empty() || response.starts_with(b"HTTP/1.1 "),
+ "the server spoke HTTP/2: {response:?}"
+ );
+}
+
+#[tokio::test]
+async fn connections_beyond_the_limit_are_closed() {
+ let (port, _stop_tx) = start_test_server().await;
+
+ // Idle connections, each holding a slot. Accepted in order, so all of
+ // them are counted before the next one.
+ let mut held = Vec::new();
+ for _ in 0..MAX_CONNECTIONS {
+ held.push(connect(port).await);
+ }
+
+ // Closed without an answer.
+ let mut excess = connect(port).await;
+ excess
+ .write_all(b"GET /api/localsend/v2/info HTTP/1.1\r\nHost: localhost\r\n\r\n")
+ .await
+ .ok();
+ assert!(read_until_closed(&mut excess).await.is_empty());
+
+ // A closed connection frees its slot for the next one.
+ drop(held.pop());
+ let served = tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ let mut stream = connect(port).await;
+ stream
+ .write_all(b"GET /api/localsend/v2/info HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
+ .await
+ .ok();
+ if read_until_closed(&mut stream).await.starts_with(b"HTTP/1.1 ") {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await;
+ assert!(
+ served.is_ok(),
+ "no connection was served after one was closed"
+ );
+}