runtime: publish each interface detach, with its reason, to embedders

This commit is contained in:
DeFiDude committed 2026-11-18 15:59:54 -07:00
1 parent 3bb885cd63
commit d623f2a604
2 files changed
+219 -11

No files matched your search

+71 -6
View File
@@ -529,6 +529,7 @@ pub struct ReticulumHandle {
pub handle_tx: mpsc::Sender<rns_interface::traits::InterfaceHandle>,
interface_controls: InterfaceControlMap,
interface_registry: InterfaceRegistry,
interface_detaches: InterfaceDetachEvents,
pub socket_base: PathBuf,
pub config: ReticulumConfig,
/// Mobile builds throttle tick rates when the app is backgrounded.
@@ -653,6 +654,50 @@ pub enum AnnounceSubscriptionError {
TransportUnavailable,
}
/// An interface the runtime detached because transport asked it to.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct InterfaceDetach {
/// Python `interface.name`: the config section's for a configured interface.
pub name: String,
pub interface_id: rns_transport::messages::InterfaceId,
/// The interface that spawned it, as a server spawns each client's.
pub parent_id: Option<rns_transport::messages::InterfaceId>,
pub reason: rns_transport::messages::DetachReason,
}
const INTERFACE_DETACH_CAPACITY: usize = 64;
/// The receiver opened with the channel holds every detach until the first
/// subscriber takes it, so one made before anyone subscribes is not lost.
#[derive(Clone)]
struct InterfaceDetachEvents {
tx: tokio::sync::broadcast::Sender<InterfaceDetach>,
first: Arc<std::sync::Mutex<Option<tokio::sync::broadcast::Receiver<InterfaceDetach>>>>,
}
impl InterfaceDetachEvents {
fn new() -> Self {
let (tx, first) = tokio::sync::broadcast::channel(INTERFACE_DETACH_CAPACITY);
Self {
tx,
first: Arc::new(std::sync::Mutex::new(Some(first))),
}
}
fn subscribe(&self) -> tokio::sync::broadcast::Receiver<InterfaceDetach> {
self.first
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take()
.unwrap_or_else(|| self.tx.subscribe())
}
fn publish(&self, detach: InterfaceDetach) {
let _ = self.tx.send(detach);
}
}
/// Typed snapshot of Reticulum interface and aggregate traffic state.
#[derive(Debug, Clone)]
pub struct InterfaceStats {
@@ -1335,6 +1380,13 @@ impl ReticulumHandle {
&self.startup_interface_failures
}
/// The detaches transport asks for; the first subscriber also gets those made before it.
pub fn subscribe_interface_detaches(
&self,
) -> tokio::sync::broadcast::Receiver<InterfaceDetach> {
self.interface_detaches.subscribe()
}
/// Last authenticated shared-client state. Generic automatic clients do
/// not opt into this policy and return `None`.
pub fn shared_instance_state(&self) -> Option<SharedInstanceState> {
@@ -2480,11 +2532,12 @@ impl ReticulumHandle {
/// Python `_detach_interface(..., internal_forced=True)`, which transport
/// calls for a bad or blackholed tunnel peer: it ignores
/// `enable_interface_management`, and a client so detached stays down until
/// restart or attach (Reticulum.py:976-1015).
/// restart or attach (Reticulum.py:976-1015). Returns the interface it
/// detached.
pub(crate) async fn detach_interface_by_id(
&self,
id: rns_transport::messages::InterfaceId,
) -> Option<bool> {
) -> Option<rns_transport::messages::InterfaceStatRpcEntry> {
let Ok(TransportQueryResponse::InterfaceStats(entries)) = self
.query_transport_result(TransportQuery::GetInterfaceStats)
.await
@@ -2498,14 +2551,14 @@ impl ReticulumHandle {
.map(|child| child.id)
.collect();
if !self.detach_entry(&entry, spawned).await {
return Some(false);
return None;
}
let name = entry
.identity
.as_ref()
.map_or(entry.name.as_str(), |identity| identity.name.as_str());
rns_transport::notice!("Interface {name} was detached");
Some(true)
Some(entry)
}
/// Tear down an interface and those it spawned; I2P listeners and local
@@ -4874,6 +4927,7 @@ pub async fn init_with_policy(
handle_tx: handle_tx.clone(),
interface_controls: interface_controls.clone(),
interface_registry: interface_registry.clone(),
interface_detaches: InterfaceDetachEvents::new(),
socket_base: socket_base.clone(),
config: rc.clone(),
is_foreground,
@@ -11215,7 +11269,7 @@ async fn spawn_configured_interface_driver(
}
/// Carry out the transport actor's interface requests until it stops or the
/// runtime shuts down.
/// runtime shuts down, telling subscribers of each detach.
async fn run_interface_control(
handle: ReticulumHandle,
mut requests: mpsc::UnboundedReceiver<rns_transport::messages::InterfaceControl>,
@@ -11233,7 +11287,17 @@ async fn run_interface_control(
reason,
}) => {
tracing::debug!(interface_id, ?reason, "transport asked for a detach");
let _ = handle.detach_interface_by_id(interface_id).await;
if let Some(entry) = handle.detach_interface_by_id(interface_id).await {
let name = entry
.identity
.map_or(entry.name, |identity| identity.short_name);
handle.interface_detaches.publish(InterfaceDetach {
name,
interface_id,
parent_id: entry.parent_id,
reason,
});
}
}
Some(_) => {}
None => return,
@@ -14025,6 +14089,7 @@ loglevel = 7
handle_tx: htx,
interface_controls,
interface_registry,
interface_detaches: InterfaceDetachEvents::new(),
socket_base: PathBuf::from("/tmp/dummy"),
config: ReticulumConfig::default(),
is_foreground: Arc::new(AtomicBool::new(true)),
@@ -1,7 +1,7 @@
//! Runtime wiring for tunnel synthesis, server interface ids and accepted
//! clients' routing state, observed from the wire and the public handle.
use super::*;
use rns_transport::messages::InterfaceStatRpcEntry;
use rns_transport::messages::{DetachReason, InterfaceStatRpcEntry};
use rns_transport::path_table::{PathEntry, PathTable};
use rns_transport::tunnel::TunnelSynthesisData;
use rns_wire::context::PacketContext;
@@ -1269,8 +1269,25 @@ async fn a_tcp_client_records_the_hub_that_answers_its_synthesis() {
let _ = std::fs::remove_dir_all(dir);
}
/// A tunnel synthesis whose signature fails.
fn bad_synthesis() -> Vec<u8> {
let mut synthesis = hub_answer(&Identity::new());
synthesis[rns_wire::constants::HEADER_MINSIZE + 120] ^= 0x01;
synthesis
}
async fn next_detach(
detaches: &mut tokio::sync::broadcast::Receiver<InterfaceDetach>,
) -> InterfaceDetach {
tokio::time::timeout(Duration::from_secs(10), detaches.recv())
.await
.expect("the detach is published")
.unwrap()
}
/// An answer with a bad signature tears the client down for good, with
/// interface management off (Transport.py:3245-3248, Reticulum.py:976-1015).
/// interface management off and nobody subscribed to detaches
/// (Transport.py:3245-3248, Reticulum.py:976-1015).
#[tokio::test]
async fn a_client_answered_with_a_bad_signature_is_torn_down() {
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -1292,12 +1309,10 @@ async fn a_client_answered_with_a_bad_signature_is_torn_down() {
.await
.is_some_and(|frame| synthesis_in(&frame).is_some())
);
let mut answer = hub_answer(&Identity::new());
answer[rns_wire::constants::HEADER_MINSIZE + 120] ^= 0x01;
connection
.reader
.get_mut()
.write_all(&rns_interface::hdlc::frame(&answer))
.write_all(&rns_interface::hdlc::frame(&bad_synthesis()))
.await
.unwrap();
@@ -1327,6 +1342,134 @@ async fn a_client_answered_with_a_bad_signature_is_torn_down() {
let _ = std::fs::remove_dir_all(dir);
}
/// The hub answers badly as the client connects, while the runtime starts:
/// that detach, made before anyone subscribes, reaches the first subscriber,
/// and a later one hears only what follows.
#[tokio::test]
async fn a_start_up_detach_reaches_the_first_subscriber() {
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = hub.local_addr().unwrap().port();
let torn_down = tokio::spawn(async move {
let (mut stream, _) = hub.accept().await.unwrap();
stream
.write_all(&rns_interface::hdlc::frame(&bad_synthesis()))
.await
.unwrap();
let _ = stream.read_to_end(&mut Vec::new()).await;
});
let dir = config_dir("detach-start-up", &tcp_client_config(port));
let handle = start(&dir).await;
tokio::time::timeout(Duration::from_secs(10), torn_down)
.await
.expect("the runtime detaches the client before anyone subscribes")
.unwrap();
let detach = next_detach(&mut handle.subscribe_interface_detaches()).await;
assert_eq!(
(detach.name.as_str(), detach.parent_id, detach.reason),
("Uplink", None, DetachReason::InvalidSynthesis)
);
assert!(
interfaces(&handle)
.await
.iter()
.all(|entry| entry.id != detach.interface_id)
);
assert!(matches!(
handle.subscribe_interface_detaches().try_recv(),
Err(tokio::sync::broadcast::error::TryRecvError::Empty)
));
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_later_detach_reaches_every_subscriber() {
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = hub.local_addr().unwrap().port();
let dir = config_dir("detach-later", &tcp_client_config(port));
let handle = start(&dir).await;
let mut subscribers = [
handle.subscribe_interface_detaches(),
handle.subscribe_interface_detaches(),
];
let mut connection = Frames::accept(&hub, false).await;
assert!(
connection
.next(Duration::from_secs(5))
.await
.is_some_and(|frame| synthesis_in(&frame).is_some())
);
let uplink = wait_for_interface(&handle, |entry| entry.name == "Uplink")
.await
.unwrap();
connection
.reader
.get_mut()
.write_all(&rns_interface::hdlc::frame(&bad_synthesis()))
.await
.unwrap();
for subscriber in &mut subscribers {
assert_eq!(
next_detach(subscriber).await,
InterfaceDetach {
name: "Uplink".to_string(),
interface_id: uplink.id,
parent_id: None,
reason: DetachReason::InvalidSynthesis,
}
);
}
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
/// A server's accepted client that fails verification goes on its own, and
/// the detach names the server it came from.
#[tokio::test]
async fn a_detached_accepted_client_names_its_server() {
let port = unused_port().await;
let dir = config_dir(
"detach-accepted",
&format!(
"[reticulum]\n share_instance = No\n enable_transport = Yes\n\n[interfaces]\n [[Hub]]\n type = TCPServerInterface\n enabled = yes\n listen_ip = 127.0.0.1\n listen_port = {port}\n"
),
);
let handle = start(&dir).await;
let mut detaches = handle.subscribe_interface_detaches();
let server = wait_for_interface(&handle, |entry| entry.name == "Hub")
.await
.unwrap();
let mut client = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
let accepted = wait_for_interface(&handle, |entry| entry.parent_id == Some(server.id))
.await
.expect("the client registers");
client
.write_all(&rns_interface::hdlc::frame(&bad_synthesis()))
.await
.unwrap();
let detach = next_detach(&mut detaches).await;
assert_eq!(
(detach.interface_id, detach.parent_id, detach.reason),
(accepted.id, Some(server.id), DetachReason::InvalidSynthesis)
);
assert_eq!(detach.name, "Client on Hub");
assert!(
interfaces(&handle)
.await
.iter()
.any(|entry| entry.id == server.id),
"the server stays"
);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
/// Python 1.6.1 `_detach_interface`: text that names no interface but spells a
/// tunnel id in hex, as `bytes.fromhex` reads it, detaches the interface whose
/// `tunnel_id or local_tunnel_id` it is (Reticulum.py:976-1015).