From fd005be9bd026645a2a680ff4386e98312ad78fe Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Tue, 10 Nov 2026 04:26:45 -0700 Subject: [PATCH] interfaces: autoconfigure hardware MTU and follow upstream frame limits --- crates/rns-interface/src/ax25kiss.rs | 23 +- crates/rns-interface/src/backbone.rs | 61 ++-- crates/rns-interface/src/hdlc.rs | 210 +++++++++--- crates/rns-interface/src/i2p.rs | 2 +- crates/rns-interface/src/kiss.rs | 119 ++++++- crates/rns-interface/src/kiss_iface.rs | 28 +- crates/rns-interface/src/local.rs | 19 +- crates/rns-interface/src/pipe.rs | 2 +- crates/rns-interface/src/serial.rs | 16 +- crates/rns-interface/src/tcp.rs | 105 +++--- crates/rns-interface/src/traits.rs | 66 ++-- crates/rns-runtime/src/interface_factory.rs | 323 +++++++++++------- crates/rns-runtime/src/reticulum.rs | 228 ++++++++----- .../src/reticulum/tests/tunnels.rs | 27 +- crates/rns-runtime/src/shared_instance.rs | 3 +- 15 files changed, 810 insertions(+), 422 deletions(-) diff --git a/crates/rns-interface/src/ax25kiss.rs b/crates/rns-interface/src/ax25kiss.rs index 4524bf0..d2e2fd4 100644 --- a/crates/rns-interface/src/ax25kiss.rs +++ b/crates/rns-interface/src/ax25kiss.rs @@ -372,8 +372,9 @@ pub async fn spawn_ax25kiss_interface( let rxb_r = shared_rxb.clone(); let read_task = tokio::spawn(async move { let mut port_r = port; - let mut deframer = kiss::KissDeframer::new(); + let mut deframer = kiss::KissByteDeframer::new(HW_MTU as usize + AX25_HEADER_SIZE); let mut buf = [0u8; 1024]; + let mut last_read = std::time::Instant::now(); loop { if !online_r.load(Ordering::SeqCst) { @@ -383,11 +384,18 @@ pub async fn spawn_ax25kiss_interface( Ok((p, b, n)) => { port_r = p; buf = b; - if n > 0 { + if n == 0 { + if deframer.buffered() > 0 + && last_read.elapsed() > Duration::from_millis(AX25_READ_TIMEOUT_MS) + { + deframer.reset(); + } + } else { + last_read = std::time::Instant::now(); rxb_r.fetch_add(n as u64, Ordering::Relaxed); - for (cmd, frame) in deframer.feed(&buf[..n]) { - match cmd { - kiss::CMD_DATA => { + for event in deframer.feed(&buf[..n]) { + match event { + kiss::KissEvent::Data(frame) => { let payload = match strip_ax25_header(&frame) { Some(p) if !p.is_empty() => p.to_vec(), _ => continue, @@ -405,13 +413,10 @@ pub async fn spawn_ax25kiss_interface( return; } } - kiss::CMD_READY => { + kiss::KissEvent::Ready => { ready_r.store(true, Ordering::SeqCst); tracing::debug!(id, "AX.25 KISS flow control: ready"); } - _ => { - tracing::debug!(id, cmd, "ignoring KISS command"); - } } } } diff --git a/crates/rns-interface/src/backbone.rs b/crates/rns-interface/src/backbone.rs index 3fb16c5..2fce2b1 100644 --- a/crates/rns-interface/src/backbone.rs +++ b/crates/rns-interface/src/backbone.rs @@ -31,12 +31,11 @@ use rns_transport::messages::{ /// the interface wire budget; the kernel may clamp the socket buffer request. pub const HW_MTU: u32 = 1_048_576; -/// Listener-side bitrate guess advertised on the parent handle. -pub const BITRATE_GUESS: u64 = 1_000_000_000; +/// Python `BackboneInterface.BITRATE_GUESS` and `BackboneClientInterface.BITRATE_GUESS`. +pub const BITRATE_GUESS: u64 = 100_000_000; -/// Per-peer bitrate guess (100 Mbps), selecting a 16 KiB MTU through -/// [`crate::traits::optimise_mtu`]. -pub const CHILD_BITRATE_GUESS: u64 = 100_000_000; +/// Largest packet a Backbone peer carries (the shared HDLC deframer bound). +const WIRE_BUDGET: u32 = crate::tcp::TCP_HW_MTU; pub const RECONNECT_WAIT: u64 = 5; pub const INITIAL_CONNECT_TIMEOUT: u64 = 5; @@ -389,10 +388,8 @@ fn tune_accepted_stream(stream: &TcpStream) { let _ = socket2::SockRef::from(stream).set_recv_buffer_size(DP_IC_RCVBUF); } -fn child_mtu() -> u32 { - crate::traits::optimise_mtu(CHILD_BITRATE_GUESS) - .map(|m| m.min(HW_MTU)) - .unwrap_or(rns_wire::constants::MTU as u32) +fn autoconfigured_mtu() -> (u32, InterfacePacketCapacity) { + crate::traits::hardware_mtu_capacity(crate::traits::optimise_mtu(BITRATE_GUESS), WIRE_BUDGET) } async fn backbone_read_loop( @@ -402,8 +399,15 @@ async fn backbone_read_loop( online: Arc, rxb: Arc, ) { - let mut deframer = hdlc::HdlcDeframer::new(); - // Large buffer to amortise syscalls; inbound capped by HdlcDeframer::MAX_FRAME_SIZE. + // Upstream bounds receive at its optimised HW_MTU (32768 at 100 Mbps); this + // stays at the wire budget until a transit node clamps link MTU to that too. + // Transport applies IFAC, so allow the largest tag. + let mut deframer = hdlc::HdlcDeframer::with_limits( + WIRE_BUDGET as usize, + rns_wire::constants::HEADER_MINSIZE, + Some(WIRE_BUDGET as usize + 64), + ); + // Large buffer to amortise syscalls. let mut buf = vec![0u8; 65536]; loop { match reader.read(&mut buf).await { @@ -804,14 +808,11 @@ fn spawn_backbone_server_on_listener( .await; }); + let (child_mtu, packet_capacity) = autoconfigured_mtu(); let handle = InterfaceHandle { id: client_id, owner: child_owner, - packet_capacity: InterfacePacketCapacity::new( - child_mtu().min(262144), - 262144, - true, - ), + packet_capacity, parent_id: Some(id), name: client_name, mode, @@ -821,8 +822,8 @@ fn spawn_backbone_server_on_listener( forward: false, repeat: false, }, - bitrate: CHILD_BITRATE_GUESS, - mtu: child_mtu(), + bitrate: BITRATE_GUESS, + mtu: child_mtu, online: c_online, rxb: Some(c_rxb), txb: Some(c_txb), @@ -847,10 +848,11 @@ fn spawn_backbone_server_on_listener( online2.store(false, Ordering::SeqCst); }); + let (mtu, packet_capacity) = autoconfigured_mtu(); Ok(InterfaceHandle { id, owner, - packet_capacity: InterfacePacketCapacity::base(500), + packet_capacity, parent_id: None, name, mode, @@ -861,7 +863,7 @@ fn spawn_backbone_server_on_listener( repeat: false, }, bitrate: BITRATE_GUESS, - mtu: rns_wire::constants::MTU as u32, + mtu, online, rxb: Some(Arc::new(AtomicU64::new(0))), txb: Some(Arc::new(AtomicU64::new(0))), @@ -1017,10 +1019,11 @@ pub async fn spawn_backbone_client( } }); + let (mtu, packet_capacity) = autoconfigured_mtu(); Ok(InterfaceHandle { id, owner, - packet_capacity: InterfacePacketCapacity::new(child_mtu().min(262144), 262144, true), + packet_capacity, parent_id: None, name, mode, @@ -1030,8 +1033,8 @@ pub async fn spawn_backbone_client( forward: false, repeat: false, }, - bitrate: CHILD_BITRATE_GUESS, - mtu: child_mtu(), + bitrate: BITRATE_GUESS, + mtu, online, rxb: Some(shared_rxb), txb: Some(shared_txb), @@ -1364,8 +1367,7 @@ mod tests { #[test] fn test_constants() { assert_eq!(HW_MTU, 1_048_576); - assert_eq!(BITRATE_GUESS, 1_000_000_000); - assert_eq!(CHILD_BITRATE_GUESS, 100_000_000); + assert_eq!(BITRATE_GUESS, 100_000_000); assert_eq!(RECONNECT_WAIT, 5); } @@ -1395,15 +1397,6 @@ mod tests { assert!(cfg.prefer_ipv6); } - #[test] - fn test_child_mtu_uses_100mbps_curve() { - // optimise_mtu(100 Mbps) is one of the step values; verify the - // result lands inside the HW_MTU ceiling. - let mtu = child_mtu(); - assert!(mtu <= HW_MTU); - 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); diff --git a/crates/rns-interface/src/hdlc.rs b/crates/rns-interface/src/hdlc.rs index 73dd1d7..5d8201c 100644 --- a/crates/rns-interface/src/hdlc.rs +++ b/crates/rns-interface/src/hdlc.rs @@ -11,8 +11,8 @@ pub const ESC: u8 = 0x7D; /// XOR mask applied to escaped bytes. pub const ESC_MASK: u8 = 0x20; -/// Upper bound on a single HDLC frame (sized for full resource transfers on TCP/Local MTUs). -const MAX_FRAME_SIZE: usize = 524288; +/// Default MTU of [`HdlcDeframer::new`]; partial frames are bounded at twice this. +const DEFAULT_MTU: usize = 262144; /// Pre-allocated capacity for the deframer accumulator. Covers typical HW_MTUs /// with headroom; larger frames grow the Vec normally. @@ -39,39 +39,44 @@ pub fn escape_into(data: &[u8], out: &mut Vec) { } } -/// Append the unescaped form of `data` to `out`. Unknown escape sequences and a -/// trailing lone ESC byte are passed through unchanged — matching the previous -/// implementation so any consumer relying on length/CRC rejection still sees -/// the same bytes. +/// Append the unescaped form of `data` to `out` as two global replacements, +/// `ESC 5E` to FLAG and then `ESC 5D` to ESC, so malformed sequences decode as +/// upstream `HDLC.unescape` does. pub fn unescape_into(data: &[u8], out: &mut Vec) { + let start = out.len(); let mut i = 0; while i < data.len() { match data[i..].iter().position(|&b| b == ESC) { Some(rel) => { let hit = i + rel; out.extend_from_slice(&data[i..hit]); - if hit + 1 < data.len() { - let next = data[hit + 1]; - if next == (FLAG ^ ESC_MASK) { - out.push(FLAG); - } else if next == (ESC ^ ESC_MASK) { - out.push(ESC); - } else { - out.push(ESC); - out.push(next); - } + if data.get(hit + 1) == Some(&(FLAG ^ ESC_MASK)) { + out.push(FLAG); i = hit + 2; } else { out.push(ESC); - return; + i = hit + 1; } } None => { out.extend_from_slice(&data[i..]); - return; + break; } } } + let end = out.len(); + let (mut r, mut w) = (start, start); + while r < end { + let b = out[r]; + out[w] = b; + w += 1; + r += if b == ESC && r + 1 < end && out[r + 1] == (ESC ^ ESC_MASK) { + 2 + } else { + 1 + }; + } + out.truncate(w); } /// Append a complete HDLC frame for `data` to `out`. @@ -99,22 +104,46 @@ pub fn frame(data: &[u8]) -> Vec { out } +/// Stream deframer with upstream `HDLC.ReceiveBuffer` semantics: a flag closes +/// one frame and opens the next, a frame is delivered only when its unescaped +/// length is above `min_frame_len` and at most `max_frame_len`, and an +/// unterminated partial frame longer than twice the MTU is dropped. pub struct HdlcDeframer { buffer: Vec, in_frame: bool, /// Reusable scratch for unescape output to avoid per-frame allocation. unescape_scratch: Vec, + /// Bytes before the opening flag that upstream keeps in its buffer. + lead: usize, + mtu: usize, + min_frame_len: usize, + max_frame_len: Option, } impl HdlcDeframer { + /// Equivalent to `ReceiveBuffer(262144, 0, None)`: every non-empty frame is delivered. pub fn new() -> Self { + Self::with_limits(DEFAULT_MTU, 0, None) + } + + /// Equivalent to `ReceiveBuffer(mtu, min_frame_len, max_frame_len)`. + pub fn with_limits(mtu: usize, min_frame_len: usize, max_frame_len: Option) -> Self { Self { buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY), in_frame: false, unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY), + lead: 0, + mtu, + min_frame_len, + max_frame_len, } } + /// Update the delivery bound, for example after the interface IFAC size changes. + pub fn set_max_frame_len(&mut self, max_frame_len: Option) { + self.max_frame_len = max_frame_len; + } + pub fn feed(&mut self, data: &[u8]) -> Vec> { let mut frames = Vec::new(); let mut i = 0; @@ -123,24 +152,21 @@ impl HdlcDeframer { Some(rel) => { let hit = i + rel; if self.in_frame { - self.append_in_frame(&data[i..hit]); - if !self.buffer.is_empty() { - self.unescape_scratch.clear(); - unescape_into(&self.buffer, &mut self.unescape_scratch); - if !self.unescape_scratch.is_empty() { - frames.push(std::mem::take(&mut self.unescape_scratch)); - // Restore capacity for the next frame. - self.unescape_scratch = Vec::with_capacity(DEFRAME_BUF_CAPACITY); - } - } - self.buffer.clear(); + self.buffer.extend_from_slice(&data[i..hit]); + self.finish_frame(&mut frames); + self.lead = 0; + } else { + self.lead = hit - i; } self.in_frame = true; i = hit + 1; } None => { if self.in_frame { - self.append_in_frame(&data[i..]); + self.buffer.extend_from_slice(&data[i..]); + if self.lead + 1 + self.buffer.len() > self.mtu.saturating_mul(2) { + self.reset(); + } } return frames; } @@ -149,21 +175,30 @@ impl HdlcDeframer { frames } - /// Append `chunk` to `self.buffer` while enforcing `MAX_FRAME_SIZE`. On - /// overflow the in-progress frame is dropped and we wait for the next FLAG - /// to resync — matching the previous byte-loop behavior. - fn append_in_frame(&mut self, chunk: &[u8]) { - if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE { - self.buffer.clear(); - self.in_frame = false; - return; + fn finish_frame(&mut self, frames: &mut Vec>) { + if !self.buffer.is_empty() { + self.unescape_scratch.clear(); + unescape_into(&self.buffer, &mut self.unescape_scratch); + let len = self.unescape_scratch.len(); + if len > self.min_frame_len && self.max_frame_len.is_none_or(|max| len <= max) { + frames.push(std::mem::replace( + &mut self.unescape_scratch, + Vec::with_capacity(DEFRAME_BUF_CAPACITY), + )); + } else if len > 0 { + tracing::debug!( + frame_len = len, + "invalid HDLC frame received, dropping frame" + ); + } } - self.buffer.extend_from_slice(chunk); + self.buffer.clear(); } pub fn reset(&mut self) { self.buffer.clear(); self.in_frame = false; + self.lead = 0; } } @@ -173,6 +208,81 @@ impl Default for HdlcDeframer { } } +/// Per-byte deframer of the upstream serial, pipe and I2P read loops. Bytes past +/// `hw_mtu` are dropped but the frame is still delivered, an unknown escape keeps +/// only the escaped byte, the escape state carries across frames, and the flag +/// that closes a frame does not open the next one. +pub struct HdlcByteDeframer { + buffer: Vec, + in_frame: bool, + escape: bool, + /// Length of the last delivered frame, which upstream keeps buffered. + held: usize, + hw_mtu: usize, +} + +impl HdlcByteDeframer { + pub fn new(hw_mtu: usize) -> Self { + Self { + buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY.min(hw_mtu)), + in_frame: false, + escape: false, + held: 0, + hw_mtu, + } + } + + pub fn feed(&mut self, data: &[u8]) -> Vec> { + let mut frames = Vec::new(); + for &byte in data { + if self.in_frame && byte == FLAG { + self.in_frame = false; + self.held = self.buffer.len(); + if !self.buffer.is_empty() { + frames.push(std::mem::take(&mut self.buffer)); + } + } else if byte == FLAG { + self.in_frame = true; + self.buffer.clear(); + self.held = 0; + } else if self.in_frame && self.buffer.len() < self.hw_mtu { + if byte == ESC { + self.escape = true; + } else { + let mut byte = byte; + if self.escape { + if byte == FLAG ^ ESC_MASK { + byte = FLAG; + } else if byte == ESC ^ ESC_MASK { + byte = ESC; + } + self.escape = false; + } + self.buffer.push(byte); + } + } + } + frames + } + + /// Bytes upstream holds in its data buffer. Upstream drivers reset after an + /// idle read timeout only while this is non-zero. + pub fn buffered(&self) -> usize { + if self.in_frame { + self.buffer.len() + } else { + self.held + } + } + + pub fn reset(&mut self) { + self.buffer.clear(); + self.held = 0; + self.in_frame = false; + self.escape = false; + } +} + #[cfg(test)] mod tests { use super::*; @@ -282,19 +392,15 @@ mod tests { } #[test] - fn test_deframer_oversized_drops_then_resyncs() { - // A frame body larger than MAX_FRAME_SIZE must drop and resync on the - // next FLAG, exactly like the per-byte implementation. - let mut deframer = HdlcDeframer::new(); - let mut oversized = vec![FLAG]; - oversized.extend(std::iter::repeat_n(0x55, MAX_FRAME_SIZE + 100)); - oversized.push(FLAG); - let frames = deframer.feed(&oversized); - assert!(frames.is_empty()); + fn test_deframer_partial_over_twice_mtu_drops_then_resyncs() { + let mut deframer = HdlcDeframer::with_limits(64, 0, None); + let mut partial = vec![FLAG]; + partial.extend(std::iter::repeat_n(0x55, 128)); + assert!(deframer.feed(&partial).is_empty()); - let small = frame(b"after-overflow"); - let frames = deframer.feed(&small); - assert_eq!(frames.len(), 1); - assert_eq!(frames[0], b"after-overflow"); + let mut rest = vec![0x55, FLAG]; + rest.extend(frame(b"after-overflow")); + let frames = deframer.feed(&rest); + assert_eq!(frames, vec![b"after-overflow".to_vec()]); } } diff --git a/crates/rns-interface/src/i2p.rs b/crates/rns-interface/src/i2p.rs index 5f70207..831c195 100644 --- a/crates/rns-interface/src/i2p.rs +++ b/crates/rns-interface/src/i2p.rs @@ -1073,7 +1073,7 @@ async fn i2p_read_loop( rxb: &AtomicU64, last_read: &std::sync::Mutex, ) { - let mut deframer = hdlc::HdlcDeframer::new(); + let mut deframer = hdlc::HdlcByteDeframer::new(HW_MTU as usize); let mut buf = [0u8; 4096]; if !initial_data.is_empty() { diff --git a/crates/rns-interface/src/kiss.rs b/crates/rns-interface/src/kiss.rs index d8690e8..c9eba53 100644 --- a/crates/rns-interface/src/kiss.rs +++ b/crates/rns-interface/src/kiss.rs @@ -48,9 +48,8 @@ pub fn escape_into(data: &[u8], out: &mut Vec) { } } -/// Append the unescaped form of `data` to `out`. Unknown escape sequences and -/// a trailing lone FESC byte are passed through unchanged — matching the -/// previous implementation byte-for-byte. +/// Append the unescaped form of `data` to `out`. As in the upstream read loops, +/// an unknown escape keeps only the escaped byte and a trailing FESC is dropped. pub fn unescape_into(data: &[u8], out: &mut Vec) { let mut i = 0; while i < data.len() { @@ -58,20 +57,13 @@ pub fn unescape_into(data: &[u8], out: &mut Vec) { Some(rel) => { let hit = i + rel; out.extend_from_slice(&data[i..hit]); - if hit + 1 < data.len() { - match data[hit + 1] { - TFEND => out.push(FEND), - TFESC => out.push(FESC), - other => { - out.push(FESC); - out.push(other); - } - } - i = hit + 2; - } else { - out.push(FESC); - return; + match data.get(hit + 1) { + Some(&TFEND) => out.push(FEND), + Some(&TFESC) => out.push(FESC), + Some(&other) => out.push(other), + None => return, } + i = hit + 2; } None => { out.extend_from_slice(&data[i..]); @@ -253,6 +245,101 @@ impl Default for RawKissDeframer { } } +/// Output of [`KissByteDeframer`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KissEvent { + /// A completed `CMD_DATA` frame. + Data(Vec), + /// One payload byte of a `CMD_READY` frame; upstream runs `process_queue` per byte. + Ready, +} + +/// Per-byte deframer of the upstream KISS, AX.25-KISS and TCP `kiss_framing` +/// read loops. The port nibble is stripped, only `CMD_DATA` frames are +/// collected and delivered, bytes past `hw_mtu` are dropped but the frame is +/// still delivered, an unknown escape keeps only the escaped byte, and the +/// FEND closing a data frame does not open the next one. +pub struct KissByteDeframer { + buffer: Vec, + in_frame: bool, + escape: bool, + command: u8, + /// Length of the last delivered frame, which upstream keeps buffered. + held: usize, + hw_mtu: usize, +} + +impl KissByteDeframer { + pub fn new(hw_mtu: usize) -> Self { + Self { + buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY.min(hw_mtu)), + in_frame: false, + escape: false, + command: CMD_UNKNOWN, + held: 0, + hw_mtu, + } + } + + pub fn feed(&mut self, data: &[u8]) -> Vec { + let mut events = Vec::new(); + for &byte in data { + if self.in_frame && byte == FEND && self.command == CMD_DATA { + self.in_frame = false; + self.held = self.buffer.len(); + if !self.buffer.is_empty() { + events.push(KissEvent::Data(std::mem::take(&mut self.buffer))); + } + } else if byte == FEND { + self.in_frame = true; + self.command = CMD_UNKNOWN; + self.buffer.clear(); + self.held = 0; + } else if self.in_frame && self.buffer.len() < self.hw_mtu { + if self.buffer.is_empty() && self.command == CMD_UNKNOWN { + self.command = byte & CMD_MASK; + } else if self.command == CMD_DATA { + if byte == FESC { + self.escape = true; + } else { + let mut byte = byte; + if self.escape { + if byte == TFEND { + byte = FEND; + } else if byte == TFESC { + byte = FESC; + } + self.escape = false; + } + self.buffer.push(byte); + } + } else if self.command == CMD_READY { + events.push(KissEvent::Ready); + } + } + } + events + } + + /// Bytes upstream holds in its data buffer. Upstream drivers reset after an + /// idle read timeout only while this is non-zero. + pub fn buffered(&self) -> usize { + if self.in_frame { + self.buffer.len() + } else { + self.held + } + } + + pub fn reset(&mut self) { + self.buffer.clear(); + self.held = 0; + self.in_frame = false; + self.escape = false; + self.command = CMD_UNKNOWN; + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/rns-interface/src/kiss_iface.rs b/crates/rns-interface/src/kiss_iface.rs index f3b7d4a..abb3c61 100644 --- a/crates/rns-interface/src/kiss_iface.rs +++ b/crates/rns-interface/src/kiss_iface.rs @@ -13,6 +13,7 @@ use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceM use rns_transport::messages::{InboundPacket, TransportMessage}; const KISS_READ_TIMEOUT_MS: u64 = 100; +const HW_MTU: usize = 564; /// Python `KISSInterface.BITRATE_GUESS`; `speed` is only the serial baud rate. pub const BITRATE_GUESS: u64 = 1200; @@ -276,8 +277,9 @@ async fn spawn_kiss_with_port( // The writer lives and dies with the read task that teardown aborts. let _writer = AbortOnDrop(writer); let mut port_r = port; - let mut deframer = kiss::KissDeframer::new(); + let mut deframer = kiss::KissByteDeframer::new(HW_MTU); let mut buf = [0u8; 1024]; + let mut last_read = std::time::Instant::now(); loop { if !online_r.load(Ordering::SeqCst) { @@ -287,14 +289,18 @@ async fn spawn_kiss_with_port( Ok((p, b, n)) => { port_r = p; buf = b; - if n > 0 { + if n == 0 { + if deframer.buffered() > 0 + && last_read.elapsed() > Duration::from_millis(KISS_READ_TIMEOUT_MS) + { + deframer.reset(); + } + } else { + last_read = std::time::Instant::now(); rxb_r.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); - for (cmd, frame) in deframer.feed(&buf[..n]) { - match cmd { - kiss::CMD_DATA => { - if frame.is_empty() { - continue; - } + for event in deframer.feed(&buf[..n]) { + match event { + kiss::KissEvent::Data(frame) => { let msg = TransportMessage::Inbound(InboundPacket { raw: Bytes::from(frame), interface_id: id, @@ -308,14 +314,10 @@ async fn spawn_kiss_with_port( return; } } - kiss::CMD_READY => { - // Python process_queue ignores the READY payload. + kiss::KissEvent::Ready => { ready_r.store(true, Ordering::SeqCst); tracing::debug!(id, "KISS flow control: ready"); } - _ => { - tracing::debug!(id, cmd, "ignoring KISS command"); - } } } } diff --git a/crates/rns-interface/src/local.rs b/crates/rns-interface/src/local.rs index 4b39121..b2c333c 100644 --- a/crates/rns-interface/src/local.rs +++ b/crates/rns-interface/src/local.rs @@ -20,6 +20,7 @@ use crate::traits::{ use rns_transport::messages::{InboundPacket, TransportMessage}; pub const LOCAL_MTU: u32 = 262_144; +const LOCAL_HW_MTU: usize = LOCAL_MTU as usize; pub const LOCAL_BITRATE: u64 = 1_000_000_000; pub const RECONNECT_WAIT: Duration = Duration::from_secs(8); pub const CLIENT_SLEEP_PAUSE_TIMEOUT: Duration = Duration::from_secs(12); @@ -338,7 +339,11 @@ async fn accepted_read_loop( pause: Option>, ) { let mut buf = [0u8; 8192]; - let mut deframer = hdlc::HdlcDeframer::new(); + let mut deframer = hdlc::HdlcDeframer::with_limits( + LOCAL_HW_MTU, + rns_wire::constants::HEADER_MINSIZE, + Some(LOCAL_HW_MTU), + ); loop { match reader.read(&mut buf).await { @@ -431,7 +436,11 @@ async fn run_local_client_connection( ) -> LocalClientConnectionEnd { let interface_id = io.interface_id; let mut buf = [0u8; 8192]; - let mut deframer = hdlc::HdlcDeframer::new(); + let mut deframer = hdlc::HdlcDeframer::with_limits( + LOCAL_HW_MTU, + rns_wire::constants::HEADER_MINSIZE, + Some(LOCAL_HW_MTU), + ); let mut keepalive = phy_keepalive.then(|| { let mut interval = tokio::time::interval_at( tokio::time::Instant::now() + KEEPALIVE_INTERVAL, @@ -938,7 +947,7 @@ mod tests { accepted.packet_capacity, InterfacePacketCapacity::new(262144, 262144, true) ); - let payload = Bytes::from_static(b"local ipc test"); + let payload = Bytes::from_static(b"local ipc test packet payload"); client_handle.tx.send(payload.clone()).await.unwrap(); let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv()) @@ -954,7 +963,7 @@ mod tests { other => panic!("unexpected: {:?}", other), } - let reply = Bytes::from_static(b"local ipc reply"); + let reply = Bytes::from_static(b"local ipc reply packet payload"); accepted.tx.send(reply.clone()).await.unwrap(); let msg2 = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv()) @@ -1214,7 +1223,7 @@ mod tests { second_accepted.owner.mark_registered(); // Online is published only after the offline queue is dropped. wait_until_online(&client_handle.online).await; - let after = Bytes::from_static(b"after reconnect"); + let after = Bytes::from_static(b"after reconnect packet payload"); client_handle.tx.send(after.clone()).await.unwrap(); let first_frame = tokio::time::timeout(std::time::Duration::from_secs(3), async { diff --git a/crates/rns-interface/src/pipe.rs b/crates/rns-interface/src/pipe.rs index c3e54e7..6b876cf 100644 --- a/crates/rns-interface/src/pipe.rs +++ b/crates/rns-interface/src/pipe.rs @@ -173,7 +173,7 @@ pub async fn spawn_pipe_interface( let read_task = tokio::spawn(async move { let (mut child, mut stdin, mut stdout) = first; loop { - let mut deframer = hdlc::HdlcDeframer::new(); + let mut deframer = hdlc::HdlcByteDeframer::new(HW_MTU as usize); let mut buf = [0u8; 2048]; loop { tokio::select! { diff --git a/crates/rns-interface/src/serial.rs b/crates/rns-interface/src/serial.rs index e8237c9..0fb8027 100644 --- a/crates/rns-interface/src/serial.rs +++ b/crates/rns-interface/src/serial.rs @@ -16,6 +16,7 @@ use rns_transport::messages::{InboundPacket, TransportMessage}; pub const DEFAULT_BAUD: u32 = 9600; const SERIAL_READ_TIMEOUT_MS: u64 = 100; +const HW_MTU: usize = 564; /// Open with DTR and RTS asserted, as POSIX `open()` and pyserial do. Windows /// otherwise leaves both low, and TinyUSB CDC (nRF52 RNodes) sends nothing @@ -165,8 +166,9 @@ pub async fn spawn_serial_interface( let rxb_r = shared_rxb.clone(); let read_task = tokio::spawn(async move { let mut port_r = port; - let mut deframer = hdlc::HdlcDeframer::new(); + let mut deframer = hdlc::HdlcByteDeframer::new(HW_MTU); let mut buf = [0u8; 1024]; + let mut last_read = std::time::Instant::now(); loop { if !online_r.load(Ordering::SeqCst) { @@ -176,12 +178,16 @@ pub async fn spawn_serial_interface( Ok((p, b, n)) => { port_r = p; buf = b; - if n > 0 { + if n == 0 { + if deframer.buffered() > 0 + && last_read.elapsed() > Duration::from_millis(SERIAL_READ_TIMEOUT_MS) + { + deframer.reset(); + } + } else { + last_read = std::time::Instant::now(); rxb_r.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); for frame in deframer.feed(&buf[..n]) { - if frame.is_empty() { - continue; - } let msg = TransportMessage::Inbound(InboundPacket { raw: Bytes::from(frame), interface_id: id, diff --git a/crates/rns-interface/src/tcp.rs b/crates/rns-interface/src/tcp.rs index c669946..c38d127 100644 --- a/crates/rns-interface/src/tcp.rs +++ b/crates/rns-interface/src/tcp.rs @@ -20,8 +20,25 @@ pub const RECONNECT_WAIT_MAX: u64 = 300; pub const DEFAULT_CONNECT_TIMEOUT: u64 = 5; pub const DEFAULT_TCP_USER_TIMEOUT: u32 = 24; +/// Python `TCPInterface.HW_MTU`. Also the largest packet the drivers carry: +/// its worst-case HDLC escaping fills the shared deframer. pub const TCP_HW_MTU: u32 = 262144; +/// Python `TCPClientInterface.BITRATE_GUESS` and `TCPServerInterface.BITRATE_GUESS`. +pub const BITRATE_GUESS: u64 = 10_000_000; + +fn autoconfigured_mtu() -> (u32, InterfacePacketCapacity) { + crate::traits::hardware_mtu_capacity(crate::traits::optimise_mtu(BITRATE_GUESS), TCP_HW_MTU) +} + +/// Receive bound. Upstream's is its `HW_MTU` after `optimise_mtu()` (16384 at +/// the 10 Mbps guess); this stays at the wire budget until a transit node +/// clamps link MTU to the optimised value too. +const TCP_RECEIVE_HW_MTU: usize = TCP_HW_MTU as usize; + +/// Largest IFAC tag a frame can carry on top of the hardware MTU. +const MAX_IFAC_SIZE: usize = 64; + // Python TCPClientInterface: TCP_PROBE_AFTER / TCP_PROBE_INTERVAL / TCP_PROBES. // Dead-peer detection: 5s idle + 12 probes × 2s ≈ 29s. pub const TCP_KEEPIDLE: u32 = 5; @@ -66,8 +83,8 @@ pub struct TcpClientConfig { pub connect_timeout_secs: u64, pub max_reconnect_tries: Option, pub mode: InterfaceMode, - /// Override the MTU used for link MTU discovery. Accepted values are - /// 500 through 262,144 bytes, inclusive. + /// Fixed hardware MTU instead of the bitrate-derived one; at least 500. + /// Packets stay within the 262,144-byte driver budget. pub fixed_mtu: Option, /// Identity used to request a signed tunnel synthesis for each non-KISS /// connection. `None`, or an identity without signing material, sends none. @@ -220,11 +237,12 @@ async fn tcp_read_loop( transport_tx: InterfaceTransportSender, state: Arc, kiss_framing: bool, + hw_mtu: usize, ) { let mut buf = [0u8; 32768]; if kiss_framing { - let mut deframer = kiss::KissDeframer::new(); + let mut deframer = kiss::KissByteDeframer::new(hw_mtu); loop { match reader.read(&mut buf).await { Ok(0) => { @@ -232,10 +250,10 @@ async fn tcp_read_loop( break; } Ok(n) => { - for (_cmd, frame) in deframer.feed(&buf[..n]) { - if frame.is_empty() { + for event in deframer.feed(&buf[..n]) { + let kiss::KissEvent::Data(frame) = event else { continue; - } + }; state.record_rx(frame.len()); let msg = TransportMessage::Inbound(InboundPacket { raw: Bytes::from(frame), @@ -257,7 +275,12 @@ async fn tcp_read_loop( } } } else { - let mut deframer = hdlc::HdlcDeframer::new(); + // The IFAC size is applied by transport, so allow the largest tag. + let mut deframer = hdlc::HdlcDeframer::with_limits( + hw_mtu, + rns_wire::constants::HEADER_MINSIZE, + Some(hw_mtu + MAX_IFAC_SIZE), + ); loop { match reader.read(&mut buf).await { Ok(0) => { @@ -331,12 +354,9 @@ pub async fn spawn_tcp_client( ) -> Result { let transport_tx = InterfaceTransportSender::new(id, transport_tx); let owner = transport_tx.owner(); - if config - .fixed_mtu - .is_some_and(|mtu| !(500..=262144).contains(&mtu)) - { + if config.fixed_mtu.is_some_and(|mtu| mtu < 500) { return Err(crate::traits::InterfaceError::SendFailed( - "fixed_mtu must be between 500 and 262144 clear packet bytes".into(), + "fixed_mtu must be at least 500 bytes".into(), )); } let online = Arc::new(AtomicBool::new(false)); @@ -450,6 +470,7 @@ pub async fn spawn_tcp_client( transport_tx.clone(), state.clone(), kiss_framing, + fixed_mtu.map_or(TCP_RECEIVE_HW_MTU, |mtu| mtu as usize), ) .await; @@ -477,17 +498,14 @@ pub async fn spawn_tcp_client( } }); - let bitrate: u64 = 10_000_000; + let (mtu, packet_capacity) = match fixed_mtu { + Some(mtu) => crate::traits::hardware_mtu_capacity(Some(mtu), TCP_HW_MTU), + None => autoconfigured_mtu(), + }; Ok(InterfaceHandle { id, owner, - packet_capacity: InterfacePacketCapacity::new( - fixed_mtu - .unwrap_or_else(|| crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU)) - .min(262144), - 262144, - fixed_mtu.is_some() || crate::traits::optimise_mtu(bitrate).is_some(), - ), + packet_capacity, parent_id: None, name, mode, @@ -497,9 +515,8 @@ pub async fn spawn_tcp_client( forward: false, repeat: false, }, - bitrate, - mtu: fixed_mtu - .unwrap_or_else(|| crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU)), + bitrate: BITRATE_GUESS, + mtu, online, rxb: Some(shared_rxb), txb: Some(shared_txb), @@ -548,7 +565,15 @@ async fn spawn_tcp_accepted( let handle_name = name.clone(); let dereg_tx = transport_tx.clone(); let read_task = tokio::spawn(async move { - tcp_read_loop(reader, id, transport_tx, state, kiss_framing).await; + tcp_read_loop( + reader, + id, + transport_tx, + state, + kiss_framing, + TCP_RECEIVE_HW_MTU, + ) + .await; online2.store(false, Ordering::SeqCst); tracing::info!(name = %handle_name, "accepted TCP client disconnected"); // Proactively notify transport so broadcasts stop targeting this dead tx. @@ -557,17 +582,11 @@ async fn spawn_tcp_accepted( .await; }); - let bitrate: u64 = 10_000_000; + let (mtu, packet_capacity) = autoconfigured_mtu(); InterfaceHandle { id, owner, - packet_capacity: InterfacePacketCapacity::new( - crate::traits::optimise_mtu(bitrate) - .unwrap_or(TCP_HW_MTU) - .min(262144), - 262144, - crate::traits::optimise_mtu(bitrate).is_some(), - ), + packet_capacity, parent_id: Some(parent_id), name, mode, @@ -577,8 +596,8 @@ async fn spawn_tcp_accepted( forward: false, repeat: false, }, - bitrate, - mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU), + bitrate: BITRATE_GUESS, + mtu, online, rxb: Some(shared_rxb), txb: Some(shared_txb), @@ -657,17 +676,11 @@ pub async fn spawn_tcp_server( online2.store(false, Ordering::SeqCst); }); - let bitrate: u64 = 10_000_000; + let (mtu, packet_capacity) = autoconfigured_mtu(); Ok(InterfaceHandle { id, owner, - packet_capacity: InterfacePacketCapacity::new( - crate::traits::optimise_mtu(bitrate) - .unwrap_or(TCP_HW_MTU) - .min(262144), - 262144, - crate::traits::optimise_mtu(bitrate).is_some(), - ), + packet_capacity, parent_id: None, name, mode, @@ -677,8 +690,8 @@ pub async fn spawn_tcp_server( forward: false, repeat: false, }, - bitrate, - mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU), + bitrate: BITRATE_GUESS, + mtu, online, rxb: Some(Arc::new(AtomicU64::new(0))), txb: Some(Arc::new(AtomicU64::new(0))), @@ -893,7 +906,7 @@ mod tests { assert_ne!(accepted.owner, server_handle.owner); assert_ne!(accepted.owner, client_handle.owner); assert_eq!(accepted.packet_capacity.max_wire_packet_bytes, 262144); - let payload = Bytes::from_static(b"hello from client"); + let payload = Bytes::from_static(b"hello from client packet payload"); client_handle.tx.send(payload.clone()).await.unwrap(); assert!( tokio::time::timeout(std::time::Duration::from_millis(20), transport_rx.recv()) @@ -916,7 +929,7 @@ mod tests { other => panic!("unexpected message: {:?}", other), } - let reply = Bytes::from_static(b"hello from server"); + let reply = Bytes::from_static(b"hello from server packet payload"); accepted.tx.send(reply.clone()).await.unwrap(); let msg2 = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv()) diff --git a/crates/rns-interface/src/traits.rs b/crates/rns-interface/src/traits.rs index 6ce1a62..b55106b 100644 --- a/crates/rns-interface/src/traits.rs +++ b/crates/rns-interface/src/traits.rs @@ -167,34 +167,69 @@ pub struct InterfaceDirection { pub repeat: bool, } -/// Select an MTU for the given bitrate in bits per second. Returns `None` -/// for rates at or below 62,500 bps. +/// Select an MTU for the given bitrate in bits per second, as Python's +/// `Interface.optimise_mtu`. Returns `None` below 62,500 bps. pub fn optimise_mtu(bitrate: u64) -> Option { if bitrate >= 1_000_000_000 { Some(524_288) - } else if bitrate > 750_000_000 { + } else if bitrate >= 750_000_000 { Some(262_144) - } else if bitrate > 400_000_000 { + } else if bitrate >= 400_000_000 { Some(131_072) - } else if bitrate > 200_000_000 { + } else if bitrate >= 200_000_000 { Some(65_536) - } else if bitrate > 100_000_000 { + } else if bitrate >= 100_000_000 { Some(32_768) - } else if bitrate > 10_000_000 { + } else if bitrate >= 10_000_000 { Some(16_384) - } else if bitrate > 5_000_000 { + } else if bitrate >= 5_000_000 { Some(8_192) - } else if bitrate > 2_000_000 { + } else if bitrate >= 2_000_000 { Some(4_096) - } else if bitrate > 1_000_000 { + } else if bitrate >= 1_000_000 { Some(2_048) - } else if bitrate > 62_500 { + } else if bitrate >= 62_500 { Some(1_024) } else { None } } +/// The reported MTU and packet capacity of an interface with a known +/// hardware MTU, within the driver's wire budget. `None` is Python's +/// `HW_MTU = None`: base-size packets and no Link MTU upgrade. +pub fn hardware_mtu_capacity( + hw_mtu: Option, + wire_budget: u32, +) -> (u32, rns_transport::messages::InterfacePacketCapacity) { + use rns_transport::messages::InterfacePacketCapacity; + match hw_mtu { + Some(mtu) => ( + mtu, + InterfacePacketCapacity::new(mtu.min(wire_budget), wire_budget, true), + ), + None => { + let base = rns_wire::constants::MTU as u32; + ( + base, + InterfacePacketCapacity::new(base.min(wire_budget), wire_budget, false), + ) + } + } +} + +/// Python `Interface.optimise_mtu` on an `AUTOCONFIGURE_MTU` interface: +/// set the bitrate and derive the MTU and packet capacity from it. +pub fn apply_autoconfigured_mtu(handle: &mut InterfaceHandle, bitrate: u64) { + let (mtu, capacity) = hardware_mtu_capacity( + optimise_mtu(bitrate), + handle.packet_capacity.max_wire_packet_bytes, + ); + handle.bitrate = bitrate; + handle.mtu = mtu; + handle.packet_capacity = capacity; +} + /// Length of interface name hash (80 bits / 10 bytes). pub const NAME_HASH_LENGTH: usize = 10; @@ -301,15 +336,6 @@ mod tests { } } - #[test] - fn test_optimise_mtu() { - assert_eq!(optimise_mtu(1_000_000_000), Some(524_288)); - assert_eq!(optimise_mtu(100_000_001), Some(32_768)); - assert_eq!(optimise_mtu(10_000_001), Some(16_384)); - assert_eq!(optimise_mtu(62_500), None); - assert_eq!(optimise_mtu(62_501), Some(1_024)); - } - #[test] fn test_interface_mode_repr() { assert_eq!(InterfaceMode::Full as u8, 0x01); diff --git a/crates/rns-runtime/src/interface_factory.rs b/crates/rns-runtime/src/interface_factory.rs index b5ebc22..3c18809 100644 --- a/crates/rns-runtime/src/interface_factory.rs +++ b/crates/rns-runtime/src/interface_factory.rs @@ -316,7 +316,7 @@ pub struct BackboneInterfaceConfig { fn parse_interface_mode(s: &str) -> Option { match s.to_lowercase().as_str() { "full" => Some(InterfaceMode::Full), - "pointtopoint" | "point_to_point" => Some(InterfaceMode::PointToPoint), + "pointtopoint" | "ptp" | "point_to_point" => Some(InterfaceMode::PointToPoint), "access_point" | "accesspoint" | "ap" => Some(InterfaceMode::AccessPoint), "roaming" => Some(InterfaceMode::Roaming), "boundary" => Some(InterfaceMode::Boundary), @@ -487,6 +487,96 @@ fn parse_duration_strict( }) } +/// Python `int()` on a config scalar: surrounding whitespace, a sign and +/// single underscores between digits are accepted. +fn python_int(raw: &str) -> Option { + let s = raw.trim(); + let digits = s.strip_prefix(['+', '-']).unwrap_or(s); + if digits.is_empty() + || digits.starts_with('_') + || digits.ends_with('_') + || digits.contains("__") + || !digits.bytes().all(|b| b.is_ascii_digit() || b == b'_') + { + return None; + } + let value: i64 = digits.replace('_', "").parse().ok()?; + Some(if s.starts_with('-') { -value } else { value }) +} + +fn invalid_scalar(field: &str, expected: &str) -> InterfaceFactoryError { + InterfaceFactoryError::InvalidValue { + field: field.into(), + message: format!("expected {expected}"), + } +} + +/// ConfigObj `as_int`: a present key that is not an integer is an error. +fn config_int(section: &ConfigSection, field: &str) -> Result, InterfaceFactoryError> { + if !section.has(field) { + return Ok(None); + } + section + .get(field) + .and_then(python_int) + .map(Some) + .ok_or_else(|| invalid_scalar(field, "an integer")) +} + +/// ConfigObj `as_float`: a present key that is not a number is an error. +fn config_float( + section: &ConfigSection, + field: &str, +) -> Result, InterfaceFactoryError> { + if !section.has(field) { + return Ok(None); + } + section + .get_float(field) + .map(Some) + .ok_or_else(|| invalid_scalar(field, "a numeric scalar")) +} + +/// ConfigObj `as_bool`: a present key that is not a boolean is an error. +fn config_bool( + section: &ConfigSection, + field: &str, +) -> Result, InterfaceFactoryError> { + if !section.has(field) { + return Ok(None); + } + section + .get_bool(field) + .map(Some) + .ok_or_else(|| invalid_scalar(field, "a boolean value")) +} + +/// A per-interface ingress duration in seconds. Upstream only adds it to the +/// current time, so a negative value acts exactly as zero. +fn config_ingress_duration( + section: &ConfigSection, + field: &str, +) -> Result, InterfaceFactoryError> { + Ok(config_float(section, field)?.map(|v| v.max(0.0))) +} + +/// IFAC size in bytes. A plain `ifac_size` is bits as in Python: values of at +/// least 8 are floor-divided by 8, smaller values select the class default. +/// `ifac_size_unit` and `ifac_size_bytes` keep their stricter parser. +fn parse_ifac_size(section: &ConfigSection) -> Result, InterfaceFactoryError> { + if section.has("ifac_size") && !section.has("ifac_size_unit") && !section.has("ifac_size_bytes") + { + let bits = config_int(section, "ifac_size")?.expect("present key"); + return Ok((bits >= 8).then(|| usize::try_from(bits / 8).unwrap_or(usize::MAX))); + } + crate::config::ifac::parse_ifac_size(section).map_err(|error| { + InterfaceFactoryError::InvalidValue { + field: "ifac_size".into(), + message: error.to_string(), + } + }) +} + /// Parse an enabled interface section into a built-in driver configuration. /// No device, socket or subprocess is opened here. Performs IFAC-size and /// ingress-override validation; callers starting a driver must also apply @@ -515,13 +605,24 @@ pub fn synthesize_interface( // Validate every explicit size even when credentials are currently absent. // A fully disabled section retains its existing skipped behavior above. - crate::config::ifac::parse_ifac_size(section).map_err(|error| { - InterfaceFactoryError::InvalidValue { - field: format!("{name}.ifac_size"), - message: error.to_string(), + parse_ifac_size(section).map_err(|error| match error { + InterfaceFactoryError::InvalidValue { message, .. } => { + InterfaceFactoryError::InvalidValue { + field: format!("{name}.ifac_size"), + message, + } } + other => other, })?; InterfacePostInit::try_from_section(section)?; + if !section.has("ifac_size_unit") + && section + .get("ifac_size") + .and_then(python_int) + .is_some_and(|bits| (1..=64).contains(&bits)) + { + warn!(interface = %name, "ifac_size is read as bits, as in Python"); + } if section.has("ifac_size_bytes") { warn!(interface = %name, "legacy ifac_size_bytes; migrate to explicit bits"); } @@ -658,7 +759,8 @@ fn synthesize_tcp_client( field: format!("{name}.fixed_mtu"), message: "must be a representable nonnegative integer".into(), })?; - config.fixed_mtu = Some(mtu); + // Python's `if fixed_mtu:` leaves zero unset (TCPInterface.py:110). + config.fixed_mtu = (mtu != 0).then_some(mtu); } if let Some(retries) = section.get_uint("max_reconnect_tries") { config.max_reconnect_tries = Some(retries as usize); @@ -694,9 +796,9 @@ fn ifac_credential( } /// Validate explicit IFAC byte sizes and TCP client `fixed_mtu` before driver -/// startup. A fixed MTU must be at least 500 and fit the driver wire budget -/// after active IFAC overhead. This does not validate every interface field; -/// automatic capacity selection happens during runtime registration. +/// startup. A fixed MTU must be at least 500 (TCPInterface.py:110-116). This +/// does not validate every interface field; automatic capacity selection +/// happens during runtime registration. pub fn validate_config_capacity( config: &InterfaceConfig, post_init: &InterfacePostInit, @@ -713,25 +815,10 @@ pub fn validate_config_capacity( let InterfaceConfig::TcpClient(tcp) = config else { return Ok(()); }; - let Some(fixed) = tcp.fixed_mtu else { - return Ok(()); - }; - let active_ifac = post_init.ifac_network_name.is_some() || post_init.ifac_passphrase.is_some(); - let tag = if active_ifac { - post_init.ifac_size.unwrap_or(post_init.default_ifac_size) - } else { - 0 - }; - let wire_budget: usize = 262144; - let maximum = wire_budget - .checked_sub(tag) - .filter(|_| !active_ifac || (1..=64).contains(&tag)); - if fixed < 500 || maximum.is_none_or(|maximum| fixed as u64 > maximum as u64) { + if tcp.fixed_mtu.is_some_and(|fixed| fixed < 500) { return Err(InterfaceFactoryError::InvalidValue { field: format!("{}.fixed_mtu", tcp.name), - message: format!( - "must be at least 500 and fit the {wire_budget}-byte wire budget with {tag} active IFAC bytes" - ), + message: "must be at least 500".into(), }); } Ok(()) @@ -1765,49 +1852,37 @@ pub struct InterfacePostInit { impl InterfacePostInit { pub fn try_from_section(section: &ConfigSection) -> Result { - let ifac_size = crate::config::ifac::parse_ifac_size(section).map_err(|error| { - InterfaceFactoryError::InvalidValue { - field: "ifac_size".into(), - message: error.to_string(), - } - })?; - for field in [ - "ic_burst_freq_new", - "ic_burst_freq", - "ic_pr_burst_freq_new", - "ic_pr_burst_freq", - "ic_new_time", - "ic_burst_hold", - "ic_burst_penalty", - "ic_held_release_interval", - "ec_pr_freq", - "destination_cost", - "pr_cost", - ] { - if section.has(field) && section.get_float(field).is_none() { - return Err(InterfaceFactoryError::InvalidValue { - field: field.into(), - message: "expected a numeric scalar".into(), - }); - } + let ifac_size = parse_ifac_size(section)?; + for field in ["destination_cost", "pr_cost"] { + config_float(section, field)?; } - let ingress_control = section.get_bool("ingress_control").unwrap_or(true); - let announce_rate_target = section.get_uint("announce_rate_target"); + let ingress_control = config_bool(section, "ingress_control")?.unwrap_or(true); + let announce_rate_target = config_int(section, "announce_rate_target")? + .filter(|v| *v > 0) + .map(|v| v as u64); + let announce_rate_grace = config_int(section, "announce_rate_grace")? + .filter(|v| *v >= 0) + .map(|v| u32::try_from(v).unwrap_or(u32::MAX)) + .or_else(|| announce_rate_target.map(|_| 0)); + let announce_rate_penalty = config_int(section, "announce_rate_penalty")? + .filter(|v| *v >= 0) + .map(|v| v as u64) + .or_else(|| announce_rate_target.map(|_| 0)); let ingress_overrides = rns_transport::ingress::IngressOverrides { enabled: if ingress_control { None } else { Some(false) }, - burst_freq_new: section.get_float("ic_burst_freq_new"), - burst_freq: section.get_float("ic_burst_freq"), - pr_burst_freq_new: section.get_float("ic_pr_burst_freq_new"), - pr_burst_freq: section.get_float("ic_pr_burst_freq"), - new_time: section.get_float("ic_new_time"), - burst_hold: section.get_float("ic_burst_hold"), - burst_penalty: section.get_float("ic_burst_penalty"), - max_held: section - .get_uint("ic_max_held_announces") - .map(|v| v as usize), - held_release_interval: section.get_float("ic_held_release_interval"), - ec_pr_freq: section.get_float("ec_pr_freq"), - egress_control: section.get_bool("egress_control"), + burst_freq_new: config_float(section, "ic_burst_freq_new")?, + burst_freq: config_float(section, "ic_burst_freq")?, + pr_burst_freq_new: config_float(section, "ic_pr_burst_freq_new")?, + pr_burst_freq: config_float(section, "ic_pr_burst_freq")?, + new_time: config_ingress_duration(section, "ic_new_time")?, + burst_hold: config_ingress_duration(section, "ic_burst_hold")?, + burst_penalty: config_ingress_duration(section, "ic_burst_penalty")?, + // A negative limit never holds, as in Python. + max_held: config_int(section, "ic_max_held_announces")? + .map(|v| usize::try_from(v).unwrap_or(0)), + held_release_interval: config_ingress_duration(section, "ic_held_release_interval")?, + ec_pr_freq: config_float(section, "ec_pr_freq")?, + egress_control: config_bool(section, "egress_control")?, }; ingress_overrides .validate() @@ -1815,20 +1890,21 @@ impl InterfacePostInit { field: error.field.into(), message: error.to_string(), })?; + let bitrate = config_int(section, "bitrate")? + .filter(|v| *v >= MINIMUM_BITRATE) + .map(|v| v as u64); + let announce_cap = config_float(section, "announce_cap")?; + let outgoing = config_bool(section, "outgoing")?.unwrap_or(true); + let recursive_prs = config_bool(section, "recursive_prs")?.unwrap_or(false); + let announces_from_internal = + config_bool(section, "announces_from_internal")?.unwrap_or(true); Ok(Self { - outgoing: section.get_bool("outgoing").unwrap_or(true), - bitrate: section.get_uint("bitrate"), - announce_cap: section - .get_float("announce_cap") - .and_then(normalize_announce_cap_percent), + outgoing, + bitrate, + announce_cap: announce_cap.and_then(normalize_announce_cap_percent), announce_rate_target, - announce_rate_grace: section - .get_uint("announce_rate_grace") - .map(|v| v as u32) - .or_else(|| announce_rate_target.map(|_| 0)), - announce_rate_penalty: section - .get_uint("announce_rate_penalty") - .or_else(|| announce_rate_target.map(|_| 0)), + announce_rate_grace, + announce_rate_penalty, ifac_network_name: ifac_credential( section, "networkname", @@ -1841,8 +1917,8 @@ impl InterfacePostInit { default_ifac_size: 8, ingress_control, ingress_overrides, - recursive_prs: section.get_bool("recursive_prs").unwrap_or(false), - announces_from_internal: section.get_bool("announces_from_internal").unwrap_or(true), + recursive_prs, + announces_from_internal, destination_cost: section .get_float("destination_cost") .map(rns_transport::stamps::StampPolicy::clamp_cost), @@ -1858,6 +1934,9 @@ impl InterfacePostInit { } } +/// `Reticulum.MINIMUM_BITRATE`: smaller configured bitrates are ignored. +const MINIMUM_BITRATE: i64 = 5; + fn normalize_announce_cap_percent(value: f64) -> Option { if value > 0.0 && value <= 100.0 { Some(value / 100.0) @@ -2049,22 +2128,32 @@ mod tests { } } - /// T1-11: ifac_size outside 1..=64 used to panic the transport actor on - /// first egress; it must be a parse-time config error. + /// A plain `ifac_size` is bits floor-divided by 8 as in Python; values + /// below 8 select the class default and non-integers are config errors. #[test] - fn test_ifac_size_out_of_range_rejected() { - for bad in ["0", "65", "4096"] { + fn test_ifac_size_bits_parse_like_python() { + for (bits, bytes) in [ + ("0", None), + ("7", None), + ("12", Some(1)), + ("65", Some(8)), + ("4096", Some(512)), + ] { let mut section = enabled_section(); - section.set("type", "TCPClientInterface"); - section.set("target_host", "127.0.0.1"); - section.set("target_port", "4242"); - section.set("ifac_size", bad); - match synthesize_interface("tcp_ifac", §ion) { - Err(InterfaceFactoryError::InvalidValue { field, .. }) => { - assert_eq!(field, "tcp_ifac.ifac_size"); - } - other => panic!("expected InvalidValue for ifac_size={bad}, got {other:?}"), + section.set("ifac_size", bits); + let post = InterfacePostInit::try_from_section(§ion).unwrap(); + assert_eq!(post.ifac_size, bytes, "ifac_size = {bits}"); + } + let mut section = enabled_section(); + section.set("type", "TCPClientInterface"); + section.set("target_host", "127.0.0.1"); + section.set("target_port", "4242"); + section.set("ifac_size", "abc"); + match synthesize_interface("tcp_ifac", §ion) { + Err(InterfaceFactoryError::InvalidValue { field, .. }) => { + assert_eq!(field, "tcp_ifac.ifac_size"); } + other => panic!("expected InvalidValue for ifac_size=abc, got {other:?}"), } // In-range sizes still parse. @@ -2280,48 +2369,30 @@ mod tests { } #[test] - fn fixed_mtu_checks_exact_integer_and_active_ifac_before_spawn() { + fn fixed_mtu_needs_an_integer_of_at_least_500_with_or_without_ifac() { let mut client = enabled_section(); client.set("type", "TCPClientInterface"); client.set("target_host", "example.com"); client.set("target_port", "4242"); - for invalid in [ - "", - "NaN", - "1.5", - "-1", - "499", - "262145", - "4294967296", - "18446744073709551615", - ] { + for invalid in ["", "NaN", "1.5", "-1", "499", "4294967296"] { client.set("fixed_mtu", invalid); assert!(synthesize_interface("tcp", &client).is_err(), "{invalid}"); } - client.set("fixed_mtu", "262144"); - assert!(synthesize_interface("tcp", &client).is_ok()); - // Every credential spelling activates the tag; an empty one does not. - for credential in ["networkname", "network_name", "passphrase", "pass_phrase"] { - let mut blank = client.clone(); - blank.set(credential, ""); - assert!(synthesize_interface("tcp", &blank).is_ok()); + client.set("fixed_mtu", "0"); + match synthesize_interface("tcp", &client).unwrap() { + InterfaceConfig::TcpClient(c) => assert_eq!(c.fixed_mtu, None), + _ => panic!("expected TcpClient"), + } + for valid in ["500", "16384", "400000"] { + client.set("fixed_mtu", valid); + assert!(synthesize_interface("tcp", &client).is_ok(), "{valid}"); let mut active = client.clone(); - active.set(credential, "k"); - assert!(synthesize_interface("tcp", &active).is_err()); - active.set("fixed_mtu", "262128"); - assert!(synthesize_interface("tcp", &active).is_ok()); - active.set("ifac_size", "512"); - active.set("ifac_size_unit", "bits"); - assert!(synthesize_interface("tcp", &active).is_err()); - active.set("fixed_mtu", "262080"); - assert!(synthesize_interface("tcp", &active).is_ok()); + active.set("network_name", "net"); + assert!( + synthesize_interface("tcp", &active).is_ok(), + "{valid} with IFAC" + ); } - client.set("ifac_size", "512"); - client.set("ifac_size_unit", "bits"); - assert!( - synthesize_interface("tcp", &client).is_ok(), - "inactive credentials do not consume wire capacity" - ); } #[cfg(feature = "serial")] diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index 80d358b..942f25d 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -81,6 +81,35 @@ struct InterfaceControlMetadata { // Per-interface stamp costs, copied raw to spawned children (TCPInterface.py:608-609). destination_cost: Option, pr_cost: Option, + /// What a connection this interface accepts takes from it. + spawn: Option, +} + +/// The listener settings Python copies to each accepted connection +/// (TCPInterface.py:588-646, BackboneInterface.py:706-757, I2PInterface.py:861-912). +#[derive(Clone)] +struct SpawnInheritance { + mode: rns_interface::traits::InterfaceMode, + outgoing: bool, + bitrate: u64, + mtu: u32, + packet_capacity: rns_transport::messages::InterfacePacketCapacity, + announce_cap: f64, + announce_rate_target: Option, + announce_rate_grace: Option, + announce_rate_penalty: Option, + recursive_prs: bool, + announces_from_internal: bool, +} + +impl SpawnInheritance { + fn apply(&self, child: &mut rns_interface::traits::InterfaceHandle) { + child.mode = self.mode; + child.bitrate = self.bitrate; + child.mtu = self.mtu; + child.packet_capacity = self.packet_capacity; + child.direction.outbound &= self.outgoing; + } } type InterfaceControlMap = Arc>>; @@ -3058,22 +3087,27 @@ fn config_u16( Ok(Some(value)) } -fn parse_ingress_overrides( - section_name: &str, +/// `[reticulum]` ingress defaults: zero or negative values leave the class default. +fn parse_global_ingress_overrides( section: &ConfigSection, ) -> Result { + let positive = |key| -> Result, ConfigError> { + Ok(config_float("reticulum", section, key)?.filter(|v| *v > 0.0)) + }; Ok(rns_transport::ingress::IngressOverrides { - burst_freq_new: config_float(section_name, section, "ic_burst_freq_new")?, - burst_freq: config_float(section_name, section, "ic_burst_freq")?, - pr_burst_freq_new: config_float(section_name, section, "ic_pr_burst_freq_new")?, - pr_burst_freq: config_float(section_name, section, "ic_pr_burst_freq")?, - new_time: config_float(section_name, section, "ic_new_time")?, - burst_hold: config_float(section_name, section, "ic_burst_hold")?, - burst_penalty: config_float(section_name, section, "ic_burst_penalty")?, - max_held: config_uint(section_name, section, "ic_max_held_announces")?.map(|v| v as usize), - held_release_interval: config_float(section_name, section, "ic_held_release_interval")?, - ec_pr_freq: config_float(section_name, section, "ec_pr_freq")?, - egress_control: config_bool(section_name, section, "egress_control")?, + burst_freq_new: positive("ic_burst_freq_new")?, + burst_freq: positive("ic_burst_freq")?, + pr_burst_freq_new: positive("ic_pr_burst_freq_new")?, + pr_burst_freq: positive("ic_pr_burst_freq")?, + new_time: positive("ic_new_time")?, + burst_hold: positive("ic_burst_hold")?, + burst_penalty: positive("ic_burst_penalty")?, + max_held: config_int("reticulum", section, "ic_max_held_announces")? + .filter(|v| *v > 0) + .map(|v| usize::try_from(v).unwrap_or(usize::MAX)), + held_release_interval: positive("ic_held_release_interval")?, + ec_pr_freq: positive("ec_pr_freq")?, + egress_control: config_bool("reticulum", section, "egress_control")?.filter(|v| *v), ..Default::default() }) } @@ -3218,16 +3252,17 @@ impl ReticulumConfig { } rc.force_shared_instance_bitrate = config_uint("reticulum", sec, "force_shared_instance_bitrate")?; - if let Some(v) = config_uint("reticulum", sec, "default_ar_target")? { - rc.default_ar_target = (v > 0).then_some(v); - } - if let Some(v) = config_uint("reticulum", sec, "default_ar_penalty")? { - rc.default_ar_penalty = Some(v); - } - if let Some(v) = config_uint("reticulum", sec, "default_ar_grace")? { - rc.default_ar_grace = Some(v.min(u32::MAX as u64) as u32); - } - rc.ingress_overrides = parse_ingress_overrides("reticulum", sec)?; + // Zero or negative falls back to the interface class default, as upstream's getters do. + let positive = |key| -> Result, ConfigError> { + Ok(config_int("reticulum", sec, key)? + .filter(|v| *v > 0) + .map(|v| v as u64)) + }; + rc.default_ar_target = positive("default_ar_target")?; + rc.default_ar_penalty = positive("default_ar_penalty")?; + rc.default_ar_grace = + positive("default_ar_grace")?.map(|v| u32::try_from(v).unwrap_or(u32::MAX)); + rc.ingress_overrides = parse_global_ingress_overrides(sec)?; let queues = &mut rc.inbound_queue_lengths; for (key, length) in [ ("qlen_in_data", &mut queues.data), @@ -4109,14 +4144,14 @@ pub async fn init_with_policy( handle_tx.clone(), &socket_base, &paths.storage_dir, - &rc.ingress_overrides, is_foreground.clone(), rnode_startup_options, &tunnel_identity, ) .await { - Ok(iface_handles) => { + Ok(mut iface_handles) => { + apply_configured_bitrate_mtu(iface_config, &post_init, &mut iface_handles); let pending_rnode = pending_configured_rnode_runtime(iface_config, &iface_handles); #[cfg(any(feature = "serial", feature = "rnode-tcp"))] @@ -4578,9 +4613,6 @@ fn interface_kind_for_config(config: &interface_factory::InterfaceConfig) -> Int struct OwnedInterfaceHandle { interface: rns_interface::traits::InterfaceHandle, driver: Option, - /// An I2P peer that Python's `I2PInterface` creates for a configured peer, - /// with the `[reticulum]` ingress settings it takes. - configured_peer: Option, /// The address a discoverable interface learns at runtime (I2P b32). discovery_address: Option>>, #[cfg(any(feature = "serial", feature = "rnode-tcp"))] @@ -4726,7 +4758,6 @@ impl From for OwnedInterfaceHandle { Self { interface, driver: None, - configured_peer: None, discovery_address: None, #[cfg(any(feature = "serial", feature = "rnode-tcp"))] hardware_failures: None, @@ -4739,7 +4770,6 @@ impl From for OwnedInterfaceHandle Self { interface: spawned.interface, driver: Some(spawned.driver), - configured_peer: None, discovery_address: None, #[cfg(any(feature = "serial", feature = "rnode-tcp"))] hardware_failures: None, @@ -5198,7 +5228,7 @@ async fn register_owned_interface_handle_with_role_and_overrides( #[allow(clippy::too_many_arguments)] async fn prepare_interface_with_role_and_overrides( - owned: OwnedInterfaceHandle, + mut owned: OwnedInterfaceHandle, role: rns_transport::messages::InterfaceRole, ingress_overrides: rns_transport::ingress::IngressOverrides, ifac_key: Option, @@ -5208,6 +5238,16 @@ async fn prepare_interface_with_role_and_overrides( kind: InterfaceKind, multipoint: bool, ) -> Result { + let inherited = owned.interface.parent_id.and_then(|parent| { + interface_controls + .lock() + .expect("interface_controls mutex poisoned") + .get(&parent) + .and_then(|parent| parent.spawn.clone()) + }); + if let Some(parent) = &inherited { + parent.apply(&mut owned.interface); + } let ingress = match ingress_for_role(role, &ingress_overrides) { Ok(ingress) => ingress, Err(error) => { @@ -5304,6 +5344,7 @@ async fn prepare_interface_with_role_and_overrides( autoconnect_source: None, destination_cost, pr_cost, + spawn: None, }, ); } @@ -5324,11 +5365,19 @@ async fn prepare_interface_with_role_and_overrides( tx: handle.tx, ifac_key, ifac_size, - announce_cap: ANNOUNCE_CAP, + announce_cap: inherited + .as_ref() + .map_or(ANNOUNCE_CAP, |parent| parent.announce_cap), announce_allowed_at: 0.0, - announce_rate_target: None, - announce_rate_grace: None, - announce_rate_penalty: None, + announce_rate_target: inherited + .as_ref() + .and_then(|parent| parent.announce_rate_target), + announce_rate_grace: inherited + .as_ref() + .and_then(|parent| parent.announce_rate_grace), + announce_rate_penalty: inherited + .as_ref() + .and_then(|parent| parent.announce_rate_penalty), online: Some(online.clone()), rxb: handle.rxb, txb: handle.txb, @@ -5341,10 +5390,12 @@ async fn prepare_interface_with_role_and_overrides( ingress, announce_queue: Vec::new(), multipoint, - // Interface.py class defaults; Python spawned sub-interfaces do not - // inherit recursive_prs/announces_from_internal (TCPInterface.py:579+). - recursive_prs: false, - announces_from_internal: true, + recursive_prs: inherited + .as_ref() + .is_some_and(|parent| parent.recursive_prs), + announces_from_internal: inherited + .as_ref() + .is_none_or(|parent| parent.announces_from_internal), destination_cost: child_stamp_costs.0, pr_cost: child_stamp_costs.1, }; @@ -5435,6 +5486,34 @@ async fn register_owned_interface_with_post_init( .map(|_| ()) } +/// Python's configured `bitrate`, which counts from `MINIMUM_BITRATE` (Reticulum.py:1018-1020). +fn configured_bitrate(post_init: &interface_factory::InterfacePostInit) -> Option { + post_init + .bitrate + .filter(|bitrate| *bitrate >= MINIMUM_BITRATE) +} + +/// Python's post-init `optimise_mtu` after a configured bitrate (Reticulum.py:1127-1128), +/// for the interface classes with `AUTOCONFIGURE_MTU`. +fn apply_configured_bitrate_mtu( + iface_config: &interface_factory::InterfaceConfig, + post_init: &interface_factory::InterfacePostInit, + handles: &mut [OwnedInterfaceHandle], +) { + let autoconfigures = match iface_config { + interface_factory::InterfaceConfig::TcpClient(c) => c.fixed_mtu.is_none(), + interface_factory::InterfaceConfig::TcpServer(_) + | interface_factory::InterfaceConfig::Backbone(_) => true, + _ => false, + }; + let Some(bitrate) = configured_bitrate(post_init).filter(|_| autoconfigures) else { + return; + }; + for owned in handles { + rns_interface::traits::apply_autoconfigured_mtu(&mut owned.interface, bitrate); + } +} + fn clone_interface_post_init( post_init: &interface_factory::InterfacePostInit, ) -> interface_factory::InterfacePostInit { @@ -5478,34 +5557,6 @@ fn i2p_key_path(storage_dir: &Path, name: &str, transport_identity_hash: &[u8; 1 )) } -/// Python's configured I2P peers take IFAC from their interface and every -/// other default (I2PInterface.py:359-381), the `[reticulum]` ingress settings -/// included (Interface.py:140-150). -fn configured_peer_post_init( - post_init: &interface_factory::InterfacePostInit, - ingress_overrides: &rns_transport::ingress::IngressOverrides, -) -> interface_factory::InterfacePostInit { - interface_factory::InterfacePostInit { - outgoing: true, - bitrate: None, - announce_cap: None, - announce_rate_target: None, - announce_rate_grace: None, - announce_rate_penalty: None, - ifac_network_name: post_init.ifac_network_name.clone(), - ifac_passphrase: post_init.ifac_passphrase.clone(), - ifac_size: post_init.ifac_size, - default_ifac_size: post_init.default_ifac_size, - ingress_control: true, - ingress_overrides: ingress_overrides.clone(), - recursive_prs: false, - announces_from_internal: true, - // I2PInterface.py:854-855 copies these to configured peers. - destination_cost: post_init.destination_cost, - pr_cost: post_init.pr_cost, - } -} - async fn prepare_interface_with_post_init( owned: OwnedInterfaceHandle, post_init: &interface_factory::InterfacePostInit, @@ -5514,14 +5565,6 @@ async fn prepare_interface_with_post_init( interface_registry: &InterfaceRegistry, kind: InterfaceKind, ) -> Result { - let peer_post_init; - let post_init = match &owned.configured_peer { - Some(ingress_overrides) => { - peer_post_init = configured_peer_post_init(post_init, ingress_overrides); - &peer_post_init - } - None => post_init, - }; let ingress = if post_init.ingress_overrides.is_empty() { rns_transport::ingress::IngressController::new() } else { @@ -5615,6 +5658,10 @@ async fn prepare_interface_with_post_init( } }; let registry_owner = registration.owner(); + let bitrate = configured_bitrate(post_init).unwrap_or(handle.bitrate); + let announce_cap = post_init.announce_cap.unwrap_or(ANNOUNCE_CAP); + let announce_rate_target = post_init.announce_rate_target.map(|v| v as f64); + let announce_rate_penalty = post_init.announce_rate_penalty.map(|v| v as f64); interface_controls .lock() .expect("interface_controls mutex poisoned") @@ -5632,6 +5679,19 @@ async fn prepare_interface_with_post_init( autoconnect_source: None, destination_cost: post_init.destination_cost, pr_cost: post_init.pr_cost, + spawn: Some(SpawnInheritance { + mode: handle.mode, + outgoing: post_init.outgoing, + bitrate, + mtu: handle.mtu, + packet_capacity: handle.packet_capacity, + announce_cap, + announce_rate_target, + announce_rate_grace: post_init.announce_rate_grace, + announce_rate_penalty, + recursive_prs: post_init.recursive_prs, + announces_from_internal: post_init.announces_from_internal, + }), }, ); let entry = rns_transport::messages::InterfaceEntry { @@ -5643,16 +5703,16 @@ async fn prepare_interface_with_post_init( parent_id: handle.parent_id, accepted: false, direction, - bitrate: post_init.bitrate.unwrap_or(handle.bitrate), + bitrate, mtu: handle.mtu, tx: handle.tx, ifac_key, ifac_size: post_init.ifac_size.unwrap_or(post_init.default_ifac_size), - announce_cap: post_init.announce_cap.unwrap_or(ANNOUNCE_CAP), + announce_cap, announce_allowed_at: 0.0, - announce_rate_target: post_init.announce_rate_target.map(|v| v as f64), + announce_rate_target, announce_rate_grace: post_init.announce_rate_grace, - announce_rate_penalty: post_init.announce_rate_penalty.map(|v| v as f64), + announce_rate_penalty, online: Some(online.clone()), rxb: handle.rxb, txb: handle.txb, @@ -8972,7 +9032,6 @@ async fn spawn_interface_with_rnode_startup_options( handle_tx: mpsc::Sender, socket_base: &Path, storage_dir: &Path, - global_ingress_overrides: &rns_transport::ingress::IngressOverrides, is_foreground: Arc, rnode_startup_options: rns_interface::rnode::RNodeStartupOptions, tunnel_identity: &rns_interface::traits::TunnelIdentity, @@ -9193,6 +9252,7 @@ async fn spawn_interface_with_rnode_startup_options( ); client_config.sam_host = c.i2p_sam_host.clone(); client_config.sam_port = c.i2p_sam_port; + client_config.mode = c.mode; client_config.tunnel_identity = Some(tunnel_identity.clone()); let peer_id = next.take().unwrap_or_else(|| next_id(&id_gen)); match rns_interface::i2p::spawn_i2p_client( @@ -9202,10 +9262,7 @@ async fn spawn_interface_with_rnode_startup_options( ) .await { - Ok(client) => handles.push(OwnedInterfaceHandle { - configured_peer: Some(global_ingress_overrides.clone()), - ..client.into() - }), + Ok(client) => handles.push(client.into()), Err(e) => { for spawned in handles { rollback_unreserved_interface(spawned, InterfaceKind::Standard).await; @@ -9627,6 +9684,7 @@ mod tests { autoconnect_source: None, destination_cost: None, pr_cost: None, + spawn: None, }, ); @@ -9776,6 +9834,7 @@ mod tests { autoconnect_source: None, destination_cost: None, pr_cost: None, + spawn: None, }, ); drop(registration); @@ -15371,6 +15430,7 @@ egress_control = Yes autoconnect_source: None, destination_cost: None, pr_cost: None, + spawn: None, }, ); diff --git a/crates/rns-runtime/src/reticulum/tests/tunnels.rs b/crates/rns-runtime/src/reticulum/tests/tunnels.rs index ed13db1..0395554 100644 --- a/crates/rns-runtime/src/reticulum/tests/tunnels.rs +++ b/crates/rns-runtime/src/reticulum/tests/tunnels.rs @@ -477,12 +477,10 @@ async fn an_unreadable_i2p_key_file_is_never_replaced() { let _ = std::fs::remove_dir_all(dir); } -/// Python's configured peers keep MODE_FULL, no announce-rate settings and -/// the `[reticulum]` ingress defaults (Interface.py:140-150), and take only -/// IFAC from their interface (I2PInterface.py:359-381); the interface's own -/// settings apply to it alone (Reticulum.py:1030, :1059). +/// Python's configured peers take their interface's mode, announce and +/// ingress settings as well as its IFAC (I2PInterface.py:814-857). #[tokio::test] -async fn configured_i2p_peers_take_only_ifac_from_their_interface() { +async fn configured_i2p_peers_inherit_their_interface_settings() { let (sam_port, _streams) = fake_sam(0).await; let peer = "peeraaaaaaaaaaaa.b32.i2p"; let dir = config_dir( @@ -506,9 +504,10 @@ async fn configured_i2p_peers_take_only_ifac_from_their_interface() { ); assert_eq!( (peer.mode.as_str(), peer.announce_rate_target), - ("Full", None) + ("Gateway", Some(3600.0)) ); - assert_eq!(peer.announce_cap, ANNOUNCE_CAP); + assert_eq!(peer.announce_cap, 0.05); + assert_eq!(peer.bitrate, server.bitrate); assert!(server.ifac_size > 0); assert_eq!(peer.ifac_size, server.ifac_size); let ingress = |id: u64| { @@ -517,7 +516,7 @@ async fn configured_i2p_peers_take_only_ifac_from_their_interface() { (overrides.burst_freq_new, overrides.new_time) }; assert_eq!(ingress(server.id), (Some(2.5), Some(1234.0))); - assert_eq!(ingress(peer.id), (Some(7.5), None)); + assert_eq!(ingress(peer.id), (Some(2.5), Some(1234.0))); handle.shutdown_and_wait().await; let _ = std::fs::remove_dir_all(dir); @@ -529,7 +528,7 @@ async fn i2p_server_peers_register_under_their_server() { let dir = config_dir( "i2p-peers", &format!( - "[reticulum]\n {}\n enable_transport = No\n\n[interfaces]\n [[Golden I2P]]\n type = I2PInterface\n enabled = yes\n connectable = yes\n network_name = tunnelnet\n i2p_sam_host = 127.0.0.1\n i2p_sam_port = {sam_port}\n", + "[reticulum]\n {}\n enable_transport = No\n\n[interfaces]\n [[Golden I2P]]\n type = I2PInterface\n enabled = yes\n connectable = yes\n network_name = tunnelnet\n mode = gateway\n announce_rate_target = 600\n announce_cap = 5\n i2p_sam_host = 127.0.0.1\n i2p_sam_port = {sam_port}\n", own_shared_instance("tunp").await ), ); @@ -559,6 +558,16 @@ async fn i2p_server_peers_register_under_their_server() { peer.ifac_size, server.ifac_size, "the peer inherits its server's IFAC" ); + assert_eq!( + ( + peer.mode.as_str(), + peer.announce_rate_target, + peer.announce_cap + ), + ("Gateway", Some(600.0), 0.05), + "the peer inherits its server's mode and announce settings" + ); + assert_eq!((peer.bitrate, peer.mtu), (server.bitrate, server.mtu)); handle.shutdown_and_wait().await; let _ = std::fs::remove_dir_all(dir); diff --git a/crates/rns-runtime/src/shared_instance.rs b/crates/rns-runtime/src/shared_instance.rs index d33670e..262cd39 100644 --- a/crates/rns-runtime/src/shared_instance.rs +++ b/crates/rns-runtime/src/shared_instance.rs @@ -416,7 +416,8 @@ async fn packet_loop( ) -> std::io::Result<()> { let (mut reader, mut writer) = tokio::io::split(stream); let mut buf = [0; 8192]; - let mut deframer = HdlcDeframer::new(); + let mut deframer = + HdlcDeframer::with_limits(262144, rns_wire::constants::HEADER_MINSIZE, Some(262144)); loop { tokio::select! { read = reader.read(&mut buf) => {