mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
interfaces: rebuild AutoInterface on per-interface sockets, as upstream
This commit is contained in:
1 parent
24b0021f98
commit
a5a684fbb0
8 files changed
+2510
-2131
No files matched your search
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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<String>,
|
||||
pub addr_v6_link_local: Option<String>,
|
||||
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<Vec<NetworkInterfaceInfo>, String> {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
let mut by_name: BTreeMap<String, NetworkInterfaceInfo> = 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<Vec<(String, Ipv6Addr, u32)>, 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<Vec<(String, Ipv6Addr, u32)>, 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<u8> = 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<u32>) -> 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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<Bytes>,
|
||||
pub online: Arc<AtomicBool>,
|
||||
pub rxb: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Peer {
|
||||
pub ifname: String,
|
||||
pub scope_id: u32,
|
||||
pub last_heard: Instant,
|
||||
pub last_outbound: Instant,
|
||||
pub child: Option<ChildLink>,
|
||||
}
|
||||
|
||||
#[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<Ipv6Addr, Peer>,
|
||||
adopted: HashMap<String, Ipv6Addr>,
|
||||
own_addrs: HashMap<String, Vec<Ipv6Addr>>,
|
||||
echoes: HashMap<String, Instant>,
|
||||
initial_echoes: HashSet<String>,
|
||||
timed_out: HashMap<String, bool>,
|
||||
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<Ipv6Addr> {
|
||||
self.adopted.get(ifname).copied()
|
||||
}
|
||||
|
||||
pub fn adopted_ifnames(&self) -> Vec<String> {
|
||||
self.adopted.keys().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn last_echo(&self, ifname: &str) -> Option<Instant> {
|
||||
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<bool> {
|
||||
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<Option<ChildLink>, 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<ChildLink> {
|
||||
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<Ipv6Addr> = 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<ChildLink> {
|
||||
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<Bytes>) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<Shared>,
|
||||
transport_rx: mpsc::Receiver<TransportMessage>,
|
||||
handle_rx: mpsc::Receiver<InterfaceHandle>,
|
||||
}
|
||||
|
||||
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<u32> {
|
||||
let index = netif::scope_id_of("lo");
|
||||
(index != 0).then_some(index)
|
||||
}
|
||||
|
||||
async fn rig(
|
||||
base: u16,
|
||||
) -> Option<(
|
||||
Arc<Shared>,
|
||||
mpsc::Receiver<TransportMessage>,
|
||||
mpsc::Receiver<InterfaceHandle>,
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user