diff --git a/crates/rns-interface/src/auto.rs b/crates/rns-interface/src/auto.rs deleted file mode 100644 index 1de31f5..0000000 --- a/crates/rns-interface/src/auto.rs +++ /dev/null @@ -1,2105 +0,0 @@ -//! Automatic peer discovery over IPv6 multicast, using link scope by default. -//! -//! Beacons use a group derived from `SHA-256(group_id)`; data uses unicast UDP. -//! The normal beacon interval is 1.6 seconds. With `mobile-throttle`, background -//! beacons use 8 seconds. Periodic maintenance removes peers after at least -//! 22 seconds without a beacon. - -use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender}; -use std::collections::{HashMap, HashSet, VecDeque}; -use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, OnceLock}; -use std::time::Instant; - -use bytes::Bytes; -use tokio::net::UdpSocket; -use tokio::sync::{Mutex, broadcast, mpsc}; - -use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; -use rns_transport::messages::{InboundPacket, TransportMessage}; - -pub const DISCOVERY_PORT: u16 = 29716; -pub const DATA_PORT: u16 = 42671; -pub const BEACON_INTERVAL: f64 = 1.6; -/// Background beacon interval with feature `mobile-throttle`, in seconds. -pub const BEACON_INTERVAL_BG: f64 = 8.0; -pub const PEER_EXPIRY: f64 = 22.0; -pub const HW_MTU: u32 = 1196; -pub const FIXED_MTU: bool = true; -pub const DEFAULT_GROUP_ID: &str = "reticulum"; -pub const UNICAST_DISCOVERY_PORT: u16 = DISCOVERY_PORT + 1; -pub const REVERSE_PEERING_INTERVAL: f64 = BEACON_INTERVAL * 3.25; -pub const PEER_JOB_INTERVAL: f64 = 4.0; -pub const MCAST_ECHO_TIMEOUT: f64 = 6.5; -pub const MULTI_IF_DEQUE_LEN: usize = 48; -pub const MULTI_IF_DEQUE_TTL: f64 = 0.75; - -// Per-platform ignores: loopback, Apple AWDL, cellular RIL, VPN tunnels. - -#[cfg(target_os = "macos")] -const IGNORED_IFACES: &[&str] = &["awdl0", "llw0", "lo0", "en5"]; - -#[cfg(target_os = "linux")] -const IGNORED_IFACES: &[&str] = &["lo"]; - -#[cfg(target_os = "android")] -const IGNORED_IFACES: &[&str] = &[ - "lo", - "dummy0", - "rmnet_data0", - "rmnet_data1", - "rmnet_data2", - "rmnet_data3", - "rmnet_data4", - "rmnet_data5", - "rmnet_data6", - "rmnet_data7", - "rmnet_ipa0", - "r_rmnet_data0", - "v4-rmnet_data0", -]; - -#[cfg(target_os = "ios")] -const IGNORED_IFACES: &[&str] = &[ - "lo0", "awdl0", "llw0", "ap1", "ipsec0", "utun0", "utun1", "utun2", "utun3", "pdp_ip0", - "pdp_ip1", "pdp_ip2", "pdp_ip3", -]; - -#[cfg(not(any( - target_os = "macos", - target_os = "linux", - target_os = "android", - target_os = "ios" -)))] -const IGNORED_IFACES: &[&str] = &["lo", "lo0"]; - -/// IPv6 multicast scope (RFC 4291 §2.7) — lower nibble of `ff_S:` byte. -/// `Link` stays on the LAN; `Site`+ require routed multicast configuration. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DiscoveryScope { - Link, - Admin, - Site, - Organisation, - Global, -} - -impl DiscoveryScope { - pub const fn as_hex_nibble(self) -> u8 { - match self { - Self::Link => 0x2, - Self::Admin => 0x4, - Self::Site => 0x5, - Self::Organisation => 0x8, - Self::Global => 0xe, - } - } -} - -impl std::str::FromStr for DiscoveryScope { - type Err = String; - fn from_str(s: &str) -> Result { - match s.trim().to_ascii_lowercase().as_str() { - "link" => Ok(Self::Link), - "admin" => Ok(Self::Admin), - "site" => Ok(Self::Site), - "organisation" | "organization" => Ok(Self::Organisation), - "global" => Ok(Self::Global), - other => Err(format!("unknown discovery scope: {other}")), - } - } -} - -impl std::fmt::Display for DiscoveryScope { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(match self { - Self::Link => "link", - Self::Admin => "admin", - Self::Site => "site", - Self::Organisation => "organisation", - Self::Global => "global", - }) - } -} - -/// IPv6 multicast transient/permanent flag (RFC 4291 §2.7) — upper nibble -/// of `ff_T_:`. Default is `Temporary`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum McastAddrType { - Temporary, - Permanent, -} - -impl McastAddrType { - pub const fn as_hex_nibble(self) -> u8 { - match self { - Self::Temporary => 0x1, - Self::Permanent => 0x0, - } - } -} - -impl std::str::FromStr for McastAddrType { - type Err = String; - fn from_str(s: &str) -> Result { - match s.trim().to_ascii_lowercase().as_str() { - "temporary" | "temp" => Ok(Self::Temporary), - "permanent" | "perm" => Ok(Self::Permanent), - other => Err(format!("unknown multicast address type: {other}")), - } - } -} - -impl std::fmt::Display for McastAddrType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(match self { - Self::Temporary => "temporary", - Self::Permanent => "permanent", - }) - } -} - -/// Async events from AutoInterface instances for embedding applications. -#[derive(Debug, Clone, serde::Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum AutoInterfaceEvent { - /// `IPV6_JOIN_GROUP` was rejected by the OS. `reason` contains the reported - /// error; this event alone does not establish a permission or network cause. - JoinFailed { - interface_name: String, - ifname: String, - reason: String, - }, - /// Carrier state changed as local multicast echoes arrived or timed out on - /// `ifname`. `ok=false` reports missing echoes within `MCAST_ECHO_TIMEOUT`; - /// it does not identify the underlying network or firewall cause. - CarrierState { - interface_name: String, - ifname: String, - ok: bool, - reason: String, - }, -} - -static AUTO_EVENT_TX: OnceLock> = OnceLock::new(); - -/// Subscribe to `AutoInterfaceEvent`s emitted by any AutoInterface in this -/// process. Channel is lazy-created; lagged subscribers see `RecvError::Lagged`. -pub fn subscribe_auto_events() -> broadcast::Receiver { - AUTO_EVENT_TX - .get_or_init(|| { - let (tx, _rx) = broadcast::channel(64); - tx - }) - .subscribe() -} - -fn dispatch_auto_event(event: AutoInterfaceEvent) { - if let Some(tx) = AUTO_EVENT_TX.get() { - // Ignore "no subscribers" errors; events are best-effort and callers - // may not have started their relay task yet. - let _ = tx.send(event); - } -} - -#[derive(Debug, Clone)] -pub struct AutoInterfaceConfig { - pub name: String, - pub group_id: String, - pub discovery_scope: DiscoveryScope, - pub discovery_port: u16, - pub data_port: u16, - pub multicast_address_type: McastAddrType, - /// Whitelist of NIC names. `None` = all (minus IGNORED_IFACES + ignored_devices). - pub devices: Option>, - /// Additional NIC names to skip on top of the platform default IGNORED_IFACES. - pub ignored_devices: Vec, - /// Bitrate override in bits per second. `None` = default 10 Mbps guess. - pub configured_bitrate: Option, - pub mode: InterfaceMode, -} - -impl Default for AutoInterfaceConfig { - fn default() -> Self { - Self { - name: "AutoInterface".to_string(), - group_id: DEFAULT_GROUP_ID.to_string(), - discovery_scope: DiscoveryScope::Link, - discovery_port: DISCOVERY_PORT, - data_port: DATA_PORT, - multicast_address_type: McastAddrType::Temporary, - devices: None, - ignored_devices: Vec::new(), - configured_bitrate: None, - mode: InterfaceMode::Full, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -struct PeerKey { - ip: Ipv6Addr, - scope_id: u32, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum PeerScopeSource { - Received, - LocalCandidate, - UnscopedNonLinkLocal, -} - -#[derive(Debug, Clone)] -struct PeerScopeCandidate { - ifname: String, - scope_id: u32, - source: PeerScopeSource, -} - -#[derive(Debug, Clone)] -struct Peer { - ip: Ipv6Addr, - ifname: String, - scope_id: u32, - scope_source: PeerScopeSource, - addr: SocketAddrV6, - last_seen: Instant, - last_reverse: Instant, -} - -type PeerTable = Arc>>; - -#[derive(Debug, Clone)] -struct DeduplicateEntry { - hash: [u8; 32], - timestamp: Instant, -} - -/// Dedupes packets seen on multiple NICs at once (e.g. WLAN + wired). -#[derive(Debug, Clone)] -pub struct MultiIfDedup { - deque: VecDeque, - max_len: usize, - ttl_secs: f64, -} - -impl MultiIfDedup { - pub fn new() -> Self { - Self { - deque: VecDeque::with_capacity(MULTI_IF_DEQUE_LEN), - max_len: MULTI_IF_DEQUE_LEN, - ttl_secs: MULTI_IF_DEQUE_TTL, - } - } - - /// Return whether this packet hash is still in the bounded TTL cache. New - /// hashes are recorded; a duplicate does not refresh its timestamp. - pub fn is_duplicate(&mut self, data: &[u8]) -> bool { - let hash = rns_crypto::sha::sha256(data); - let now = Instant::now(); - - while let Some(front) = self.deque.front() { - if now.duration_since(front.timestamp).as_secs_f64() > self.ttl_secs { - self.deque.pop_front(); - } else { - break; - } - } - - for entry in &self.deque { - if entry.hash == hash { - return true; - } - } - - if self.deque.len() >= self.max_len { - self.deque.pop_front(); - } - self.deque.push_back(DeduplicateEntry { - hash, - timestamp: now, - }); - - false - } -} - -impl Default for MultiIfDedup { - fn default() -> Self { - Self::new() - } -} - -/// Compare the first 32 beacon bytes with `SHA-256(group_id + peer_addr_string)`. -/// Shorter inputs fail; trailing bytes are ignored. This shared-group digest -/// does not authenticate a peer identity. -pub fn verify_beacon(beacon: &[u8], group_id: &str, peer_addr: &Ipv6Addr) -> bool { - if beacon.len() < 32 { - return false; - } - let expected = make_beacon(group_id, peer_addr); - beacon[..32] == expected[..] -} - -#[cfg(any(target_os = "macos", test))] -fn normalize_link_local_addr(addr: Ipv6Addr) -> Ipv6Addr { - if (addr.segments()[0] & 0xffc0) != 0xfe80 { - return addr; - } - let mut segments = addr.segments(); - segments[1] = 0; - Ipv6Addr::new( - segments[0], - segments[1], - segments[2], - segments[3], - segments[4], - segments[5], - segments[6], - segments[7], - ) -} - -fn is_link_local_v6(addr: Ipv6Addr) -> bool { - (addr.segments()[0] & 0xffc0) == 0xfe80 -} - -fn peer_scope_candidates( - peer_ip: Ipv6Addr, - received_scope: u32, - link_locals: &[(String, Ipv6Addr, u32)], -) -> Vec { - // Python Reticulum associates AutoInterface peers with the receiving - // ifname and sends to fe80::peer%ifindex. Some platforms report scope 0 - // from a wildcard-bound socket, so expand link-local peers to scoped local - // candidates instead of storing an unusable fe80::peer%0 address. - if received_scope != 0 { - let ifname = link_locals - .iter() - .find(|(_, _, scope_id)| *scope_id == received_scope) - .map(|(name, _, _)| name.clone()) - .unwrap_or_else(|| format!("ifindex:{received_scope}")); - return vec![PeerScopeCandidate { - ifname, - scope_id: received_scope, - source: PeerScopeSource::Received, - }]; - } - - if !is_link_local_v6(peer_ip) { - return vec![PeerScopeCandidate { - ifname: String::new(), - scope_id: 0, - source: PeerScopeSource::UnscopedNonLinkLocal, - }]; - } - - let mut candidates = Vec::new(); - for (ifname, _, scope_id) in link_locals { - if *scope_id == 0 - || candidates - .iter() - .any(|c: &PeerScopeCandidate| c.scope_id == *scope_id) - { - continue; - } - candidates.push(PeerScopeCandidate { - ifname: ifname.clone(), - scope_id: *scope_id, - source: PeerScopeSource::LocalCandidate, - }); - } - candidates -} - -fn upsert_peer_candidates( - table: &mut HashMap, - peer_ip: Ipv6Addr, - data_port: u16, - received_scope: u32, - link_locals: &[(String, Ipv6Addr, u32)], - now: Instant, - source: &'static str, -) -> usize { - let candidates = peer_scope_candidates(peer_ip, received_scope, link_locals); - if candidates.is_empty() { - tracing::warn!( - peer = %peer_ip, - received_scope, - local_candidates = link_locals.len(), - source, - "auto: discovered link-local peer but no usable scope candidates are available" - ); - return 0; - } - - let mut inserted = 0usize; - for candidate in candidates { - let key = PeerKey { - ip: peer_ip, - scope_id: candidate.scope_id, - }; - let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, candidate.scope_id); - table - .entry(key) - .and_modify(|p| { - p.ifname = candidate.ifname.clone(); - p.scope_id = candidate.scope_id; - p.scope_source = candidate.source; - p.addr = data_addr; - p.last_seen = now; - }) - .or_insert_with(|| { - inserted += 1; - Peer { - ip: peer_ip, - ifname: candidate.ifname, - scope_id: candidate.scope_id, - scope_source: candidate.source, - addr: data_addr, - last_seen: now, - last_reverse: now, - } - }); - } - inserted -} - -/// Derive `ff_T_S_:0:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX` from address-type nibble, -/// scope nibble, and bytes 2..14 of `SHA-256(group_id)`. -pub fn derive_multicast_address( - group_id: &str, - scope: DiscoveryScope, - addr_type: McastAddrType, -) -> Ipv6Addr { - let hash = rns_crypto::sha::sha256(group_id.as_bytes()); - let high = - 0xff00u16 | ((addr_type.as_hex_nibble() as u16) << 4) | (scope.as_hex_nibble() as u16); - Ipv6Addr::new( - high, - 0, - u16::from_be_bytes([hash[2], hash[3]]), - u16::from_be_bytes([hash[4], hash[5]]), - u16::from_be_bytes([hash[6], hash[7]]), - u16::from_be_bytes([hash[8], hash[9]]), - u16::from_be_bytes([hash[10], hash[11]]), - u16::from_be_bytes([hash[12], hash[13]]), - ) -} - -/// `Link` scope + `Temporary` address type (Python's defaults). -pub fn multicast_group_for(group_id: &str) -> Ipv6Addr { - derive_multicast_address(group_id, DiscoveryScope::Link, McastAddrType::Temporary) -} - -/// `SHA-256(group_id || link_local_addr_string)`, the beacon payload. -fn make_beacon(group_id: &str, link_local: &Ipv6Addr) -> [u8; 32] { - let mut input = group_id.as_bytes().to_vec(); - input.extend_from_slice(link_local.to_string().as_bytes()); - rns_crypto::sha::sha256(&input) -} - -/// One enumerated host NIC, returned by [`list_network_interfaces`]. -#[derive(Debug, Clone, serde::Serialize)] -pub struct NetworkInterfaceInfo { - pub name: String, - pub addr_v4: Option, - pub addr_v6_link_local: Option, - pub is_up: bool, - pub is_loopback: bool, -} - -/// Enumerate addresses reported by the host and group them by NIC name, -/// including loopback and normally ignored names. Callers apply filters. -/// `is_up` means an address was found; it is not a carrier or reachability test. -pub fn list_network_interfaces() -> Result, String> { - use std::collections::BTreeMap; - - let mut by_name: BTreeMap = BTreeMap::new(); - let ifaces = - if_addrs::get_if_addrs().map_err(|e| format!("if_addrs::get_if_addrs() failed: {e}"))?; - for iface in ifaces { - let entry = by_name - .entry(iface.name.clone()) - .or_insert_with(|| NetworkInterfaceInfo { - name: iface.name.clone(), - addr_v4: None, - addr_v6_link_local: None, - is_up: false, - is_loopback: iface.is_loopback(), - }); - entry.is_loopback = entry.is_loopback || iface.is_loopback(); - match iface.addr.ip() { - std::net::IpAddr::V4(v4) => { - if entry.addr_v4.is_none() { - entry.addr_v4 = Some(v4.to_string()); - } - entry.is_up = true; - } - std::net::IpAddr::V6(v6) => { - // fe80::/10 — link-local prefix used by AutoInterface discovery. - if (v6.segments()[0] & 0xffc0) == 0xfe80 && entry.addr_v6_link_local.is_none() { - entry.addr_v6_link_local = Some(v6.to_string()); - } - entry.is_up = true; - } - } - } - - #[cfg(target_os = "macos")] - { - match darwin_link_local_addrs(None, &[], false) { - Ok(addrs) => { - for (name, addr, _) in addrs { - let entry = - by_name - .entry(name.clone()) - .or_insert_with(|| NetworkInterfaceInfo { - name, - addr_v4: None, - addr_v6_link_local: None, - is_up: true, - is_loopback: false, - }); - entry.addr_v6_link_local = Some(addr.to_string()); - entry.is_up = true; - } - } - Err(e) => tracing::debug!(error = %e, "Darwin getifaddrs link-local list failed"), - } - } - - Ok(by_name.into_values().collect()) -} - -fn iface_passes_filters( - iface_name: &str, - devices: Option<&[String]>, - ignored_devices: &[String], -) -> bool { - if IGNORED_IFACES.contains(&iface_name) { - return false; - } - if ignored_devices.iter().any(|n| n == iface_name) { - return false; - } - if let Some(allowed) = devices - && !allowed.iter().any(|n| n == iface_name) - { - return false; - } - true -} - -/// Enumerate link-local IPv6 addresses, applying device/ignore filters. -/// Drops addresses with unresolvable scope id — `scope_id = 0` silently -/// routes via the default NIC, which is wrong on multi-homed hosts. -fn get_link_local_addrs( - devices: Option<&[String]>, - ignored_devices: &[String], -) -> Vec<(String, Ipv6Addr, u32)> { - // Android's libc getifaddrs() hides IPv6 link-local from app context; - // must use Java NetworkInterface.getNetworkInterfaces() via JNI. - #[cfg(target_os = "android")] - { - match get_link_local_addrs_android(devices, ignored_devices) { - Ok(v) if !v.is_empty() => { - tracing::info!(count = v.len(), "Android JNI link-local enumerate"); - return v; - } - Ok(_) => { - tracing::warn!( - "Android JNI link-local enumerate returned 0 — falling back to if_addrs" - ); - } - Err(e) => { - tracing::warn!(error = %e, "Android JNI link-local enumerate failed"); - } - } - } - - let mut result = Vec::new(); - match if_addrs::get_if_addrs() { - Ok(ifaces) => { - tracing::debug!(count = ifaces.len(), "if_addrs enumerated interfaces"); - for iface in ifaces { - tracing::debug!(name = %iface.name, addr = ?iface.addr.ip(), "if_addrs entry"); - if !iface_passes_filters(&iface.name, devices, ignored_devices) { - continue; - } - if let std::net::IpAddr::V6(addr) = iface.addr.ip() - && (addr.segments()[0] & 0xffc0) == 0xfe80 - { - let scope_id = iface_scope_id(&iface); - if scope_id == 0 { - tracing::warn!( - iface = %iface.name, - addr = %addr, - "skipping link-local: could not resolve scope id (would send on wrong NIC)" - ); - continue; - } - result.push((iface.name.clone(), addr, scope_id)); - } - } - } - Err(e) => { - tracing::warn!(error = %e, "if_addrs::get_if_addrs() failed"); - } - } - - #[cfg(target_os = "macos")] - if result.is_empty() { - match darwin_link_local_addrs(devices, ignored_devices, true) { - Ok(addrs) if !addrs.is_empty() => { - tracing::debug!( - count = addrs.len(), - "Darwin getifaddrs link-local enumerate" - ); - return addrs; - } - Ok(_) => {} - Err(e) => tracing::warn!(error = %e, "Darwin getifaddrs link-local enumerate failed"), - } - } - - result -} - -#[cfg(target_os = "macos")] -fn darwin_link_local_addrs( - devices: Option<&[String]>, - ignored_devices: &[String], - apply_filters: bool, -) -> Result, String> { - use std::ffi::CStr; - use std::ptr; - - let mut ifap: *mut libc::ifaddrs = ptr::null_mut(); - // SAFETY: getifaddrs initialises `ifap` on success; the linked list is - // released with freeifaddrs before return. - if unsafe { libc::getifaddrs(&mut ifap) } != 0 { - return Err(std::io::Error::last_os_error().to_string()); - } - - struct IfAddrsGuard(*mut libc::ifaddrs); - impl Drop for IfAddrsGuard { - fn drop(&mut self) { - // SAFETY: pointer came from successful getifaddrs and is released once. - unsafe { libc::freeifaddrs(self.0) }; - } - } - let _guard = IfAddrsGuard(ifap); - - let mut result = Vec::new(); - let mut cursor = ifap; - while !cursor.is_null() { - // SAFETY: cursor walks the null-terminated getifaddrs list. - let ifa = unsafe { &*cursor }; - cursor = ifa.ifa_next; - - if ifa.ifa_addr.is_null() || ifa.ifa_name.is_null() { - continue; - } - // SAFETY: getifaddrs provides a nul-terminated interface name. - let name = unsafe { CStr::from_ptr(ifa.ifa_name) } - .to_string_lossy() - .into_owned(); - if apply_filters && !iface_passes_filters(&name, devices, ignored_devices) { - continue; - } - if ifa.ifa_flags & libc::IFF_UP as u32 == 0 { - continue; - } - let explicitly_allowed = devices.is_some_and(|allowed| allowed.iter().any(|n| n == &name)); - if apply_filters && !explicitly_allowed && ifa.ifa_flags & libc::IFF_POINTOPOINT as u32 != 0 - { - tracing::debug!(iface = %name, "skipping Darwin point-to-point link-local"); - continue; - } - // SAFETY: ifa_addr is non-null and points to a sockaddr for this entry. - let family = unsafe { (*ifa.ifa_addr).sa_family as i32 }; - if family != libc::AF_INET6 { - continue; - } - - // SAFETY: family is AF_INET6, so sockaddr_in6 layout is valid. - let sin6 = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in6) }; - let addr = normalize_link_local_addr(Ipv6Addr::from(sin6.sin6_addr.s6_addr)); - if (addr.segments()[0] & 0xffc0) != 0xfe80 { - continue; - } - - let scope_id = if sin6.sin6_scope_id != 0 { - sin6.sin6_scope_id - } else { - iface_name_to_scope_id(&name) - }; - if scope_id == 0 { - tracing::warn!( - iface = %name, - addr = %addr, - "skipping Darwin link-local: could not resolve scope id" - ); - continue; - } - if result.iter().any(|(existing, _, _)| existing == &name) { - continue; - } - tracing::debug!(iface = %name, addr = %addr, scope_id, "Darwin link-local found"); - result.push((name, addr, scope_id)); - } - - Ok(result) -} - -#[cfg(target_os = "android")] -fn get_link_local_addrs_android( - devices: Option<&[String]>, - ignored_devices: &[String], -) -> Result, String> { - use jni::objects::JObject; - - let vm = crate::android_usb::java_vm().ok_or("JavaVM not initialized")?; - let env = vm - .attach_current_thread() - .map_err(|e| format!("attach_current_thread: {e}"))?; - - let ni_class = env - .find_class("java/net/NetworkInterface") - .map_err(|e| format!("NetworkInterface class: {e}"))?; - let inet6_class = env - .find_class("java/net/Inet6Address") - .map_err(|e| format!("Inet6Address class: {e}"))?; - - let ifaces_enum = env - .call_static_method( - ni_class, - "getNetworkInterfaces", - "()Ljava/util/Enumeration;", - &[], - ) - .map_err(|e| format!("getNetworkInterfaces: {e}"))? - .l() - .map_err(|e| format!("getNetworkInterfaces obj: {e}"))?; - if ifaces_enum.is_null() { - return Err("getNetworkInterfaces returned null".into()); - } - - let mut result: Vec<(String, Ipv6Addr, u32)> = Vec::new(); - - while env - .call_method(ifaces_enum, "hasMoreElements", "()Z", &[]) - .map_err(|e| format!("hasMoreElements: {e}"))? - .z() - .map_err(|e| format!("hasMoreElements bool: {e}"))? - { - let iface_obj: JObject = env - .call_method(ifaces_enum, "nextElement", "()Ljava/lang/Object;", &[]) - .map_err(|e| format!("nextElement (iface): {e}"))? - .l() - .map_err(|e| format!("nextElement iface obj: {e}"))?; - if iface_obj.is_null() { - continue; - } - - let is_up = env - .call_method(iface_obj, "isUp", "()Z", &[]) - .map_err(|e| format!("isUp: {e}"))? - .z() - .map_err(|e| format!("isUp bool: {e}"))?; - if !is_up { - continue; - } - - let name_obj: JObject = env - .call_method(iface_obj, "getName", "()Ljava/lang/String;", &[]) - .map_err(|e| format!("getName: {e}"))? - .l() - .map_err(|e| format!("getName obj: {e}"))?; - let name: String = if name_obj.is_null() { - String::new() - } else { - env.get_string(name_obj.into()) - .map(|s| s.to_string_lossy().to_string()) - .unwrap_or_default() - }; - if !iface_passes_filters(&name, devices, ignored_devices) { - continue; - } - - let scope_id = env - .call_method(iface_obj, "getIndex", "()I", &[]) - .map_err(|e| format!("getIndex: {e}"))? - .i() - .map_err(|e| format!("getIndex int: {e}"))? as u32; - if scope_id == 0 { - tracing::warn!( - iface = %name, - "skipping JNI link-local: getIndex returned 0 (interface may have just gone down)" - ); - continue; - } - - let addrs_enum: JObject = env - .call_method( - iface_obj, - "getInetAddresses", - "()Ljava/util/Enumeration;", - &[], - ) - .map_err(|e| format!("getInetAddresses: {e}"))? - .l() - .map_err(|e| format!("getInetAddresses obj: {e}"))?; - if addrs_enum.is_null() { - continue; - } - - while env - .call_method(addrs_enum, "hasMoreElements", "()Z", &[]) - .map_err(|e| format!("addr hasMoreElements: {e}"))? - .z() - .map_err(|e| format!("addr hasMoreElements bool: {e}"))? - { - let addr_obj: JObject = env - .call_method(addrs_enum, "nextElement", "()Ljava/lang/Object;", &[]) - .map_err(|e| format!("nextElement (addr): {e}"))? - .l() - .map_err(|e| format!("nextElement addr obj: {e}"))?; - if addr_obj.is_null() { - continue; - } - - let is_v6 = env - .is_instance_of(addr_obj, inet6_class) - .map_err(|e| format!("is_instance_of Inet6Address: {e}"))?; - if !is_v6 { - continue; - } - - let is_ll = env - .call_method(addr_obj, "isLinkLocalAddress", "()Z", &[]) - .map_err(|e| format!("isLinkLocalAddress: {e}"))? - .z() - .map_err(|e| format!("isLinkLocalAddress bool: {e}"))?; - if !is_ll { - continue; - } - - let raw_obj: JObject = env - .call_method(addr_obj, "getAddress", "()[B", &[]) - .map_err(|e| format!("getAddress: {e}"))? - .l() - .map_err(|e| format!("getAddress obj: {e}"))?; - if raw_obj.is_null() { - continue; - } - let raw: Vec = env - .convert_byte_array(raw_obj.into_inner()) - .unwrap_or_default(); - if raw.len() != 16 { - continue; - } - let mut bytes = [0u8; 16]; - bytes.copy_from_slice(&raw); - let v6 = Ipv6Addr::from(bytes); - tracing::info!(iface = %name, addr = %v6, scope_id, "JNI link-local found"); - result.push((name.clone(), v6, scope_id)); - } - } - - Ok(result) -} - -fn iface_scope_id(iface: &if_addrs::Interface) -> u32 { - if let Some(index) = iface.index { - return index; - } - - #[cfg(windows)] - { - let adapter_index = iface_name_to_scope_id(&iface.adapter_name); - if adapter_index != 0 { - return adapter_index; - } - } - - iface_name_to_scope_id(&iface.name) -} - -/// Convert interface name to scope ID via POSIX/Windows `if_nametoindex`. -/// Returns 0 if the lookup fails; callers must skip the address. -#[cfg(any(unix, windows))] -fn iface_name_to_scope_id(name: &str) -> u32 { - use std::ffi::CString; - if let Ok(cname) = CString::new(name) { - // SAFETY: if_nametoindex takes a NUL-terminated C string and returns - // an index or 0 on error, with no ownership implications. - unsafe { libc_if_nametoindex(cname.as_ptr()) } - } else { - 0 - } -} - -#[cfg(unix)] -unsafe extern "C" { - #[link_name = "if_nametoindex"] - fn libc_if_nametoindex(ifname: *const std::ffi::c_char) -> u32; -} - -#[cfg(windows)] -#[link(name = "iphlpapi")] -unsafe extern "C" { - #[link_name = "if_nametoindex"] - fn libc_if_nametoindex(ifname: *const std::ffi::c_char) -> u32; -} - -#[cfg(not(any(unix, windows)))] -fn iface_name_to_scope_id(_name: &str) -> u32 { - 0 -} - -/// Bind UDP/IPv6 with REUSEADDR/REUSEPORT so multicast peers can share the port. -fn bind_reusable_udp_v6(port: u16) -> std::io::Result { - bind_one(port) -} - -fn bind_one(port: u16) -> std::io::Result { - use socket2::{Domain, Protocol, Socket, Type}; - let sock = Socket::new(Domain::IPV6, Type::DGRAM, Some(Protocol::UDP))?; - if let Err(e) = sock.set_reuse_address(true) { - tracing::warn!(port, error = %e, "SO_REUSEADDR failed"); - } - #[cfg(unix)] - if let Err(e) = sock.set_reuse_port(true) { - tracing::warn!(port, error = %e, "SO_REUSEPORT failed"); - } - // IPv6-only — link-local + scope_ids assume v6 semantics. - if let Err(e) = sock.set_only_v6(true) { - tracing::warn!(port, error = %e, "IPV6_V6ONLY failed"); - } - sock.set_nonblocking(true)?; - let addr: SocketAddr = SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, port, 0, 0).into(); - sock.bind(&addr.into())?; - UdpSocket::from_std(sock.into()) -} - -fn set_multicast_if_v6(sock: &UdpSocket, scope_id: u32) -> std::io::Result<()> { - let sock_ref = socket2::SockRef::from(sock); - sock_ref.set_multicast_if_v6(scope_id) -} - -/// Diagnostic: probe alternate ports to localize bind failures. -#[cfg(target_os = "android")] -fn probe_alternate_ports(base: u16) { - let candidates: [u16; 4] = [base.saturating_add(1), base.saturating_add(2), 50000, 0]; - for p in candidates { - match bind_one(p) { - Ok(s) => { - let local = s.local_addr(); - tracing::info!(probe_port = p, ?local, "probe bind succeeded"); - drop(s); - } - Err(e) => { - tracing::warn!(probe_port = p, error = %e, "probe bind failed"); - } - } - } -} - -fn hex32(bytes: &[u8]) -> String { - let take = bytes.len().min(32); - let mut s = String::with_capacity(take * 2); - for b in &bytes[..take] { - s.push_str(&format!("{:02x}", b)); - } - s -} - -fn hex_prefix(bytes: &[u8], n: usize) -> String { - let take = bytes.len().min(n); - let mut s = String::with_capacity(take * 2); - for b in &bytes[..take] { - s.push_str(&format!("{:02x}", b)); - } - s -} - -fn multicast_join_candidates( - link_locals: &[(String, Ipv6Addr, u32)], - joined_memberships: &HashSet<(String, u32)>, -) -> Vec<(String, Ipv6Addr, u32)> { - link_locals - .iter() - .filter(|(ifname, _, scope_id)| !joined_memberships.contains(&(ifname.clone(), *scope_id))) - .cloned() - .collect() -} - -/// Spawn the auto-discovery interface. -pub async fn spawn_auto_interface( - config: AutoInterfaceConfig, - id: InterfaceId, - transport_tx: mpsc::Sender, - is_foreground: Arc, -) -> Result { - let transport_tx = InterfaceTransportSender::new(id, transport_tx); - let owner = transport_tx.owner(); - let mcast_group = derive_multicast_address( - &config.group_id, - config.discovery_scope, - config.multicast_address_type, - ); - let initial_link_locals = - get_link_local_addrs(config.devices.as_deref(), &config.ignored_devices); - - if initial_link_locals.is_empty() { - tracing::warn!(name = %config.name, "no link-local IPv6 addresses found"); - } - - // Adopted NIC set; jobs task refreshes on link flap. Each iteration snapshots. - let link_locals: Arc>> = - Arc::new(Mutex::new(initial_link_locals.clone())); - - // Per-NIC last-echo timestamp — updated by discovery RX when it sees our - // own beacon (multicast carrier confirmed). Read by jobs for carrier check. - let multicast_echoes: Arc>> = - Arc::new(Mutex::new(HashMap::new())); - - let data_sock = Arc::new(bind_reusable_udp_v6(config.data_port).map_err(|e| { - #[cfg(target_os = "android")] - if e.kind() == std::io::ErrorKind::AddrInUse { - probe_alternate_ports(config.data_port); - } - std::io::Error::new( - e.kind(), - format!("data socket bind ({}): {e}", config.data_port), - ) - })?); - let data_local = data_sock.local_addr()?; - tracing::info!(name = %config.name, addr = %data_local, "auto data socket bound"); - - let disc_sock = Arc::new(bind_reusable_udp_v6(config.discovery_port).map_err(|e| { - std::io::Error::new( - e.kind(), - format!("discovery socket bind ({}): {e}", config.discovery_port), - ) - })?); - tracing::info!(name = %config.name, port = config.discovery_port, "auto discovery socket bound"); - - let mut joined_memberships: HashSet<(String, u32)> = HashSet::new(); - let mut reported_join_failures: HashSet<(String, u32)> = HashSet::new(); - for (iface_name, _ll_addr, scope_id) in &initial_link_locals { - if let Err(e) = set_multicast_if_v6(disc_sock.as_ref(), *scope_id) { - tracing::warn!( - iface = %iface_name, - scope_id, - error = %e, - raw_os_error = ?e.raw_os_error(), - "failed to set IPv6 multicast outbound interface" - ); - } - match disc_sock.join_multicast_v6(&mcast_group, *scope_id) { - Ok(()) => { - joined_memberships.insert((iface_name.clone(), *scope_id)); - } - Err(e) => { - // iOS can reject the first operation while Local Network - // authorization is being resolved. Keep the interface alive; - // the jobs task retries missing memberships periodically. - if e.kind() == std::io::ErrorKind::PermissionDenied { - reported_join_failures.insert((iface_name.clone(), *scope_id)); - tracing::warn!( - iface = %iface_name, - error = %e, - "multicast join denied by OS — permission, entitlement, firewall, or capability missing" - ); - dispatch_auto_event(AutoInterfaceEvent::JoinFailed { - interface_name: config.name.clone(), - ifname: iface_name.clone(), - reason: format!("os_permission_denied: {e}"), - }); - } else { - tracing::debug!( - iface = %iface_name, - error = %e, - "failed to join multicast group" - ); - } - } - } - } - - let online = Arc::new(AtomicBool::new(true)); - let (tx, mut rx) = mpsc::channel::(256); - let name = config.name.clone(); - let mode = config.mode; - - let shared_rxb = Arc::new(AtomicU64::new(0)); - let shared_txb = Arc::new(AtomicU64::new(0)); - - let peers: PeerTable = Arc::new(Mutex::new(HashMap::new())); - - let online_b = online.clone(); - let group_id = config.group_id.clone(); - let disc_sock_send = disc_sock.clone(); - let beacon_link_locals = link_locals.clone(); - let disc_port = config.discovery_port; - let is_fg_beacon = is_foreground.clone(); - tokio::spawn(async move { - let mut interval = - tokio::time::interval(std::time::Duration::from_secs_f64(BEACON_INTERVAL)); - #[cfg(feature = "mobile-throttle")] - let mut was_foreground = true; - #[cfg(not(feature = "mobile-throttle"))] - let _ = &is_fg_beacon; - loop { - interval.tick().await; - if !online_b.load(Ordering::SeqCst) { - break; - } - // Slow beacons in background to save battery. - #[cfg(feature = "mobile-throttle")] - { - let is_fg = is_fg_beacon.load(Ordering::Relaxed); - if is_fg != was_foreground { - let secs = if is_fg { - BEACON_INTERVAL - } else { - BEACON_INTERVAL_BG - }; - interval = tokio::time::interval(std::time::Duration::from_secs_f64(secs)); - interval.tick().await; - was_foreground = is_fg; - } - } - // Snapshot adopted set; jobs task may have replaced it on link flap. - let snapshot = { beacon_link_locals.lock().await.clone() }; - for (_name, ll_addr, scope_id) in &snapshot { - let beacon = make_beacon(&group_id, ll_addr); - let dest = SocketAddrV6::new(mcast_group, disc_port, 0, *scope_id); - if let Err(e) = set_multicast_if_v6(disc_sock_send.as_ref(), *scope_id) { - tracing::warn!( - iface = %_name, - ll = %ll_addr, - scope_id, - error = %e, - raw_os_error = ?e.raw_os_error(), - "auto: failed to select multicast outbound interface" - ); - } - let res = disc_sock_send.send_to(&beacon, dest).await; - match res { - Ok(n) => tracing::debug!( - iface = %_name, - ll = %ll_addr, - scope_id, - dst = %dest, - hash = %hex32(&beacon), - sent_bytes = n, - "auto-instr beacon TX" - ), - Err(e) => tracing::warn!( - iface = %_name, - ll = %ll_addr, - scope_id, - dst = %dest, - hash = %hex32(&beacon), - error = %e, - raw_os_error = ?e.raw_os_error(), - "auto: beacon TX failed" - ), - } - } - } - }); - - let peers_disc = peers.clone(); - let online_d = online.clone(); - let data_port = config.data_port; - let auth_group_id = config.group_id.clone(); - let disc_link_locals = link_locals.clone(); - let disc_echoes = multicast_echoes.clone(); - let disc_sock_recv = disc_sock.clone(); - tokio::spawn(async move { - let mut buf = [0u8; 256]; - // Python's read loops swallow exceptions and keep serving; Linux - // surfaces transient async errors (ICMP unreachable) via recv_from, - // so only sustained failure may kill the loop. - let mut consecutive_errors = 0u32; - loop { - if !online_d.load(Ordering::SeqCst) { - break; - } - match disc_sock_recv.recv_from(&mut buf).await { - Ok((n, src)) => { - consecutive_errors = 0; - if n < 32 { - tracing::debug!(src = %src, n, "auto-instr mcast RX too short"); - continue; - } - if let SocketAddr::V6(src_v6) = src { - let peer_ip = *src_v6.ip(); - // Match source LL against ours — non-empty means self-echo. - let snapshot = { disc_link_locals.lock().await.clone() }; - let self_iface = { - snapshot - .iter() - .find(|(_, ll, _)| *ll == peer_ip) - .map(|(name, _, _)| name.clone()) - }; - let is_self = self_iface.is_some(); - let expected = make_beacon(&auth_group_id, &peer_ip); - let match_ok = expected[..] == buf[..32]; - // Hash hex strings only materialize when debug is on. - if tracing::enabled!(tracing::Level::DEBUG) { - tracing::debug!( - src = %src_v6, - scope_id = src_v6.scope_id(), - n, - is_self, - recv_hash = %hex32(&buf[..32]), - expected_hash = %hex32(&expected), - match_ok, - "auto-instr mcast RX" - ); - } - if let Some(ifname) = self_iface { - // Self-echo: carrier confirmed; record for jobs task. - let mut echoes = disc_echoes.lock().await; - echoes.insert(ifname, Instant::now()); - continue; - } - if !match_ok { - continue; - } - let received_scope = src_v6.scope_id(); - let now = Instant::now(); - let mut table = peers_disc.lock().await; - let inserted = upsert_peer_candidates( - &mut table, - peer_ip, - data_port, - received_scope, - &snapshot, - now, - "multicast", - ); - tracing::debug!( - peer = %peer_ip, - received_scope, - inserted, - peer_records = table.len(), - "auto: peer discovered/refreshed" - ); - } else { - tracing::debug!(src = %src, "auto-instr mcast RX non-v6 source"); - } - } - Err(e) => { - consecutive_errors += 1; - tracing::warn!(error = %e, consecutive_errors, "auto discovery recv error"); - if consecutive_errors >= 50 { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - } - } - } - }); - - // Unicast + reverse-peering keeps peers reachable on one-way multicast paths. - let peers_unicast = peers.clone(); - let online_u = online.clone(); - let unicast_group_id = config.group_id.clone(); - let unicast_link_locals = link_locals.clone(); - let unicast_disc_port = config.discovery_port + 1; - let unicast_sock = match bind_reusable_udp_v6(unicast_disc_port) { - Ok(sock) => Some(Arc::new(sock)), - Err(e) => { - tracing::debug!( - port = unicast_disc_port, - error = %e, - raw_os_error = ?e.raw_os_error(), - "auto: could not bind unicast discovery port" - ); - None - } - }; - if let Some(unicast_sock) = unicast_sock { - let urecv_sock = unicast_sock.clone(); - let urecv_peers = peers_unicast.clone(); - let urecv_online = online_u.clone(); - let urecv_group_id = unicast_group_id.clone(); - let urecv_link_locals = unicast_link_locals.clone(); - tokio::spawn(async move { - let mut buf = [0u8; 256]; - let mut consecutive_errors = 0u32; - loop { - if !urecv_online.load(Ordering::SeqCst) { - break; - } - match urecv_sock.recv_from(&mut buf).await { - Ok((n, src)) => { - consecutive_errors = 0; - if n < 32 { - continue; - } - if let SocketAddr::V6(src_v6) = src { - let peer_ip = *src_v6.ip(); - let snapshot = { urecv_link_locals.lock().await.clone() }; - let is_self = { snapshot.iter().any(|(_, ll, _)| *ll == peer_ip) }; - if is_self { - continue; - } - if !verify_beacon(&buf[..n], &urecv_group_id, &peer_ip) { - continue; - } - let received_scope = src_v6.scope_id(); - let now = Instant::now(); - let mut table = urecv_peers.lock().await; - let inserted = upsert_peer_candidates( - &mut table, - peer_ip, - data_port, - received_scope, - &snapshot, - now, - "unicast", - ); - tracing::debug!( - peer = %peer_ip, - received_scope, - inserted, - peer_records = table.len(), - "auto: unicast peer discovered" - ); - } - } - Err(e) => { - consecutive_errors += 1; - tracing::debug!( - error = %e, - consecutive_errors, - "auto unicast discovery recv error" - ); - if consecutive_errors >= 50 { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - } - } - } - }); - - let rev_peers = peers_unicast; - let rev_online = online_u; - let rev_group_id = unicast_group_id; - let rev_link_locals = unicast_link_locals; - let is_fg_rev = is_foreground.clone(); - tokio::spawn(async move { - let mut interval = - tokio::time::interval(std::time::Duration::from_secs_f64(REVERSE_PEERING_INTERVAL)); - #[cfg(feature = "mobile-throttle")] - let mut was_foreground = true; - #[cfg(not(feature = "mobile-throttle"))] - let _ = &is_fg_rev; - loop { - interval.tick().await; - if !rev_online.load(Ordering::SeqCst) { - break; - } - #[cfg(feature = "mobile-throttle")] - { - let is_fg = is_fg_rev.load(Ordering::Relaxed); - if is_fg != was_foreground { - let secs = if is_fg { - REVERSE_PEERING_INTERVAL - } else { - BEACON_INTERVAL_BG * 3.25 - }; - interval = tokio::time::interval(std::time::Duration::from_secs_f64(secs)); - interval.tick().await; - was_foreground = is_fg; - } - } - let snapshot = { rev_link_locals.lock().await.clone() }; - let now = Instant::now(); - // Snapshot due peers under a short lock; sends happen lock-free - // so discovery/data tasks aren't stalled by the fan-out. - let due: Vec<(PeerKey, Peer)> = { - let table = rev_peers.lock().await; - table - .iter() - .filter(|(_, peer)| { - now.duration_since(peer.last_reverse).as_secs_f64() - >= REVERSE_PEERING_INTERVAL - }) - .map(|(key, peer)| (*key, peer.clone())) - .collect() - }; - for (_, peer) in &due { - let mut targets: Vec<_> = snapshot - .iter() - .filter(|(_, _, scope_id)| peer.scope_id == 0 || *scope_id == peer.scope_id) - .collect(); - if targets.is_empty() { - targets = snapshot.iter().collect(); - } - for (_name, ll_addr, scope_id) in targets { - let beacon = make_beacon(&rev_group_id, ll_addr); - let dest = - SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id); - if let Err(e) = unicast_sock.send_to(&beacon, dest).await { - tracing::debug!( - peer = %peer.ip, - peer_ifname = %peer.ifname, - peer_scope_id = peer.scope_id, - local_iface = %_name, - local_scope_id = scope_id, - dst = %dest, - error = %e, - raw_os_error = ?e.raw_os_error(), - "auto: reverse peering TX failed" - ); - } - } - } - if !due.is_empty() { - let mut table = rev_peers.lock().await; - for (key, _) in &due { - if let Some(peer) = table.get_mut(key) { - peer.last_reverse = now; - } - } - } - } - }); - } - - // Periodic jobs: NIC re-enum, peer aging, carrier detection (every PEER_JOB_INTERVAL). - // Decoupled from beacon loop to avoid multicast-join thrash on link flap. - let jobs_link_locals = link_locals.clone(); - let jobs_peers = peers.clone(); - let jobs_online = online.clone(); - let jobs_devices = config.devices.clone(); - let jobs_ignored = config.ignored_devices.clone(); - let jobs_disc_sock = disc_sock.clone(); - let jobs_mcast = mcast_group; - let jobs_echoes = multicast_echoes.clone(); - let jobs_iface_name = config.name.clone(); - tokio::spawn(async move { - let mut interval = - tokio::time::interval(std::time::Duration::from_secs_f64(PEER_JOB_INTERVAL)); - // Skip immediate first tick — initial joins happened at spawn. - interval.tick().await; - let mut carrier_state: HashMap = HashMap::new(); - loop { - interval.tick().await; - if !jobs_online.load(Ordering::SeqCst) { - break; - } - - // (1) Age out stale peers. - { - let now = Instant::now(); - let mut table = jobs_peers.lock().await; - table.retain(|_ip, peer| { - now.duration_since(peer.last_seen).as_secs_f64() < PEER_EXPIRY - }); - } - - // (2) Re-enumerate; diff against adopted set; join/leave multicast. - let new_set = get_link_local_addrs(jobs_devices.as_deref(), &jobs_ignored); - let (added, removed): (Vec<_>, Vec<_>) = { - let current = jobs_link_locals.lock().await; - let added: Vec<_> = new_set - .iter() - .filter(|(_, a, _)| !current.iter().any(|(_, ca, _)| ca == a)) - .cloned() - .collect(); - let removed: Vec<_> = current - .iter() - .filter(|(_, a, _)| !new_set.iter().any(|(_, ca, _)| ca == a)) - .cloned() - .collect(); - (added, removed) - }; - if !added.is_empty() || !removed.is_empty() { - tracing::info!( - iface = %jobs_iface_name, - added_count = added.len(), - removed_count = removed.len(), - "AutoInterface link-local set changed" - ); - } - let join_candidates = multicast_join_candidates(&new_set, &joined_memberships); - for (ifname, addr, scope_id) in &join_candidates { - let membership = (ifname.clone(), *scope_id); - if let Err(e) = set_multicast_if_v6(jobs_disc_sock.as_ref(), *scope_id) { - tracing::warn!( - iface = %jobs_iface_name, - nic = %ifname, - addr = %addr, - scope_id, - error = %e, - raw_os_error = ?e.raw_os_error(), - "AutoInterface failed to set multicast interface for new NIC" - ); - } - match jobs_disc_sock.join_multicast_v6(&jobs_mcast, *scope_id) { - Ok(()) => { - joined_memberships.insert(membership.clone()); - reported_join_failures.remove(&membership); - tracing::info!( - iface = %jobs_iface_name, - nic = %ifname, - addr = %addr, - scope_id, - "AutoInterface joined multicast on NIC" - ); - } - Err(e) => { - let first_report = reported_join_failures.insert(membership); - if first_report && e.kind() == std::io::ErrorKind::PermissionDenied { - dispatch_auto_event(AutoInterfaceEvent::JoinFailed { - interface_name: jobs_iface_name.clone(), - ifname: ifname.clone(), - reason: format!("os_permission_denied: {e}"), - }); - } - if first_report { - tracing::warn!( - iface = %jobs_iface_name, - nic = %ifname, - error = %e, - "AutoInterface multicast join failed; will retry" - ); - } else { - tracing::debug!( - iface = %jobs_iface_name, - nic = %ifname, - error = %e, - "AutoInterface multicast join retry failed" - ); - } - } - } - } - for (ifname, _addr, scope_id) in &removed { - let membership = (ifname.clone(), *scope_id); - if joined_memberships.remove(&membership) { - let _ = jobs_disc_sock.leave_multicast_v6(&jobs_mcast, *scope_id); - } - reported_join_failures.remove(&membership); - jobs_echoes.lock().await.remove(ifname); - carrier_state.remove(ifname); - } - *jobs_link_locals.lock().await = new_set.clone(); - - // (3) Carrier detection: dispatch CarrierState transitions per NIC. - let now = Instant::now(); - let echoes = jobs_echoes.lock().await.clone(); - for (ifname, _, _) in &new_set { - let last = echoes.get(ifname); - let ok = match last { - Some(t) => now.duration_since(*t).as_secs_f64() <= MCAST_ECHO_TIMEOUT, - None => false, - }; - let prev = carrier_state.insert(ifname.clone(), ok); - if prev != Some(ok) { - let reason = match (prev, ok) { - (None, false) => "initial: no echo seen yet".to_string(), - (None, true) => "first multicast echo received".to_string(), - (Some(true), false) => format!( - "no multicast echo for >{:.1}s (firewall? bridge? AP reboot?)", - MCAST_ECHO_TIMEOUT - ), - (Some(false), true) => "multicast echo recovered".to_string(), - _ => unreachable!("prev != Some(ok) was true above"), - }; - let _ = last; - if !ok && prev == Some(true) { - tracing::warn!( - iface = %jobs_iface_name, - nic = %ifname, - "AutoInterface carrier lost on {ifname}: {reason}" - ); - } else if ok { - tracing::info!( - iface = %jobs_iface_name, - nic = %ifname, - "AutoInterface carrier ok on {ifname}: {reason}" - ); - } - dispatch_auto_event(AutoInterfaceEvent::CarrierState { - interface_name: jobs_iface_name.clone(), - ifname: ifname.clone(), - ok, - reason, - }); - } - } - } - }); - - let peers_write = peers.clone(); - let data_sock_w = data_sock.clone(); - let task_txb = shared_txb.clone(); - tokio::spawn(async move { - while let Some(data) = rx.recv().await { - let len = data.len(); - // Hex prefix only materializes when debug logging is active; the - // error path below recomputes it (errors are rare). - let debug_enabled = tracing::enabled!(tracing::Level::DEBUG); - let prefix = if debug_enabled { - hex_prefix(&data, 16) - } else { - String::new() - }; - // Snapshot under a short lock so the discovery/jobs tasks are not - // blocked while we await per-peer sends. - let targets: Vec = { - let table = peers_write.lock().await; - table.values().cloned().collect() - }; - let peer_count = targets.len(); - if peer_count == 0 && debug_enabled { - tracing::debug!( - len, - prefix = %prefix, - "auto-instr data TX skipped: no discovered peers" - ); - } - for peer in &targets { - let res = data_sock_w.send_to(&data, peer.addr).await; - match res { - Ok(n) => { - if debug_enabled { - tracing::debug!( - peer = %peer.ip, - ifname = %peer.ifname, - scope_id = peer.scope_id, - scope_source = ?peer.scope_source, - dst = %peer.addr, - len, - sent_bytes = n, - prefix = %prefix, - peer_count, - "auto-instr data TX" - ); - } - task_txb.fetch_add(len as u64, Ordering::Relaxed); - } - Err(e) => { - tracing::warn!( - peer = %peer.ip, - ifname = %peer.ifname, - scope_id = peer.scope_id, - scope_source = ?peer.scope_source, - dst = %peer.addr, - len, - prefix = %hex_prefix(&data, 16), - peer_count, - error = %e, - raw_os_error = ?e.raw_os_error(), - "auto: data TX failed" - ); - } - } - } - } - }); - - let online_r = online.clone(); - let task_rxb = shared_rxb.clone(); - let dedup = Arc::new(Mutex::new(MultiIfDedup::new())); - let read_task = tokio::spawn(async move { - let mut buf = [0u8; 2048]; - let mut consecutive_errors = 0u32; - loop { - match data_sock.recv_from(&mut buf).await { - Ok((n, _src)) => { - consecutive_errors = 0; - if n == 0 { - continue; - } - tracing::debug!( - src = %_src, - n, - prefix = %hex_prefix(&buf[..n], 16), - "auto-instr data RX" - ); - { - let mut dd = dedup.lock().await; - if dd.is_duplicate(&buf[..n]) { - tracing::trace!(id, "auto: dropping duplicate packet"); - continue; - } - } - task_rxb.fetch_add(n as u64, Ordering::Relaxed); - let msg = TransportMessage::Inbound(InboundPacket { - raw: Bytes::copy_from_slice(&buf[..n]), - interface_id: id, - rssi: None, - snr: None, - q: None, - }); - if transport_tx.send(msg).await.is_err() { - tracing::warn!(id, "transport channel closed"); - break; - } - } - Err(e) => { - consecutive_errors += 1; - tracing::warn!(error = %e, consecutive_errors, "auto data recv error"); - if consecutive_errors >= 50 { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - } - } - } - online_r.store(false, Ordering::SeqCst); - }); - - let bitrate = config.configured_bitrate.unwrap_or(10_000_000); - - Ok(InterfaceHandle { - id, - owner, - packet_capacity: InterfacePacketCapacity::new(1196, 1196, true), - parent_id: None, - name, - mode, - direction: InterfaceDirection { - inbound: true, - outbound: true, - forward: false, - repeat: false, - }, - bitrate, - mtu: HW_MTU, - online, - rxb: Some(shared_rxb), - txb: Some(shared_txb), - inspection: None, - tx, - read_task, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_multicast_group_derivation() { - let group = multicast_group_for("reticulum"); - assert_eq!(group.segments()[0], 0xff12); - assert_eq!(group.segments()[1], 0); - assert_eq!(group.segments()[2], 0xd70b); - let group2 = multicast_group_for("reticulum"); - assert_eq!(group, group2); - let group3 = multicast_group_for("other_group"); - assert_ne!(group, group3); - // ff12:0:d70b:fb1c:16e4:5e39:485e:31e1. - assert_eq!(group.segments()[3], 0xfb1c); - assert_eq!(group.segments()[4], 0x16e4); - assert_eq!(group.segments()[5], 0x5e39); - assert_eq!(group.segments()[6], 0x485e); - assert_eq!(group.segments()[7], 0x31e1); - } - - #[test] - fn multicast_join_candidates_retries_unchanged_missing_membership() { - let en0_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1); - let en1_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2); - let link_locals = vec![ - ("en0".to_string(), en0_addr, 4), - ("en1".to_string(), en1_addr, 7), - ]; - let joined = HashSet::from([("en0".to_string(), 4)]); - - assert_eq!( - multicast_join_candidates(&link_locals, &joined), - vec![("en1".to_string(), en1_addr, 7)] - ); - assert_eq!( - multicast_join_candidates(&link_locals, &HashSet::new()), - link_locals - ); - } - - #[test] - fn test_derive_multicast_address_all_scopes() { - // High u16 = 0xff_T_S; bytes 2-13 of SHA-256("reticulum") fill the body. - let body = [0xd70b, 0xfb1c, 0x16e4, 0x5e39, 0x485e, 0x31e1]; - - for (scope, scope_hex) in [ - (DiscoveryScope::Link, 0x2u16), - (DiscoveryScope::Admin, 0x4u16), - (DiscoveryScope::Site, 0x5u16), - (DiscoveryScope::Organisation, 0x8u16), - (DiscoveryScope::Global, 0xeu16), - ] { - for (addr_type, type_hex) in [ - (McastAddrType::Temporary, 0x1u16), - (McastAddrType::Permanent, 0x0u16), - ] { - let group = derive_multicast_address("reticulum", scope, addr_type); - let expected_high = 0xff00 | (type_hex << 4) | scope_hex; - assert_eq!( - group.segments()[0], - expected_high, - "scope {scope:?} type {addr_type:?}" - ); - assert_eq!(group.segments()[1], 0); - for (i, want) in body.iter().enumerate() { - assert_eq!(group.segments()[2 + i], *want); - } - } - } - } - - #[test] - fn test_discovery_scope_parse_roundtrip() { - use std::str::FromStr; - for s in [ - "link", - "admin", - "site", - "organisation", - "organization", - "global", - ] { - let parsed = DiscoveryScope::from_str(s).expect("parse"); - // Round-trip through Display (organization → organisation is fine). - let _back = parsed.to_string(); - } - assert!(DiscoveryScope::from_str("LINK").is_ok()); - assert!(DiscoveryScope::from_str("nonsense").is_err()); - } - - #[test] - fn test_mcast_addr_type_parse_roundtrip() { - use std::str::FromStr; - assert_eq!( - McastAddrType::from_str("temporary").unwrap(), - McastAddrType::Temporary - ); - assert_eq!( - McastAddrType::from_str("temp").unwrap(), - McastAddrType::Temporary - ); - assert_eq!( - McastAddrType::from_str("permanent").unwrap(), - McastAddrType::Permanent - ); - assert_eq!( - McastAddrType::from_str("perm").unwrap(), - McastAddrType::Permanent - ); - assert!(McastAddrType::from_str("nope").is_err()); - } - - #[test] - fn test_beacon_deterministic() { - let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1); - let b1 = make_beacon("reticulum", &addr); - let b2 = make_beacon("reticulum", &addr); - assert_eq!(b1, b2); - assert_eq!(b1.len(), 32); - } - - #[test] - fn test_beacon_auth() { - let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1); - let beacon = make_beacon("reticulum", &addr); - assert!(verify_beacon(&beacon, "reticulum", &addr)); - assert!(!verify_beacon(&beacon, "other_group", &addr)); - let other_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2); - assert!(!verify_beacon(&beacon, "reticulum", &other_addr)); - assert!(!verify_beacon(&beacon[..16], "reticulum", &addr)); - } - - #[test] - fn peer_scope_candidates_preserves_received_scope() { - let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2); - let locals = vec![ - ("en0".to_string(), Ipv6Addr::LOCALHOST, 11), - ("eth0".to_string(), Ipv6Addr::LOCALHOST, 22), - ]; - - let candidates = peer_scope_candidates(peer, 22, &locals); - - assert_eq!(candidates.len(), 1); - assert_eq!(candidates[0].ifname, "eth0"); - assert_eq!(candidates[0].scope_id, 22); - assert_eq!(candidates[0].source, PeerScopeSource::Received); - } - - #[test] - fn peer_scope_candidates_expands_zero_scope_for_link_local() { - let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2); - let locals = vec![ - ("en0".to_string(), Ipv6Addr::LOCALHOST, 11), - ("eth0".to_string(), Ipv6Addr::LOCALHOST, 22), - ("duplicate".to_string(), Ipv6Addr::LOCALHOST, 22), - ]; - - let candidates = peer_scope_candidates(peer, 0, &locals); - - assert_eq!(candidates.len(), 2); - assert_eq!(candidates[0].ifname, "en0"); - assert_eq!(candidates[0].scope_id, 11); - assert_eq!(candidates[0].source, PeerScopeSource::LocalCandidate); - assert_eq!(candidates[1].ifname, "eth0"); - assert_eq!(candidates[1].scope_id, 22); - } - - #[test] - fn upsert_peer_candidates_keys_same_ip_by_scope() { - let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2); - let locals = vec![ - ("en0".to_string(), Ipv6Addr::LOCALHOST, 11), - ("eth0".to_string(), Ipv6Addr::LOCALHOST, 22), - ]; - let mut table = HashMap::new(); - - let inserted = upsert_peer_candidates( - &mut table, - peer, - DATA_PORT, - 0, - &locals, - Instant::now(), - "test", - ); - - assert_eq!(inserted, 2); - assert_eq!(table.len(), 2); - assert!(table.contains_key(&PeerKey { - ip: peer, - scope_id: 11, - })); - assert!(table.contains_key(&PeerKey { - ip: peer, - scope_id: 22, - })); - assert_eq!( - table - .get(&PeerKey { - ip: peer, - scope_id: 11, - }) - .unwrap() - .addr - .scope_id(), - 11 - ); - } - - #[test] - fn test_scope_id_prefers_enumerated_interface_index() { - let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1); - let iface = test_interface("__ratspeak_missing_iface__", addr, Some(1234)); - assert_eq!(iface_scope_id(&iface), 1234); - } - - #[cfg(target_os = "linux")] - #[test] - fn if_addrs_link_local_feature_is_enabled() { - let proc_addrs = std::fs::read_to_string("/proc/net/if_inet6").unwrap_or_default(); - let host_has_link_local = proc_addrs.lines().any(|line| { - line.split_whitespace() - .nth(3) - .is_some_and(|scope| scope.eq_ignore_ascii_case("20")) - }); - if !host_has_link_local { - return; - } - - let addrs = if_addrs::get_if_addrs().expect("list network interfaces"); - assert!( - addrs.iter().any(|iface| { - matches!(&iface.addr, if_addrs::IfAddr::V6(addr) if addr.is_link_local()) - }), - "Linux has link-local IPv6 addresses in /proc/net/if_inet6, but if-addrs returned none; \ - keep the workspace if-addrs dependency feature `link-local` enabled" - ); - } - - fn test_interface(name: &str, ip: Ipv6Addr, index: Option) -> if_addrs::Interface { - let addr = if_addrs::IfAddr::V6(if_addrs::Ifv6Addr { - ip, - netmask: Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0xffff, 0, 0, 0, 0), - prefixlen: 64, - broadcast: None, - }); - - #[cfg(windows)] - { - if_addrs::Interface { - name: name.to_string(), - addr, - index, - adapter_name: name.to_string(), - } - } - #[cfg(not(windows))] - { - if_addrs::Interface { - name: name.to_string(), - addr, - index, - } - } - } - - #[test] - fn test_normalize_link_local_addr_clears_embedded_scope_segment() { - let addr = Ipv6Addr::new(0xfe80, 0x18, 0, 0, 0, 0, 0, 1); - let normalized = normalize_link_local_addr(addr); - assert_eq!(normalized, Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)); - - let global = Ipv6Addr::new(0xfddd, 0xebe4, 0, 0, 0, 0, 0, 1); - assert_eq!(normalize_link_local_addr(global), global); - } - - #[test] - fn test_constants() { - assert_eq!(HW_MTU, 1196); - assert_eq!(DISCOVERY_PORT, 29716); - assert_eq!(DATA_PORT, 42671); - assert_eq!(UNICAST_DISCOVERY_PORT, 29717); - } - - #[test] - fn test_multi_if_dedup() { - let mut dedup = MultiIfDedup::new(); - let data1 = b"packet one"; - let data2 = b"packet two"; - - assert!(!dedup.is_duplicate(data1)); - assert!(dedup.is_duplicate(data1)); - assert!(!dedup.is_duplicate(data2)); - } - - #[test] - fn test_dedup_max_capacity() { - let mut dedup = MultiIfDedup::new(); - for i in 0..MULTI_IF_DEQUE_LEN + 10 { - let data = format!("packet_{}", i); - assert!(!dedup.is_duplicate(data.as_bytes())); - } - assert!(dedup.deque.len() <= MULTI_IF_DEQUE_LEN); - } - - #[test] - fn test_reverse_peering_interval() { - let expected = BEACON_INTERVAL * 3.25; - assert!((REVERSE_PEERING_INTERVAL - expected).abs() < 0.001); - } -} diff --git a/crates/rns-interface/src/auto/mod.rs b/crates/rns-interface/src/auto/mod.rs new file mode 100644 index 0000000..4cc7ac1 --- /dev/null +++ b/crates/rns-interface/src/auto/mod.rs @@ -0,0 +1,1191 @@ +//! AutoInterface: zero-configuration peering over IPv6 link-local multicast, +//! ported from `RNS/Interfaces/AutoInterface.py`. +//! +//! Every adopted NIC gets a multicast discovery socket, a unicast discovery +//! socket and a data socket bound to its link-local address. Each discovered +//! peer is spawned as its own `AutoInterfacePeer[/]` child +//! interface that sends only to that peer; the parent interface itself never +//! transmits. + +mod netif; +mod peers; + +pub use netif::{NetworkInterfaceInfo, list_network_interfaces}; + +use std::collections::{HashMap, HashSet}; +use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Instant; + +use bytes::Bytes; +use rns_transport::messages::{ + InboundPacket, InterfacePacketCapacity, InterfaceTransportSender, TransportMessage, +}; +use tokio::net::UdpSocket; +use tokio::sync::{broadcast, mpsc}; +use tokio::task::JoinHandle; + +use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode}; +use peers::{ChildLink, Core, Discovered}; + +pub const DISCOVERY_PORT: u16 = 29716; +pub const DATA_PORT: u16 = 42671; +pub const BEACON_INTERVAL: f64 = 1.6; +/// Background beacon interval with feature `mobile-throttle`, in seconds. +pub const BEACON_INTERVAL_BG: f64 = 8.0; +pub const PEERING_TIMEOUT: f64 = 22.0; +pub const PEER_EXPIRY: f64 = PEERING_TIMEOUT; +pub const HW_MTU: u32 = 1196; +pub const FIXED_MTU: bool = true; +pub const DEFAULT_GROUP_ID: &str = "reticulum"; +pub const UNICAST_DISCOVERY_PORT: u16 = DISCOVERY_PORT + 1; +pub const REVERSE_PEERING_INTERVAL: f64 = BEACON_INTERVAL * 3.25; +pub const PEER_JOB_INTERVAL: f64 = 4.0; +pub const MCAST_ECHO_TIMEOUT: f64 = 6.5; +pub const MULTI_IF_DEQUE_LEN: usize = 48; +pub const MULTI_IF_DEQUE_TTL: f64 = 0.75; +pub const BITRATE_GUESS: u64 = 10_000_000; +/// Peering wait before the interface goes online (`final_init`). +pub const PEERING_WAIT: f64 = BEACON_INTERVAL * 1.2; + +pub const ALL_IGNORE_IFS: &[&str] = &["lo0"]; +pub const DARWIN_IGNORE_IFS: &[&str] = &["awdl0", "llw0", "lo0", "en5"]; +pub const ANDROID_IGNORE_IFS: &[&str] = &[ + "dummy0", "lo", "tun0", "rmnet0", "rmnet1", "rmnet2", "rmnet3", "rmnet4", "rmnet5", "rmnet6", + "rmnet7", +]; + +/// `Interface.bitrate` default, kept when no NIC could be adopted. +const UNCONFIGURED_BITRATE: u64 = 62_500; +const DATA_BUFFER: usize = 8192; +const DISCOVERY_BUFFER: usize = 1024; + +/// The platform classes AutoInterface treats differently. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AutoPlatform { + Darwin, + Android, + Other, +} + +impl AutoPlatform { + pub const CURRENT: Self = if cfg!(target_os = "android") { + Self::Android + } else if cfg!(any(target_os = "macos", target_os = "ios")) { + Self::Darwin + } else { + Self::Other + }; +} + +/// Whether a system interface is considered for adoption, given the +/// `devices` allow-list and `ignored_devices`. +pub fn interface_selectable( + platform: AutoPlatform, + ifname: &str, + devices: Option<&[String]>, + ignored_devices: &[String], +) -> bool { + let allowed = devices.unwrap_or(&[]); + let explicitly_allowed = allowed.iter().any(|d| d == ifname); + if platform == AutoPlatform::Darwin + && DARWIN_IGNORE_IFS.contains(&ifname) + && !explicitly_allowed + { + return false; + } + if platform == AutoPlatform::Darwin && ifname == "lo0" { + return false; + } + if platform == AutoPlatform::Android + && ANDROID_IGNORE_IFS.contains(&ifname) + && !explicitly_allowed + { + return false; + } + if ignored_devices.iter().any(|d| d == ifname) || ALL_IGNORE_IFS.contains(&ifname) { + return false; + } + allowed.is_empty() || explicitly_allowed +} + +/// Seconds without a beacon or data before a peer is removed. +pub fn peering_timeout(platform: AutoPlatform) -> f64 { + if platform == AutoPlatform::Android { + // Low-power modes on many Android chipsets delay beacons. + PEER_EXPIRY * 1.25 + } else { + PEERING_TIMEOUT + } +} + +/// IPv6 multicast scope (RFC 4291 §2.7), the low nibble of the `ffTS:` byte. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DiscoveryScope { + Link, + Admin, + Site, + Organisation, + Global, +} + +impl DiscoveryScope { + pub const fn as_hex_nibble(self) -> u8 { + match self { + Self::Link => 0x2, + Self::Admin => 0x4, + Self::Site => 0x5, + Self::Organisation => 0x8, + Self::Global => 0xe, + } + } +} + +impl std::str::FromStr for DiscoveryScope { + type Err = String; + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "link" => Ok(Self::Link), + "admin" => Ok(Self::Admin), + "site" => Ok(Self::Site), + "organisation" => Ok(Self::Organisation), + "global" => Ok(Self::Global), + _ => Err(format!("unknown discovery scope: {s}")), + } + } +} + +impl std::fmt::Display for DiscoveryScope { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Link => "link", + Self::Admin => "admin", + Self::Site => "site", + Self::Organisation => "organisation", + Self::Global => "global", + }) + } +} + +/// IPv6 multicast transient/permanent flag (RFC 4291 §2.7), the high nibble +/// of the `ffTS:` byte. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum McastAddrType { + Temporary, + Permanent, +} + +impl McastAddrType { + pub const fn as_hex_nibble(self) -> u8 { + match self { + Self::Temporary => 0x1, + Self::Permanent => 0x0, + } + } + + /// `permanent` (any case) selects Permanent; every other value Temporary. + pub fn parse(value: &str) -> Self { + if value.to_lowercase() == "permanent" { + Self::Permanent + } else { + Self::Temporary + } + } +} + +impl std::str::FromStr for McastAddrType { + type Err = std::convert::Infallible; + fn from_str(s: &str) -> Result { + Ok(Self::parse(s)) + } +} + +impl std::fmt::Display for McastAddrType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Temporary => "temporary", + Self::Permanent => "permanent", + }) + } +} + +/// Async events from AutoInterface instances for embedding applications. +#[derive(Debug, Clone, serde::Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum AutoInterfaceEvent { + /// `IPV6_JOIN_GROUP` was rejected by the OS. `reason` contains the reported + /// error; this event alone does not establish a permission or network cause. + JoinFailed { + interface_name: String, + ifname: String, + reason: String, + }, + /// The multicast echo state of `ifname` changed. `ok=false` means none of + /// our own beacons came back within `MCAST_ECHO_TIMEOUT`. + CarrierState { + interface_name: String, + ifname: String, + ok: bool, + reason: String, + }, +} + +static AUTO_EVENT_TX: OnceLock> = OnceLock::new(); + +/// Subscribe to `AutoInterfaceEvent`s emitted by any AutoInterface in this +/// process. Channel is lazy-created; lagged subscribers see `RecvError::Lagged`. +pub fn subscribe_auto_events() -> broadcast::Receiver { + AUTO_EVENT_TX + .get_or_init(|| { + let (tx, _rx) = broadcast::channel(64); + tx + }) + .subscribe() +} + +fn dispatch_auto_event(event: AutoInterfaceEvent) { + if let Some(tx) = AUTO_EVENT_TX.get() { + let _ = tx.send(event); + } +} + +#[derive(Debug, Clone)] +pub struct AutoInterfaceConfig { + pub name: String, + pub group_id: String, + pub discovery_scope: DiscoveryScope, + pub discovery_port: u16, + pub data_port: u16, + pub multicast_address_type: McastAddrType, + /// Allow-list of NIC names; `None` or empty allows every NIC. + pub devices: Option>, + /// NIC names never adopted. + pub ignored_devices: Vec, + /// Reticulum's `configured_bitrate` (a `bitrate` of at least + /// `MINIMUM_BITRATE`); `None` uses `BITRATE_GUESS`. + pub configured_bitrate: Option, + pub mode: InterfaceMode, +} + +impl Default for AutoInterfaceConfig { + fn default() -> Self { + Self { + name: "AutoInterface".to_string(), + group_id: DEFAULT_GROUP_ID.to_string(), + discovery_scope: DiscoveryScope::Link, + discovery_port: DISCOVERY_PORT, + data_port: DATA_PORT, + multicast_address_type: McastAddrType::Temporary, + devices: None, + ignored_devices: Vec::new(), + configured_bitrate: None, + mode: InterfaceMode::Full, + } + } +} + +#[derive(Debug, Clone)] +struct DeduplicateEntry { + hash: [u8; 32], + timestamp: Instant, +} + +/// Dedupes packets seen on multiple NICs at once (e.g. WLAN + wired). +#[derive(Debug, Clone)] +pub struct MultiIfDedup { + deque: std::collections::VecDeque, + max_len: usize, + ttl_secs: f64, +} + +impl MultiIfDedup { + pub fn new() -> Self { + Self { + deque: std::collections::VecDeque::with_capacity(MULTI_IF_DEQUE_LEN), + max_len: MULTI_IF_DEQUE_LEN, + ttl_secs: MULTI_IF_DEQUE_TTL, + } + } + + /// Return whether this packet hash is still in the bounded TTL cache. New + /// hashes are recorded; a duplicate does not refresh its timestamp. + pub fn is_duplicate(&mut self, data: &[u8]) -> bool { + let hash = rns_crypto::sha::sha256(data); + let now = Instant::now(); + + while let Some(front) = self.deque.front() { + if now.duration_since(front.timestamp).as_secs_f64() > self.ttl_secs { + self.deque.pop_front(); + } else { + break; + } + } + + if self.deque.iter().any(|entry| entry.hash == hash) { + return true; + } + + if self.deque.len() >= self.max_len { + self.deque.pop_front(); + } + self.deque.push_back(DeduplicateEntry { + hash, + timestamp: now, + }); + + false + } +} + +impl Default for MultiIfDedup { + fn default() -> Self { + Self::new() + } +} + +/// `SHA-256(group_id || address string)`: the discovery token a node with +/// link-local address `addr` sends. +pub fn discovery_token(group_id: &str, addr: &Ipv6Addr) -> [u8; 32] { + let mut input = group_id.as_bytes().to_vec(); + input.extend_from_slice(addr.to_string().as_bytes()); + rns_crypto::sha::sha256(&input) +} + +/// Compare the first 32 bytes of a discovery packet with the token expected +/// from `peer_addr`. Shorter packets fail; trailing bytes are ignored. +pub fn verify_beacon(beacon: &[u8], group_id: &str, peer_addr: &Ipv6Addr) -> bool { + beacon.len() >= 32 && beacon[..32] == discovery_token(group_id, peer_addr) +} + +/// The name of the child interface spawned for a peer. +pub fn peer_interface_name(ifname: &str, addr: &Ipv6Addr) -> String { + format!("AutoInterfacePeer[{ifname}/{addr}]") +} + +/// Derive `ffTS:0:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX` from the address-type nibble, +/// the scope nibble and bytes 2..14 of `SHA-256(group_id)`. +pub fn derive_multicast_address( + group_id: &str, + scope: DiscoveryScope, + addr_type: McastAddrType, +) -> Ipv6Addr { + let hash = rns_crypto::sha::sha256(group_id.as_bytes()); + let high = + 0xff00u16 | ((addr_type.as_hex_nibble() as u16) << 4) | (scope.as_hex_nibble() as u16); + Ipv6Addr::new( + high, + 0, + u16::from_be_bytes([hash[2], hash[3]]), + u16::from_be_bytes([hash[4], hash[5]]), + u16::from_be_bytes([hash[6], hash[7]]), + u16::from_be_bytes([hash[8], hash[9]]), + u16::from_be_bytes([hash[10], hash[11]]), + u16::from_be_bytes([hash[12], hash[13]]), + ) +} + +/// `Link` scope + `Temporary` address type (Python's defaults). +pub fn multicast_group_for(group_id: &str) -> Ipv6Addr { + derive_multicast_address(group_id, DiscoveryScope::Link, McastAddrType::Temporary) +} + +/// One NIC as enumerated: the address it is adopted with (the last +/// link-local listed, as upstream selects) and all of its link-locals. +#[derive(Debug, Clone, PartialEq, Eq)] +struct NicAddrs { + ifname: String, + link_local: Ipv6Addr, + all: Vec, + scope_id: u32, +} + +fn group_link_locals(addrs: Vec<(String, Ipv6Addr, u32)>) -> Vec { + let mut nics: Vec = Vec::new(); + for (ifname, addr, scope_id) in addrs { + match nics.iter_mut().find(|n| n.ifname == ifname) { + Some(nic) => { + nic.link_local = addr; + nic.all.push(addr); + } + None => nics.push(NicAddrs { + ifname, + link_local: addr, + all: vec![addr], + scope_id, + }), + } + } + nics +} + +enum NicError { + Discovery(std::io::Error), + Data(std::io::Error), +} + +/// Sockets and tasks of one adopted NIC; dropping it closes them. +struct NicHandle { + link_local: Ipv6Addr, + scope_id: u32, + tasks: Vec>, +} + +impl Drop for NicHandle { + fn drop(&mut self) { + for task in &self.tasks { + task.abort(); + } + } +} + +fn udp_socket_v6(reuse: bool) -> std::io::Result { + use socket2::{Domain, Protocol, Socket, Type}; + let sock = Socket::new(Domain::IPV6, Type::DGRAM, Some(Protocol::UDP))?; + if reuse { + sock.set_reuse_address(true)?; + #[cfg(unix)] + sock.set_reuse_port(true)?; + } + sock.set_only_v6(true)?; + sock.set_nonblocking(true)?; + Ok(sock) +} + +fn into_tokio(sock: socket2::Socket) -> std::io::Result { + UdpSocket::from_std(sock.into()) +} + +fn bind_udp(addr: SocketAddrV6, reuse: bool) -> std::io::Result { + let sock = udp_socket_v6(reuse)?; + sock.bind(&SocketAddr::V6(addr).into())?; + into_tokio(sock) +} + +/// Windows rejects binding to a link-local or multicast address, so upstream +/// binds the discovery sockets to the unspecified address there. +fn discovery_bind_addr(addr: Ipv6Addr, port: u16, scope_id: u32) -> SocketAddrV6 { + if cfg!(windows) { + SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, port, 0, 0) + } else { + SocketAddrV6::new(addr, port, 0, scope_id) + } +} + +struct Shared { + id: InterfaceId, + name: String, + mode: InterfaceMode, + group_id: String, + mcast_group: Ipv6Addr, + discovery_scope: DiscoveryScope, + discovery_port: u16, + unicast_discovery_port: u16, + data_port: u16, + devices: Option>, + ignored_devices: Vec, + peering_timeout: f64, + bitrate: AtomicU64, + online: Arc, + final_init_done: AtomicBool, + rxb: Arc, + txb: Arc, + core: Mutex, + nics: Mutex>, + failed_nics: Mutex>, + id_gen: Arc, + parent: InterfaceTransportSender, + actor_tx: mpsc::Sender, + handle_tx: mpsc::Sender, + outbound: Arc, + is_foreground: Arc, +} + +impl std::fmt::Display for Shared { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "AutoInterface[{}]", self.name) + } +} + +impl Shared { + #[allow(clippy::too_many_arguments)] + fn new( + config: AutoInterfaceConfig, + id: InterfaceId, + id_gen: Arc, + actor_tx: mpsc::Sender, + handle_tx: mpsc::Sender, + is_foreground: Arc, + outbound: UdpSocket, + ) -> Self { + Self { + id, + mcast_group: derive_multicast_address( + &config.group_id, + config.discovery_scope, + config.multicast_address_type, + ), + name: config.name, + mode: config.mode, + group_id: config.group_id, + discovery_scope: config.discovery_scope, + discovery_port: config.discovery_port, + unicast_discovery_port: config.discovery_port.wrapping_add(1), + data_port: config.data_port, + devices: config.devices, + ignored_devices: config.ignored_devices, + peering_timeout: peering_timeout(AutoPlatform::CURRENT), + bitrate: AtomicU64::new(UNCONFIGURED_BITRATE), + online: Arc::new(AtomicBool::new(false)), + final_init_done: AtomicBool::new(false), + rxb: Arc::new(AtomicU64::new(0)), + txb: Arc::new(AtomicU64::new(0)), + core: Mutex::new(Core::default()), + nics: Mutex::new(HashMap::new()), + failed_nics: Mutex::new(HashSet::new()), + id_gen, + parent: InterfaceTransportSender::new(id, actor_tx.clone()), + actor_tx, + handle_tx, + outbound: Arc::new(outbound), + is_foreground, + } + } + + fn core(&self) -> std::sync::MutexGuard<'_, Core> { + self.core.lock().expect("auto core mutex poisoned") + } + + fn enumerate(&self) -> Vec { + group_link_locals(netif::get_link_local_addrs( + self.devices.as_deref(), + &self.ignored_devices, + )) + } + + fn running(&self) -> bool { + self.online.load(Ordering::SeqCst) && self.final_init_done.load(Ordering::SeqCst) + } + + /// Open the discovery and data sockets of one NIC, adopt it and start its + /// tasks (AutoInterface.py:253-312, :337-347). + fn start_nic(self: &Arc, nic: &NicAddrs) -> Result { + let (unicast, mcast, beacon) = self.discovery_sockets(nic).map_err(NicError::Discovery)?; + let scope = nic.scope_id; + // A data listener that cannot bind is fatal in upstream's final_init. + let data = bind_udp( + SocketAddrV6::new(nic.link_local, self.data_port, 0, scope), + false, + ) + .map_err(|e| { + NicError::Data(std::io::Error::new( + e.kind(), + format!( + "data socket bind ({}%{}:{}): {e}", + nic.link_local, nic.ifname, self.data_port + ), + )) + })?; + + self.core() + .adopt(&nic.ifname, nic.link_local, &nic.all, Instant::now()); + tracing::debug!( + iface = %self, + nic = %nic.ifname, + link_local = %nic.link_local, + group = %self.mcast_group, + "adopted system interface" + ); + + let tasks = vec![ + tokio::spawn(self.clone().beacon_loop(beacon, nic.link_local, scope)), + tokio::spawn( + self.clone() + .discovery_loop(mcast, nic.ifname.clone(), scope), + ), + tokio::spawn( + self.clone() + .discovery_loop(unicast, nic.ifname.clone(), scope), + ), + tokio::spawn(self.clone().data_loop(data)), + ]; + Ok(NicHandle { + link_local: nic.link_local, + scope_id: scope, + tasks, + }) + } + + /// Unicast discovery, multicast discovery and beacon sockets of one NIC. + fn discovery_sockets( + &self, + nic: &NicAddrs, + ) -> std::io::Result<(UdpSocket, UdpSocket, UdpSocket)> { + let scope = nic.scope_id; + let unicast = bind_udp( + discovery_bind_addr(nic.link_local, self.unicast_discovery_port, scope), + true, + )?; + + let mcast = udp_socket_v6(true)?; + mcast.set_multicast_if_v6(scope)?; + mcast.join_multicast_v6(&self.mcast_group, scope)?; + let mcast_scope = if self.discovery_scope == DiscoveryScope::Link { + scope + } else { + 0 + }; + mcast.bind( + &SocketAddr::V6(discovery_bind_addr( + self.mcast_group, + self.discovery_port, + mcast_scope, + )) + .into(), + )?; + let mcast = into_tokio(mcast)?; + + let beacon = udp_socket_v6(false)?; + beacon.set_multicast_if_v6(scope)?; + beacon.bind(&SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)).into())?; + Ok((unicast, mcast, into_tokio(beacon)?)) + } + + /// `Ok(false)`: the NIC's discovery sockets failed and it was skipped. + /// `Err`: its data listener could not bind. + fn adopt_nic(self: &Arc, nic: &NicAddrs) -> std::io::Result { + match self.start_nic(nic) { + Ok(handle) => { + self.failed_nics + .lock() + .expect("auto failed-nic mutex poisoned") + .remove(&nic.ifname); + self.nics + .lock() + .expect("auto nic mutex poisoned") + .insert(nic.ifname.clone(), handle); + Ok(true) + } + Err(NicError::Data(e)) => { + self.core().release(&nic.ifname); + Err(e) + } + Err(NicError::Discovery(e)) => { + self.core().release(&nic.ifname); + let first = self + .failed_nics + .lock() + .expect("auto failed-nic mutex poisoned") + .insert(nic.ifname.clone()); + if first { + tracing::error!( + "Could not configure the system interface {} for use with {}, skipping it. The contained exception was: {}", + nic.ifname, + self, + e + ); + if e.kind() == std::io::ErrorKind::PermissionDenied { + dispatch_auto_event(AutoInterfaceEvent::JoinFailed { + interface_name: self.name.clone(), + ifname: nic.ifname.clone(), + reason: format!("os_permission_denied: {e}"), + }); + } + } + Ok(false) + } + } + } + + fn beacon_interval(&self) -> f64 { + #[cfg(feature = "mobile-throttle")] + if !self.is_foreground.load(Ordering::Relaxed) { + return BEACON_INTERVAL_BG; + } + let _ = &self.is_foreground; + BEACON_INTERVAL + } + + fn reverse_peering_interval(&self) -> f64 { + self.beacon_interval() * 3.25 + } + + /// `announce_handler` / `peer_announce` (AutoInterface.py:485-520). + async fn beacon_loop(self: Arc, sock: UdpSocket, link_local: Ipv6Addr, scope: u32) { + let token = discovery_token(&self.group_id, &link_local); + let dest = SocketAddrV6::new(self.mcast_group, self.discovery_port, 0, scope); + loop { + if let Err(e) = sock.send_to(&token, dest).await { + tracing::warn!( + "{} Detected possible carrier loss on scope {}: {}", + self, + scope, + e + ); + } + tokio::time::sleep(std::time::Duration::from_secs_f64(self.beacon_interval())).await; + } + } + + /// `discovery_handler` (AutoInterface.py:358-374). + async fn discovery_loop(self: Arc, sock: UdpSocket, ifname: String, scope: u32) { + let mut buf = [0u8; DISCOVERY_BUFFER]; + loop { + match sock.recv_from(&mut buf).await { + Ok((n, SocketAddr::V6(src))) => { + self.on_discovery(&buf[..n], *src.ip(), &ifname, scope) + .await; + } + Ok(_) => {} + Err(e) => { + tracing::debug!(iface = %self, nic = %ifname, error = %e, "discovery receive error"); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + } + } + } + + async fn on_discovery(self: &Arc, data: &[u8], src: Ipv6Addr, ifname: &str, scope: u32) { + if !self.final_init_done.load(Ordering::SeqCst) || data.is_empty() { + return; + } + if !verify_beacon(data, &self.group_id, &src) { + tracing::debug!( + "{} received peering packet on {} from {}, but authentication hash was incorrect.", + self, + ifname, + src + ); + return; + } + // Children inherit the parent's registration (IFAC, ingress control). + if !self.parent.ready().await { + return; + } + self.add_peer(src, ifname, scope).await; + } + + /// `add_peer` (AutoInterface.py:526-607). + async fn add_peer(self: &Arc, addr: Ipv6Addr, ifname: &str, scope: u32) { + let outcome = self.core().discovered(addr, ifname, scope, Instant::now()); + match outcome { + Discovered::Echo(_) | Discovered::Refreshed => {} + Discovered::UnexpectedEcho => { + tracing::warn!( + "{} received multicast echo on unexpected interface {}", + self, + ifname + ); + } + Discovered::Added => { + let (handle, link) = self.spawn_child(addr, ifname, scope); + let child_id = link.id; + if let Ok(Some(stale)) | Err(stale) = self.core().attach(addr, link) { + stale.online.store(false, Ordering::SeqCst); + } + if crate::traits::handoff_accepted_interface(&self.handle_tx, handle) + .await + .is_err() + { + self.core().clear_child(addr, child_id); + return; + } + tracing::debug!("{} added peer {} on {}", self, addr, ifname); + } + } + } + + /// An `AutoInterfacePeer` for one peer: it sends only to that peer and + /// receives what the parent's data sockets accept from it. + fn spawn_child( + &self, + addr: Ipv6Addr, + ifname: &str, + scope: u32, + ) -> (InterfaceHandle, ChildLink) { + let id = self.id_gen.fetch_add(1, Ordering::SeqCst); + let sender = InterfaceTransportSender::new(id, self.actor_tx.clone()); + let owner = sender.owner(); + let online = Arc::new(AtomicBool::new(true)); + let rxb = Arc::new(AtomicU64::new(0)); + let txb = Arc::new(AtomicU64::new(0)); + let (tx, out_rx) = mpsc::channel::(256); + let (in_tx, in_rx) = mpsc::channel::(256); + let name = peer_interface_name(ifname, &addr); + let read_task = tokio::spawn(child_task(ChildTask { + id, + name: name.clone(), + sender, + online: online.clone(), + dest: SocketAddrV6::new(addr, self.data_port, 0, scope), + outbound: self.outbound.clone(), + txb: txb.clone(), + parent_txb: self.txb.clone(), + in_rx, + out_rx, + })); + let handle = InterfaceHandle { + id, + owner, + packet_capacity: InterfacePacketCapacity::new(HW_MTU, HW_MTU, FIXED_MTU), + parent_id: Some(self.id), + name, + mode: self.mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate: self.bitrate.load(Ordering::SeqCst), + mtu: HW_MTU, + online: online.clone(), + rxb: Some(rxb.clone()), + txb: Some(txb), + inspection: None, + tx, + read_task, + }; + ( + handle, + ChildLink { + id, + inbound: in_tx, + online, + rxb, + }, + ) + } + + /// The data listener's `process_incoming` (AutoInterface.py:613-615). + async fn data_loop(self: Arc, sock: UdpSocket) { + let mut buf = vec![0u8; DATA_BUFFER]; + loop { + match sock.recv_from(&mut buf).await { + Ok((n, SocketAddr::V6(src))) if n > 0 => self.on_data(&buf[..n], *src.ip()), + Ok(_) => {} + Err(e) => { + tracing::debug!(iface = %self, error = %e, "data receive error"); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + } + } + } + + fn on_data(&self, data: &[u8], src: Ipv6Addr) { + if !self.running() { + return; + } + let Some(child) = self.core().inbound(src, data, Instant::now()) else { + return; + }; + self.rxb.fetch_add(data.len() as u64, Ordering::Relaxed); + child.rxb.fetch_add(data.len() as u64, Ordering::Relaxed); + if child + .inbound + .try_send(Bytes::copy_from_slice(data)) + .is_err() + { + tracing::debug!(iface = %self, peer = %src, "peer inbound queue full; dropping packet"); + } + } + + /// `peer_jobs` (AutoInterface.py:376-483). + async fn run_jobs(self: Arc) { + loop { + tokio::time::sleep(std::time::Duration::from_secs_f64(PEER_JOB_INTERVAL)).await; + if self.final_init_done.load(Ordering::SeqCst) && !self.online.load(Ordering::SeqCst) { + break; + } + let now = Instant::now(); + self.expire_peers(now); + self.reverse_peering(now).await; + self.refresh_nics(); + self.check_echoes(now); + } + } + + fn expire_peers(&self, now: Instant) { + let expired = self.core().expire(now, self.peering_timeout); + for (addr, peer) in expired { + if let Some(child) = peer.child { + child.online.store(false, Ordering::SeqCst); + } + tracing::debug!("{} removed peer {} on {}", self, addr, peer.ifname); + } + } + + async fn reverse_peering(&self, now: Instant) { + let due = self + .core() + .reverse_due(now, self.reverse_peering_interval()); + for (addr, ifname, scope) in due { + let Some(link_local) = self.core().adopted(&ifname) else { + continue; + }; + let token = discovery_token(&self.group_id, &link_local); + let dest = SocketAddrV6::new(addr, self.unicast_discovery_port, 0, scope); + if let Err(e) = self.outbound.send_to(&token, dest).await { + tracing::error!( + "Could not send reverse peering packet to {} on {}: {}", + addr, + ifname, + e + ); + } + } + } + + /// Re-read the link-local addresses. A changed address restarts that + /// NIC's sockets, as upstream restarts its data listener; NICs that + /// appear or vanish after startup are adopted or released. + fn refresh_nics(self: &Arc) { + let current = self.enumerate(); + let mut restart = Vec::new(); + { + let mut nics = self.nics.lock().expect("auto nic mutex poisoned"); + let mut released = Vec::new(); + for (ifname, handle) in nics.iter() { + match current.iter().find(|n| &n.ifname == ifname) { + None => released.push(ifname.clone()), + Some(nic) + if nic.link_local != handle.link_local + || nic.scope_id != handle.scope_id => + { + tracing::debug!( + "Replacing link-local address {} for {} with {}", + handle.link_local, + ifname, + nic.link_local + ); + released.push(ifname.clone()); + restart.push(nic.clone()); + } + Some(_) => {} + } + } + for ifname in released { + nics.remove(&ifname); + self.core().release(&ifname); + } + for nic in ¤t { + if !nics.contains_key(&nic.ifname) && !restart.contains(nic) { + restart.push(nic.clone()); + } + } + } + for nic in restart { + if let Err(e) = self.adopt_nic(&nic) { + tracing::warn!("Could not start new UDP listener for {}: {}", self, e); + } + } + } + + fn check_echoes(&self, now: Instant) { + let mut core = self.core(); + for ifname in core.adopted_ifnames() { + let timed_out = core + .last_echo(&ifname) + .is_none_or(|t| now.duration_since(t).as_secs_f64() > MCAST_ECHO_TIMEOUT); + let previous = core.set_timed_out(&ifname, timed_out); + if timed_out && previous == Some(false) { + tracing::warn!("Multicast echo timeout for {}. Carrier lost.", ifname); + } else if !timed_out && previous == Some(true) { + tracing::warn!("{} Carrier recovered on {}", self, ifname); + } + if previous != Some(timed_out) { + dispatch_auto_event(AutoInterfaceEvent::CarrierState { + interface_name: self.name.clone(), + ifname: ifname.clone(), + ok: !timed_out, + reason: if timed_out { + format!("no multicast echo for more than {MCAST_ECHO_TIMEOUT}s") + } else { + "multicast echo within timeout".to_string() + }, + }); + } + if !core.echo_received(&ifname) { + tracing::error!( + "{} No multicast echoes received on {}. The networking hardware or a firewall may be blocking multicast traffic.", + self, + ifname + ); + } + } + } +} + +struct ChildTask { + id: InterfaceId, + name: String, + sender: InterfaceTransportSender, + online: Arc, + dest: SocketAddrV6, + outbound: Arc, + txb: Arc, + parent_txb: Arc, + in_rx: mpsc::Receiver, + out_rx: mpsc::Receiver, +} + +/// `AutoInterfacePeer.process_incoming` / `process_outgoing` +/// (AutoInterface.py:652-681). Ends, and deregisters the child, once the +/// parent drops the peer or transport drops the child. +async fn child_task(mut task: ChildTask) { + loop { + tokio::select! { + biased; + inbound = task.in_rx.recv() => { + let Some(raw) = inbound else { break }; + let message = TransportMessage::Inbound(InboundPacket { + raw, + interface_id: task.id, + rssi: None, + snr: None, + q: None, + }); + if task.sender.send(message).await.is_err() { + break; + } + } + outbound = task.out_rx.recv() => { + let Some(data) = outbound else { break }; + if !task.online.load(Ordering::SeqCst) { + continue; + } + match task.outbound.send_to(&data, task.dest).await { + Ok(_) => { + task.txb.fetch_add(data.len() as u64, Ordering::Relaxed); + task.parent_txb.fetch_add(data.len() as u64, Ordering::Relaxed); + } + Err(e) => tracing::error!( + "Could not transmit on {}. The contained exception was: {}", + task.name, + e + ), + } + } + } + } + task.online.store(false, Ordering::SeqCst); + tracing::debug!("The interface {} is being torn down.", task.name); + let _ = task + .sender + .send(TransportMessage::DeregisterInterface { id: task.id }) + .await; +} + +/// `detach` (AutoInterface.py:619-632): closes every socket, stops every +/// task and takes the spawned peers down with the parent. +struct Teardown { + shared: Arc, + jobs: Option>, +} + +impl Drop for Teardown { + fn drop(&mut self) { + self.shared.online.store(false, Ordering::SeqCst); + if let Some(jobs) = self.jobs.take() { + jobs.abort(); + } + let nics = std::mem::take(&mut *self.shared.nics.lock().expect("auto nic mutex poisoned")); + drop(nics); + for child in self.shared.core().drain_children() { + child.online.store(false, Ordering::SeqCst); + } + } +} + +/// Spawn an AutoInterface. Peers discovered later are spawned as child +/// interfaces (with `parent_id` set to `id`, ids taken from `id_gen`) and +/// delivered on `handle_tx` for registration. +/// +/// Like upstream's `final_init`, this returns only after the peering wait +/// (`PEERING_WAIT`), and the interface is online from then on. +pub async fn spawn_auto_interface( + config: AutoInterfaceConfig, + id: InterfaceId, + id_gen: Arc, + transport_tx: mpsc::Sender, + handle_tx: mpsc::Sender, + is_foreground: Arc, +) -> Result { + let outbound = bind_udp(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0), false)?; + let configured_bitrate = config.configured_bitrate; + let shared = Arc::new(Shared::new( + config, + id, + id_gen, + transport_tx, + handle_tx, + is_foreground, + outbound, + )); + let owner = shared.parent.owner(); + let mut teardown = Teardown { + shared: shared.clone(), + jobs: None, + }; + + let mut suitable = 0usize; + for nic in shared.enumerate() { + if shared.adopt_nic(&nic)? { + suitable += 1; + } + } + let bitrate = if suitable == 0 { + tracing::warn!( + "{} could not autoconfigure. This interface currently provides no connectivity.", + shared + ); + UNCONFIGURED_BITRATE + } else { + configured_bitrate.unwrap_or(BITRATE_GUESS) + }; + shared.bitrate.store(bitrate, Ordering::SeqCst); + + teardown.jobs = Some(tokio::spawn(shared.clone().run_jobs())); + tracing::info!( + "{} discovering peers for {} seconds...", + shared, + (PEERING_WAIT * 100.0).round() / 100.0 + ); + tokio::time::sleep(std::time::Duration::from_secs_f64(PEERING_WAIT)).await; + shared.online.store(true, Ordering::SeqCst); + shared.final_init_done.store(true, Ordering::SeqCst); + + // The parent never transmits (`process_outgoing` is a no-op); its queue + // closing means transport dropped it, which detaches the interface. + let (tx, mut rx) = mpsc::channel::(64); + let read_task = tokio::spawn(async move { + let _teardown = teardown; + while rx.recv().await.is_some() {} + }); + + Ok(InterfaceHandle { + id, + owner, + packet_capacity: InterfacePacketCapacity::new(HW_MTU, HW_MTU, FIXED_MTU), + parent_id: None, + name: shared.name.clone(), + mode: shared.mode, + direction: InterfaceDirection { + inbound: true, + outbound: true, + forward: false, + repeat: false, + }, + bitrate, + mtu: HW_MTU, + online: shared.online.clone(), + rxb: Some(shared.rxb.clone()), + txb: Some(shared.txb.clone()), + inspection: None, + tx, + read_task, + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/rns-interface/src/auto/netif.rs b/crates/rns-interface/src/auto/netif.rs new file mode 100644 index 0000000..43cee8a --- /dev/null +++ b/crates/rns-interface/src/auto/netif.rs @@ -0,0 +1,537 @@ +//! Host NIC enumeration for AutoInterface. + +use std::net::Ipv6Addr; + +use super::{AutoPlatform, interface_selectable}; + +/// One enumerated host NIC, returned by [`list_network_interfaces`]. +#[derive(Debug, Clone, serde::Serialize)] +pub struct NetworkInterfaceInfo { + pub name: String, + pub addr_v4: Option, + pub addr_v6_link_local: Option, + pub is_up: bool, + pub is_loopback: bool, +} + +/// Enumerate addresses reported by the host and group them by NIC name, +/// including loopback and normally ignored names. Callers apply filters. +/// `is_up` means an address was found; it is not a carrier or reachability test. +pub fn list_network_interfaces() -> Result, String> { + use std::collections::BTreeMap; + + let mut by_name: BTreeMap = BTreeMap::new(); + let ifaces = + if_addrs::get_if_addrs().map_err(|e| format!("if_addrs::get_if_addrs() failed: {e}"))?; + for iface in ifaces { + let entry = by_name + .entry(iface.name.clone()) + .or_insert_with(|| NetworkInterfaceInfo { + name: iface.name.clone(), + addr_v4: None, + addr_v6_link_local: None, + is_up: false, + is_loopback: iface.is_loopback(), + }); + entry.is_loopback = entry.is_loopback || iface.is_loopback(); + match iface.addr.ip() { + std::net::IpAddr::V4(v4) => { + if entry.addr_v4.is_none() { + entry.addr_v4 = Some(v4.to_string()); + } + entry.is_up = true; + } + std::net::IpAddr::V6(v6) => { + // fe80::/10 — link-local prefix used by AutoInterface discovery. + if (v6.segments()[0] & 0xffc0) == 0xfe80 && entry.addr_v6_link_local.is_none() { + entry.addr_v6_link_local = Some(v6.to_string()); + } + entry.is_up = true; + } + } + } + + #[cfg(target_os = "macos")] + { + match darwin_link_local_addrs(None, &[], false) { + Ok(addrs) => { + for (name, addr, _) in addrs { + let entry = + by_name + .entry(name.clone()) + .or_insert_with(|| NetworkInterfaceInfo { + name, + addr_v4: None, + addr_v6_link_local: None, + is_up: true, + is_loopback: false, + }); + entry.addr_v6_link_local = Some(addr.to_string()); + entry.is_up = true; + } + } + Err(e) => tracing::debug!(error = %e, "Darwin getifaddrs link-local list failed"), + } + } + + Ok(by_name.into_values().collect()) +} + +/// Clear the scope that BSD kernels embed in the second segment of a +/// link-local address (`descope_linklocal`, AutoInterface.py:80-85). +#[cfg(any(target_os = "macos", test))] +fn normalize_link_local_addr(addr: Ipv6Addr) -> Ipv6Addr { + if (addr.segments()[0] & 0xffc0) != 0xfe80 { + return addr; + } + let mut segments = addr.segments(); + segments[1] = 0; + Ipv6Addr::from(segments) +} + +fn passes_filters( + iface_name: &str, + devices: Option<&[String]>, + ignored_devices: &[String], +) -> bool { + interface_selectable(AutoPlatform::CURRENT, iface_name, devices, ignored_devices) +} + +/// Enumerate link-local IPv6 addresses, applying device/ignore filters. +/// Drops addresses with unresolvable scope id — `scope_id = 0` silently +/// routes via the default NIC, which is wrong on multi-homed hosts. +pub(super) fn get_link_local_addrs( + devices: Option<&[String]>, + ignored_devices: &[String], +) -> Vec<(String, Ipv6Addr, u32)> { + // Android's libc getifaddrs() hides IPv6 link-local from app context; + // must use Java NetworkInterface.getNetworkInterfaces() via JNI. + #[cfg(target_os = "android")] + { + match get_link_local_addrs_android(devices, ignored_devices) { + Ok(v) if !v.is_empty() => { + tracing::info!(count = v.len(), "Android JNI link-local enumerate"); + return v; + } + Ok(_) => { + tracing::warn!( + "Android JNI link-local enumerate returned 0 — falling back to if_addrs" + ); + } + Err(e) => { + tracing::warn!(error = %e, "Android JNI link-local enumerate failed"); + } + } + } + + let mut result = Vec::new(); + match if_addrs::get_if_addrs() { + Ok(ifaces) => { + tracing::debug!(count = ifaces.len(), "if_addrs enumerated interfaces"); + for iface in ifaces { + tracing::debug!(name = %iface.name, addr = ?iface.addr.ip(), "if_addrs entry"); + if !passes_filters(&iface.name, devices, ignored_devices) { + continue; + } + if let std::net::IpAddr::V6(addr) = iface.addr.ip() + && (addr.segments()[0] & 0xffc0) == 0xfe80 + { + let scope_id = iface_scope_id(&iface); + if scope_id == 0 { + tracing::warn!( + iface = %iface.name, + addr = %addr, + "skipping link-local: could not resolve scope id (would send on wrong NIC)" + ); + continue; + } + result.push((iface.name.clone(), addr, scope_id)); + } + } + } + Err(e) => { + tracing::warn!(error = %e, "if_addrs::get_if_addrs() failed"); + } + } + + #[cfg(target_os = "macos")] + if result.is_empty() { + match darwin_link_local_addrs(devices, ignored_devices, true) { + Ok(addrs) if !addrs.is_empty() => { + tracing::debug!( + count = addrs.len(), + "Darwin getifaddrs link-local enumerate" + ); + return addrs; + } + Ok(_) => {} + Err(e) => tracing::warn!(error = %e, "Darwin getifaddrs link-local enumerate failed"), + } + } + + result +} + +#[cfg(target_os = "macos")] +fn darwin_link_local_addrs( + devices: Option<&[String]>, + ignored_devices: &[String], + apply_filters: bool, +) -> Result, String> { + use std::ffi::CStr; + use std::ptr; + + let mut ifap: *mut libc::ifaddrs = ptr::null_mut(); + // SAFETY: getifaddrs initialises `ifap` on success; the linked list is + // released with freeifaddrs before return. + if unsafe { libc::getifaddrs(&mut ifap) } != 0 { + return Err(std::io::Error::last_os_error().to_string()); + } + + struct IfAddrsGuard(*mut libc::ifaddrs); + impl Drop for IfAddrsGuard { + fn drop(&mut self) { + // SAFETY: pointer came from successful getifaddrs and is released once. + unsafe { libc::freeifaddrs(self.0) }; + } + } + let _guard = IfAddrsGuard(ifap); + + let mut result = Vec::new(); + let mut cursor = ifap; + while !cursor.is_null() { + // SAFETY: cursor walks the null-terminated getifaddrs list. + let ifa = unsafe { &*cursor }; + cursor = ifa.ifa_next; + + if ifa.ifa_addr.is_null() || ifa.ifa_name.is_null() { + continue; + } + // SAFETY: getifaddrs provides a nul-terminated interface name. + let name = unsafe { CStr::from_ptr(ifa.ifa_name) } + .to_string_lossy() + .into_owned(); + if apply_filters && !passes_filters(&name, devices, ignored_devices) { + continue; + } + if ifa.ifa_flags & libc::IFF_UP as u32 == 0 { + continue; + } + // SAFETY: ifa_addr is non-null and points to a sockaddr for this entry. + let family = unsafe { (*ifa.ifa_addr).sa_family as i32 }; + if family != libc::AF_INET6 { + continue; + } + + // SAFETY: family is AF_INET6, so sockaddr_in6 layout is valid. + let sin6 = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in6) }; + let addr = normalize_link_local_addr(Ipv6Addr::from(sin6.sin6_addr.s6_addr)); + if (addr.segments()[0] & 0xffc0) != 0xfe80 { + continue; + } + + let scope_id = if sin6.sin6_scope_id != 0 { + sin6.sin6_scope_id + } else { + iface_name_to_scope_id(&name) + }; + if scope_id == 0 { + tracing::warn!( + iface = %name, + addr = %addr, + "skipping Darwin link-local: could not resolve scope id" + ); + continue; + } + if result.iter().any(|(existing, _, _)| existing == &name) { + continue; + } + tracing::debug!(iface = %name, addr = %addr, scope_id, "Darwin link-local found"); + result.push((name, addr, scope_id)); + } + + Ok(result) +} + +#[cfg(target_os = "android")] +fn get_link_local_addrs_android( + devices: Option<&[String]>, + ignored_devices: &[String], +) -> Result, String> { + use jni::objects::JObject; + + let vm = crate::android_usb::java_vm().ok_or("JavaVM not initialized")?; + let env = vm + .attach_current_thread() + .map_err(|e| format!("attach_current_thread: {e}"))?; + + let ni_class = env + .find_class("java/net/NetworkInterface") + .map_err(|e| format!("NetworkInterface class: {e}"))?; + let inet6_class = env + .find_class("java/net/Inet6Address") + .map_err(|e| format!("Inet6Address class: {e}"))?; + + let ifaces_enum = env + .call_static_method( + ni_class, + "getNetworkInterfaces", + "()Ljava/util/Enumeration;", + &[], + ) + .map_err(|e| format!("getNetworkInterfaces: {e}"))? + .l() + .map_err(|e| format!("getNetworkInterfaces obj: {e}"))?; + if ifaces_enum.is_null() { + return Err("getNetworkInterfaces returned null".into()); + } + + let mut result: Vec<(String, Ipv6Addr, u32)> = Vec::new(); + + while env + .call_method(ifaces_enum, "hasMoreElements", "()Z", &[]) + .map_err(|e| format!("hasMoreElements: {e}"))? + .z() + .map_err(|e| format!("hasMoreElements bool: {e}"))? + { + let iface_obj: JObject = env + .call_method(ifaces_enum, "nextElement", "()Ljava/lang/Object;", &[]) + .map_err(|e| format!("nextElement (iface): {e}"))? + .l() + .map_err(|e| format!("nextElement iface obj: {e}"))?; + if iface_obj.is_null() { + continue; + } + + let is_up = env + .call_method(iface_obj, "isUp", "()Z", &[]) + .map_err(|e| format!("isUp: {e}"))? + .z() + .map_err(|e| format!("isUp bool: {e}"))?; + if !is_up { + continue; + } + + let name_obj: JObject = env + .call_method(iface_obj, "getName", "()Ljava/lang/String;", &[]) + .map_err(|e| format!("getName: {e}"))? + .l() + .map_err(|e| format!("getName obj: {e}"))?; + let name: String = if name_obj.is_null() { + String::new() + } else { + env.get_string(name_obj.into()) + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_default() + }; + if !passes_filters(&name, devices, ignored_devices) { + continue; + } + + let scope_id = env + .call_method(iface_obj, "getIndex", "()I", &[]) + .map_err(|e| format!("getIndex: {e}"))? + .i() + .map_err(|e| format!("getIndex int: {e}"))? as u32; + if scope_id == 0 { + tracing::warn!( + iface = %name, + "skipping JNI link-local: getIndex returned 0 (interface may have just gone down)" + ); + continue; + } + + let addrs_enum: JObject = env + .call_method( + iface_obj, + "getInetAddresses", + "()Ljava/util/Enumeration;", + &[], + ) + .map_err(|e| format!("getInetAddresses: {e}"))? + .l() + .map_err(|e| format!("getInetAddresses obj: {e}"))?; + if addrs_enum.is_null() { + continue; + } + + while env + .call_method(addrs_enum, "hasMoreElements", "()Z", &[]) + .map_err(|e| format!("addr hasMoreElements: {e}"))? + .z() + .map_err(|e| format!("addr hasMoreElements bool: {e}"))? + { + let addr_obj: JObject = env + .call_method(addrs_enum, "nextElement", "()Ljava/lang/Object;", &[]) + .map_err(|e| format!("nextElement (addr): {e}"))? + .l() + .map_err(|e| format!("nextElement addr obj: {e}"))?; + if addr_obj.is_null() { + continue; + } + + let is_v6 = env + .is_instance_of(addr_obj, inet6_class) + .map_err(|e| format!("is_instance_of Inet6Address: {e}"))?; + if !is_v6 { + continue; + } + + let is_ll = env + .call_method(addr_obj, "isLinkLocalAddress", "()Z", &[]) + .map_err(|e| format!("isLinkLocalAddress: {e}"))? + .z() + .map_err(|e| format!("isLinkLocalAddress bool: {e}"))?; + if !is_ll { + continue; + } + + let raw_obj: JObject = env + .call_method(addr_obj, "getAddress", "()[B", &[]) + .map_err(|e| format!("getAddress: {e}"))? + .l() + .map_err(|e| format!("getAddress obj: {e}"))?; + if raw_obj.is_null() { + continue; + } + let raw: Vec = env + .convert_byte_array(raw_obj.into_inner()) + .unwrap_or_default(); + if raw.len() != 16 { + continue; + } + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&raw); + let v6 = Ipv6Addr::from(bytes); + tracing::info!(iface = %name, addr = %v6, scope_id, "JNI link-local found"); + result.push((name.clone(), v6, scope_id)); + } + } + + Ok(result) +} + +#[cfg(test)] +pub(super) fn scope_id_of(name: &str) -> u32 { + iface_name_to_scope_id(name) +} + +fn iface_scope_id(iface: &if_addrs::Interface) -> u32 { + if let Some(index) = iface.index { + return index; + } + + #[cfg(windows)] + { + let adapter_index = iface_name_to_scope_id(&iface.adapter_name); + if adapter_index != 0 { + return adapter_index; + } + } + + iface_name_to_scope_id(&iface.name) +} + +/// Convert interface name to scope ID via POSIX/Windows `if_nametoindex`. +/// Returns 0 if the lookup fails; callers must skip the address. +#[cfg(any(unix, windows))] +fn iface_name_to_scope_id(name: &str) -> u32 { + use std::ffi::CString; + if let Ok(cname) = CString::new(name) { + // SAFETY: if_nametoindex takes a NUL-terminated C string and returns + // an index or 0 on error, with no ownership implications. + unsafe { libc_if_nametoindex(cname.as_ptr()) } + } else { + 0 + } +} + +#[cfg(unix)] +unsafe extern "C" { + #[link_name = "if_nametoindex"] + fn libc_if_nametoindex(ifname: *const std::ffi::c_char) -> u32; +} + +#[cfg(windows)] +#[link(name = "iphlpapi")] +unsafe extern "C" { + #[link_name = "if_nametoindex"] + fn libc_if_nametoindex(ifname: *const std::ffi::c_char) -> u32; +} + +#[cfg(not(any(unix, windows)))] +fn iface_name_to_scope_id(_name: &str) -> u32 { + 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_interface(name: &str, ip: Ipv6Addr, index: Option) -> if_addrs::Interface { + let addr = if_addrs::IfAddr::V6(if_addrs::Ifv6Addr { + ip, + netmask: Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0xffff, 0, 0, 0, 0), + prefixlen: 64, + broadcast: None, + }); + + #[cfg(windows)] + { + if_addrs::Interface { + name: name.to_string(), + addr, + index, + adapter_name: name.to_string(), + } + } + #[cfg(not(windows))] + { + if_addrs::Interface { + name: name.to_string(), + addr, + index, + } + } + } + + #[test] + fn scope_id_prefers_enumerated_interface_index() { + let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1); + let iface = test_interface("__ratspeak_missing_iface__", addr, Some(1234)); + assert_eq!(iface_scope_id(&iface), 1234); + } + + #[test] + fn normalize_link_local_addr_clears_embedded_scope_segment() { + let addr = Ipv6Addr::new(0xfe80, 0x18, 0, 0, 0, 0, 0, 1); + assert_eq!( + normalize_link_local_addr(addr), + Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1) + ); + let global = Ipv6Addr::new(0xfddd, 0xebe4, 0, 0, 0, 0, 0, 1); + assert_eq!(normalize_link_local_addr(global), global); + } + + #[cfg(target_os = "linux")] + #[test] + fn if_addrs_link_local_feature_is_enabled() { + let proc_addrs = std::fs::read_to_string("/proc/net/if_inet6").unwrap_or_default(); + let host_has_link_local = proc_addrs.lines().any(|line| { + line.split_whitespace() + .nth(3) + .is_some_and(|scope| scope.eq_ignore_ascii_case("20")) + }); + if !host_has_link_local { + return; + } + let addrs = if_addrs::get_if_addrs().expect("list network interfaces"); + assert!( + addrs.iter().any(|iface| { + matches!(&iface.addr, if_addrs::IfAddr::V6(addr) if addr.is_link_local()) + }), + "Linux has link-local IPv6 addresses in /proc/net/if_inet6, but if-addrs returned none; \ + keep the workspace if-addrs dependency feature `link-local` enabled" + ); + } +} diff --git a/crates/rns-interface/src/auto/peers.rs b/crates/rns-interface/src/auto/peers.rs new file mode 100644 index 0000000..1d4c9ad --- /dev/null +++ b/crates/rns-interface/src/auto/peers.rs @@ -0,0 +1,361 @@ +//! Peer table for AutoInterface (`peers`, `spawned_interfaces`, +//! `multicast_echoes` and `add_peer` in RNS/Interfaces/AutoInterface.py). + +use std::collections::{HashMap, HashSet}; +use std::net::Ipv6Addr; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64}; +use std::time::Instant; + +use bytes::Bytes; +use tokio::sync::mpsc; + +use super::MultiIfDedup; +use crate::traits::InterfaceId; + +/// The spawned `AutoInterfacePeer` registration for one peer. +#[derive(Debug, Clone)] +pub(super) struct ChildLink { + pub id: InterfaceId, + /// Feeds the child's read task, which hands packets to transport. + pub inbound: mpsc::Sender, + pub online: Arc, + pub rxb: Arc, +} + +#[derive(Debug)] +pub(super) struct Peer { + pub ifname: String, + pub scope_id: u32, + pub last_heard: Instant, + pub last_outbound: Instant, + pub child: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Discovered { + /// Our own beacon came back on the named adopted interface. + Echo(String), + /// One of our addresses that no adopted interface currently selects. + UnexpectedEcho, + /// A new peer; the caller spawns its child interface. + Added, + Refreshed, +} + +#[derive(Debug, Default)] +pub(super) struct Core { + peers: HashMap, + adopted: HashMap, + own_addrs: HashMap>, + echoes: HashMap, + initial_echoes: HashSet, + timed_out: HashMap, + dedup: MultiIfDedup, +} + +impl Core { + /// `link_local` is the selected address; `all` lists every link-local + /// address of the interface (`link_local_addresses`). + pub fn adopt(&mut self, ifname: &str, link_local: Ipv6Addr, all: &[Ipv6Addr], now: Instant) { + self.adopted.insert(ifname.to_string(), link_local); + self.own_addrs.insert(ifname.to_string(), all.to_vec()); + self.echoes.insert(ifname.to_string(), now); + } + + pub fn release(&mut self, ifname: &str) { + self.adopted.remove(ifname); + self.own_addrs.remove(ifname); + self.echoes.remove(ifname); + self.initial_echoes.remove(ifname); + self.timed_out.remove(ifname); + } + + pub fn adopted(&self, ifname: &str) -> Option { + self.adopted.get(ifname).copied() + } + + pub fn adopted_ifnames(&self) -> Vec { + self.adopted.keys().cloned().collect() + } + + pub fn last_echo(&self, ifname: &str) -> Option { + self.echoes.get(ifname).copied() + } + + pub fn echo_received(&self, ifname: &str) -> bool { + self.initial_echoes.contains(ifname) + } + + /// Record the echo-timeout state, returning the previous one. + pub fn set_timed_out(&mut self, ifname: &str, timed_out: bool) -> Option { + self.timed_out.insert(ifname.to_string(), timed_out) + } + + /// `add_peer` (AutoInterface.py:526-607): a beacon from `addr` passed the + /// token check on `ifname`. + pub fn discovered( + &mut self, + addr: Ipv6Addr, + ifname: &str, + scope_id: u32, + now: Instant, + ) -> Discovered { + if let Some(own) = self + .adopted + .iter() + .find(|(_, ll)| **ll == addr) + .map(|(name, _)| name.clone()) + { + self.echoes.insert(own.clone(), now); + self.initial_echoes.insert(own.clone()); + return Discovered::Echo(own); + } + if self.own_addrs.values().any(|addrs| addrs.contains(&addr)) { + return Discovered::UnexpectedEcho; + } + if let Some(peer) = self.peers.get_mut(&addr) { + peer.last_heard = now; + return Discovered::Refreshed; + } + self.peers.insert( + addr, + Peer { + ifname: ifname.to_string(), + scope_id, + last_heard: now, + last_outbound: now, + child: None, + }, + ); + Discovered::Added + } + + /// Install the child spawned for a peer, returning any child it replaces. + /// Returns the child back if the peer has gone in the meantime. + pub fn attach( + &mut self, + addr: Ipv6Addr, + child: ChildLink, + ) -> Result, ChildLink> { + match self.peers.get_mut(&addr) { + Some(peer) => Ok(peer.child.replace(child)), + None => Err(child), + } + } + + /// `process_incoming` of the parent and the peer child + /// (AutoInterface.py:613-615, :652-668): only data from a source with a + /// spawned child is delivered, duplicates seen on another NIC within the + /// TTL are dropped, and delivered data refreshes the peer. + pub fn inbound(&mut self, src: Ipv6Addr, data: &[u8], now: Instant) -> Option { + let child = self.peers.get(&src)?.child.as_ref()?; + if !child.online.load(std::sync::atomic::Ordering::SeqCst) { + return None; + } + let child = child.clone(); + if self.dedup.is_duplicate(data) { + return None; + } + if let Some(peer) = self.peers.get_mut(&src) { + peer.last_heard = now; + } + Some(child) + } + + /// Timed-out peers (`peer_jobs`, AutoInterface.py:382-396). + pub fn expire(&mut self, now: Instant, peering_timeout: f64) -> Vec<(Ipv6Addr, Peer)> { + let expired: Vec = self + .peers + .iter() + .filter(|(_, peer)| now.duration_since(peer.last_heard).as_secs_f64() > peering_timeout) + .map(|(addr, _)| *addr) + .collect(); + expired + .into_iter() + .filter_map(|addr| self.peers.remove(&addr).map(|peer| (addr, peer))) + .collect() + } + + /// Peers due a reverse peering beacon (AutoInterface.py:398-408). + pub fn reverse_due(&mut self, now: Instant, interval: f64) -> Vec<(Ipv6Addr, String, u32)> { + let mut due = Vec::new(); + for (addr, peer) in &mut self.peers { + if now.duration_since(peer.last_outbound).as_secs_f64() > interval { + peer.last_outbound = now; + due.push((*addr, peer.ifname.clone(), peer.scope_id)); + } + } + due + } + + /// Drop the child of `addr` if it is still the one with `id`. + pub fn clear_child(&mut self, addr: Ipv6Addr, id: InterfaceId) { + if let Some(peer) = self.peers.get_mut(&addr) + && peer.child.as_ref().is_some_and(|c| c.id == id) + { + peer.child = None; + } + } + + pub fn drain_children(&mut self) -> Vec { + self.peers + .values_mut() + .filter_map(|peer| peer.child.take()) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::Ordering; + use std::time::Duration; + + fn addr(s: &str) -> Ipv6Addr { + s.parse().unwrap() + } + + fn child(id: InterfaceId) -> (ChildLink, mpsc::Receiver) { + let (tx, rx) = mpsc::channel(8); + ( + ChildLink { + id, + inbound: tx, + online: Arc::new(AtomicBool::new(true)), + rxb: Arc::new(AtomicU64::new(0)), + }, + rx, + ) + } + + #[test] + fn own_address_is_an_echo_not_a_peer() { + let mut core = Core::default(); + let now = Instant::now(); + core.adopt("eth0", addr("fe80::1"), &[addr("fe80::1")], now); + assert_eq!( + core.discovered(addr("fe80::1"), "eth0", 2, now), + Discovered::Echo("eth0".into()) + ); + assert!(core.echo_received("eth0")); + assert_eq!(core.peers.len(), 0); + } + + #[test] + fn echo_is_credited_to_the_interface_owning_the_address() { + let mut core = Core::default(); + let now = Instant::now(); + core.adopt("eth0", addr("fe80::1"), &[addr("fe80::1")], now); + core.adopt("wlan0", addr("fe80::2"), &[addr("fe80::2")], now); + assert_eq!( + core.discovered(addr("fe80::2"), "eth0", 2, now), + Discovered::Echo("wlan0".into()) + ); + assert!(!core.echo_received("eth0")); + } + + #[test] + fn secondary_own_address_is_neither_echo_nor_peer() { + let mut core = Core::default(); + let now = Instant::now(); + core.adopt( + "eth0", + addr("fe80::2"), + &[addr("fe80::1"), addr("fe80::2")], + now, + ); + assert_eq!( + core.discovered(addr("fe80::1"), "eth0", 2, now), + Discovered::UnexpectedEcho + ); + assert_eq!(core.peers.len(), 0); + } + + #[test] + fn a_peer_is_keyed_by_address_and_keeps_its_first_interface() { + let mut core = Core::default(); + let now = Instant::now(); + let p = addr("fe80::dead:beef:cafe:1234"); + assert_eq!(core.discovered(p, "eth0", 2, now), Discovered::Added); + assert_eq!(core.discovered(p, "wlan0", 3, now), Discovered::Refreshed); + assert_eq!(core.peers.len(), 1); + assert_eq!(core.peers[&p].ifname, "eth0"); + assert_eq!(core.peers[&p].scope_id, 2); + } + + #[test] + fn data_from_unknown_source_or_childless_peer_is_dropped() { + let mut core = Core::default(); + let now = Instant::now(); + assert!(core.inbound(addr("fe80::9"), b"x", now).is_none()); + let p = addr("fe80::5"); + core.discovered(p, "eth0", 2, now); + assert!(core.inbound(p, b"x", now).is_none()); + } + + #[test] + fn delivered_data_refreshes_the_peer_and_duplicates_do_not() { + let mut core = Core::default(); + let t0 = Instant::now(); + let p = addr("fe80::5"); + core.discovered(p, "eth0", 2, t0); + let (c, _rx) = child(7); + assert!(core.attach(p, c).unwrap().is_none()); + let t1 = t0 + Duration::from_secs(10); + assert_eq!(core.inbound(p, b"one", t1).map(|c| c.id), Some(7)); + assert_eq!(core.peers[&p].last_heard, t1); + let t2 = t1 + Duration::from_millis(100); + assert!(core.inbound(p, b"one", t2).is_none()); + assert_eq!(core.peers[&p].last_heard, t1); + } + + #[test] + fn offline_child_receives_nothing() { + let mut core = Core::default(); + let now = Instant::now(); + let p = addr("fe80::5"); + core.discovered(p, "eth0", 2, now); + let (c, _rx) = child(7); + c.online.store(false, Ordering::SeqCst); + core.attach(p, c).unwrap(); + assert!(core.inbound(p, b"x", now).is_none()); + } + + #[test] + fn peers_expire_strictly_after_the_timeout() { + let mut core = Core::default(); + let t0 = Instant::now(); + let p = addr("fe80::5"); + core.discovered(p, "eth0", 2, t0); + assert!(core.expire(t0 + Duration::from_secs(22), 22.0).is_empty()); + let gone = core.expire(t0 + Duration::from_millis(22_001), 22.0); + assert_eq!(gone.len(), 1); + assert_eq!(core.peers.len(), 0); + } + + #[test] + fn reverse_peering_is_due_after_the_interval_and_then_resets() { + let mut core = Core::default(); + let t0 = Instant::now(); + let p = addr("fe80::5"); + core.discovered(p, "eth0", 2, t0); + assert!( + core.reverse_due(t0 + Duration::from_secs(5), 5.2) + .is_empty() + ); + let t1 = t0 + Duration::from_secs(6); + assert_eq!(core.reverse_due(t1, 5.2), vec![(p, "eth0".to_string(), 2)]); + assert!( + core.reverse_due(t1 + Duration::from_secs(1), 5.2) + .is_empty() + ); + } + + #[test] + fn attach_to_a_forgotten_peer_hands_the_child_back() { + let mut core = Core::default(); + let (c, _rx) = child(3); + assert!(core.attach(addr("fe80::5"), c).is_err()); + } +} diff --git a/crates/rns-interface/src/auto/tests.rs b/crates/rns-interface/src/auto/tests.rs new file mode 100644 index 0000000..c5c01de --- /dev/null +++ b/crates/rns-interface/src/auto/tests.rs @@ -0,0 +1,394 @@ +use super::*; + +/// A free run of `n` consecutive UDP ports. +fn free_ports(n: u16) -> u16 { + loop { + let probe = std::net::UdpSocket::bind("[::]:0").unwrap(); + let base = probe.local_addr().unwrap().port(); + drop(probe); + if base.checked_add(n).is_some() + && (0..n).all(|i| std::net::UdpSocket::bind(("::", base + i)).is_ok()) + { + return base; + } + } +} + +#[test] +fn beacon_is_deterministic_and_bound_to_group_and_address() { + let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1); + let token = discovery_token("reticulum", &addr); + assert_eq!(token, discovery_token("reticulum", &addr)); + assert!(verify_beacon(&token, "reticulum", &addr)); + assert!(!verify_beacon(&token, "other_group", &addr)); + assert!(!verify_beacon( + &token, + "reticulum", + &Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2) + )); + assert!(!verify_beacon(&token[..16], "reticulum", &addr)); +} + +#[test] +fn link_locals_group_per_interface_selecting_the_last() { + let a: Ipv6Addr = "fe80::1".parse().unwrap(); + let b: Ipv6Addr = "fe80::2".parse().unwrap(); + let c: Ipv6Addr = "fe80::3".parse().unwrap(); + let nics = group_link_locals(vec![ + ("eth0".into(), a, 2), + ("wlan0".into(), c, 3), + ("eth0".into(), b, 2), + ]); + assert_eq!(nics.len(), 2); + assert_eq!(nics[0].ifname, "eth0"); + assert_eq!(nics[0].link_local, b); + assert_eq!(nics[0].all, vec![a, b]); + assert_eq!(nics[1].link_local, c); +} + +#[test] +fn multi_if_dedup_drops_repeats_and_stays_bounded() { + let mut dedup = MultiIfDedup::new(); + assert!(!dedup.is_duplicate(b"packet one")); + assert!(dedup.is_duplicate(b"packet one")); + assert!(!dedup.is_duplicate(b"packet two")); + for i in 0..MULTI_IF_DEQUE_LEN + 10 { + dedup.is_duplicate(format!("packet_{i}").as_bytes()); + } + assert!(dedup.deque.len() <= MULTI_IF_DEQUE_LEN); +} + +mod peer_children { + use super::*; + use std::time::Duration; + use tokio::time::timeout; + + struct Rig { + shared: Arc, + transport_rx: mpsc::Receiver, + handle_rx: mpsc::Receiver, + } + + async fn rig(data_port: u16) -> Rig { + let (transport_tx, transport_rx) = mpsc::channel(64); + let (handle_tx, handle_rx) = mpsc::channel(8); + let config = AutoInterfaceConfig { + name: "unit".into(), + data_port, + ..AutoInterfaceConfig::default() + }; + let outbound = bind_udp(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0), false).unwrap(); + let shared = Arc::new(Shared::new( + config, + 40, + Arc::new(AtomicU64::new(100)), + transport_tx, + handle_tx, + Arc::new(AtomicBool::new(true)), + outbound, + )); + shared.parent.owner().mark_registered(); + shared.online.store(true, Ordering::SeqCst); + shared.final_init_done.store(true, Ordering::SeqCst); + Rig { + shared, + transport_rx, + handle_rx, + } + } + + async fn next_child(rig: &mut Rig) -> InterfaceHandle { + let child = timeout(Duration::from_secs(2), rig.handle_rx.recv()) + .await + .expect("child handed off") + .unwrap(); + child.owner.mark_registered(); + child + } + + async fn next_inbound(rig: &mut Rig) -> Option<(InterfaceId, Bytes)> { + match timeout(Duration::from_millis(300), rig.transport_rx.recv()).await { + Ok(Some(TransportMessage::InterfaceEvent { message, .. })) => match *message { + TransportMessage::Inbound(p) => Some((p.interface_id, p.raw)), + _ => None, + }, + _ => None, + } + } + + #[tokio::test] + async fn each_peer_becomes_its_own_child_interface() { + let mut rig = rig(DATA_PORT).await; + let a: Ipv6Addr = "fe80::dead:beef:cafe:1234".parse().unwrap(); + let b: Ipv6Addr = "fe80::dead:beef:cafe:5678".parse().unwrap(); + rig.shared.add_peer(a, "eth0", 2).await; + rig.shared.add_peer(b, "eth0", 2).await; + rig.shared.add_peer(a, "eth0", 2).await; + let ca = next_child(&mut rig).await; + let cb = next_child(&mut rig).await; + assert!( + rig.handle_rx.try_recv().is_err(), + "a refresh spawns no child" + ); + assert_eq!(ca.parent_id, Some(40)); + assert_eq!(ca.name, "AutoInterfacePeer[eth0/fe80::dead:beef:cafe:1234]"); + assert_eq!(cb.name, "AutoInterfacePeer[eth0/fe80::dead:beef:cafe:5678]"); + assert_ne!(ca.id, cb.id); + assert_eq!(ca.mtu, HW_MTU); + } + + #[tokio::test] + async fn data_is_delivered_on_the_senders_child_only() { + let mut rig = rig(DATA_PORT).await; + let peer = Ipv6Addr::LOCALHOST; + rig.shared.add_peer(peer, "lo", 0).await; + let child = next_child(&mut rig).await; + + rig.shared + .on_data(b"from a stranger", "fe80::9".parse().unwrap()); + assert!(next_inbound(&mut rig).await.is_none()); + + rig.shared.on_data(b"from the peer", peer); + let (id, raw) = next_inbound(&mut rig).await.expect("delivered"); + assert_eq!(id, child.id); + assert_eq!(&raw[..], b"from the peer"); + + rig.shared.on_data(b"from the peer", peer); + assert!( + next_inbound(&mut rig).await.is_none(), + "multi-NIC duplicate" + ); + } + + #[tokio::test] + async fn nothing_is_delivered_before_final_init_or_after_detach() { + let mut rig = rig(DATA_PORT).await; + rig.shared.add_peer(Ipv6Addr::LOCALHOST, "lo", 0).await; + let _child = next_child(&mut rig).await; + rig.shared.final_init_done.store(false, Ordering::SeqCst); + rig.shared.on_data(b"early", Ipv6Addr::LOCALHOST); + assert!(next_inbound(&mut rig).await.is_none()); + rig.shared.final_init_done.store(true, Ordering::SeqCst); + rig.shared.online.store(false, Ordering::SeqCst); + rig.shared.on_data(b"late", Ipv6Addr::LOCALHOST); + assert!(next_inbound(&mut rig).await.is_none()); + } + + #[tokio::test] + async fn discovery_is_ignored_until_final_init() { + let mut rig = rig(DATA_PORT).await; + let peer: Ipv6Addr = "fe80::77".parse().unwrap(); + let token = discovery_token(&rig.shared.group_id, &peer); + rig.shared.final_init_done.store(false, Ordering::SeqCst); + rig.shared.on_discovery(&token, peer, "eth0", 2).await; + assert!(rig.handle_rx.try_recv().is_err()); + rig.shared.final_init_done.store(true, Ordering::SeqCst); + rig.shared.on_discovery(&token[..31], peer, "eth0", 2).await; + assert!(rig.handle_rx.try_recv().is_err()); + rig.shared.on_discovery(&token, peer, "eth0", 2).await; + next_child(&mut rig).await; + } + + #[tokio::test] + async fn a_child_sends_only_to_its_own_peer() { + let listener = UdpSocket::bind("[::1]:0").await.unwrap(); + let mut rig = rig(listener.local_addr().unwrap().port()).await; + rig.shared.add_peer(Ipv6Addr::LOCALHOST, "lo", 0).await; + rig.shared + .add_peer("fe80::dead:1".parse().unwrap(), "eth0", 2) + .await; + let to_loopback = next_child(&mut rig).await; + let other = next_child(&mut rig).await; + to_loopback + .tx + .send(Bytes::from_static(b"unicast")) + .await + .unwrap(); + let mut buf = [0u8; 64]; + let (n, _) = timeout(Duration::from_secs(2), listener.recv_from(&mut buf)) + .await + .expect("datagram from the child") + .unwrap(); + assert_eq!(&buf[..n], b"unicast"); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(to_loopback.txb.as_ref().unwrap().load(Ordering::SeqCst), 7); + assert_eq!(other.txb.as_ref().unwrap().load(Ordering::SeqCst), 0); + assert_eq!(rig.shared.txb.load(Ordering::SeqCst), 7); + } + + #[tokio::test] + async fn expired_peer_deregisters_its_child() { + let mut rig = rig(DATA_PORT).await; + rig.shared.add_peer(Ipv6Addr::LOCALHOST, "lo", 0).await; + let child = next_child(&mut rig).await; + let later = Instant::now() + Duration::from_secs_f64(PEERING_TIMEOUT + 1.0); + rig.shared.expire_peers(later); + assert!(!child.online.load(Ordering::SeqCst)); + drop(child.tx); + let mut deregistered = false; + while let Ok(Some(m)) = timeout(Duration::from_secs(1), rig.transport_rx.recv()).await { + if let TransportMessage::InterfaceEvent { message, .. } = m + && matches!(*message, TransportMessage::DeregisterInterface { .. }) + { + deregistered = true; + break; + } + } + assert!(deregistered); + rig.shared.on_data(b"after expiry", Ipv6Addr::LOCALHOST); + assert!(next_inbound(&mut rig).await.is_none()); + } + + #[tokio::test] + async fn detaching_the_parent_takes_children_offline() { + let mut rig = rig(DATA_PORT).await; + rig.shared.add_peer(Ipv6Addr::LOCALHOST, "lo", 0).await; + let child = next_child(&mut rig).await; + drop(Teardown { + shared: rig.shared.clone(), + jobs: None, + }); + assert!(!rig.shared.online.load(Ordering::SeqCst)); + assert!(!child.online.load(Ordering::SeqCst)); + } + + #[tokio::test] + async fn spawn_waits_out_the_peering_wait_before_going_online() { + let (transport_tx, _rx) = mpsc::channel(8); + let base = free_ports(3); + let config = AutoInterfaceConfig { + discovery_port: base, + data_port: base + 2, + ..AutoInterfaceConfig::default() + }; + let started = Instant::now(); + let handle = spawn_auto_interface( + config, + 1, + Arc::new(AtomicU64::new(10)), + transport_tx, + mpsc::channel(1).0, + Arc::new(AtomicBool::new(true)), + ) + .await + .unwrap(); + assert!(started.elapsed().as_secs_f64() >= PEERING_WAIT); + assert!(handle.online.load(Ordering::SeqCst)); + handle.online.store(false, Ordering::SeqCst); + handle.read_task.abort(); + } +} + +mod loopback_nic { + use super::*; + use std::time::Duration; + use tokio::time::timeout; + + fn exclusive_bind_ok(port: u16) -> bool { + std::net::UdpSocket::bind(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, port, 0, 0)).is_ok() + } + + fn lo_index() -> Option { + let index = netif::scope_id_of("lo"); + (index != 0).then_some(index) + } + + async fn rig( + base: u16, + ) -> Option<( + Arc, + mpsc::Receiver, + mpsc::Receiver, + NicAddrs, + )> { + let scope_id = lo_index()?; + let (transport_tx, transport_rx) = mpsc::channel(64); + let (handle_tx, handle_rx) = mpsc::channel(8); + let config = AutoInterfaceConfig { + name: "lo-unit".into(), + group_id: format!("lo-unit-{base}-{}", std::process::id()), + discovery_port: base, + data_port: base + 2, + ..AutoInterfaceConfig::default() + }; + let outbound = bind_udp(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0), false).ok()?; + let shared = Arc::new(Shared::new( + config, + 50, + Arc::new(AtomicU64::new(500)), + transport_tx, + handle_tx, + Arc::new(AtomicBool::new(true)), + outbound, + )); + shared.parent.owner().mark_registered(); + let nic = NicAddrs { + ifname: "lo".into(), + link_local: Ipv6Addr::LOCALHOST, + all: vec![Ipv6Addr::LOCALHOST], + scope_id, + }; + Some((shared, transport_rx, handle_rx, nic)) + } + + #[tokio::test] + async fn detach_releases_every_nic_socket() { + let base = free_ports(3); + let Some((shared, _trx, _hrx, nic)) = rig(base).await else { + eprintln!("skipped: no loopback interface index"); + return; + }; + if !shared.adopt_nic(&nic).unwrap_or(false) { + eprintln!("skipped: loopback multicast unavailable"); + return; + } + tokio::time::sleep(Duration::from_millis(200)).await; + assert!( + !exclusive_bind_ok(base + 2), + "data socket held while running" + ); + drop(Teardown { + shared: shared.clone(), + jobs: None, + }); + tokio::time::sleep(Duration::from_millis(100)).await; + for port in [base, base + 1, base + 2] { + assert!( + exclusive_bind_ok(port), + "port {port} still held after detach" + ); + } + } + + #[tokio::test] + async fn own_address_is_an_echo_and_stranger_data_is_dropped() { + let base = free_ports(3); + let Some((shared, mut trx, mut hrx, nic)) = rig(base).await else { + return; + }; + if !shared.adopt_nic(&nic).unwrap_or(false) { + return; + } + shared.online.store(true, Ordering::SeqCst); + shared.final_init_done.store(true, Ordering::SeqCst); + let peer = UdpSocket::bind("[::1]:0").await.unwrap(); + let data_dest = SocketAddrV6::new(Ipv6Addr::LOCALHOST, base + 2, 0, 0); + + // A stranger's data is dropped. + peer.send_to(b"before peering", data_dest).await.unwrap(); + assert!( + timeout(Duration::from_millis(300), trx.recv()) + .await + .is_err() + ); + + shared + .add_peer(Ipv6Addr::LOCALHOST, "lo", nic.scope_id) + .await; + assert!( + hrx.try_recv().is_err(), + "own address must not become a peer" + ); + assert!(shared.core().echo_received("lo")); + } +} diff --git a/crates/rns-runtime/src/interface_factory.rs b/crates/rns-runtime/src/interface_factory.rs index 3c18809..75054d1 100644 --- a/crates/rns-runtime/src/interface_factory.rs +++ b/crates/rns-runtime/src/interface_factory.rs @@ -985,15 +985,10 @@ fn synthesize_auto( let discovery_port = parse_port_opt(name, "discovery_port", section)?.unwrap_or(29716); let data_port = parse_port_opt(name, "data_port", section)?.unwrap_or(42671); - let multicast_address_type = match section.get("multicast_address_type") { - Some(s) => rns_interface::auto::McastAddrType::from_str(s).map_err(|message| { - InterfaceFactoryError::InvalidValue { - field: "multicast_address_type".to_string(), - message, - } - })?, - None => rns_interface::auto::McastAddrType::Temporary, - }; + let multicast_address_type = section + .get("multicast_address_type") + .map(rns_interface::auto::McastAddrType::parse) + .unwrap_or(rns_interface::auto::McastAddrType::Temporary); // Python `as_list`; an empty whitelist allows every interface // (AutoInterface.py:111-112, :229). @@ -1002,9 +997,11 @@ fn synthesize_auto( .filter(|devices| !devices.is_empty()); let ignored_devices = section.get_list("ignored_devices").unwrap_or_default(); + // Reticulum.py:1018-1020, :1204: only `bitrate` counts, and only from + // MINIMUM_BITRATE up; a user `configured_bitrate` key is overwritten. let configured_bitrate = section - .get_uint("configured_bitrate") - .or_else(|| section.get_uint("bitrate")); + .get_uint("bitrate") + .filter(|bitrate| *bitrate >= crate::constants::MINIMUM_BITRATE); Ok(InterfaceConfig::Auto(AutoInterfaceConfig { name: name.to_string(), @@ -2671,7 +2668,7 @@ mod tests { vec!["eth0".into(), "wlan0".into(), "br-lan".into()], ); section.set_list("ignored_devices", vec!["vmnet1".into(), "docker0".into()]); - section.set("configured_bitrate", "100000000"); + section.set("bitrate", "100000000"); let config = synthesize_interface("campus_auto", §ion).unwrap(); match config { diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index 68b8d1e..d088333 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -8842,7 +8842,9 @@ pub async fn spawn_auto_interface_runtime_with_config( let iface_handle = rns_interface::auto::spawn_auto_interface( config, id, + handle.id_gen.clone(), handle.transport_tx.clone(), + handle.handle_tx.clone(), handle.is_foreground.clone(), ) .await @@ -9381,10 +9383,17 @@ async fn spawn_interface_with_rnode_startup_options( configured_bitrate: c.configured_bitrate, mode: c.mode, }; - rns_interface::auto::spawn_auto_interface(auto_config, id, transport_tx, is_foreground) - .await - .map(|h| vec![h.into()]) - .map_err(|e| format!("Auto: {e}")) + rns_interface::auto::spawn_auto_interface( + auto_config, + id, + id_gen, + transport_tx, + handle_tx, + is_foreground, + ) + .await + .map(|h| vec![h.into()]) + .map_err(|e| format!("Auto: {e}")) } #[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))] interface_factory::InterfaceConfig::RNode(c) => { diff --git a/crates/rns-runtime/src/shared_instance.rs b/crates/rns-runtime/src/shared_instance.rs index 262cd39..26cdd85 100644 --- a/crates/rns-runtime/src/shared_instance.rs +++ b/crates/rns-runtime/src/shared_instance.rs @@ -886,26 +886,21 @@ mod tests { } #[tokio::test] - async fn occupied_auto_port_is_reported_without_breaking_tcp() { - let auto = std::net::UdpSocket::bind("[::]:0").unwrap(); - let data_port = auto.local_addr().unwrap().port(); + async fn occupied_interface_port_is_reported_without_breaking_tcp() { + let occupied = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + let udp_port = occupied.local_addr().unwrap().port(); let (tcp_port, _) = ports(); let config = TestConfig::new(1, 2, 1); std::fs::write(config.0.join("config"), format!( - "[reticulum]\nshare_instance = No\n[interfaces]\n[[LAN]]\ntype = AutoInterface\nenabled = Yes\ndata_port = {data_port}\n[[TCP]]\ntype = TCPServerInterface\nenabled = Yes\nlisten_ip = 127.0.0.1\nlisten_port = {tcp_port}\n" + "[reticulum]\nshare_instance = No\n[interfaces]\n[[LAN]]\ntype = UDPInterface\nenabled = Yes\nlisten_ip = 127.0.0.1\nlisten_port = {udp_port}\nforward_ip = 127.0.0.1\nforward_port = {udp_port}\n[[TCP]]\ntype = TCPServerInterface\nenabled = Yes\nlisten_ip = 127.0.0.1\nlisten_port = {tcp_port}\n" )).unwrap(); let runtime = config.start(InstancePolicy::Standalone).await.unwrap(); assert_eq!(runtime.startup_interface_failures().len(), 1); assert_eq!(runtime.startup_interface_failures()[0].0, "LAN"); - assert!( - runtime.startup_interface_failures()[0] - .1 - .contains("socket bind") - ); let _tcp = tokio::net::TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, tcp_port)) .await .unwrap(); - assert_eq!(auto.local_addr().unwrap().port(), data_port); + assert_eq!(occupied.local_addr().unwrap().port(), udp_port); runtime.shutdown_and_wait().await; } }