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/// Cache of path-response announces for local destinations:
626/// (destination, path-request tag) → (created, raw announce).
627type LocalPathResponseCache = HashMap<([u8; 16], Vec<u8>), (f64, Vec<u8>)>;
628
629#[derive(Debug, Clone)]
630pub(crate) struct KnownDestinationState {
631    announced: crate::destination::AnnouncedIdentity,
632    was_used: bool,
633    last_used_at: Option<f64>,
634    retained: bool,
635}
636
637struct KnownDestinationCleanup {
638    candidates: Vec<[u8; 16]>,
639    cursor: usize,
640    started_at: Instant,
641    removed: usize,
642}
643
644#[derive(Debug, Clone, Copy)]
645pub(crate) struct TrafficSample {
646    sampled_at: f64,
647    rxb: u64,
648    txb: u64,
649    rx_packets: u64,
650    tx_packets: u64,
651    arxb: u64,
652    atxb: u64,
653    prxb: u64,
654    ptxb: u64,
655}
656
657impl TrafficSample {
658    fn from_stats(sampled_at: f64, stats: &crate::interface::InterfaceStats) -> Self {
659        Self {
660            sampled_at,
661            rxb: stats.rxb,
662            txb: stats.txb,
663            rx_packets: stats.rx_packets,
664            tx_packets: stats.tx_packets,
665            arxb: stats.arxb,
666            atxb: stats.atxb,
667            prxb: stats.prxb,
668            ptxb: stats.ptxb,
669        }
670    }
671}
672
673/// The driver loop. Owns the engine and all interface entries.
674pub(crate) struct ManagedInterface {
675    pub(crate) parent_id: InterfaceId,
676    pub(crate) type_name: String,
677    pub(crate) control: Option<crate::interface::ListenerControl>,
678    pub(crate) static_ids: Vec<InterfaceId>,
679}
680
681pub struct Driver {
682    resource_preparation: Option<resource_preparation::Worker>,
683    pub(crate) tracked_link_send: Option<([u8; 32], crate::link_send::Completion)>,
684    pub(crate) pending_link_frames: std::collections::VecDeque<PendingLinkFrame>,
685    pub(crate) engine: TransportEngine,
686    pub(crate) interfaces: crate::interface::InterfaceMap<InterfaceEntry>,
687    /// Parent listener for dynamically spawned interfaces.
688    pub(crate) dynamic_interface_parents: HashMap<InterfaceId, InterfaceId>,
689    /// Previous cumulative counters used to calculate current one-second rates.
690    pub(crate) traffic_samples: HashMap<InterfaceId, TrafficSample>,
691    pub(crate) rng: OsRng,
692    pub(crate) rx: EventReceiver,
693    pub(crate) callbacks: Box<dyn Callbacks>,
694    pub(crate) started: f64,
695    pub(crate) lifecycle_state: LifecycleState,
696    pub(crate) drain_started_at: Option<Instant>,
697    pub(crate) drain_deadline: Option<Instant>,
698    pub(crate) listener_controls: Vec<crate::interface::ListenerControl>,
699    pub(crate) interface_management: Option<crate::node::InterfaceManagementConfig>,
700    pub(crate) managed_interfaces: HashMap<String, ManagedInterface>,
701    pub(crate) retired_interface_parents: HashSet<InterfaceId>,
702    /// Writers that may hold frames queued without a wakeup.
703    pub(crate) writers_to_wake: Vec<InterfaceId>,
704    /// Ingress burst state last published to the event queue, per interface.
705    pub(crate) published_ingress_bursts: crate::interface::InterfaceMap<(Option<f64>, Option<f64>)>,
706    pub(crate) announce_cache: Option<crate::announce_cache::AnnounceCache>,
707    /// Destination hash for rnstransport.tunnel.synthesize (PLAIN).
708    pub(crate) tunnel_synth_dest: [u8; 16],
709    /// Transport identity (optional, needed for tunnel synthesis).
710    pub(crate) transport_identity: Option<rns_crypto::identity::Identity>,
711    /// Link manager: handles link lifecycle, request/response.
712    pub(crate) link_manager: LinkManager,
713    /// Management configuration for ACL checks.
714    pub(crate) management_config: crate::management::ManagementConfig,
715    /// Last time management announces were emitted.
716    pub(crate) last_management_announce: f64,
717    /// Whether initial management announce has been sent (delayed 5s after start).
718    pub(crate) initial_announce_sent: bool,
719    /// Cache of known announced identities and lifecycle state, keyed by destination hash.
720    pub(crate) known_destinations: HashMap<[u8; 16], KnownDestinationState>,
721    /// Store for received remote ratchets, if persistence/use is enabled.
722    pub(crate) ratchet_store: Option<Arc<dyn crate::storage::RatchetStore>>,
723    /// TTL for received ratchets, in seconds.
724    pub(crate) ratchet_expiry_secs: f64,
725    /// TTL for known destinations without an active path, in seconds.
726    pub(crate) known_destinations_ttl: f64,
727    /// Maximum number of retained known destinations.
728    pub(crate) known_destinations_max_entries: usize,
729    /// TTL for announce rate-limiter entries without an active path, in seconds.
730    pub(crate) rate_limiter_ttl_secs: f64,
731    /// Destination hash for rnstransport.path.request (PLAIN).
732    pub(crate) path_request_dest: [u8; 16],
733    /// Proof strategies per destination hash.
734    /// Maps dest_hash → (strategy, optional signing identity for generating proofs).
735    pub(crate) proof_strategies: HashMap<
736        [u8; 16],
737        (
738            rns_core::types::ProofStrategy,
739            Option<rns_crypto::identity::Identity>,
740        ),
741    >,
742    /// Tracked sent packets for proof matching: packet_hash → (dest_hash, sent_time).
743    pub(crate) sent_packets: HashMap<[u8; 32], ([u8; 16], f64)>,
744    /// Completed proofs for probe polling: packet_hash → (rtt_seconds, received_time).
745    pub(crate) completed_proofs: HashMap<[u8; 32], (f64, f64)>,
746    /// Locally registered destinations: hash → dest_type.
747    pub(crate) local_destinations: HashMap<[u8; 16], u8>,
748    /// Latest explicit SINGLE announces to replay after shared-client reconnect.
749    shared_announces: HashMap<[u8; 16], SharedAnnounceRecord>,
750    /// Shared local interfaces that went down and should replay announces on reconnect.
751    shared_reconnect_pending: HashMap<InterfaceId, bool>,
752    /// Path-response announces recently sent for local destinations, keyed by
753    /// (destination, path-request tag), replayed byte-for-byte for a repeated
754    /// tag within `LOCAL_PATH_RESPONSE_WINDOW`: (created, raw announce).
755    pub(crate) local_path_responses: LocalPathResponseCache,
756    /// Hole-punch manager for direct P2P connections.
757    pub(crate) holepunch_manager: HolePunchManager,
758    /// Event sender for worker threads to send results back to the driver loop.
759    pub(crate) event_tx: crate::event::EventSender,
760    /// Maximum queued outbound frames per interface writer worker.
761    pub(crate) interface_writer_queue_capacity: usize,
762    /// Linux mark inherited by dynamically created IP underlay sockets.
763    pub(crate) underlay_mark: Option<u32>,
764    /// Default announce-rate controls for interfaces on transport nodes.
765    pub(crate) announce_rate_defaults: AnnounceRateDefaults,
766    /// Default ingress/egress controls for interfaces on transport nodes.
767    pub(crate) ingress_control_defaults: rns_core::transport::types::IngressControlConfig,
768    /// Shared timer interval used by the node timer thread.
769    pub(crate) tick_interval_ms: Arc<AtomicU64>,
770    /// Runtime-config handles for backbone server interfaces, keyed by config name.
771    #[cfg(feature = "iface-backbone")]
772    pub(crate) backbone_runtime: HashMap<String, BackboneRuntimeConfigHandle>,
773    /// Live peer-state handles for backbone server interfaces, keyed by config name.
774    #[cfg(feature = "iface-backbone")]
775    pub(crate) backbone_peer_state: HashMap<String, BackbonePeerStateHandle>,
776    /// Runtime-config handles for backbone client interfaces, keyed by config name.
777    #[cfg(feature = "iface-backbone")]
778    pub(crate) backbone_client_runtime: HashMap<String, BackboneClientRuntimeConfigHandle>,
779    /// Runtime-config state for backbone discovery metadata, keyed by config name.
780    #[cfg(feature = "iface-backbone")]
781    pub(crate) backbone_discovery_runtime: HashMap<String, BackboneDiscoveryRuntimeHandle>,
782    /// Ordered outbound Backbone peer pool, if enabled.
783    #[cfg(feature = "iface-backbone")]
784    backbone_peer_pool: Option<BackbonePeerPool>,
785    /// Shared allocator for listener-created and discovery-created dynamic interfaces.
786    pub(crate) next_dynamic_interface_id: Arc<AtomicU64>,
787    /// Runtime-config handles for TCP server interfaces, keyed by config name.
788    #[cfg(feature = "iface-tcp")]
789    pub(crate) tcp_server_runtime: HashMap<String, TcpServerRuntimeConfigHandle>,
790    /// Runtime-config handles for TCP client interfaces, keyed by config name.
791    #[cfg(feature = "iface-tcp")]
792    pub(crate) tcp_client_runtime: HashMap<String, TcpClientRuntimeConfigHandle>,
793    /// Runtime-config state for TCP server discovery metadata, keyed by config name.
794    #[cfg(feature = "iface-tcp")]
795    pub(crate) tcp_server_discovery_runtime: HashMap<String, TcpServerDiscoveryRuntimeHandle>,
796    /// Runtime-config handles for UDP interfaces, keyed by config name.
797    #[cfg(feature = "iface-udp")]
798    pub(crate) udp_runtime: HashMap<String, UdpRuntimeConfigHandle>,
799    /// Runtime-config handles for Auto interfaces, keyed by config name.
800    #[cfg(feature = "iface-auto")]
801    pub(crate) auto_runtime: HashMap<String, AutoRuntimeConfigHandle>,
802    /// Runtime-config handles for I2P interfaces, keyed by config name.
803    #[cfg(feature = "iface-i2p")]
804    pub(crate) i2p_runtime: HashMap<String, I2pRuntimeConfigHandle>,
805    /// Runtime-config handles for Pipe interfaces, keyed by config name.
806    #[cfg(feature = "iface-pipe")]
807    pub(crate) pipe_runtime: HashMap<String, PipeRuntimeConfigHandle>,
808    /// Runtime-config handles for RNode interfaces, keyed by config name.
809    #[cfg(feature = "iface-rnode")]
810    pub(crate) rnode_runtime: HashMap<String, RNodeRuntimeConfigHandle>,
811    /// Startup/default interface metadata for generic cross-cutting runtime config.
812    pub(crate) interface_runtime_defaults:
813        HashMap<String, rns_core::transport::types::InterfaceInfo>,
814    /// Current IFAC runtime config for static interfaces that support IFAC mutation.
815    pub(crate) interface_ifac_runtime: HashMap<String, IfacRuntimeConfig>,
816    /// Startup/default IFAC runtime config for static interfaces.
817    pub(crate) interface_ifac_runtime_defaults: HashMap<String, IfacRuntimeConfig>,
818    /// Storage for discovered interfaces.
819    pub(crate) discovered_interfaces: crate::discovery::DiscoveredInterfaceStorage,
820    /// Required stamp value for accepting discovered interfaces.
821    pub(crate) discovery_required_value: u8,
822    /// Bounded cache of discovery payloads with previously rejected stamps.
823    pub(crate) discovery_stamp_cache: crate::discovery::DiscoveryStampCache,
824    /// Name hash for interface discovery announces ("rnstransport.discovery.interface").
825    pub(crate) discovery_name_hash: [u8; 10],
826    /// Destination hash for the probe responder (if respond_to_probes is enabled).
827    pub(crate) probe_responder_hash: Option<[u8; 16]>,
828    /// Whether interface discovery is enabled.
829    pub(crate) discover_interfaces: bool,
830    /// Explicit mode for interfaces created from discovery announces.
831    pub(crate) autoconnect_interface_mode: Option<u8>,
832    /// Gravity for interfaces created from discovery announces.
833    pub(crate) autoconnect_interface_gravity: i64,
834    /// Internal announce propagation override for discovered interfaces.
835    pub(crate) autoconnect_announces_to_internal: Option<bool>,
836    /// Allow auto-connecting discovered interfaces from unverified implementations.
837    pub(crate) autoconnect_unverified_implementations: bool,
838    /// Announcer for discoverable interfaces (None if nothing to announce).
839    pub(crate) interface_announcer: Option<crate::discovery::InterfaceAnnouncer>,
840    /// Shared async announce verification queue.
841    pub(crate) announce_verify_queue: Arc<Mutex<AnnounceVerifyQueue>>,
842    /// Whether inbound announces should be verified off the driver thread.
843    pub(crate) async_announce_verification: bool,
844    /// Tick counter for periodic discovery cleanup (every ~3600 ticks = ~1 hour).
845    pub(crate) discovery_cleanup_counter: u32,
846    /// Runtime-configurable discovery cleanup interval.
847    pub(crate) discovery_cleanup_interval_ticks: u32,
848    /// Tick counter for periodic MEMSTATS logging (every 300 ticks = ~5 min).
849    pub(crate) memory_stats_counter: u32,
850    /// Tick counter for periodic memory/cache cleanup (every ~3600 ticks = ~1 hour).
851    pub(crate) cache_cleanup_counter: u32,
852    /// Tick counter for incremental announce-cache cleanup scheduling.
853    pub(crate) announce_cache_cleanup_counter: u32,
854    /// Runtime-configurable cleanup interval for known destinations.
855    pub(crate) known_destinations_cleanup_interval_ticks: u32,
856    /// Incremental known-destination cleanup pass, if one is active.
857    known_destination_cleanup: Option<KnownDestinationCleanup>,
858    /// Low-priority ratchet filesystem cleanup associated with the last pass.
859    ratchet_cleanup_handle: Option<std::thread::JoinHandle<()>>,
860    /// Count of known-destination cap evictions since start.
861    pub(crate) known_destinations_cap_evict_count: usize,
862    /// Runtime-configurable interval for starting announce cache cleanup.
863    pub(crate) announce_cache_cleanup_interval_ticks: u32,
864    /// When set, announce cache cleanup is in progress (contains active packet hashes).
865    pub(crate) cache_cleanup_active_hashes: Option<Vec<[u8; 32]>>,
866    /// Directory iterator for incremental announce cache cleanup.
867    pub(crate) cache_cleanup_entries: Option<std::fs::ReadDir>,
868    /// Running total of files removed during current cache cleanup cycle.
869    pub(crate) cache_cleanup_removed: usize,
870    /// Runtime-configurable announce cache cleanup batch size.
871    pub(crate) announce_cache_cleanup_batch_size: usize,
872    /// Runtime-configurable management announce interval.
873    pub(crate) management_announce_interval_secs: f64,
874    /// Startup/default runtime-config values.
875    pub(crate) runtime_config_defaults: RuntimeConfigDefaults,
876    /// Hook slots for the programmable hook system (one per HookPoint).
877    #[cfg(feature = "hooks")]
878    pub(crate) hook_slots: [HookSlot; HookPoint::COUNT],
879    /// Hook manager. None if initialization failed.
880    #[cfg(feature = "hooks")]
881    pub(crate) hook_manager: Option<HookManager>,
882    #[cfg(feature = "hooks")]
883    pub(crate) provider_bridge: Option<ProviderBridge>,
884    /// Per hook point count of `Modify` replacements that failed validation
885    /// and were therefore treated as `Drop`.
886    #[cfg(feature = "hooks")]
887    pub(crate) hook_rejected_modifications: [u64; HookPoint::COUNT],
888}
889
890impl Driver {
891    /// Create a new driver.
892    pub fn new(
893        config: TransportConfig,
894        rx: EventReceiver,
895        tx: crate::event::EventSender,
896        callbacks: Box<dyn Callbacks>,
897    ) -> Self {
898        let announce_queue_max_entries = config.announce_queue_max_entries;
899        let tunnel_synth_dest = rns_core::destination::destination_hash(
900            "rnstransport",
901            &["tunnel", "synthesize"],
902            None,
903        );
904        let path_request_dest =
905            rns_core::destination::destination_hash("rnstransport", &["path", "request"], None);
906        let discovery_name_hash = crate::discovery::discovery_name_hash();
907        let mut engine = TransportEngine::new(config);
908        engine.seed_table_hashing(&mut OsRng);
909        engine.register_destination(tunnel_synth_dest, rns_core::constants::DESTINATION_PLAIN);
910        // Register path request destination so inbound path requests are delivered locally
911        engine.register_destination(path_request_dest, rns_core::constants::DESTINATION_PLAIN);
912        // Note: discovery destination is NOT registered as local — it's a SINGLE destination
913        // whose hash depends on the sender's identity. We match it by name_hash instead.
914        let mut local_destinations = HashMap::new();
915        local_destinations.insert(tunnel_synth_dest, rns_core::constants::DESTINATION_PLAIN);
916        local_destinations.insert(path_request_dest, rns_core::constants::DESTINATION_PLAIN);
917        let runtime_config_defaults = RuntimeConfigDefaults {
918            tick_interval_ms: DEFAULT_TICK_INTERVAL_MS,
919            known_destinations_ttl: DEFAULT_KNOWN_DESTINATIONS_TTL,
920            rate_limiter_ttl_secs: DEFAULT_RATE_LIMITER_TTL_SECS,
921            known_destinations_cleanup_interval_ticks:
922                DEFAULT_KNOWN_DESTINATIONS_CLEANUP_INTERVAL_TICKS,
923            announce_cache_cleanup_interval_ticks: DEFAULT_ANNOUNCE_CACHE_CLEANUP_INTERVAL_TICKS,
924            announce_cache_cleanup_batch_size: DEFAULT_ANNOUNCE_CACHE_CLEANUP_BATCH_SIZE,
925            discovery_cleanup_interval_ticks: DEFAULT_DISCOVERY_CLEANUP_INTERVAL_TICKS,
926            management_announce_interval_secs: DEFAULT_MANAGEMENT_ANNOUNCE_INTERVAL_SECS,
927            direct_connect_policy: crate::event::HolePunchPolicy::default(),
928            #[cfg(feature = "hooks")]
929            provider_queue_max_events: crate::provider_bridge::ProviderBridgeConfig::default()
930                .queue_max_events,
931            #[cfg(feature = "hooks")]
932            provider_queue_max_bytes: crate::provider_bridge::ProviderBridgeConfig::default()
933                .queue_max_bytes,
934        };
935        Driver {
936            tracked_link_send: None,
937            pending_link_frames: std::collections::VecDeque::new(),
938            engine,
939            interfaces: Default::default(),
940            dynamic_interface_parents: HashMap::new(),
941            traffic_samples: HashMap::new(),
942            rng: OsRng,
943            rx,
944            callbacks,
945            started: time::now(),
946            lifecycle_state: LifecycleState::Active,
947            drain_started_at: None,
948            drain_deadline: None,
949            listener_controls: Vec::new(),
950            interface_management: None,
951            managed_interfaces: HashMap::new(),
952            retired_interface_parents: HashSet::new(),
953            published_ingress_bursts: Default::default(),
954            writers_to_wake: Vec::new(),
955            announce_cache: None,
956            tunnel_synth_dest,
957            transport_identity: None,
958            link_manager: LinkManager::new(),
959            management_config: Default::default(),
960            last_management_announce: 0.0,
961            initial_announce_sent: false,
962            known_destinations: HashMap::new(),
963            ratchet_store: None,
964            ratchet_expiry_secs: rns_core::constants::RATCHET_EXPIRY as f64,
965            known_destinations_ttl: DEFAULT_KNOWN_DESTINATIONS_TTL,
966            known_destinations_max_entries: DEFAULT_KNOWN_DESTINATIONS_MAX_ENTRIES,
967            rate_limiter_ttl_secs: DEFAULT_RATE_LIMITER_TTL_SECS,
968            path_request_dest,
969            proof_strategies: HashMap::new(),
970            sent_packets: HashMap::new(),
971            completed_proofs: HashMap::new(),
972            local_destinations,
973            shared_announces: HashMap::new(),
974            shared_reconnect_pending: HashMap::new(),
975            local_path_responses: HashMap::new(),
976            holepunch_manager: HolePunchManager::new(
977                vec![],
978                rns_core::holepunch::ProbeProtocol::Rnsp,
979                None,
980            ),
981            event_tx: tx,
982            interface_writer_queue_capacity: crate::interface::DEFAULT_ASYNC_WRITER_QUEUE_CAPACITY,
983            underlay_mark: None,
984            announce_rate_defaults: AnnounceRateDefaults::default(),
985            ingress_control_defaults: rns_core::transport::types::IngressControlConfig::enabled(),
986            tick_interval_ms: Arc::new(AtomicU64::new(DEFAULT_TICK_INTERVAL_MS)),
987            #[cfg(feature = "iface-backbone")]
988            backbone_runtime: HashMap::new(),
989            #[cfg(feature = "iface-backbone")]
990            backbone_peer_state: HashMap::new(),
991            #[cfg(feature = "iface-backbone")]
992            backbone_client_runtime: HashMap::new(),
993            #[cfg(feature = "iface-backbone")]
994            backbone_discovery_runtime: HashMap::new(),
995            #[cfg(feature = "iface-backbone")]
996            backbone_peer_pool: None,
997            next_dynamic_interface_id: Arc::new(AtomicU64::new(10000)),
998            #[cfg(feature = "iface-tcp")]
999            tcp_server_runtime: HashMap::new(),
1000            #[cfg(feature = "iface-tcp")]
1001            tcp_client_runtime: HashMap::new(),
1002            #[cfg(feature = "iface-tcp")]
1003            tcp_server_discovery_runtime: HashMap::new(),
1004            #[cfg(feature = "iface-udp")]
1005            udp_runtime: HashMap::new(),
1006            #[cfg(feature = "iface-auto")]
1007            auto_runtime: HashMap::new(),
1008            #[cfg(feature = "iface-i2p")]
1009            i2p_runtime: HashMap::new(),
1010            #[cfg(feature = "iface-pipe")]
1011            pipe_runtime: HashMap::new(),
1012            #[cfg(feature = "iface-rnode")]
1013            rnode_runtime: HashMap::new(),
1014            interface_runtime_defaults: HashMap::new(),
1015            interface_ifac_runtime: HashMap::new(),
1016            interface_ifac_runtime_defaults: HashMap::new(),
1017            discovered_interfaces: crate::discovery::DiscoveredInterfaceStorage::new(
1018                std::env::temp_dir().join("rns-discovered-interfaces"),
1019            ),
1020            discovery_required_value: crate::discovery::DEFAULT_STAMP_VALUE,
1021            discovery_stamp_cache: crate::discovery::DiscoveryStampCache::default(),
1022            discovery_name_hash,
1023            probe_responder_hash: None,
1024            discover_interfaces: false,
1025            autoconnect_interface_mode: None,
1026            autoconnect_interface_gravity: 0,
1027            autoconnect_announces_to_internal: None,
1028            autoconnect_unverified_implementations: false,
1029            interface_announcer: None,
1030            announce_verify_queue: Arc::new(Mutex::new(AnnounceVerifyQueue::new(
1031                announce_queue_max_entries,
1032            ))),
1033            async_announce_verification: false,
1034            discovery_cleanup_counter: 0,
1035            discovery_cleanup_interval_ticks: runtime_config_defaults
1036                .discovery_cleanup_interval_ticks,
1037            memory_stats_counter: 0,
1038            cache_cleanup_counter: 0,
1039            announce_cache_cleanup_counter: 0,
1040            known_destinations_cleanup_interval_ticks: runtime_config_defaults
1041                .known_destinations_cleanup_interval_ticks,
1042            known_destination_cleanup: None,
1043            ratchet_cleanup_handle: None,
1044            resource_preparation: None,
1045            known_destinations_cap_evict_count: 0,
1046            announce_cache_cleanup_interval_ticks: runtime_config_defaults
1047                .announce_cache_cleanup_interval_ticks,
1048            cache_cleanup_active_hashes: None,
1049            cache_cleanup_entries: None,
1050            cache_cleanup_removed: 0,
1051            announce_cache_cleanup_batch_size: runtime_config_defaults
1052                .announce_cache_cleanup_batch_size,
1053            management_announce_interval_secs: runtime_config_defaults
1054                .management_announce_interval_secs,
1055            runtime_config_defaults,
1056            #[cfg(feature = "hooks")]
1057            hook_slots: create_hook_slots(),
1058            #[cfg(feature = "hooks")]
1059            hook_manager: HookManager::new().ok(),
1060            #[cfg(feature = "hooks")]
1061            provider_bridge: None,
1062            #[cfg(feature = "hooks")]
1063            hook_rejected_modifications: [0; HookPoint::COUNT],
1064        }
1065    }
1066
1067    pub fn set_announce_verify_queue_config(
1068        &mut self,
1069        max_entries: usize,
1070        max_bytes: usize,
1071        max_stale_secs: f64,
1072        overflow_policy: OverflowPolicy,
1073    ) {
1074        self.announce_verify_queue = Arc::new(Mutex::new(AnnounceVerifyQueue::with_limits(
1075            max_entries,
1076            max_bytes,
1077            max_stale_secs,
1078            overflow_policy,
1079        )));
1080    }
1081
1082    pub fn set_announce_rate_defaults(&mut self, defaults: AnnounceRateDefaults) {
1083        self.announce_rate_defaults = defaults;
1084    }
1085
1086    pub fn set_ingress_control_defaults(
1087        &mut self,
1088        defaults: rns_core::transport::types::IngressControlConfig,
1089    ) {
1090        self.ingress_control_defaults = defaults;
1091    }
1092
1093    pub(crate) fn apply_announce_rate_defaults(
1094        &self,
1095        info: &mut rns_core::transport::types::InterfaceInfo,
1096    ) {
1097        if !self.engine.transport_enabled() || info.announce_rate_target.is_some() {
1098            return;
1099        }
1100
1101        let Some(target) = self.announce_rate_defaults.target else {
1102            return;
1103        };
1104
1105        info.announce_rate_target = Some(target);
1106        if info.announce_rate_grace == 0 {
1107            info.announce_rate_grace = self.announce_rate_defaults.grace;
1108        }
1109        if info.announce_rate_penalty == 0.0 {
1110            info.announce_rate_penalty = self.announce_rate_defaults.penalty;
1111        }
1112    }
1113
1114    pub(crate) fn apply_ingress_control_defaults(
1115        &self,
1116        info: &mut rns_core::transport::types::InterfaceInfo,
1117    ) {
1118        if !self.engine.transport_enabled() {
1119            return;
1120        }
1121
1122        let baseline = if info.ingress_control.enabled {
1123            rns_core::transport::types::IngressControlConfig::enabled()
1124        } else {
1125            rns_core::transport::types::IngressControlConfig::disabled()
1126        };
1127        let defaults = self.ingress_control_defaults;
1128        let ic = &mut info.ingress_control;
1129
1130        if ic.max_held_announces == baseline.max_held_announces {
1131            ic.max_held_announces = defaults.max_held_announces;
1132        }
1133        if ic.burst_hold == baseline.burst_hold {
1134            ic.burst_hold = defaults.burst_hold;
1135        }
1136        if ic.burst_freq_new == baseline.burst_freq_new {
1137            ic.burst_freq_new = defaults.burst_freq_new;
1138        }
1139        if ic.burst_freq == baseline.burst_freq {
1140            ic.burst_freq = defaults.burst_freq;
1141        }
1142        if ic.pr_burst_freq_new == baseline.pr_burst_freq_new {
1143            ic.pr_burst_freq_new = defaults.pr_burst_freq_new;
1144        }
1145        if ic.pr_burst_freq == baseline.pr_burst_freq {
1146            ic.pr_burst_freq = defaults.pr_burst_freq;
1147        }
1148        if ic.new_time == baseline.new_time {
1149            ic.new_time = defaults.new_time;
1150        }
1151        if ic.burst_penalty == baseline.burst_penalty {
1152            ic.burst_penalty = defaults.burst_penalty;
1153        }
1154        if ic.held_release_interval == baseline.held_release_interval {
1155            ic.held_release_interval = defaults.held_release_interval;
1156        }
1157        if ic.egress_enabled == baseline.egress_enabled {
1158            ic.egress_enabled = defaults.egress_enabled;
1159        }
1160        if ic.egress_pr_freq == baseline.egress_pr_freq {
1161            ic.egress_pr_freq = defaults.egress_pr_freq;
1162        }
1163    }
1164
1165    fn wrap_interface_writer(
1166        &self,
1167        interface_id: InterfaceId,
1168        interface_name: &str,
1169        writer: Box<dyn crate::interface::Writer>,
1170    ) -> (
1171        Box<dyn crate::interface::Writer>,
1172        crate::interface::AsyncWriterMetrics,
1173    ) {
1174        crate::interface::wrap_async_writer(
1175            writer,
1176            interface_id,
1177            interface_name,
1178            self.event_tx.clone(),
1179            self.interface_writer_queue_capacity,
1180        )
1181    }
1182
1183    #[cfg(feature = "hooks")]
1184    fn provider_events_enabled(&self) -> bool {
1185        self.provider_bridge.is_some()
1186    }
1187
1188    /// Whether any program is attached at `point`. Per-packet hook points
1189    /// check this before building a hook context, which reads the clock.
1190    #[cfg(feature = "hooks")]
1191    pub(crate) fn hooks_attached(&self, point: HookPoint) -> bool {
1192        !self.hook_slots[point as usize].programs.is_empty()
1193    }
1194
1195    #[cfg(feature = "hooks")]
1196    fn run_backbone_peer_hook(
1197        &mut self,
1198        attach_point: &str,
1199        point: HookPoint,
1200        event: &BackbonePeerHookEvent,
1201    ) {
1202        let ctx = backbone_peer_hook_context(event);
1203        let now = time::now();
1204        let engine_ref = EngineRef {
1205            engine: &self.engine,
1206            interfaces: &self.interfaces,
1207            link_manager: &self.link_manager,
1208            now,
1209        };
1210        let provider_events_enabled = self.provider_events_enabled();
1211        if let Some(ref e) = run_hook_inner(
1212            &mut self.hook_slots[point as usize].programs,
1213            &self.hook_manager,
1214            &engine_ref,
1215            &ctx,
1216            now,
1217            provider_events_enabled,
1218        ) {
1219            self.forward_hook_side_effects(attach_point, e);
1220        }
1221    }
1222
1223    #[cfg(feature = "iface-backbone")]
1224    fn make_discoverable_interface(
1225        runtime: &BackboneDiscoveryRuntimeHandle,
1226    ) -> crate::discovery::DiscoverableInterface {
1227        crate::discovery::DiscoverableInterface {
1228            interface_name: runtime.interface_name.clone(),
1229            config: runtime.current.config.clone(),
1230            transport_enabled: runtime.current.transport_enabled,
1231            ifac_netname: runtime.current.ifac_netname.clone(),
1232            ifac_netkey: runtime.current.ifac_netkey.clone(),
1233        }
1234    }
1235
1236    #[cfg(feature = "iface-backbone")]
1237    fn sync_backbone_discovery_runtime(
1238        &mut self,
1239        interface_name: &str,
1240    ) -> Result<(), RuntimeConfigError> {
1241        let handle = self
1242            .backbone_discovery_runtime
1243            .get(interface_name)
1244            .ok_or(RuntimeConfigError {
1245                code: RuntimeConfigErrorCode::NotFound,
1246                message: format!("backbone interface '{}' not found", interface_name),
1247            })?
1248            .clone();
1249
1250        if handle.current.discoverable {
1251            let iface = Self::make_discoverable_interface(&handle);
1252            if let Some(announcer) = self.interface_announcer.as_mut() {
1253                announcer.upsert_interface(iface);
1254            } else if let Some(identity) = self.transport_identity.as_ref() {
1255                self.interface_announcer = Some(crate::discovery::InterfaceAnnouncer::new(
1256                    *identity.hash(),
1257                    vec![iface],
1258                ));
1259            }
1260        } else if let Some(announcer) = self.interface_announcer.as_mut() {
1261            announcer.remove_interface(interface_name);
1262            if announcer.is_empty() {
1263                self.interface_announcer = None;
1264            }
1265        }
1266
1267        Ok(())
1268    }
1269
1270    #[cfg(feature = "iface-tcp")]
1271    fn make_tcp_server_discoverable_interface(
1272        runtime: &TcpServerDiscoveryRuntimeHandle,
1273    ) -> crate::discovery::DiscoverableInterface {
1274        crate::discovery::DiscoverableInterface {
1275            interface_name: runtime.interface_name.clone(),
1276            config: runtime.current.config.clone(),
1277            transport_enabled: runtime.current.transport_enabled,
1278            ifac_netname: runtime.current.ifac_netname.clone(),
1279            ifac_netkey: runtime.current.ifac_netkey.clone(),
1280        }
1281    }
1282
1283    #[cfg(feature = "iface-tcp")]
1284    fn sync_tcp_server_discovery_runtime(
1285        &mut self,
1286        interface_name: &str,
1287    ) -> Result<(), RuntimeConfigError> {
1288        let handle = self
1289            .tcp_server_discovery_runtime
1290            .get(interface_name)
1291            .ok_or(RuntimeConfigError {
1292                code: RuntimeConfigErrorCode::NotFound,
1293                message: format!("tcp server interface '{}' not found", interface_name),
1294            })?
1295            .clone();
1296
1297        if handle.current.discoverable {
1298            let iface = Self::make_tcp_server_discoverable_interface(&handle);
1299            if let Some(announcer) = self.interface_announcer.as_mut() {
1300                announcer.upsert_interface(iface);
1301            } else if let Some(identity) = self.transport_identity.as_ref() {
1302                self.interface_announcer = Some(crate::discovery::InterfaceAnnouncer::new(
1303                    *identity.hash(),
1304                    vec![iface],
1305                ));
1306            }
1307        } else if let Some(announcer) = self.interface_announcer.as_mut() {
1308            announcer.remove_interface(interface_name);
1309            if announcer.is_empty() {
1310                self.interface_announcer = None;
1311            }
1312        }
1313
1314        Ok(())
1315    }
1316
1317    #[cfg(feature = "hooks")]
1318    fn update_hook_program<F>(
1319        &mut self,
1320        name: &str,
1321        attach_point: &str,
1322        mut update: F,
1323    ) -> Result<(), String>
1324    where
1325        F: FnMut(&mut rns_hooks::LoadedProgram),
1326    {
1327        let point_idx = crate::config::parse_hook_point(attach_point)
1328            .ok_or_else(|| format!("unknown hook point '{}'", attach_point))?;
1329        let program = self.hook_slots[point_idx]
1330            .programs
1331            .iter_mut()
1332            .find(|program| program.name == name)
1333            .ok_or_else(|| format!("hook '{}' not found at point '{}'", name, attach_point))?;
1334        update(program);
1335        Ok(())
1336    }
1337
1338    pub(crate) fn set_tick_interval_handle(&mut self, tick_interval_ms: Arc<AtomicU64>) {
1339        self.tick_interval_ms = tick_interval_ms;
1340    }
1341
1342    #[allow(dead_code)]
1343    pub(crate) fn set_packet_hashlist_max_entries(&mut self, max_entries: usize) {
1344        self.engine.set_packet_hashlist_max_entries(max_entries);
1345    }
1346
1347    /// Turn a packet hook chain result into the action the hook point takes.
1348    ///
1349    /// `Drop` stops the packet. `Modify` with replacement bytes is validated
1350    /// against `max_len` and the packet decoder; a replacement that fails
1351    /// validation is treated as `Drop` and counted in
1352    /// `hook_rejected_modifications`. `Modify` without bytes, `Continue` and
1353    /// `Halt` keep the current bytes.
1354    #[cfg(feature = "hooks")]
1355    pub(crate) fn packet_hook_outcome(
1356        &mut self,
1357        point: HookPoint,
1358        exec: &rns_hooks::ExecuteResult,
1359        max_len: usize,
1360    ) -> PacketHookOutcome {
1361        let Some(result) = exec.hook_result.as_ref() else {
1362            return PacketHookOutcome::Keep;
1363        };
1364        if result.is_drop() {
1365            return PacketHookOutcome::Drop;
1366        }
1367        if rns_hooks::Verdict::from_u32(result.verdict) != Some(rns_hooks::Verdict::Modify) {
1368            return PacketHookOutcome::Keep;
1369        }
1370        let Some(data) = exec.modified_data.as_deref() else {
1371            return PacketHookOutcome::Keep;
1372        };
1373        match validate_hook_replacement(data, max_len) {
1374            Ok(packet) => PacketHookOutcome::Replace(packet),
1375            Err(reason) => {
1376                let rejected = &mut self.hook_rejected_modifications[point as usize];
1377                *rejected = rejected.saturating_add(1);
1378                log::debug!("{:?} hook: {}; dropping packet", point, reason);
1379                PacketHookOutcome::Drop
1380            }
1381        }
1382    }
1383
1384    /// Largest packet a hook may substitute for one handled on `interface`.
1385    #[cfg(feature = "hooks")]
1386    pub(crate) fn hook_packet_limit(&self, interface: InterfaceId) -> usize {
1387        self.interfaces
1388            .get(&interface)
1389            .map(|entry| entry.info.mtu as usize)
1390            .filter(|mtu| *mtu > 0)
1391            .unwrap_or(rns_core::constants::MTU)
1392    }
1393
1394    /// Point a pending confirmed link send at the replacement bytes a hook
1395    /// produced for the packet it was tracking.
1396    #[cfg(feature = "hooks")]
1397    pub(crate) fn retarget_tracked_link_send(&mut self, original: &[u8], replacement: &RawPacket) {
1398        let Some((hash, _)) = self.tracked_link_send.as_mut() else {
1399            return;
1400        };
1401        if RawPacket::unpack(original).is_ok_and(|packet| packet.packet_hash == *hash) {
1402            *hash = replacement.packet_hash;
1403        }
1404    }
1405
1406    #[cfg(feature = "hooks")]
1407    fn forward_hook_side_effects(&mut self, attach_point: &str, exec: &rns_hooks::ExecuteResult) {
1408        if !exec.injected_actions.is_empty() {
1409            self.dispatch_all(convert_injected_actions(exec.injected_actions.clone()));
1410        }
1411        if let Some(ref bridge) = self.provider_bridge {
1412            for event in &exec.provider_events {
1413                bridge.emit_event(
1414                    attach_point,
1415                    event.hook_name.clone(),
1416                    event.payload_type.clone(),
1417                    event.payload.clone(),
1418                );
1419            }
1420        }
1421    }
1422
1423    #[cfg(feature = "hooks")]
1424    fn collect_hook_side_effects(
1425        &mut self,
1426        attach_point: &str,
1427        exec: &rns_hooks::ExecuteResult,
1428        out: &mut Vec<TransportAction>,
1429    ) {
1430        if !exec.injected_actions.is_empty() {
1431            out.extend(convert_injected_actions(exec.injected_actions.clone()));
1432        }
1433        if let Some(ref bridge) = self.provider_bridge {
1434            for event in &exec.provider_events {
1435                bridge.emit_event(
1436                    attach_point,
1437                    event.hook_name.clone(),
1438                    event.payload_type.clone(),
1439                    event.payload.clone(),
1440                );
1441            }
1442        }
1443    }
1444
1445    /// Set the probe addresses, protocol, and optional device for hole punching.
1446    pub fn set_probe_config(
1447        &mut self,
1448        addrs: Vec<std::net::SocketAddr>,
1449        protocol: rns_core::holepunch::ProbeProtocol,
1450        device: Option<String>,
1451    ) {
1452        let policy = self.holepunch_manager.policy();
1453        let allow_private = self.holepunch_manager.allow_private_endpoints();
1454        self.holepunch_manager = HolePunchManager::new(addrs, protocol, device);
1455        self.holepunch_manager.set_underlay_mark(self.underlay_mark);
1456        self.holepunch_manager.set_policy(policy);
1457        self.holepunch_manager
1458            .set_allow_private_endpoints(allow_private);
1459    }
1460}
1461
1462pub(crate) struct PendingLinkFrame {
1463    interface: InterfaceId,
1464    data: Vec<u8>,
1465    is_announce: bool,
1466    completion: Option<crate::link_send::Completion>,
1467}