Skip to main content

rns_net/
driver.rs

1//! Driver loop: receives events, drives the TransportEngine, dispatches actions.
2
3use std::collections::{HashMap, HashSet};
4use std::io;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, Instant};
8
9type MemoryRollup = (f64, f64, f64, f64, f64, f64, f64, f64);
10#[cfg(feature = "iface-backbone")]
11type BackboneCandidateOrder = (
12    std::cmp::Reverse<u8>,
13    u8,
14    u8,
15    u8,
16    std::cmp::Reverse<u32>,
17    std::cmp::Reverse<u64>,
18    [u8; 32],
19);
20
21use rns_core::packet::RawPacket;
22use rns_core::transport::announce_verify_queue::{AnnounceVerifyQueue, OverflowPolicy};
23use rns_core::transport::tables::PathEntry;
24use rns_core::transport::types::{InterfaceId, ReceivedAnnounce, TransportAction, TransportConfig};
25use rns_core::transport::TransportEngine;
26use rns_crypto::{OsRng, Rng};
27
28#[cfg(feature = "hooks")]
29use crate::provider_bridge::ProviderBridge;
30#[cfg(feature = "hooks")]
31use rns_hooks::{create_hook_slots, EngineAccess, HookContext, HookManager, HookPoint, HookSlot};
32
33#[cfg(feature = "hooks")]
34use crate::event::BackbonePeerHookEvent;
35use crate::event::{
36    BackbonePeerPoolMemberStatus, BackbonePeerPoolStatus, BackbonePeerStateEntry, BlackholeInfo,
37    DrainStatus, Event, EventReceiver, InterfaceStatsResponse, KnownDestinationEntry,
38    LifecycleState, LocalDestinationEntry, NextHopResponse, PathTableEntry, QueryRequest,
39    QueryResponse, RateTableEntry, RuntimeConfigApplyMode, RuntimeConfigEntry, RuntimeConfigError,
40    RuntimeConfigErrorCode, RuntimeConfigSource, RuntimeConfigValue, SingleInterfaceStat,
41    TrafficDetail,
42};
43use crate::holepunch::orchestrator::{HolePunchManager, HolePunchManagerAction};
44use crate::ifac;
45#[cfg(all(feature = "iface-auto", test))]
46use crate::interface::auto::AutoRuntime;
47#[cfg(feature = "iface-auto")]
48use crate::interface::auto::AutoRuntimeConfigHandle;
49#[cfg(feature = "iface-backbone")]
50use crate::interface::backbone::{
51    start_client_with_ifac, BackboneClientConfig, BackboneClientRuntime,
52    BackboneClientRuntimeConfigHandle, BackbonePeerStateHandle, BackboneRuntimeConfigHandle,
53};
54#[cfg(all(feature = "iface-backbone", target_os = "linux", test))]
55use crate::interface::backbone::{BackboneAbuseConfig, BackboneServerRuntime};
56#[cfg(all(feature = "iface-i2p", test))]
57use crate::interface::i2p::I2pRuntime;
58#[cfg(feature = "iface-i2p")]
59use crate::interface::i2p::I2pRuntimeConfigHandle;
60#[cfg(all(feature = "iface-pipe", test))]
61use crate::interface::pipe::PipeRuntime;
62#[cfg(feature = "iface-pipe")]
63use crate::interface::pipe::PipeRuntimeConfigHandle;
64#[cfg(feature = "iface-rnode")]
65use crate::interface::rnode::{
66    validate_sub_config, RNodeRuntime, RNodeRuntimeConfigHandle, RNodeSubConfig,
67};
68#[cfg(feature = "iface-tcp")]
69use crate::interface::tcp::TcpClientRuntimeConfigHandle;
70#[cfg(all(feature = "iface-tcp", test))]
71use crate::interface::tcp_server::TcpServerRuntime;
72#[cfg(feature = "iface-tcp")]
73use crate::interface::tcp_server::TcpServerRuntimeConfigHandle;
74#[cfg(all(feature = "iface-udp", test))]
75use crate::interface::udp::UdpRuntime;
76#[cfg(feature = "iface-udp")]
77use crate::interface::udp::UdpRuntimeConfigHandle;
78use crate::interface::{InterfaceEntry, InterfaceStats};
79use crate::link_manager::{LinkManager, LinkManagerAction};
80use crate::time;
81
82const DEFAULT_KNOWN_DESTINATIONS_TTL: f64 = 48.0 * 60.0 * 60.0;
83const DEFAULT_KNOWN_DESTINATIONS_MAX_ENTRIES: usize = 8192;
84const DEFAULT_RATE_LIMITER_TTL_SECS: f64 = 48.0 * 60.0 * 60.0;
85const DEFAULT_TICK_INTERVAL_MS: u64 = 1000;
86const DEFAULT_KNOWN_DESTINATIONS_CLEANUP_INTERVAL_TICKS: u32 = 3600;
87const KNOWN_DESTINATION_CLEANUP_BATCH_SIZE: usize = 64;
88const DEFAULT_ANNOUNCE_CACHE_CLEANUP_INTERVAL_TICKS: u32 = 3600;
89const DEFAULT_ANNOUNCE_CACHE_CLEANUP_BATCH_SIZE: usize = 10_000;
90const DEFAULT_DISCOVERY_CLEANUP_INTERVAL_TICKS: u32 = 3600;
91const DEFAULT_MANAGEMENT_ANNOUNCE_INTERVAL_SECS: f64 = 3600.0;
92const DEFAULT_LINK_TEARDOWN_FLUSH: Duration = Duration::from_millis(150);
93const SEND_RETRY_BACKOFF_MIN: Duration = Duration::from_millis(25);
94const SEND_RETRY_BACKOFF_MAX: Duration = Duration::from_millis(1000);
95
96/// Default announce-rate controls applied to transport-node interfaces.
97#[derive(Debug, Clone, Copy, PartialEq)]
98pub struct AnnounceRateDefaults {
99    pub target: Option<f64>,
100    pub penalty: f64,
101    pub grace: u32,
102}
103
104impl Default for AnnounceRateDefaults {
105    fn default() -> Self {
106        Self {
107            target: Some(3600.0),
108            penalty: 0.0,
109            grace: 5,
110        }
111    }
112}
113
114mod dispatch;
115mod events;
116mod interface_management;
117mod lifecycle;
118mod queries;
119mod resource_preparation;
120mod runtime_config;
121
122#[cfg(test)]
123pub(crate) mod tests;
124
125fn inject_transport_header(raw: &[u8], next_hop: &[u8; 16]) -> Vec<u8> {
126    if raw.len() < 18 {
127        return raw.to_vec();
128    }
129
130    let new_flags = (rns_core::constants::HEADER_2 << 6)
131        | (rns_core::constants::TRANSPORT_TRANSPORT << 4)
132        | (raw[0] & 0x0F);
133
134    let mut new_raw = Vec::with_capacity(raw.len() + 16);
135    new_raw.push(new_flags);
136    new_raw.push(raw[1]);
137    new_raw.extend_from_slice(next_hop);
138    new_raw.extend_from_slice(&raw[2..]);
139    new_raw
140}
141
142fn recover_mutex_guard<'a, T>(mutex: &'a Mutex<T>, label: &str) -> std::sync::MutexGuard<'a, T> {
143    match mutex.lock() {
144        Ok(guard) => guard,
145        Err(poisoned) => {
146            log::error!("recovering from poisoned mutex: {}", label);
147            poisoned.into_inner()
148        }
149    }
150}
151
152#[derive(Debug, Clone, Copy)]
153pub(crate) struct RuntimeConfigDefaults {
154    pub(crate) tick_interval_ms: u64,
155    pub(crate) known_destinations_ttl: f64,
156    pub(crate) rate_limiter_ttl_secs: f64,
157    pub(crate) known_destinations_cleanup_interval_ticks: u32,
158    pub(crate) announce_cache_cleanup_interval_ticks: u32,
159    pub(crate) announce_cache_cleanup_batch_size: usize,
160    pub(crate) discovery_cleanup_interval_ticks: u32,
161    pub(crate) management_announce_interval_secs: f64,
162    pub(crate) direct_connect_policy: crate::event::HolePunchPolicy,
163    #[cfg(feature = "hooks")]
164    pub(crate) provider_queue_max_events: usize,
165    #[cfg(feature = "hooks")]
166    pub(crate) provider_queue_max_bytes: usize,
167}
168
169#[cfg(feature = "iface-backbone")]
170#[derive(Debug, Clone)]
171pub(crate) struct BackboneDiscoveryRuntime {
172    pub(crate) discoverable: bool,
173    pub(crate) config: crate::discovery::DiscoveryConfig,
174    pub(crate) transport_enabled: bool,
175    pub(crate) ifac_netname: Option<String>,
176    pub(crate) ifac_netkey: Option<String>,
177}
178
179#[cfg(feature = "iface-backbone")]
180#[derive(Debug, Clone)]
181pub(crate) struct BackboneDiscoveryRuntimeHandle {
182    pub(crate) interface_name: String,
183    pub(crate) current: BackboneDiscoveryRuntime,
184    pub(crate) startup: BackboneDiscoveryRuntime,
185}
186
187#[cfg(feature = "iface-tcp")]
188#[derive(Debug, Clone)]
189pub(crate) struct TcpServerDiscoveryRuntime {
190    pub(crate) discoverable: bool,
191    pub(crate) config: crate::discovery::DiscoveryConfig,
192    pub(crate) transport_enabled: bool,
193    pub(crate) ifac_netname: Option<String>,
194    pub(crate) ifac_netkey: Option<String>,
195}
196
197#[cfg(feature = "iface-tcp")]
198#[derive(Debug, Clone)]
199pub(crate) struct TcpServerDiscoveryRuntimeHandle {
200    pub(crate) interface_name: String,
201    pub(crate) current: TcpServerDiscoveryRuntime,
202    pub(crate) startup: TcpServerDiscoveryRuntime,
203}
204
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub(crate) struct IfacRuntimeConfig {
207    pub(crate) netname: Option<String>,
208    pub(crate) netkey: Option<String>,
209    pub(crate) size: usize,
210}
211
212#[cfg(feature = "iface-backbone")]
213impl BackboneDiscoveryRuntimeHandle {
214    pub(crate) fn from_parts(
215        interface_name: String,
216        startup_config: crate::discovery::DiscoveryConfig,
217        transport_enabled: bool,
218        ifac_netname: Option<String>,
219        ifac_netkey: Option<String>,
220        discoverable: bool,
221    ) -> Self {
222        let startup = BackboneDiscoveryRuntime {
223            discoverable,
224            config: startup_config,
225            transport_enabled,
226            ifac_netname,
227            ifac_netkey,
228        };
229        Self {
230            interface_name,
231            current: startup.clone(),
232            startup,
233        }
234    }
235}
236
237#[cfg(feature = "iface-tcp")]
238impl TcpServerDiscoveryRuntimeHandle {
239    pub(crate) fn from_parts(
240        interface_name: String,
241        startup_config: crate::discovery::DiscoveryConfig,
242        transport_enabled: bool,
243        ifac_netname: Option<String>,
244        ifac_netkey: Option<String>,
245        discoverable: bool,
246    ) -> Self {
247        let startup = TcpServerDiscoveryRuntime {
248            discoverable,
249            config: startup_config,
250            transport_enabled,
251            ifac_netname,
252            ifac_netkey,
253        };
254        Self {
255            interface_name,
256            current: startup.clone(),
257            startup,
258        }
259    }
260}
261
262impl IfacRuntimeConfig {
263    pub(crate) fn from_parts(netname: Option<String>, netkey: Option<String>, size: usize) -> Self {
264        Self {
265            netname,
266            netkey,
267            size,
268        }
269    }
270}
271
272#[cfg(feature = "iface-backbone")]
273#[derive(Debug, Clone)]
274pub struct BackbonePeerPoolSettings {
275    pub max_connected: usize,
276    pub failure_threshold: usize,
277    pub failure_window: Duration,
278    pub cooldown: Duration,
279}
280
281#[cfg(feature = "iface-backbone")]
282pub(crate) const BACKBONE_PEER_POOL_CONFIGURED_DEFAULT_PRIORITY: u8 = 60;
283#[cfg(feature = "iface-backbone")]
284pub(crate) const BACKBONE_PEER_POOL_DISCOVERED_PRIORITY: u8 = 40;
285
286#[cfg(feature = "iface-backbone")]
287pub(crate) struct BackbonePeerPoolCandidateConfig {
288    pub(crate) client: BackboneClientConfig,
289    pub(crate) mode: u8,
290    pub(crate) gravity: i64,
291    pub(crate) recursive_prs: bool,
292    pub(crate) announces_from_internal: bool,
293    pub(crate) announces_to_internal: Option<bool>,
294    pub(crate) ingress_control: rns_core::transport::types::IngressControlConfig,
295    pub(crate) ifac_runtime: IfacRuntimeConfig,
296    pub(crate) ifac_enabled: bool,
297    pub(crate) interface_type_name: String,
298    pub(crate) source: BackbonePeerPoolCandidateSource,
299    pub(crate) priority: u8,
300    pub(crate) discovery: Option<BackbonePeerPoolDiscoveryCandidate>,
301}
302
303#[cfg(feature = "iface-backbone")]
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub(crate) enum BackbonePeerPoolCandidateSource {
306    Configured,
307    Discovered,
308}
309
310#[cfg(feature = "iface-backbone")]
311impl BackbonePeerPoolCandidateSource {
312    fn as_str(self) -> &'static str {
313        match self {
314            Self::Configured => "configured",
315            Self::Discovered => "discovered",
316        }
317    }
318}
319
320#[cfg(feature = "iface-backbone")]
321#[derive(Debug, Clone)]
322pub(crate) struct BackbonePeerPoolDiscoveryCandidate {
323    pub(crate) discovery_hash: [u8; 32],
324    pub(crate) status: crate::discovery::DiscoveredStatus,
325    pub(crate) hops: u8,
326    pub(crate) stamp_value: u32,
327    pub(crate) last_heard: f64,
328}
329
330#[cfg(feature = "iface-backbone")]
331struct BackbonePeerPool {
332    settings: BackbonePeerPoolSettings,
333    candidates: Vec<BackbonePeerPoolCandidate>,
334}
335
336#[cfg(feature = "iface-backbone")]
337struct BackbonePeerPoolCandidate {
338    config: BackbonePeerPoolCandidateConfig,
339    active_id: Option<InterfaceId>,
340    failures: Vec<f64>,
341    retry_after: Option<f64>,
342    cooldown_until: Option<f64>,
343    last_error: Option<String>,
344}
345
346/// Thin wrapper providing `EngineAccess` for a `TransportEngine` + Driver interfaces.
347#[cfg(feature = "hooks")]
348struct EngineRef<'a> {
349    engine: &'a TransportEngine,
350    interfaces: &'a crate::interface::InterfaceMap<InterfaceEntry>,
351    link_manager: &'a LinkManager,
352    now: f64,
353}
354
355#[cfg(feature = "hooks")]
356impl<'a> EngineAccess for EngineRef<'a> {
357    fn has_path(&self, dest: &[u8; 16]) -> bool {
358        self.engine.has_path(dest)
359    }
360    fn hops_to(&self, dest: &[u8; 16]) -> Option<u8> {
361        self.engine.hops_to(dest)
362    }
363    fn next_hop(&self, dest: &[u8; 16]) -> Option<[u8; 16]> {
364        self.engine.next_hop(dest)
365    }
366    fn is_blackholed(&self, identity: &[u8; 16]) -> bool {
367        self.engine.is_blackholed(identity, self.now)
368    }
369    fn interface_name(&self, id: u64) -> Option<String> {
370        self.interfaces
371            .get(&InterfaceId(id))
372            .map(|e| e.info.name.clone())
373    }
374    fn interface_mode(&self, id: u64) -> Option<u8> {
375        self.interfaces.get(&InterfaceId(id)).map(|e| e.info.mode)
376    }
377    fn identity_hash(&self) -> Option<[u8; 16]> {
378        self.engine.identity_hash().copied()
379    }
380    fn announce_rate(&self, id: u64) -> Option<i32> {
381        self.interfaces
382            .get(&InterfaceId(id))
383            .map(|e| (e.stats.outgoing_announce_freq() * 1000.0) as i32)
384    }
385    fn link_state(&self, link_hash: &[u8; 16]) -> Option<u8> {
386        use rns_core::link::types::LinkState;
387        self.link_manager.link_state(link_hash).map(|s| match s {
388            LinkState::Pending => 0,
389            LinkState::Handshake => 1,
390            LinkState::Active => 2,
391            LinkState::Stale => 3,
392            LinkState::Closed => 4,
393        })
394    }
395}
396
397/// Extract the 16-byte destination hash from a raw packet header.
398///
399/// HEADER_1 (raw[0] & 0x40 == 0): dest at bytes 2..18
400/// HEADER_2 (raw[0] & 0x40 != 0): dest at bytes 18..34 (after transport ID)
401#[cfg(any(test, feature = "hooks"))]
402fn extract_dest_hash(raw: &[u8]) -> [u8; 16] {
403    let mut dest = [0u8; 16];
404    if raw.is_empty() {
405        return dest;
406    }
407    let is_header2 = raw[0] & 0x40 != 0;
408    let start = if is_header2 { 18 } else { 2 };
409    let end = start + 16;
410    if raw.len() >= end {
411        dest.copy_from_slice(&raw[start..end]);
412    }
413    dest
414}
415
416/// Execute a hook chain on disjoint Driver fields (avoids &mut self borrow conflict).
417#[cfg(feature = "hooks")]
418fn run_hook_inner(
419    programs: &mut [rns_hooks::LoadedProgram],
420    hook_manager: &Option<HookManager>,
421    engine_access: &dyn EngineAccess,
422    ctx: &HookContext,
423    now: f64,
424    provider_events_enabled: bool,
425) -> Option<rns_hooks::ExecuteResult> {
426    if programs.is_empty() {
427        return None;
428    }
429    let mgr = hook_manager.as_ref()?;
430    mgr.run_chain_with_provider_events(programs, ctx, engine_access, now, provider_events_enabled)
431}
432
433/// What a packet hook point does after its hook chain ran.
434///
435/// Only hook points that hold the raw packet bytes before acting on them apply
436/// a `Modify` verdict (`PreIngress`, `SendOnInterface`,
437/// `BroadcastOnAllInterfaces`, `DeliverLocal`). Every other hook point treats
438/// `Modify` as `Continue` and ignores the replacement bytes.
439#[cfg(feature = "hooks")]
440pub(crate) enum PacketHookOutcome {
441    /// Carry on with the bytes the hook point already holds.
442    Keep,
443    /// Stop processing this packet.
444    Drop,
445    /// Carry on with the replacement bytes, decoded with the same decoder the
446    /// normal path uses. Hashes and header fields come from the replacement.
447    Replace(RawPacket),
448}
449
450/// Validate replacement bytes from a `Modify` verdict: they must be non-empty,
451/// fit within `max_len`, and decode as a packet.
452#[cfg(feature = "hooks")]
453fn validate_hook_replacement(data: &[u8], max_len: usize) -> Result<RawPacket, &'static str> {
454    if data.is_empty() {
455        return Err("replacement is empty");
456    }
457    if data.len() > max_len {
458        return Err("replacement exceeds the packet size limit");
459    }
460    RawPacket::unpack(data).map_err(|_| "replacement does not decode as a packet")
461}
462
463#[cfg(feature = "hooks")]
464fn backbone_peer_hook_context(event: &BackbonePeerHookEvent) -> HookContext<'_> {
465    HookContext::BackbonePeer {
466        server_interface_id: event.server_interface_id.0,
467        peer_interface_id: event.peer_interface_id.map(|id| id.0),
468        peer_ip: event.peer_ip,
469        peer_port: event.peer_port,
470        connected_for: event.connected_for,
471        had_received_data: event.had_received_data,
472        penalty_level: event.penalty_level,
473        blacklist_for: event.blacklist_for,
474    }
475}
476
477/// Convert a Vec of ActionWire into TransportActions for dispatch.
478#[cfg(feature = "hooks")]
479fn convert_injected_actions(actions: Vec<rns_hooks::ActionWire>) -> Vec<TransportAction> {
480    actions
481        .into_iter()
482        .map(|a| {
483            use rns_hooks::ActionWire;
484            match a {
485                ActionWire::SendOnInterface { interface, raw } => {
486                    TransportAction::SendOnInterface {
487                        interface: InterfaceId(interface),
488                        raw: raw.into(),
489                    }
490                }
491                ActionWire::BroadcastOnAllInterfaces {
492                    raw,
493                    exclude,
494                    has_exclude,
495                } => TransportAction::BroadcastOnAllInterfaces {
496                    raw: raw.into(),
497                    exclude: if has_exclude != 0 {
498                        Some(InterfaceId(exclude))
499                    } else {
500                        None
501                    },
502                },
503                ActionWire::DeliverLocal {
504                    destination_hash,
505                    raw,
506                    packet_hash,
507                    receiving_interface,
508                } => TransportAction::DeliverLocal {
509                    destination_hash,
510                    raw: raw.into(),
511                    packet_hash,
512                    receiving_interface: InterfaceId(receiving_interface),
513                },
514                ActionWire::PathUpdated {
515                    destination_hash,
516                    hops,
517                    next_hop,
518                    interface,
519                } => TransportAction::PathUpdated {
520                    destination_hash,
521                    hops,
522                    next_hop,
523                    interface: InterfaceId(interface),
524                },
525                ActionWire::CacheAnnounce { packet_hash, raw } => TransportAction::CacheAnnounce {
526                    packet_hash,
527                    raw: raw.into(),
528                },
529                ActionWire::TunnelEstablished {
530                    tunnel_id,
531                    interface,
532                } => TransportAction::TunnelEstablished {
533                    tunnel_id,
534                    interface: InterfaceId(interface),
535                },
536                ActionWire::TunnelSynthesize {
537                    interface,
538                    data,
539                    dest_hash,
540                } => TransportAction::TunnelSynthesize {
541                    interface: InterfaceId(interface),
542                    data,
543                    dest_hash,
544                },
545                ActionWire::ForwardToLocalClients {
546                    raw,
547                    exclude,
548                    has_exclude,
549                } => TransportAction::ForwardToLocalClients {
550                    raw: raw.into(),
551                    exclude: if has_exclude != 0 {
552                        Some(InterfaceId(exclude))
553                    } else {
554                        None
555                    },
556                },
557                ActionWire::ForwardPlainBroadcast {
558                    raw,
559                    to_local,
560                    exclude,
561                    has_exclude,
562                } => TransportAction::ForwardPlainBroadcast {
563                    raw: raw.into(),
564                    to_local: to_local != 0,
565                    exclude: if has_exclude != 0 {
566                        Some(InterfaceId(exclude))
567                    } else {
568                        None
569                    },
570                },
571                ActionWire::AnnounceReceived {
572                    destination_hash,
573                    identity_hash,
574                    public_key,
575                    name_hash,
576                    random_hash,
577                    app_data,
578                    hops,
579                    receiving_interface,
580                } => TransportAction::AnnounceReceived(Box::new(ReceivedAnnounce {
581                    destination_hash,
582                    identity_hash,
583                    public_key,
584                    name_hash,
585                    random_hash,
586                    ratchet: None,
587                    app_data,
588                    hops,
589                    receiving_interface: InterfaceId(receiving_interface),
590                    rx: rns_core::transport::RxMetadata::default(),
591                })),
592            }
593        })
594        .collect()
595}
596
597/// Infer the interface type string from a dynamic interface's name.
598/// Dynamic interfaces (TCP server clients, backbone peers, auto peers, local server clients)
599/// include their type in the name prefix set at construction.
600fn infer_interface_type(name: &str) -> String {
601    if name.starts_with("TCPServerInterface") {
602        "TCPServerClientInterface".to_string()
603    } else if name.starts_with("BackboneInterface") {
604        "BackboneInterface".to_string()
605    } else if name.starts_with("LocalInterface") {
606        "LocalServerClientInterface".to_string()
607    } else if name.starts_with("WeaveInterfacePeer[") {
608        "WeaveInterfacePeer".to_string()
609    } else {
610        // AutoInterface peers use "{group_name}:{peer_addr}" format where
611        // group_name is the config section name (typically "AutoInterface" or similar).
612        "AutoInterface".to_string()
613    }
614}
615
616pub use crate::common::callbacks::Callbacks;
617
618#[derive(Clone)]
619struct SharedAnnounceRecord {
620    name_hash: [u8; 10],
621    identity_prv_key: [u8; 64],
622    app_data: Option<Vec<u8>>,
623}
624
625#[derive(Debug, Clone)]
626pub(crate) struct KnownDestinationState {
627    announced: crate::destination::AnnouncedIdentity,
628    was_used: bool,
629    last_used_at: Option<f64>,
630    retained: bool,
631}
632
633struct KnownDestinationCleanup {
634    candidates: Vec<[u8; 16]>,
635    cursor: usize,
636    started_at: Instant,
637    removed: usize,
638}
639
640#[derive(Debug, Clone, Copy)]
641pub(crate) struct TrafficSample {
642    sampled_at: f64,
643    rxb: u64,
644    txb: u64,
645    rx_packets: u64,
646    tx_packets: u64,
647    arxb: u64,
648    atxb: u64,
649    prxb: u64,
650    ptxb: u64,
651}
652
653impl TrafficSample {
654    fn from_stats(sampled_at: f64, stats: &crate::interface::InterfaceStats) -> Self {
655        Self {
656            sampled_at,
657            rxb: stats.rxb,
658            txb: stats.txb,
659            rx_packets: stats.rx_packets,
660            tx_packets: stats.tx_packets,
661            arxb: stats.arxb,
662            atxb: stats.atxb,
663            prxb: stats.prxb,
664            ptxb: stats.ptxb,
665        }
666    }
667}
668
669/// The driver loop. Owns the engine and all interface entries.
670pub(crate) struct ManagedInterface {
671    pub(crate) parent_id: InterfaceId,
672    pub(crate) type_name: String,
673    pub(crate) control: Option<crate::interface::ListenerControl>,
674    pub(crate) static_ids: Vec<InterfaceId>,
675}
676
677pub struct Driver {
678    resource_preparation: Option<resource_preparation::Worker>,
679    pub(crate) tracked_link_send: Option<([u8; 32], crate::link_send::Completion)>,
680    pub(crate) pending_link_frames: std::collections::VecDeque<PendingLinkFrame>,
681    pub(crate) engine: TransportEngine,
682    pub(crate) interfaces: crate::interface::InterfaceMap<InterfaceEntry>,
683    /// Parent listener for dynamically spawned interfaces.
684    pub(crate) dynamic_interface_parents: HashMap<InterfaceId, InterfaceId>,
685    /// Previous cumulative counters used to calculate current one-second rates.
686    pub(crate) traffic_samples: HashMap<InterfaceId, TrafficSample>,
687    pub(crate) rng: OsRng,
688    pub(crate) rx: EventReceiver,
689    pub(crate) callbacks: Box<dyn Callbacks>,
690    pub(crate) started: f64,
691    pub(crate) lifecycle_state: LifecycleState,
692    pub(crate) drain_started_at: Option<Instant>,
693    pub(crate) drain_deadline: Option<Instant>,
694    pub(crate) listener_controls: Vec<crate::interface::ListenerControl>,
695    pub(crate) interface_management: Option<crate::node::InterfaceManagementConfig>,
696    pub(crate) managed_interfaces: HashMap<String, ManagedInterface>,
697    pub(crate) retired_interface_parents: HashSet<InterfaceId>,
698    /// Writers that may hold frames queued without a wakeup.
699    pub(crate) writers_to_wake: Vec<InterfaceId>,
700    /// Ingress burst state last published to the event queue, per interface.
701    pub(crate) published_ingress_bursts: crate::interface::InterfaceMap<(Option<f64>, Option<f64>)>,
702    pub(crate) announce_cache: Option<crate::announce_cache::AnnounceCache>,
703    /// Destination hash for rnstransport.tunnel.synthesize (PLAIN).
704    pub(crate) tunnel_synth_dest: [u8; 16],
705    /// Transport identity (optional, needed for tunnel synthesis).
706    pub(crate) transport_identity: Option<rns_crypto::identity::Identity>,
707    /// Link manager: handles link lifecycle, request/response.
708    pub(crate) link_manager: LinkManager,
709    /// Management configuration for ACL checks.
710    pub(crate) management_config: crate::management::ManagementConfig,
711    /// Last time management announces were emitted.
712    pub(crate) last_management_announce: f64,
713    /// Whether initial management announce has been sent (delayed 5s after start).
714    pub(crate) initial_announce_sent: bool,
715    /// Cache of known announced identities and lifecycle state, keyed by destination hash.
716    pub(crate) known_destinations: HashMap<[u8; 16], KnownDestinationState>,
717    /// Store for received remote ratchets, if persistence/use is enabled.
718    pub(crate) ratchet_store: Option<Arc<dyn crate::storage::RatchetStore>>,
719    /// TTL for received ratchets, in seconds.
720    pub(crate) ratchet_expiry_secs: f64,
721    /// TTL for known destinations without an active path, in seconds.
722    pub(crate) known_destinations_ttl: f64,
723    /// Maximum number of retained known destinations.
724    pub(crate) known_destinations_max_entries: usize,
725    /// TTL for announce rate-limiter entries without an active path, in seconds.
726    pub(crate) rate_limiter_ttl_secs: f64,
727    /// Destination hash for rnstransport.path.request (PLAIN).
728    pub(crate) path_request_dest: [u8; 16],
729    /// Proof strategies per destination hash.
730    /// Maps dest_hash → (strategy, optional signing identity for generating proofs).
731    pub(crate) proof_strategies: HashMap<
732        [u8; 16],
733        (
734            rns_core::types::ProofStrategy,
735            Option<rns_crypto::identity::Identity>,
736        ),
737    >,
738    /// Tracked sent packets for proof matching: packet_hash → (dest_hash, sent_time).
739    pub(crate) sent_packets: HashMap<[u8; 32], ([u8; 16], f64)>,
740    /// Completed proofs for probe polling: packet_hash → (rtt_seconds, received_time).
741    pub(crate) completed_proofs: HashMap<[u8; 32], (f64, f64)>,
742    /// Locally registered destinations: hash → dest_type.
743    pub(crate) local_destinations: HashMap<[u8; 16], u8>,
744    /// Latest explicit SINGLE announces to replay after shared-client reconnect.
745    shared_announces: HashMap<[u8; 16], SharedAnnounceRecord>,
746    /// Shared local interfaces that went down and should replay announces on reconnect.
747    shared_reconnect_pending: HashMap<InterfaceId, bool>,
748    /// Hole-punch manager for direct P2P connections.
749    pub(crate) holepunch_manager: HolePunchManager,
750    /// Event sender for worker threads to send results back to the driver loop.
751    pub(crate) event_tx: crate::event::EventSender,
752    /// Maximum queued outbound frames per interface writer worker.
753    pub(crate) interface_writer_queue_capacity: usize,
754    /// Linux mark inherited by dynamically created IP underlay sockets.
755    pub(crate) underlay_mark: Option<u32>,
756    /// Default announce-rate controls for interfaces on transport nodes.
757    pub(crate) announce_rate_defaults: AnnounceRateDefaults,
758    /// Default ingress/egress controls for interfaces on transport nodes.
759    pub(crate) ingress_control_defaults: rns_core::transport::types::IngressControlConfig,
760    /// Shared timer interval used by the node timer thread.
761    pub(crate) tick_interval_ms: Arc<AtomicU64>,
762    /// Runtime-config handles for backbone server interfaces, keyed by config name.
763    #[cfg(feature = "iface-backbone")]
764    pub(crate) backbone_runtime: HashMap<String, BackboneRuntimeConfigHandle>,
765    /// Live peer-state handles for backbone server interfaces, keyed by config name.
766    #[cfg(feature = "iface-backbone")]
767    pub(crate) backbone_peer_state: HashMap<String, BackbonePeerStateHandle>,
768    /// Runtime-config handles for backbone client interfaces, keyed by config name.
769    #[cfg(feature = "iface-backbone")]
770    pub(crate) backbone_client_runtime: HashMap<String, BackboneClientRuntimeConfigHandle>,
771    /// Runtime-config state for backbone discovery metadata, keyed by config name.
772    #[cfg(feature = "iface-backbone")]
773    pub(crate) backbone_discovery_runtime: HashMap<String, BackboneDiscoveryRuntimeHandle>,
774    /// Ordered outbound Backbone peer pool, if enabled.
775    #[cfg(feature = "iface-backbone")]
776    backbone_peer_pool: Option<BackbonePeerPool>,
777    /// Shared allocator for listener-created and discovery-created dynamic interfaces.
778    pub(crate) next_dynamic_interface_id: Arc<AtomicU64>,
779    /// Runtime-config handles for TCP server interfaces, keyed by config name.
780    #[cfg(feature = "iface-tcp")]
781    pub(crate) tcp_server_runtime: HashMap<String, TcpServerRuntimeConfigHandle>,
782    /// Runtime-config handles for TCP client interfaces, keyed by config name.
783    #[cfg(feature = "iface-tcp")]
784    pub(crate) tcp_client_runtime: HashMap<String, TcpClientRuntimeConfigHandle>,
785    /// Runtime-config state for TCP server discovery metadata, keyed by config name.
786    #[cfg(feature = "iface-tcp")]
787    pub(crate) tcp_server_discovery_runtime: HashMap<String, TcpServerDiscoveryRuntimeHandle>,
788    /// Runtime-config handles for UDP interfaces, keyed by config name.
789    #[cfg(feature = "iface-udp")]
790    pub(crate) udp_runtime: HashMap<String, UdpRuntimeConfigHandle>,
791    /// Runtime-config handles for Auto interfaces, keyed by config name.
792    #[cfg(feature = "iface-auto")]
793    pub(crate) auto_runtime: HashMap<String, AutoRuntimeConfigHandle>,
794    /// Runtime-config handles for I2P interfaces, keyed by config name.
795    #[cfg(feature = "iface-i2p")]
796    pub(crate) i2p_runtime: HashMap<String, I2pRuntimeConfigHandle>,
797    /// Runtime-config handles for Pipe interfaces, keyed by config name.
798    #[cfg(feature = "iface-pipe")]
799    pub(crate) pipe_runtime: HashMap<String, PipeRuntimeConfigHandle>,
800    /// Runtime-config handles for RNode interfaces, keyed by config name.
801    #[cfg(feature = "iface-rnode")]
802    pub(crate) rnode_runtime: HashMap<String, RNodeRuntimeConfigHandle>,
803    /// Startup/default interface metadata for generic cross-cutting runtime config.
804    pub(crate) interface_runtime_defaults:
805        HashMap<String, rns_core::transport::types::InterfaceInfo>,
806    /// Current IFAC runtime config for static interfaces that support IFAC mutation.
807    pub(crate) interface_ifac_runtime: HashMap<String, IfacRuntimeConfig>,
808    /// Startup/default IFAC runtime config for static interfaces.
809    pub(crate) interface_ifac_runtime_defaults: HashMap<String, IfacRuntimeConfig>,
810    /// Storage for discovered interfaces.
811    pub(crate) discovered_interfaces: crate::discovery::DiscoveredInterfaceStorage,
812    /// Required stamp value for accepting discovered interfaces.
813    pub(crate) discovery_required_value: u8,
814    /// Bounded cache of discovery payloads with previously rejected stamps.
815    pub(crate) discovery_stamp_cache: crate::discovery::DiscoveryStampCache,
816    /// Name hash for interface discovery announces ("rnstransport.discovery.interface").
817    pub(crate) discovery_name_hash: [u8; 10],
818    /// Destination hash for the probe responder (if respond_to_probes is enabled).
819    pub(crate) probe_responder_hash: Option<[u8; 16]>,
820    /// Whether interface discovery is enabled.
821    pub(crate) discover_interfaces: bool,
822    /// Explicit mode for interfaces created from discovery announces.
823    pub(crate) autoconnect_interface_mode: Option<u8>,
824    /// Gravity for interfaces created from discovery announces.
825    pub(crate) autoconnect_interface_gravity: i64,
826    /// Internal announce propagation override for discovered interfaces.
827    pub(crate) autoconnect_announces_to_internal: Option<bool>,
828    /// Allow auto-connecting discovered interfaces from unverified implementations.
829    pub(crate) autoconnect_unverified_implementations: bool,
830    /// Announcer for discoverable interfaces (None if nothing to announce).
831    pub(crate) interface_announcer: Option<crate::discovery::InterfaceAnnouncer>,
832    /// Shared async announce verification queue.
833    pub(crate) announce_verify_queue: Arc<Mutex<AnnounceVerifyQueue>>,
834    /// Whether inbound announces should be verified off the driver thread.
835    pub(crate) async_announce_verification: bool,
836    /// Tick counter for periodic discovery cleanup (every ~3600 ticks = ~1 hour).
837    pub(crate) discovery_cleanup_counter: u32,
838    /// Runtime-configurable discovery cleanup interval.
839    pub(crate) discovery_cleanup_interval_ticks: u32,
840    /// Tick counter for periodic MEMSTATS logging (every 300 ticks = ~5 min).
841    pub(crate) memory_stats_counter: u32,
842    /// Tick counter for periodic memory/cache cleanup (every ~3600 ticks = ~1 hour).
843    pub(crate) cache_cleanup_counter: u32,
844    /// Tick counter for incremental announce-cache cleanup scheduling.
845    pub(crate) announce_cache_cleanup_counter: u32,
846    /// Runtime-configurable cleanup interval for known destinations.
847    pub(crate) known_destinations_cleanup_interval_ticks: u32,
848    /// Incremental known-destination cleanup pass, if one is active.
849    known_destination_cleanup: Option<KnownDestinationCleanup>,
850    /// Low-priority ratchet filesystem cleanup associated with the last pass.
851    ratchet_cleanup_handle: Option<std::thread::JoinHandle<()>>,
852    /// Count of known-destination cap evictions since start.
853    pub(crate) known_destinations_cap_evict_count: usize,
854    /// Runtime-configurable interval for starting announce cache cleanup.
855    pub(crate) announce_cache_cleanup_interval_ticks: u32,
856    /// When set, announce cache cleanup is in progress (contains active packet hashes).
857    pub(crate) cache_cleanup_active_hashes: Option<Vec<[u8; 32]>>,
858    /// Directory iterator for incremental announce cache cleanup.
859    pub(crate) cache_cleanup_entries: Option<std::fs::ReadDir>,
860    /// Running total of files removed during current cache cleanup cycle.
861    pub(crate) cache_cleanup_removed: usize,
862    /// Runtime-configurable announce cache cleanup batch size.
863    pub(crate) announce_cache_cleanup_batch_size: usize,
864    /// Runtime-configurable management announce interval.
865    pub(crate) management_announce_interval_secs: f64,
866    /// Startup/default runtime-config values.
867    pub(crate) runtime_config_defaults: RuntimeConfigDefaults,
868    /// Hook slots for the programmable hook system (one per HookPoint).
869    #[cfg(feature = "hooks")]
870    pub(crate) hook_slots: [HookSlot; HookPoint::COUNT],
871    /// Hook manager. None if initialization failed.
872    #[cfg(feature = "hooks")]
873    pub(crate) hook_manager: Option<HookManager>,
874    #[cfg(feature = "hooks")]
875    pub(crate) provider_bridge: Option<ProviderBridge>,
876    /// Per hook point count of `Modify` replacements that failed validation
877    /// and were therefore treated as `Drop`.
878    #[cfg(feature = "hooks")]
879    pub(crate) hook_rejected_modifications: [u64; HookPoint::COUNT],
880}
881
882impl Driver {
883    /// Create a new driver.
884    pub fn new(
885        config: TransportConfig,
886        rx: EventReceiver,
887        tx: crate::event::EventSender,
888        callbacks: Box<dyn Callbacks>,
889    ) -> Self {
890        let announce_queue_max_entries = config.announce_queue_max_entries;
891        let tunnel_synth_dest = rns_core::destination::destination_hash(
892            "rnstransport",
893            &["tunnel", "synthesize"],
894            None,
895        );
896        let path_request_dest =
897            rns_core::destination::destination_hash("rnstransport", &["path", "request"], None);
898        let discovery_name_hash = crate::discovery::discovery_name_hash();
899        let mut engine = TransportEngine::new(config);
900        engine.seed_table_hashing(&mut OsRng);
901        engine.register_destination(tunnel_synth_dest, rns_core::constants::DESTINATION_PLAIN);
902        // Register path request destination so inbound path requests are delivered locally
903        engine.register_destination(path_request_dest, rns_core::constants::DESTINATION_PLAIN);
904        // Note: discovery destination is NOT registered as local — it's a SINGLE destination
905        // whose hash depends on the sender's identity. We match it by name_hash instead.
906        let mut local_destinations = HashMap::new();
907        local_destinations.insert(tunnel_synth_dest, rns_core::constants::DESTINATION_PLAIN);
908        local_destinations.insert(path_request_dest, rns_core::constants::DESTINATION_PLAIN);
909        let runtime_config_defaults = RuntimeConfigDefaults {
910            tick_interval_ms: DEFAULT_TICK_INTERVAL_MS,
911            known_destinations_ttl: DEFAULT_KNOWN_DESTINATIONS_TTL,
912            rate_limiter_ttl_secs: DEFAULT_RATE_LIMITER_TTL_SECS,
913            known_destinations_cleanup_interval_ticks:
914                DEFAULT_KNOWN_DESTINATIONS_CLEANUP_INTERVAL_TICKS,
915            announce_cache_cleanup_interval_ticks: DEFAULT_ANNOUNCE_CACHE_CLEANUP_INTERVAL_TICKS,
916            announce_cache_cleanup_batch_size: DEFAULT_ANNOUNCE_CACHE_CLEANUP_BATCH_SIZE,
917            discovery_cleanup_interval_ticks: DEFAULT_DISCOVERY_CLEANUP_INTERVAL_TICKS,
918            management_announce_interval_secs: DEFAULT_MANAGEMENT_ANNOUNCE_INTERVAL_SECS,
919            direct_connect_policy: crate::event::HolePunchPolicy::default(),
920            #[cfg(feature = "hooks")]
921            provider_queue_max_events: crate::provider_bridge::ProviderBridgeConfig::default()
922                .queue_max_events,
923            #[cfg(feature = "hooks")]
924            provider_queue_max_bytes: crate::provider_bridge::ProviderBridgeConfig::default()
925                .queue_max_bytes,
926        };
927        Driver {
928            tracked_link_send: None,
929            pending_link_frames: std::collections::VecDeque::new(),
930            engine,
931            interfaces: Default::default(),
932            dynamic_interface_parents: HashMap::new(),
933            traffic_samples: HashMap::new(),
934            rng: OsRng,
935            rx,
936            callbacks,
937            started: time::now(),
938            lifecycle_state: LifecycleState::Active,
939            drain_started_at: None,
940            drain_deadline: None,
941            listener_controls: Vec::new(),
942            interface_management: None,
943            managed_interfaces: HashMap::new(),
944            retired_interface_parents: HashSet::new(),
945            published_ingress_bursts: Default::default(),
946            writers_to_wake: Vec::new(),
947            announce_cache: None,
948            tunnel_synth_dest,
949            transport_identity: None,
950            link_manager: LinkManager::new(),
951            management_config: Default::default(),
952            last_management_announce: 0.0,
953            initial_announce_sent: false,
954            known_destinations: HashMap::new(),
955            ratchet_store: None,
956            ratchet_expiry_secs: rns_core::constants::RATCHET_EXPIRY as f64,
957            known_destinations_ttl: DEFAULT_KNOWN_DESTINATIONS_TTL,
958            known_destinations_max_entries: DEFAULT_KNOWN_DESTINATIONS_MAX_ENTRIES,
959            rate_limiter_ttl_secs: DEFAULT_RATE_LIMITER_TTL_SECS,
960            path_request_dest,
961            proof_strategies: HashMap::new(),
962            sent_packets: HashMap::new(),
963            completed_proofs: HashMap::new(),
964            local_destinations,
965            shared_announces: HashMap::new(),
966            shared_reconnect_pending: HashMap::new(),
967            holepunch_manager: HolePunchManager::new(
968                vec![],
969                rns_core::holepunch::ProbeProtocol::Rnsp,
970                None,
971            ),
972            event_tx: tx,
973            interface_writer_queue_capacity: crate::interface::DEFAULT_ASYNC_WRITER_QUEUE_CAPACITY,
974            underlay_mark: None,
975            announce_rate_defaults: AnnounceRateDefaults::default(),
976            ingress_control_defaults: rns_core::transport::types::IngressControlConfig::enabled(),
977            tick_interval_ms: Arc::new(AtomicU64::new(DEFAULT_TICK_INTERVAL_MS)),
978            #[cfg(feature = "iface-backbone")]
979            backbone_runtime: HashMap::new(),
980            #[cfg(feature = "iface-backbone")]
981            backbone_peer_state: HashMap::new(),
982            #[cfg(feature = "iface-backbone")]
983            backbone_client_runtime: HashMap::new(),
984            #[cfg(feature = "iface-backbone")]
985            backbone_discovery_runtime: HashMap::new(),
986            #[cfg(feature = "iface-backbone")]
987            backbone_peer_pool: None,
988            next_dynamic_interface_id: Arc::new(AtomicU64::new(10000)),
989            #[cfg(feature = "iface-tcp")]
990            tcp_server_runtime: HashMap::new(),
991            #[cfg(feature = "iface-tcp")]
992            tcp_client_runtime: HashMap::new(),
993            #[cfg(feature = "iface-tcp")]
994            tcp_server_discovery_runtime: HashMap::new(),
995            #[cfg(feature = "iface-udp")]
996            udp_runtime: HashMap::new(),
997            #[cfg(feature = "iface-auto")]
998            auto_runtime: HashMap::new(),
999            #[cfg(feature = "iface-i2p")]
1000            i2p_runtime: HashMap::new(),
1001            #[cfg(feature = "iface-pipe")]
1002            pipe_runtime: HashMap::new(),
1003            #[cfg(feature = "iface-rnode")]
1004            rnode_runtime: HashMap::new(),
1005            interface_runtime_defaults: HashMap::new(),
1006            interface_ifac_runtime: HashMap::new(),
1007            interface_ifac_runtime_defaults: HashMap::new(),
1008            discovered_interfaces: crate::discovery::DiscoveredInterfaceStorage::new(
1009                std::env::temp_dir().join("rns-discovered-interfaces"),
1010            ),
1011            discovery_required_value: crate::discovery::DEFAULT_STAMP_VALUE,
1012            discovery_stamp_cache: crate::discovery::DiscoveryStampCache::default(),
1013            discovery_name_hash,
1014            probe_responder_hash: None,
1015            discover_interfaces: false,
1016            autoconnect_interface_mode: None,
1017            autoconnect_interface_gravity: 0,
1018            autoconnect_announces_to_internal: None,
1019            autoconnect_unverified_implementations: false,
1020            interface_announcer: None,
1021            announce_verify_queue: Arc::new(Mutex::new(AnnounceVerifyQueue::new(
1022                announce_queue_max_entries,
1023            ))),
1024            async_announce_verification: false,
1025            discovery_cleanup_counter: 0,
1026            discovery_cleanup_interval_ticks: runtime_config_defaults
1027                .discovery_cleanup_interval_ticks,
1028            memory_stats_counter: 0,
1029            cache_cleanup_counter: 0,
1030            announce_cache_cleanup_counter: 0,
1031            known_destinations_cleanup_interval_ticks: runtime_config_defaults
1032                .known_destinations_cleanup_interval_ticks,
1033            known_destination_cleanup: None,
1034            ratchet_cleanup_handle: None,
1035            resource_preparation: None,
1036            known_destinations_cap_evict_count: 0,
1037            announce_cache_cleanup_interval_ticks: runtime_config_defaults
1038                .announce_cache_cleanup_interval_ticks,
1039            cache_cleanup_active_hashes: None,
1040            cache_cleanup_entries: None,
1041            cache_cleanup_removed: 0,
1042            announce_cache_cleanup_batch_size: runtime_config_defaults
1043                .announce_cache_cleanup_batch_size,
1044            management_announce_interval_secs: runtime_config_defaults
1045                .management_announce_interval_secs,
1046            runtime_config_defaults,
1047            #[cfg(feature = "hooks")]
1048            hook_slots: create_hook_slots(),
1049            #[cfg(feature = "hooks")]
1050            hook_manager: HookManager::new().ok(),
1051            #[cfg(feature = "hooks")]
1052            provider_bridge: None,
1053            #[cfg(feature = "hooks")]
1054            hook_rejected_modifications: [0; HookPoint::COUNT],
1055        }
1056    }
1057
1058    pub fn set_announce_verify_queue_config(
1059        &mut self,
1060        max_entries: usize,
1061        max_bytes: usize,
1062        max_stale_secs: f64,
1063        overflow_policy: OverflowPolicy,
1064    ) {
1065        self.announce_verify_queue = Arc::new(Mutex::new(AnnounceVerifyQueue::with_limits(
1066            max_entries,
1067            max_bytes,
1068            max_stale_secs,
1069            overflow_policy,
1070        )));
1071    }
1072
1073    pub fn set_announce_rate_defaults(&mut self, defaults: AnnounceRateDefaults) {
1074        self.announce_rate_defaults = defaults;
1075    }
1076
1077    pub fn set_ingress_control_defaults(
1078        &mut self,
1079        defaults: rns_core::transport::types::IngressControlConfig,
1080    ) {
1081        self.ingress_control_defaults = defaults;
1082    }
1083
1084    pub(crate) fn apply_announce_rate_defaults(
1085        &self,
1086        info: &mut rns_core::transport::types::InterfaceInfo,
1087    ) {
1088        if !self.engine.transport_enabled() || info.announce_rate_target.is_some() {
1089            return;
1090        }
1091
1092        let Some(target) = self.announce_rate_defaults.target else {
1093            return;
1094        };
1095
1096        info.announce_rate_target = Some(target);
1097        if info.announce_rate_grace == 0 {
1098            info.announce_rate_grace = self.announce_rate_defaults.grace;
1099        }
1100        if info.announce_rate_penalty == 0.0 {
1101            info.announce_rate_penalty = self.announce_rate_defaults.penalty;
1102        }
1103    }
1104
1105    pub(crate) fn apply_ingress_control_defaults(
1106        &self,
1107        info: &mut rns_core::transport::types::InterfaceInfo,
1108    ) {
1109        if !self.engine.transport_enabled() {
1110            return;
1111        }
1112
1113        let baseline = if info.ingress_control.enabled {
1114            rns_core::transport::types::IngressControlConfig::enabled()
1115        } else {
1116            rns_core::transport::types::IngressControlConfig::disabled()
1117        };
1118        let defaults = self.ingress_control_defaults;
1119        let ic = &mut info.ingress_control;
1120
1121        if ic.max_held_announces == baseline.max_held_announces {
1122            ic.max_held_announces = defaults.max_held_announces;
1123        }
1124        if ic.burst_hold == baseline.burst_hold {
1125            ic.burst_hold = defaults.burst_hold;
1126        }
1127        if ic.burst_freq_new == baseline.burst_freq_new {
1128            ic.burst_freq_new = defaults.burst_freq_new;
1129        }
1130        if ic.burst_freq == baseline.burst_freq {
1131            ic.burst_freq = defaults.burst_freq;
1132        }
1133        if ic.pr_burst_freq_new == baseline.pr_burst_freq_new {
1134            ic.pr_burst_freq_new = defaults.pr_burst_freq_new;
1135        }
1136        if ic.pr_burst_freq == baseline.pr_burst_freq {
1137            ic.pr_burst_freq = defaults.pr_burst_freq;
1138        }
1139        if ic.new_time == baseline.new_time {
1140            ic.new_time = defaults.new_time;
1141        }
1142        if ic.burst_penalty == baseline.burst_penalty {
1143            ic.burst_penalty = defaults.burst_penalty;
1144        }
1145        if ic.held_release_interval == baseline.held_release_interval {
1146            ic.held_release_interval = defaults.held_release_interval;
1147        }
1148        if ic.egress_enabled == baseline.egress_enabled {
1149            ic.egress_enabled = defaults.egress_enabled;
1150        }
1151        if ic.egress_pr_freq == baseline.egress_pr_freq {
1152            ic.egress_pr_freq = defaults.egress_pr_freq;
1153        }
1154    }
1155
1156    fn wrap_interface_writer(
1157        &self,
1158        interface_id: InterfaceId,
1159        interface_name: &str,
1160        writer: Box<dyn crate::interface::Writer>,
1161    ) -> (
1162        Box<dyn crate::interface::Writer>,
1163        crate::interface::AsyncWriterMetrics,
1164    ) {
1165        crate::interface::wrap_async_writer(
1166            writer,
1167            interface_id,
1168            interface_name,
1169            self.event_tx.clone(),
1170            self.interface_writer_queue_capacity,
1171        )
1172    }
1173
1174    #[cfg(feature = "hooks")]
1175    fn provider_events_enabled(&self) -> bool {
1176        self.provider_bridge.is_some()
1177    }
1178
1179    /// Whether any program is attached at `point`. Per-packet hook points
1180    /// check this before building a hook context, which reads the clock.
1181    #[cfg(feature = "hooks")]
1182    pub(crate) fn hooks_attached(&self, point: HookPoint) -> bool {
1183        !self.hook_slots[point as usize].programs.is_empty()
1184    }
1185
1186    #[cfg(feature = "hooks")]
1187    fn run_backbone_peer_hook(
1188        &mut self,
1189        attach_point: &str,
1190        point: HookPoint,
1191        event: &BackbonePeerHookEvent,
1192    ) {
1193        let ctx = backbone_peer_hook_context(event);
1194        let now = time::now();
1195        let engine_ref = EngineRef {
1196            engine: &self.engine,
1197            interfaces: &self.interfaces,
1198            link_manager: &self.link_manager,
1199            now,
1200        };
1201        let provider_events_enabled = self.provider_events_enabled();
1202        if let Some(ref e) = run_hook_inner(
1203            &mut self.hook_slots[point as usize].programs,
1204            &self.hook_manager,
1205            &engine_ref,
1206            &ctx,
1207            now,
1208            provider_events_enabled,
1209        ) {
1210            self.forward_hook_side_effects(attach_point, e);
1211        }
1212    }
1213
1214    #[cfg(feature = "iface-backbone")]
1215    fn make_discoverable_interface(
1216        runtime: &BackboneDiscoveryRuntimeHandle,
1217    ) -> crate::discovery::DiscoverableInterface {
1218        crate::discovery::DiscoverableInterface {
1219            interface_name: runtime.interface_name.clone(),
1220            config: runtime.current.config.clone(),
1221            transport_enabled: runtime.current.transport_enabled,
1222            ifac_netname: runtime.current.ifac_netname.clone(),
1223            ifac_netkey: runtime.current.ifac_netkey.clone(),
1224        }
1225    }
1226
1227    #[cfg(feature = "iface-backbone")]
1228    fn sync_backbone_discovery_runtime(
1229        &mut self,
1230        interface_name: &str,
1231    ) -> Result<(), RuntimeConfigError> {
1232        let handle = self
1233            .backbone_discovery_runtime
1234            .get(interface_name)
1235            .ok_or(RuntimeConfigError {
1236                code: RuntimeConfigErrorCode::NotFound,
1237                message: format!("backbone interface '{}' not found", interface_name),
1238            })?
1239            .clone();
1240
1241        if handle.current.discoverable {
1242            let iface = Self::make_discoverable_interface(&handle);
1243            if let Some(announcer) = self.interface_announcer.as_mut() {
1244                announcer.upsert_interface(iface);
1245            } else if let Some(identity) = self.transport_identity.as_ref() {
1246                self.interface_announcer = Some(crate::discovery::InterfaceAnnouncer::new(
1247                    *identity.hash(),
1248                    vec![iface],
1249                ));
1250            }
1251        } else if let Some(announcer) = self.interface_announcer.as_mut() {
1252            announcer.remove_interface(interface_name);
1253            if announcer.is_empty() {
1254                self.interface_announcer = None;
1255            }
1256        }
1257
1258        Ok(())
1259    }
1260
1261    #[cfg(feature = "iface-tcp")]
1262    fn make_tcp_server_discoverable_interface(
1263        runtime: &TcpServerDiscoveryRuntimeHandle,
1264    ) -> crate::discovery::DiscoverableInterface {
1265        crate::discovery::DiscoverableInterface {
1266            interface_name: runtime.interface_name.clone(),
1267            config: runtime.current.config.clone(),
1268            transport_enabled: runtime.current.transport_enabled,
1269            ifac_netname: runtime.current.ifac_netname.clone(),
1270            ifac_netkey: runtime.current.ifac_netkey.clone(),
1271        }
1272    }
1273
1274    #[cfg(feature = "iface-tcp")]
1275    fn sync_tcp_server_discovery_runtime(
1276        &mut self,
1277        interface_name: &str,
1278    ) -> Result<(), RuntimeConfigError> {
1279        let handle = self
1280            .tcp_server_discovery_runtime
1281            .get(interface_name)
1282            .ok_or(RuntimeConfigError {
1283                code: RuntimeConfigErrorCode::NotFound,
1284                message: format!("tcp server interface '{}' not found", interface_name),
1285            })?
1286            .clone();
1287
1288        if handle.current.discoverable {
1289            let iface = Self::make_tcp_server_discoverable_interface(&handle);
1290            if let Some(announcer) = self.interface_announcer.as_mut() {
1291                announcer.upsert_interface(iface);
1292            } else if let Some(identity) = self.transport_identity.as_ref() {
1293                self.interface_announcer = Some(crate::discovery::InterfaceAnnouncer::new(
1294                    *identity.hash(),
1295                    vec![iface],
1296                ));
1297            }
1298        } else if let Some(announcer) = self.interface_announcer.as_mut() {
1299            announcer.remove_interface(interface_name);
1300            if announcer.is_empty() {
1301                self.interface_announcer = None;
1302            }
1303        }
1304
1305        Ok(())
1306    }
1307
1308    #[cfg(feature = "hooks")]
1309    fn update_hook_program<F>(
1310        &mut self,
1311        name: &str,
1312        attach_point: &str,
1313        mut update: F,
1314    ) -> Result<(), String>
1315    where
1316        F: FnMut(&mut rns_hooks::LoadedProgram),
1317    {
1318        let point_idx = crate::config::parse_hook_point(attach_point)
1319            .ok_or_else(|| format!("unknown hook point '{}'", attach_point))?;
1320        let program = self.hook_slots[point_idx]
1321            .programs
1322            .iter_mut()
1323            .find(|program| program.name == name)
1324            .ok_or_else(|| format!("hook '{}' not found at point '{}'", name, attach_point))?;
1325        update(program);
1326        Ok(())
1327    }
1328
1329    pub(crate) fn set_tick_interval_handle(&mut self, tick_interval_ms: Arc<AtomicU64>) {
1330        self.tick_interval_ms = tick_interval_ms;
1331    }
1332
1333    #[allow(dead_code)]
1334    pub(crate) fn set_packet_hashlist_max_entries(&mut self, max_entries: usize) {
1335        self.engine.set_packet_hashlist_max_entries(max_entries);
1336    }
1337
1338    /// Turn a packet hook chain result into the action the hook point takes.
1339    ///
1340    /// `Drop` stops the packet. `Modify` with replacement bytes is validated
1341    /// against `max_len` and the packet decoder; a replacement that fails
1342    /// validation is treated as `Drop` and counted in
1343    /// `hook_rejected_modifications`. `Modify` without bytes, `Continue` and
1344    /// `Halt` keep the current bytes.
1345    #[cfg(feature = "hooks")]
1346    pub(crate) fn packet_hook_outcome(
1347        &mut self,
1348        point: HookPoint,
1349        exec: &rns_hooks::ExecuteResult,
1350        max_len: usize,
1351    ) -> PacketHookOutcome {
1352        let Some(result) = exec.hook_result.as_ref() else {
1353            return PacketHookOutcome::Keep;
1354        };
1355        if result.is_drop() {
1356            return PacketHookOutcome::Drop;
1357        }
1358        if rns_hooks::Verdict::from_u32(result.verdict) != Some(rns_hooks::Verdict::Modify) {
1359            return PacketHookOutcome::Keep;
1360        }
1361        let Some(data) = exec.modified_data.as_deref() else {
1362            return PacketHookOutcome::Keep;
1363        };
1364        match validate_hook_replacement(data, max_len) {
1365            Ok(packet) => PacketHookOutcome::Replace(packet),
1366            Err(reason) => {
1367                let rejected = &mut self.hook_rejected_modifications[point as usize];
1368                *rejected = rejected.saturating_add(1);
1369                log::debug!("{:?} hook: {}; dropping packet", point, reason);
1370                PacketHookOutcome::Drop
1371            }
1372        }
1373    }
1374
1375    /// Largest packet a hook may substitute for one handled on `interface`.
1376    #[cfg(feature = "hooks")]
1377    pub(crate) fn hook_packet_limit(&self, interface: InterfaceId) -> usize {
1378        self.interfaces
1379            .get(&interface)
1380            .map(|entry| entry.info.mtu as usize)
1381            .filter(|mtu| *mtu > 0)
1382            .unwrap_or(rns_core::constants::MTU)
1383    }
1384
1385    /// Point a pending confirmed link send at the replacement bytes a hook
1386    /// produced for the packet it was tracking.
1387    #[cfg(feature = "hooks")]
1388    pub(crate) fn retarget_tracked_link_send(&mut self, original: &[u8], replacement: &RawPacket) {
1389        let Some((hash, _)) = self.tracked_link_send.as_mut() else {
1390            return;
1391        };
1392        if RawPacket::unpack(original).is_ok_and(|packet| packet.packet_hash == *hash) {
1393            *hash = replacement.packet_hash;
1394        }
1395    }
1396
1397    #[cfg(feature = "hooks")]
1398    fn forward_hook_side_effects(&mut self, attach_point: &str, exec: &rns_hooks::ExecuteResult) {
1399        if !exec.injected_actions.is_empty() {
1400            self.dispatch_all(convert_injected_actions(exec.injected_actions.clone()));
1401        }
1402        if let Some(ref bridge) = self.provider_bridge {
1403            for event in &exec.provider_events {
1404                bridge.emit_event(
1405                    attach_point,
1406                    event.hook_name.clone(),
1407                    event.payload_type.clone(),
1408                    event.payload.clone(),
1409                );
1410            }
1411        }
1412    }
1413
1414    #[cfg(feature = "hooks")]
1415    fn collect_hook_side_effects(
1416        &mut self,
1417        attach_point: &str,
1418        exec: &rns_hooks::ExecuteResult,
1419        out: &mut Vec<TransportAction>,
1420    ) {
1421        if !exec.injected_actions.is_empty() {
1422            out.extend(convert_injected_actions(exec.injected_actions.clone()));
1423        }
1424        if let Some(ref bridge) = self.provider_bridge {
1425            for event in &exec.provider_events {
1426                bridge.emit_event(
1427                    attach_point,
1428                    event.hook_name.clone(),
1429                    event.payload_type.clone(),
1430                    event.payload.clone(),
1431                );
1432            }
1433        }
1434    }
1435
1436    /// Set the probe addresses, protocol, and optional device for hole punching.
1437    pub fn set_probe_config(
1438        &mut self,
1439        addrs: Vec<std::net::SocketAddr>,
1440        protocol: rns_core::holepunch::ProbeProtocol,
1441        device: Option<String>,
1442    ) {
1443        let policy = self.holepunch_manager.policy();
1444        let allow_private = self.holepunch_manager.allow_private_endpoints();
1445        self.holepunch_manager = HolePunchManager::new(addrs, protocol, device);
1446        self.holepunch_manager.set_underlay_mark(self.underlay_mark);
1447        self.holepunch_manager.set_policy(policy);
1448        self.holepunch_manager
1449            .set_allow_private_endpoints(allow_private);
1450    }
1451}
1452
1453pub(crate) struct PendingLinkFrame {
1454    interface: InterfaceId,
1455    data: Vec<u8>,
1456    is_announce: bool,
1457    completion: Option<crate::link_send::Completion>,
1458}