mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
backbone: block fast-flapping clients
This commit is contained in:
1 parent
7100021b75
commit
aeeb3c1ab9
3 files changed
+770
-2
No files matched your search
@@ -4,10 +4,11 @@
|
||||
//! buffers. Inbound deframer is capped (vs Python's unbounded) to avoid
|
||||
//! malformed-peer memory blow-up.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -37,8 +38,21 @@ pub const TCP_PROBES: u32 = 12;
|
||||
/// Linux TCP_USER_TIMEOUT — drops stuck conns when peer goes silent without RST.
|
||||
pub const TCP_USER_TIMEOUT: u32 = 24;
|
||||
|
||||
pub const BLOCK_FAST_FLAPPING: bool = true;
|
||||
pub const FAST_FLAPPING_THRESHOLD: Duration = Duration::from_secs(20);
|
||||
pub const FAST_FLAPPING_GRACE: u64 = 5;
|
||||
pub const FAST_FLAPPING_BLOCK_TIME: Duration = Duration::from_secs(12 * 60 * 60);
|
||||
|
||||
const TX_CHANNEL_DEPTH: usize = 1024;
|
||||
|
||||
/// Bounds process-global fast-flap state to a conservative few hundred KiB.
|
||||
///
|
||||
/// Once full, unexpired tracked (including blocked) IPs retain their state and
|
||||
/// new IPs remain admissible but are not tracked. Strictly expired entries can
|
||||
/// be reclaimed. This prevents an address spray from turning the abuse
|
||||
/// safeguard itself into an unbounded allocation.
|
||||
const MAX_TRACKED_FAST_FLAP_IPS: usize = 4096;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BackboneServerConfig {
|
||||
pub name: String,
|
||||
@@ -48,6 +62,14 @@ pub struct BackboneServerConfig {
|
||||
pub mode: InterfaceMode,
|
||||
/// Optional kernel ifname; binds to its current IP (falls back to `listen_ip`).
|
||||
pub device: Option<String>,
|
||||
/// Reject an IP after more than `fast_flapping_grace` short connections.
|
||||
pub block_fast_flapping: bool,
|
||||
/// Connections shorter than this duration count as fast flaps.
|
||||
pub fast_flapping_threshold: Duration,
|
||||
/// Number of short connections tolerated before blocking starts.
|
||||
pub fast_flapping_grace: u64,
|
||||
/// Time since the latest short connection before its state expires.
|
||||
pub fast_flapping_block_time: Duration,
|
||||
}
|
||||
|
||||
impl BackboneServerConfig {
|
||||
@@ -59,6 +81,10 @@ impl BackboneServerConfig {
|
||||
prefer_ipv6: false,
|
||||
mode: InterfaceMode::Full,
|
||||
device: None,
|
||||
block_fast_flapping: BLOCK_FAST_FLAPPING,
|
||||
fast_flapping_threshold: FAST_FLAPPING_THRESHOLD,
|
||||
fast_flapping_grace: FAST_FLAPPING_GRACE,
|
||||
fast_flapping_block_time: FAST_FLAPPING_BLOCK_TIME,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,6 +114,181 @@ impl BackboneClientConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct FastFlapPolicy {
|
||||
enabled: bool,
|
||||
threshold: Duration,
|
||||
grace: u64,
|
||||
block_time: Duration,
|
||||
}
|
||||
|
||||
impl From<&BackboneServerConfig> for FastFlapPolicy {
|
||||
fn from(config: &BackboneServerConfig) -> Self {
|
||||
Self {
|
||||
enabled: config.block_fast_flapping,
|
||||
threshold: config.fast_flapping_threshold,
|
||||
grace: config.fast_flapping_grace,
|
||||
block_time: config.fast_flapping_block_time,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait MonotonicClock: Send + Sync {
|
||||
fn now(&self) -> Duration;
|
||||
}
|
||||
|
||||
struct SystemMonotonicClock;
|
||||
|
||||
impl MonotonicClock for SystemMonotonicClock {
|
||||
fn now(&self) -> Duration {
|
||||
static EPOCH: OnceLock<Instant> = OnceLock::new();
|
||||
EPOCH.get_or_init(Instant::now).elapsed()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct FastFlapEntry {
|
||||
last_flap: Duration,
|
||||
flaps: u64,
|
||||
}
|
||||
|
||||
struct FastFlapTable {
|
||||
entries: HashMap<IpAddr, FastFlapEntry>,
|
||||
capacity: usize,
|
||||
}
|
||||
|
||||
impl FastFlapTable {
|
||||
fn new(capacity: usize) -> Self {
|
||||
Self {
|
||||
entries: HashMap::new(),
|
||||
capacity,
|
||||
}
|
||||
}
|
||||
|
||||
fn prune_expired(&mut self, now: Duration, block_time: Duration) {
|
||||
self.entries
|
||||
.retain(|_, entry| now.saturating_sub(entry.last_flap) <= block_time);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FastFlapRuntime {
|
||||
clock: Arc<dyn MonotonicClock>,
|
||||
table: Arc<Mutex<FastFlapTable>>,
|
||||
}
|
||||
|
||||
impl FastFlapRuntime {
|
||||
fn production() -> Self {
|
||||
static TABLE: OnceLock<Arc<Mutex<FastFlapTable>>> = OnceLock::new();
|
||||
Self {
|
||||
clock: Arc::new(SystemMonotonicClock),
|
||||
table: Arc::clone(TABLE.get_or_init(|| {
|
||||
Arc::new(Mutex::new(FastFlapTable::new(MAX_TRACKED_FAST_FLAP_IPS)))
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
fn admit(&self, remote_ip: IpAddr, policy: FastFlapPolicy) -> FastFlapAdmission {
|
||||
let started_at = self.clock.now();
|
||||
if !policy.enabled {
|
||||
return FastFlapAdmission::Allowed(FastFlapConnection {
|
||||
remote_ip,
|
||||
started_at: Some(started_at),
|
||||
policy,
|
||||
runtime: self.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = table.entries.get(&remote_ip).copied() {
|
||||
if started_at.saturating_sub(entry.last_flap) > policy.block_time {
|
||||
table.entries.remove(&remote_ip);
|
||||
} else if entry.flaps > policy.grace {
|
||||
return FastFlapAdmission::Rejected { flaps: entry.flaps };
|
||||
}
|
||||
} else if table.entries.len() >= table.capacity {
|
||||
table.prune_expired(started_at, policy.block_time);
|
||||
}
|
||||
drop(table);
|
||||
|
||||
FastFlapAdmission::Allowed(FastFlapConnection {
|
||||
remote_ip,
|
||||
started_at: Some(started_at),
|
||||
policy,
|
||||
runtime: self.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn record_disconnect(&self, remote_ip: IpAddr, started_at: Duration, policy: FastFlapPolicy) {
|
||||
if !policy.enabled {
|
||||
return;
|
||||
}
|
||||
|
||||
let now = self.clock.now();
|
||||
if now.saturating_sub(started_at) >= policy.threshold {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = table.entries.get_mut(&remote_ip) {
|
||||
entry.last_flap = now;
|
||||
entry.flaps = entry.flaps.saturating_add(1);
|
||||
return;
|
||||
}
|
||||
if table.entries.len() >= table.capacity {
|
||||
table.prune_expired(now, policy.block_time);
|
||||
}
|
||||
if table.entries.len() >= table.capacity {
|
||||
tracing::debug!(
|
||||
remote_ip = %remote_ip,
|
||||
capacity = table.capacity,
|
||||
"backbone fast-flap table is full; declining to track new IP",
|
||||
);
|
||||
return;
|
||||
}
|
||||
table.entries.insert(
|
||||
remote_ip,
|
||||
FastFlapEntry {
|
||||
last_flap: now,
|
||||
flaps: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum FastFlapAdmission {
|
||||
Allowed(FastFlapConnection),
|
||||
Rejected { flaps: u64 },
|
||||
}
|
||||
|
||||
struct FastFlapConnection {
|
||||
remote_ip: IpAddr,
|
||||
started_at: Option<Duration>,
|
||||
policy: FastFlapPolicy,
|
||||
runtime: FastFlapRuntime,
|
||||
}
|
||||
|
||||
impl FastFlapConnection {
|
||||
fn record_disconnect(&mut self) {
|
||||
if let Some(started_at) = self.started_at.take() {
|
||||
self.runtime
|
||||
.record_disconnect(self.remote_ip, started_at, self.policy);
|
||||
}
|
||||
}
|
||||
|
||||
fn disconnected(mut self) {
|
||||
self.record_disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FastFlapConnection {
|
||||
fn drop(&mut self) {
|
||||
// The guard lives in the child read-task future, so cancellation and
|
||||
// panic exits account for the connection just like normal EOF/errors.
|
||||
self.record_disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
fn keepalive_durations() -> (Duration, Duration, u32, Duration) {
|
||||
(
|
||||
Duration::from_secs(TCP_PROBE_AFTER as u64),
|
||||
@@ -220,6 +421,25 @@ pub async fn spawn_backbone_server(
|
||||
id_gen: Arc<AtomicU64>,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
spawn_backbone_server_with_runtime(
|
||||
config,
|
||||
id,
|
||||
id_gen,
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
FastFlapRuntime::production(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn spawn_backbone_server_with_runtime(
|
||||
config: BackboneServerConfig,
|
||||
id: InterfaceId,
|
||||
id_gen: Arc<AtomicU64>,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
fast_flap_runtime: FastFlapRuntime,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let listen_ip = resolve_listen_addr(&config);
|
||||
let bind_addr = if listen_ip.starts_with('[') {
|
||||
@@ -230,6 +450,26 @@ pub async fn spawn_backbone_server(
|
||||
format!("{}:{}", listen_ip, config.listen_port)
|
||||
};
|
||||
let listener = TcpListener::bind(&bind_addr).await?;
|
||||
spawn_backbone_server_on_listener(
|
||||
config,
|
||||
id,
|
||||
id_gen,
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
fast_flap_runtime,
|
||||
listener,
|
||||
)
|
||||
}
|
||||
|
||||
fn spawn_backbone_server_on_listener(
|
||||
config: BackboneServerConfig,
|
||||
id: InterfaceId,
|
||||
id_gen: Arc<AtomicU64>,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
fast_flap_runtime: FastFlapRuntime,
|
||||
listener: TcpListener,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let local_addr = listener.local_addr()?;
|
||||
tracing::info!(name = %config.name, addr = %local_addr, "backbone server listening");
|
||||
|
||||
@@ -237,6 +477,7 @@ pub async fn spawn_backbone_server(
|
||||
let online2 = online.clone();
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let fast_flap_policy = FastFlapPolicy::from(&config);
|
||||
|
||||
// Parent listener is inbound-only; drain task warns on stray writes.
|
||||
let (tx, mut listener_rx) = mpsc::channel::<Bytes>(1);
|
||||
@@ -254,6 +495,19 @@ pub async fn spawn_backbone_server(
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((stream, peer)) => {
|
||||
let fast_flap_connection =
|
||||
match fast_flap_runtime.admit(peer.ip(), fast_flap_policy) {
|
||||
FastFlapAdmission::Allowed(connection) => connection,
|
||||
FastFlapAdmission::Rejected { flaps } => {
|
||||
tracing::warn!(
|
||||
remote_ip = %peer.ip(),
|
||||
flaps,
|
||||
"backbone: rejecting fast-flapping connection",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
|
||||
let client_name = format!("{}/client_{}", config.name, client_id);
|
||||
tracing::info!(
|
||||
@@ -282,6 +536,7 @@ pub async fn spawn_backbone_server(
|
||||
let read_handle = tokio::spawn(async move {
|
||||
backbone_read_loop(reader, client_id, transport_tx2, c_online_r, c_rxb_r)
|
||||
.await;
|
||||
fast_flap_connection.disconnected();
|
||||
tracing::info!(name = %cname, "backbone client disconnected");
|
||||
// Proactive notify so broadcasts don't target dead tx.
|
||||
let _ = dereg_tx
|
||||
@@ -514,6 +769,94 @@ pub async fn spawn_backbone_client(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestClock {
|
||||
now: Arc<Mutex<Duration>>,
|
||||
}
|
||||
|
||||
impl TestClock {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
now: Arc::new(Mutex::new(Duration::ZERO)),
|
||||
}
|
||||
}
|
||||
|
||||
fn advance(&self, duration: Duration) {
|
||||
let mut now = self.now.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*now = now
|
||||
.checked_add(duration)
|
||||
.expect("test monotonic clock overflow");
|
||||
}
|
||||
}
|
||||
|
||||
impl MonotonicClock for TestClock {
|
||||
fn now(&self) -> Duration {
|
||||
*self.now.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
fn test_runtime(capacity: usize) -> (FastFlapRuntime, TestClock) {
|
||||
let clock = TestClock::new();
|
||||
(
|
||||
FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table: Arc::new(Mutex::new(FastFlapTable::new(capacity))),
|
||||
},
|
||||
clock,
|
||||
)
|
||||
}
|
||||
|
||||
fn default_policy() -> FastFlapPolicy {
|
||||
FastFlapPolicy {
|
||||
enabled: BLOCK_FAST_FLAPPING,
|
||||
threshold: FAST_FLAPPING_THRESHOLD,
|
||||
grace: FAST_FLAPPING_GRACE,
|
||||
block_time: FAST_FLAPPING_BLOCK_TIME,
|
||||
}
|
||||
}
|
||||
|
||||
fn allow_connection(
|
||||
runtime: &FastFlapRuntime,
|
||||
ip: IpAddr,
|
||||
policy: FastFlapPolicy,
|
||||
) -> FastFlapConnection {
|
||||
match runtime.admit(ip, policy) {
|
||||
FastFlapAdmission::Allowed(connection) => connection,
|
||||
FastFlapAdmission::Rejected { flaps } => {
|
||||
panic!("expected connection from {ip} to be allowed, recorded flaps: {flaps}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_rejected(runtime: &FastFlapRuntime, ip: IpAddr, policy: FastFlapPolicy) {
|
||||
assert!(matches!(
|
||||
runtime.admit(ip, policy),
|
||||
FastFlapAdmission::Rejected { .. }
|
||||
));
|
||||
}
|
||||
|
||||
fn record_short_connection(
|
||||
runtime: &FastFlapRuntime,
|
||||
clock: &TestClock,
|
||||
ip: IpAddr,
|
||||
policy: FastFlapPolicy,
|
||||
) {
|
||||
let connection = allow_connection(runtime, ip, policy);
|
||||
clock.advance(Duration::from_millis(1));
|
||||
connection.disconnected();
|
||||
}
|
||||
|
||||
fn tracked_flaps(runtime: &FastFlapRuntime, ip: IpAddr) -> Option<u64> {
|
||||
runtime
|
||||
.table
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.entries
|
||||
.get(&ip)
|
||||
.map(|entry| entry.flaps)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_backbone_server_config() {
|
||||
@@ -521,6 +864,13 @@ mod tests {
|
||||
assert_eq!(cfg.listen_port, 4243);
|
||||
assert!(!cfg.prefer_ipv6);
|
||||
assert!(cfg.device.is_none());
|
||||
assert!(cfg.block_fast_flapping);
|
||||
assert_eq!(cfg.fast_flapping_threshold, Duration::from_secs(20));
|
||||
assert_eq!(cfg.fast_flapping_grace, 5);
|
||||
assert_eq!(
|
||||
cfg.fast_flapping_block_time,
|
||||
Duration::from_secs(12 * 60 * 60)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -573,6 +923,237 @@ mod tests {
|
||||
assert!(mtu >= rns_wire::constants::MTU as u32 / 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_flap_grace_is_strictly_greater_than_five() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let policy = default_policy();
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
|
||||
|
||||
// Upstream's strict `flaps > grace` admits and records six short
|
||||
// connections for grace=5. The following (seventh) admission blocks.
|
||||
for _ in 0..=policy.grace {
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
}
|
||||
assert_eq!(tracked_flaps(&runtime, ip), Some(6));
|
||||
assert_rejected(&runtime, ip, policy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threshold_and_expiry_boundaries_are_strict() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let stable_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2));
|
||||
let blocked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 3));
|
||||
|
||||
let stable = allow_connection(&runtime, stable_ip, policy);
|
||||
clock.advance(policy.threshold);
|
||||
stable.disconnected();
|
||||
assert_eq!(tracked_flaps(&runtime, stable_ip), None);
|
||||
|
||||
record_short_connection(&runtime, &clock, blocked_ip, policy);
|
||||
clock.advance(policy.block_time);
|
||||
assert_rejected(&runtime, blocked_ip, policy);
|
||||
clock.advance(Duration::from_nanos(1));
|
||||
let readmitted = allow_connection(&runtime, blocked_ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, blocked_ip), None);
|
||||
readmitted.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_connection_does_not_reset_existing_flaps() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 1;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 4));
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
let stable = allow_connection(&runtime, ip, policy);
|
||||
clock.advance(policy.threshold);
|
||||
stable.disconnected();
|
||||
assert_eq!(tracked_flaps(&runtime, ip), Some(1));
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, ip), Some(2));
|
||||
assert_rejected(&runtime, ip, policy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_connection_does_not_refresh_expiry() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 5));
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
clock.advance(policy.block_time - Duration::from_nanos(1));
|
||||
assert_rejected(&runtime, ip, policy);
|
||||
clock.advance(Duration::from_nanos(2));
|
||||
let readmitted = allow_connection(&runtime, ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, ip), None);
|
||||
readmitted.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_policy_neither_tracks_nor_blocks() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.enabled = false;
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 6));
|
||||
|
||||
for _ in 0..10 {
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
}
|
||||
assert_eq!(tracked_flaps(&runtime, ip), None);
|
||||
let admitted = allow_connection(&runtime, ip, policy);
|
||||
admitted.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_is_ip_scoped() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let blocked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 7));
|
||||
let other_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 8));
|
||||
|
||||
record_short_connection(&runtime, &clock, blocked_ip, policy);
|
||||
assert_rejected(&runtime, blocked_ip, policy);
|
||||
let other = allow_connection(&runtime, other_ip, policy);
|
||||
other.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_share_one_process_global_ip_keyspace() {
|
||||
let clock = TestClock::new();
|
||||
let table = Arc::new(Mutex::new(FastFlapTable::new(16)));
|
||||
let first_listener = FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table: Arc::clone(&table),
|
||||
};
|
||||
let second_listener = FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table,
|
||||
};
|
||||
let policy = default_policy();
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9));
|
||||
|
||||
for index in 0..=policy.grace {
|
||||
let listener = if index % 2 == 0 {
|
||||
&first_listener
|
||||
} else {
|
||||
&second_listener
|
||||
};
|
||||
record_short_connection(listener, &clock, ip, policy);
|
||||
}
|
||||
assert_rejected(&first_listener, ip, policy);
|
||||
assert_rejected(&second_listener, ip, policy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_table_preserves_unexpired_entries_and_reuses_expired_slots() {
|
||||
let (runtime, clock) = test_runtime(1);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let tracked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10));
|
||||
let untracked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 11));
|
||||
|
||||
record_short_connection(&runtime, &clock, tracked_ip, policy);
|
||||
record_short_connection(&runtime, &clock, untracked_ip, policy);
|
||||
|
||||
assert_eq!(tracked_flaps(&runtime, tracked_ip), Some(1));
|
||||
assert_eq!(tracked_flaps(&runtime, untracked_ip), None);
|
||||
assert_rejected(&runtime, tracked_ip, policy);
|
||||
let untracked = allow_connection(&runtime, untracked_ip, policy);
|
||||
untracked.disconnected();
|
||||
|
||||
clock.advance(policy.block_time + Duration::from_nanos(1));
|
||||
record_short_connection(&runtime, &clock, untracked_ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, tracked_ip), None);
|
||||
assert_eq!(tracked_flaps(&runtime, untracked_ip), Some(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aborted_child_read_task_records_short_connection() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
.unwrap();
|
||||
let listen_addr = listener.local_addr().unwrap();
|
||||
let config =
|
||||
BackboneServerConfig::new("abort-accounting-test", "127.0.0.1", listen_addr.port());
|
||||
let id_gen = Arc::new(AtomicU64::new(100));
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(8);
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel(8);
|
||||
let parent = spawn_backbone_server_on_listener(
|
||||
config,
|
||||
1,
|
||||
id_gen,
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
runtime.clone(),
|
||||
listener,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let _stream = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let child = tokio::time::timeout(Duration::from_secs(1), handle_rx.recv())
|
||||
.await
|
||||
.expect("accepted child handle timed out")
|
||||
.expect("child handle channel closed");
|
||||
clock.advance(Duration::from_millis(1));
|
||||
child.read_task.abort();
|
||||
let _ = child.read_task.await;
|
||||
|
||||
assert_eq!(
|
||||
tracked_flaps(&runtime, IpAddr::V4(Ipv4Addr::LOCALHOST)),
|
||||
Some(1)
|
||||
);
|
||||
parent.read_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_admission_does_not_consume_child_id_or_handle() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
.unwrap();
|
||||
let listen_addr = listener.local_addr().unwrap();
|
||||
let mut config =
|
||||
BackboneServerConfig::new("blocked-id-test", "127.0.0.1", listen_addr.port());
|
||||
config.fast_flapping_grace = 0;
|
||||
let id_gen = Arc::new(AtomicU64::new(100));
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(8);
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel(8);
|
||||
let parent = spawn_backbone_server_on_listener(
|
||||
config,
|
||||
1,
|
||||
Arc::clone(&id_gen),
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
runtime,
|
||||
listener,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut stream = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let mut byte = [0u8; 1];
|
||||
let closed = tokio::time::timeout(Duration::from_secs(1), stream.read(&mut byte))
|
||||
.await
|
||||
.expect("blocked connection was not closed");
|
||||
assert!(matches!(closed, Ok(0) | Err(_)));
|
||||
assert_eq!(id_gen.load(Ordering::SeqCst), 100);
|
||||
assert!(handle_rx.try_recv().is_err());
|
||||
|
||||
parent.read_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_backbone_max_reconnect_dereg() {
|
||||
// Connect attempts to a port nobody is listening on; with
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Mirrors `Reticulum._synthesize_interface` in the Python reference but
|
||||
//! rejects external-program interfaces.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config::ConfigSection;
|
||||
use rns_interface::tcp::{TcpClientConfig, TcpServerConfig};
|
||||
use rns_interface::traits::InterfaceMode;
|
||||
@@ -237,6 +239,14 @@ pub struct BackboneInterfaceConfig {
|
||||
pub max_reconnect_tries: Option<usize>,
|
||||
/// Parsed for Python config compatibility; advisory only.
|
||||
pub i2p_tunneled: bool,
|
||||
/// Listener-only fast-flap blocking switch. Python default: enabled.
|
||||
pub block_fast_flapping: bool,
|
||||
/// Listener-only short-connection threshold. Python default: 20 seconds.
|
||||
pub fast_flapping_threshold: Duration,
|
||||
/// Listener-only tolerated short-connection count. Python default: 5.
|
||||
pub fast_flapping_grace: u64,
|
||||
/// Listener-only block time. Configured in minutes; Python default: 720.
|
||||
pub fast_flapping_block_time: Duration,
|
||||
}
|
||||
|
||||
fn parse_interface_mode(s: &str) -> Option<InterfaceMode> {
|
||||
@@ -274,6 +284,92 @@ fn parse_port_opt(
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn parse_bool_strict(
|
||||
name: &str,
|
||||
field: &str,
|
||||
section: &ConfigSection,
|
||||
default: bool,
|
||||
) -> Result<bool, InterfaceFactoryError> {
|
||||
if !section.has(field) {
|
||||
return Ok(default);
|
||||
}
|
||||
section
|
||||
.get_bool(field)
|
||||
.ok_or_else(|| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: "expected a boolean value".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_uint_strict(
|
||||
name: &str,
|
||||
field: &str,
|
||||
section: &ConfigSection,
|
||||
default: u64,
|
||||
) -> Result<u64, InterfaceFactoryError> {
|
||||
if !section.has(field) {
|
||||
return Ok(default);
|
||||
}
|
||||
let raw = section
|
||||
.get(field)
|
||||
.ok_or_else(|| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: "expected a non-negative integer".to_string(),
|
||||
})?;
|
||||
raw.parse::<u64>()
|
||||
.map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is not a non-negative integer"),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_duration_strict(
|
||||
name: &str,
|
||||
field: &str,
|
||||
section: &ConfigSection,
|
||||
unit_seconds: f64,
|
||||
default: Duration,
|
||||
) -> Result<Duration, InterfaceFactoryError> {
|
||||
if !section.has(field) {
|
||||
return Ok(default);
|
||||
}
|
||||
let raw = section
|
||||
.get(field)
|
||||
.ok_or_else(|| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: "expected a finite non-negative number".to_string(),
|
||||
})?;
|
||||
let value = raw
|
||||
.parse::<f64>()
|
||||
.map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is not a number"),
|
||||
})?;
|
||||
if !value.is_finite() {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is not finite"),
|
||||
});
|
||||
}
|
||||
if value < 0.0 {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' must not be negative"),
|
||||
});
|
||||
}
|
||||
let seconds = value * unit_seconds;
|
||||
if !seconds.is_finite() {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is too large"),
|
||||
});
|
||||
}
|
||||
Duration::try_from_secs_f64(seconds).map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is outside the supported duration range"),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn synthesize_interface(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -1133,6 +1229,32 @@ fn synthesize_backbone(
|
||||
let connect_timeout = section.get_uint("connect_timeout").unwrap_or(5);
|
||||
let max_reconnect_tries = section.get_uint("max_reconnect_tries").map(|v| v as usize);
|
||||
let i2p_tunneled = section.get_bool("i2p_tunneled").unwrap_or(false);
|
||||
let block_fast_flapping = parse_bool_strict(
|
||||
name,
|
||||
"block_fast_flapping",
|
||||
section,
|
||||
rns_interface::backbone::BLOCK_FAST_FLAPPING,
|
||||
)?;
|
||||
let fast_flapping_threshold = parse_duration_strict(
|
||||
name,
|
||||
"fast_flapping_threshold",
|
||||
section,
|
||||
1.0,
|
||||
rns_interface::backbone::FAST_FLAPPING_THRESHOLD,
|
||||
)?;
|
||||
let fast_flapping_grace = parse_uint_strict(
|
||||
name,
|
||||
"fast_flapping_grace",
|
||||
section,
|
||||
rns_interface::backbone::FAST_FLAPPING_GRACE,
|
||||
)?;
|
||||
let fast_flapping_block_time = parse_duration_strict(
|
||||
name,
|
||||
"fast_flapping_block_time",
|
||||
section,
|
||||
60.0,
|
||||
rns_interface::backbone::FAST_FLAPPING_BLOCK_TIME,
|
||||
)?;
|
||||
|
||||
Ok(InterfaceConfig::Backbone(BackboneInterfaceConfig {
|
||||
name: name.to_string(),
|
||||
@@ -1145,6 +1267,10 @@ fn synthesize_backbone(
|
||||
connect_timeout,
|
||||
max_reconnect_tries,
|
||||
i2p_tunneled,
|
||||
block_fast_flapping,
|
||||
fast_flapping_threshold,
|
||||
fast_flapping_grace,
|
||||
fast_flapping_block_time,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -2284,11 +2410,68 @@ mod tests {
|
||||
assert_eq!(c.connect_timeout, 5);
|
||||
assert!(c.max_reconnect_tries.is_none());
|
||||
assert!(!c.i2p_tunneled);
|
||||
assert!(c.block_fast_flapping);
|
||||
assert_eq!(c.fast_flapping_threshold, Duration::from_secs(20));
|
||||
assert_eq!(c.fast_flapping_grace, 5);
|
||||
assert_eq!(c.fast_flapping_block_time, Duration::from_secs(720 * 60));
|
||||
}
|
||||
_ => panic!("expected Backbone"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_synthesize_backbone_fast_flap_overrides_allow_fractions() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "BackboneInterface");
|
||||
section.set("listen_on", "0.0.0.0");
|
||||
section.set("port", "4242");
|
||||
section.set("block_fast_flapping", "no");
|
||||
section.set("fast_flapping_threshold", "1.25");
|
||||
section.set("fast_flapping_grace", "9");
|
||||
section.set("fast_flapping_block_time", "0.5");
|
||||
|
||||
let config = synthesize_interface("backbone_flap_overrides", §ion).unwrap();
|
||||
match config {
|
||||
InterfaceConfig::Backbone(c) => {
|
||||
assert!(!c.block_fast_flapping);
|
||||
assert_eq!(c.fast_flapping_threshold, Duration::from_millis(1250));
|
||||
assert_eq!(c.fast_flapping_grace, 9);
|
||||
assert_eq!(c.fast_flapping_block_time, Duration::from_secs(30));
|
||||
}
|
||||
_ => panic!("expected Backbone"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_synthesize_backbone_rejects_invalid_fast_flap_values() {
|
||||
for (field, value) in [
|
||||
("block_fast_flapping", "sometimes"),
|
||||
("fast_flapping_threshold", "not-a-number"),
|
||||
("fast_flapping_threshold", "NaN"),
|
||||
("fast_flapping_threshold", "-0.1"),
|
||||
("fast_flapping_threshold", "1e30"),
|
||||
("fast_flapping_grace", "-1"),
|
||||
("fast_flapping_grace", "1.5"),
|
||||
("fast_flapping_grace", "18446744073709551616"),
|
||||
("fast_flapping_block_time", "inf"),
|
||||
("fast_flapping_block_time", "-1"),
|
||||
("fast_flapping_block_time", "1e307"),
|
||||
] {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "BackboneInterface");
|
||||
section.set("listen_on", "0.0.0.0");
|
||||
section.set("port", "4242");
|
||||
section.set(field, value);
|
||||
|
||||
match synthesize_interface("backbone_invalid_flap", §ion) {
|
||||
Err(InterfaceFactoryError::InvalidValue {
|
||||
field: error_field, ..
|
||||
}) => assert_eq!(error_field, format!("backbone_invalid_flap.{field}")),
|
||||
other => panic!("expected InvalidValue for {field}={value}, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_synthesize_backbone_connect_timeout() {
|
||||
let mut section = ConfigSection::new();
|
||||
|
||||
@@ -4906,6 +4906,10 @@ async fn spawn_interface(
|
||||
config.mode = c.mode;
|
||||
config.prefer_ipv6 = c.prefer_ipv6;
|
||||
config.device = c.device.clone();
|
||||
config.block_fast_flapping = c.block_fast_flapping;
|
||||
config.fast_flapping_threshold = c.fast_flapping_threshold;
|
||||
config.fast_flapping_grace = c.fast_flapping_grace;
|
||||
config.fast_flapping_block_time = c.fast_flapping_block_time;
|
||||
rns_interface::backbone::spawn_backbone_server(
|
||||
config,
|
||||
id,
|
||||
|
||||
Reference in new issue
Block a user