Skip to main content

fips_core/node/
mod.rs

1//! FIPS Node Entity
2//!
3//! Top-level structure representing a running FIPS instance. The Node
4//! holds all state required for mesh routing: identity, tree state,
5//! Bloom filters, coordinate caches, transports, links, and peers.
6
7mod accessors_impl;
8mod acl;
9mod bloom;
10mod core_impl;
11mod dataplane_integration;
12mod endpoint_channels;
13mod endpoint_event;
14mod endpoint_service;
15mod endpoint_traffic;
16mod error;
17mod handlers;
18mod identity_cache;
19mod io_impl;
20mod lifecycle;
21mod link_registry;
22mod peer_lifecycle;
23mod peer_runtime;
24mod rate_limit;
25#[cfg(test)]
26mod recent_requests;
27mod retry;
28mod route_impl;
29pub(crate) mod session;
30mod session_access_impl;
31mod session_registry;
32pub(crate) mod session_wire;
33mod state;
34pub(crate) mod stats;
35pub(crate) mod stats_history;
36mod support_state;
37#[cfg(test)]
38mod tests;
39mod tree;
40pub(crate) mod wire;
41
42pub use endpoint_event::ExternalPacketIo;
43pub use error::NodeError;
44pub use identity_cache::NodeDeliveredPacket;
45pub use state::NodeState;
46
47pub(crate) use crate::proto::lookup_state::{RecentDiscoveryRequests, RecentResponseForward};
48pub(crate) use endpoint_channels::{
49    ENDPOINT_STALE_DATA_DROP_MS, EndpointDataBatchRx, EndpointDataBatchTx, EndpointDataPayload,
50    NodeEndpointControlCommand, NodeEndpointDataBatch, endpoint_data_batch_channel,
51};
52pub(in crate::node) use endpoint_event::EndpointEventRuntime;
53pub(crate) use endpoint_event::{
54    EndpointDataDelivery, EndpointDataIo, EndpointDirectSink, EndpointEventReceiver,
55    EndpointEventSender, FipsEndpointDirectPacketRunMeta, NodeEndpointEvent, NodeEndpointPeer,
56    NodeEndpointRelayStatus, UpdatePeersOutcome,
57};
58pub use endpoint_event::{
59    FipsEndpointDirectDeliveryError, FipsEndpointDirectPacketBatch, FipsEndpointDirectPacketRun,
60    FipsEndpointDirectSink,
61};
62pub(in crate::node) use endpoint_service::EndpointServiceRuntime;
63pub(crate) use endpoint_service::{
64    EndpointServiceDatagramDelivery, EndpointServiceEventReceiver, EndpointServiceEventSender,
65    NodeEndpointServiceEvent,
66};
67pub(crate) use endpoint_traffic::{PendingEndpointData, PendingSessionTrafficQueues};
68pub(in crate::node) use identity_cache::IdentityCache;
69pub(in crate::node) use link_registry::{LinkRegistry, PendingConnect, TransportDropTracker};
70pub(in crate::node) use peer_lifecycle::*;
71pub(in crate::node) use peer_runtime::*;
72pub(in crate::node) use session_registry::*;
73pub(in crate::node) use support_state::{
74    BootstrapTransports, DiscoveryFallbackTransit, LocalSendFailures, SessionDirectDegradation,
75};
76
77use self::rate_limit::HandshakeRateLimiter;
78use self::wire::{FLAG_CE, FLAG_KEY_EPOCH};
79use crate::bloom::{BloomFilter, BloomState};
80use crate::cache::CoordCache;
81use crate::config::{NostrDiscoveryPolicy, PeerConfig, RoutingMode};
82use crate::dataplane::{
83    AdmissionConfig, DATAPLANE_TRANSPORT_SEND_BATCH_PACKETS, DataplaneDirectFspSources,
84    DataplaneFastIngressRx, DataplaneLiveNode, DataplaneLiveNodeTurn,
85};
86use crate::node::session::SessionEntry;
87use crate::node::session_wire::{FSP_PHASE_ESTABLISHED, FspCommonPrefix};
88use crate::peer::{ActivePeer, PeerConnection};
89use crate::proto::lookup_limits::{DiscoveryBackoff, DiscoveryForwardRateLimiter};
90use crate::proto::rate_limit::RoutingErrorRateLimiter;
91use crate::proto::routing::{LearnedRouteTable, LearnedRouteTableSnapshot};
92#[cfg(any(target_os = "linux", target_os = "macos"))]
93use crate::transport::ethernet::EthernetTransport;
94use crate::transport::tcp::TcpTransport;
95use crate::transport::tor::TorTransport;
96use crate::transport::udp::UdpTransport;
97#[cfg(feature = "webrtc-transport")]
98use crate::transport::webrtc::WebRtcTransport;
99use crate::transport::{
100    Link, LinkId, PacketRx, PacketTx, TransportAddr, TransportError, TransportHandle, TransportId,
101};
102use crate::tree::TreeState;
103use crate::upper::hosts::HostMap;
104use crate::upper::icmp_rate_limit::IcmpRateLimiter;
105use crate::upper::tun::{TunError, TunOutboundRx, TunState, TunTx};
106use crate::utils::index::{IndexAllocator, SessionIndex};
107use crate::{
108    Config, ConfigError, FipsAddress, Identity, IdentityError, LinkMessageType, NodeAddr,
109    PeerIdentity, encode_npub,
110};
111use rand::Rng;
112use std::collections::{HashMap, HashSet, VecDeque};
113use std::fmt;
114use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
115use std::sync::{Arc, Condvar, Mutex as StdMutex};
116use std::thread::JoinHandle;
117use thiserror::Error;
118use tracing::{debug, warn};
119
120type DataplaneNode = DataplaneLiveNode;
121
122const LOCAL_SEND_FAILURE_FAST_DEAD_WINDOW: std::time::Duration = std::time::Duration::from_secs(3);
123#[cfg(test)]
124pub(crate) const ENDPOINT_EVENT_TEST_PAYLOAD_LEN: usize = 512;
125const SESSION_DIRECT_DEGRADED_HOLD_MS: u64 = 20_000;
126const SESSION_DIRECT_DEGRADED_MIN_SAMPLE: u64 = 16;
127const SESSION_DIRECT_DEGRADED_LOSS_THRESHOLD: f64 = 0.08;
128const SESSION_DIRECT_RECOVERY_LOSS_THRESHOLD: f64 = 0.02;
129const SESSION_DIRECT_MIN_EXCLUSIVE_TRUST_MS: u64 = 6_500;
130const ROUTING_FALLBACK_MIN_COST_ADVANTAGE: f64 = 0.25;
131const ENDPOINT_EVENT_BACKLOG_HIGH_WATER: usize = 4096;
132
133/// Half-range of the symmetric jitter applied to per-session rekey timers.
134///
135/// Each FMP/FSP session draws an offset uniformly from
136/// `[-REKEY_JITTER_SECS, +REKEY_JITTER_SECS]` seconds at construction and
137/// after each cutover. This preserves the configured mean interval while
138/// reducing dual-initiation bursts in symmetric-start meshes.
139pub(crate) const REKEY_JITTER_SECS: i64 = 15;
140
141/// A running FIPS node instance.
142///
143/// This is the top-level container holding all node state.
144///
145/// ## Peer Lifecycle
146///
147/// Peers go through two phases:
148/// 1. **Connection phase** (`connections`): Handshake in progress, indexed by LinkId
149/// 2. **Active phase** (`peers`): Authenticated, indexed by NodeAddr
150///
151/// The link registry dispatches incoming packets to the right connection before
152/// authentication completes.
153// Discovery lookup constants moved to config: node.discovery.attempt_timeouts_secs, node.discovery.ttl
154pub struct Node {
155    // === Identity ===
156    /// This node's cryptographic identity.
157    identity: Identity,
158
159    /// Random epoch generated at startup for peer restart detection.
160    /// Exchanged inside Noise handshake messages so peers can detect restarts.
161    startup_epoch: [u8; 8],
162
163    /// Instant when the node was created, for uptime reporting.
164    started_at: std::time::Instant,
165
166    // === Configuration ===
167    /// Loaded configuration.
168    config: Config,
169
170    // === State ===
171    /// Node operational state.
172    state: NodeState,
173
174    /// Whether this is a leaf-only node.
175    is_leaf_only: bool,
176
177    // === Spanning Tree ===
178    /// Local spanning tree state.
179    tree_state: TreeState,
180
181    // === Bloom Filter ===
182    /// Local Bloom filter state.
183    bloom_state: BloomState,
184
185    // === Routing ===
186    /// Address -> coordinates cache (from session setup and discovery).
187    coord_cache: CoordCache,
188    /// Locally learned reverse-path next-hop hints.
189    learned_routes: LearnedRouteTable,
190    /// Destinations whose direct first-hop path is temporarily suspect because
191    /// session-layer MMP observed sustained loss while using that direct path.
192    session_direct_degradation: SessionDirectDegradation,
193    /// Recent discovery requests for dedup and reverse-path forwarding.
194    recent_requests: RecentDiscoveryRequests,
195    /// Per-destination path MTU lookup, keyed by FipsAddress (mirrors
196    /// `coord_cache.entries[*].path_mtu`). Sync read-only access from
197    /// the TUN reader/writer threads at TCP MSS clamp time so the
198    /// SYN/SYN-ACK clamp can use the smaller of the local-egress floor
199    /// and the learned per-destination path MTU.
200    path_mtu_lookup: Arc<std::sync::RwLock<HashMap<crate::FipsAddress, u16>>>,
201
202    // === Transports & Links ===
203    /// Active transports (owned by Node).
204    transports: HashMap<TransportId, TransportHandle>,
205    /// Short-lived cache for numeric UDP candidate -> compatible local transport.
206    /// This avoids repeated interface scans and route-probe sockets while direct
207    /// retry code is reconsidering the same LAN/NAT hints.
208    udp_transport_resolution_cache: lifecycle::UdpTransportResolutionCache,
209    /// Per-transport kernel drop tracking for congestion detection.
210    transport_drops: TransportDropTracker,
211    /// Per-transport wildcard socket-local drop tracking for observability.
212    transport_socket_drops: TransportDropTracker,
213    /// Per-transport Linux namespace receive-buffer error tracking for observability.
214    transport_namespace_drops: TransportDropTracker,
215    /// Active links plus reverse address dispatch index.
216    links: LinkRegistry,
217
218    // === Packet Channel ===
219    /// Packet sender for transports.
220    packet_tx: Option<PacketTx>,
221    /// Packet receiver (for event loop).
222    packet_rx: Option<PacketRx>,
223
224    // === Dataplane ===
225    /// Canonical dataplane state owned by the node.
226    dataplane: DataplaneNode,
227    /// Control ingress surfaced while a synchronous dataplane send is waiting.
228    deferred_dataplane_control_turns: VecDeque<DataplaneLiveNodeTurn>,
229    /// Pre-routed established FMP packets accepted directly from UDP receive.
230    dataplane_fast_ingress_rx: Option<DataplaneFastIngressRx>,
231    /// Direct-FSP transport-address classifier published to packet ingress.
232    dataplane_direct_fsp_sources: DataplaneDirectFspSources,
233    /// True when peer path state changed since the classifier was built.
234    dataplane_direct_fsp_sources_dirty: bool,
235    /// Maximum same-destination UDP payloads sent in one dataplane batch.
236    dataplane_transport_send_batch_packets: usize,
237
238    // === Peer Lifecycle ===
239    /// Pending handshake connections plus authenticated peers.
240    peers: PeerLifecycleRegistry,
241
242    // === End-to-End Sessions ===
243    /// Session table for end-to-end encrypted sessions.
244    /// Keyed by remote NodeAddr.
245    sessions: SessionRegistry,
246
247    // === Identity Cache ===
248    /// Maps FipsAddress prefix bytes (bytes 1-15) to cached peer identity data.
249    /// Enables reverse lookup from IPv6 destination to session/routing identity.
250    identity_cache: IdentityCache,
251
252    // === Pending TUN Packets ===
253    /// TUN packets and endpoint payloads queued while waiting for session establishment.
254    pending_session_traffic: PendingSessionTrafficQueues,
255    // === Pending Discovery Lookups ===
256    /// Tracks in-flight discovery lookups and owns dedupe/cap admission.
257    pending_lookups: handlers::discovery::PendingDiscoveryLookups,
258
259    // === Resource Limits ===
260    /// Maximum connections (0 = unlimited).
261    max_connections: usize,
262    /// Maximum peers (0 = unlimited).
263    max_peers: usize,
264    /// Maximum links (0 = unlimited).
265    max_links: usize,
266
267    // === Counters ===
268    /// Next link ID to allocate.
269    next_link_id: u64,
270    /// Next transport ID to allocate.
271    next_transport_id: u32,
272
273    // === Node Statistics ===
274    /// Routing, forwarding, discovery, and error signal counters.
275    stats: stats::NodeStats,
276
277    /// Time-series history of node-level metrics (1s/1m rings).
278    stats_history: stats_history::StatsHistory,
279
280    // === TUN Interface ===
281    /// TUN device state.
282    tun_state: TunState,
283    /// TUN interface name (for cleanup).
284    tun_name: Option<String>,
285    /// TUN packet sender channel.
286    tun_tx: Option<TunTx>,
287    /// Receiver for outbound packets from the TUN reader.
288    tun_outbound_rx: Option<TunOutboundRx>,
289    /// App-owned packet sink used by embedded/no-TUN integrations.
290    external_packet_tx: Option<tokio::sync::mpsc::Sender<NodeDeliveredPacket>>,
291    /// Endpoint control receiver used by embedded/no-daemon integrations.
292    endpoint_control_rx: Option<tokio::sync::mpsc::Receiver<NodeEndpointControlCommand>>,
293    /// Endpoint data batch receiver used by embedded/no-daemon integrations.
294    endpoint_data_rx: Option<EndpointDataBatchRx>,
295    /// Endpoint data event delivery runtime used by embedded/no-daemon integrations.
296    endpoint_events: EndpointEventRuntime,
297    /// Registered FSP DataPacket services and their app delivery queue.
298    endpoint_services: EndpointServiceRuntime,
299    /// TUN reader thread handle.
300    tun_reader_handle: Option<JoinHandle<()>>,
301    /// TUN writer thread handle.
302    tun_writer_handle: Option<JoinHandle<()>>,
303    /// Shutdown pipe: writing to this fd unblocks the TUN reader thread on macOS.
304    /// On Linux, deleting the interface via netlink serves the same purpose.
305    #[cfg(target_os = "macos")]
306    tun_shutdown_fd: Option<std::os::unix::io::RawFd>,
307
308    // === DNS Responder ===
309    /// Receiver for resolved identities from the DNS responder.
310    dns_identity_rx: Option<crate::upper::dns::DnsIdentityRx>,
311    /// DNS responder task handle.
312    dns_task: Option<tokio::task::JoinHandle<()>>,
313
314    // === Index-Based Session Dispatch ===
315    /// Allocator for session indices.
316    index_allocator: IndexAllocator,
317    /// Pending outbound handshakes by our sender_idx.
318    /// Tracks which LinkId corresponds to which session index.
319    pending_outbound: PendingOutboundHandshakes,
320
321    // === Rate Limiting ===
322    /// Rate limiter for msg1 processing (DoS protection).
323    msg1_rate_limiter: HandshakeRateLimiter,
324    /// Rate limiter for ICMP Packet Too Big messages.
325    icmp_rate_limiter: IcmpRateLimiter,
326    /// Rate limiter for routing error signals (CoordsRequired / PathBroken).
327    routing_error_rate_limiter: RoutingErrorRateLimiter,
328    /// Rate limiter for source-side CoordsRequired/PathBroken responses.
329    coords_response_rate_limiter: RoutingErrorRateLimiter,
330    /// Backoff for failed discovery lookups (originator-side).
331    discovery_backoff: DiscoveryBackoff,
332    /// Rate limiter for forwarded discovery requests (transit-side).
333    discovery_forward_limiter: DiscoveryForwardRateLimiter,
334
335    // === Pending Transport Connects ===
336    /// Links waiting for transport-level connection establishment before
337    /// sending handshake msg1. For connection-oriented transports (TCP, Tor),
338    /// the transport connect runs in the background; the tick handler polls
339    /// connection_state() and initiates the handshake when connected.
340    pending_connects: Vec<PendingConnect>,
341
342    // === Connection Retry ===
343    /// Retry state for peers whose outbound connections have failed.
344    /// Keyed by NodeAddr. Entries are created when a handshake times out
345    /// or fails, and removed on successful promotion or when max retries
346    /// are exhausted.
347    retry_pending: retry::PendingRouteRetries,
348
349    /// Optional Nostr/STUN overlay discovery coordinator for `udp:nat` peers.
350    nostr_discovery: Option<Arc<crate::discovery::nostr::NostrDiscovery>>,
351    /// mDNS / DNS-SD responder + browser for local-link peer discovery.
352    /// Identity is unverified at this layer — the Noise XX handshake
353    /// initiated against an mDNS-observed endpoint is what proves the
354    /// peer holds the matching private key.
355    lan_discovery: Option<Arc<crate::discovery::lan::LanDiscovery>>,
356    /// Same-host JSON registry under `~/.fips/instances`. Records are
357    /// loopback routing hints only; peer identity is still verified by the
358    /// Noise handshake.
359    local_instance_registry: Option<crate::discovery::local::LocalInstanceRegistry>,
360    local_instance_started_at_ms: Option<u64>,
361    last_local_instance_publish_ms: Option<u64>,
362    last_local_instance_scan_ms: Option<u64>,
363    /// Wall-clock ms when Nostr discovery successfully started, used to
364    /// schedule the one-shot startup advert sweep after a settle delay.
365    /// `None` until discovery comes up; remains `None` if discovery is
366    /// disabled or failed to start.
367    nostr_discovery_started_at_ms: Option<u64>,
368    /// Whether the one-shot startup advert sweep has run. Set to true
369    /// after the first sweep fires (under `policy: open`); thereafter
370    /// only the per-tick `queue_open_discovery_retries` continues.
371    startup_open_discovery_sweep_done: bool,
372    /// Per-peer UDP transports adopted from NAT traversal handoff plus the
373    /// originating peer npub for protocol-mismatch cooldown bookkeeping.
374    bootstrap_transports: BootstrapTransports,
375    /// Peers that should not be used as reply-learned fallback transit for
376    /// other destinations. Direct lookups to the peer are still permitted.
377    discovery_fallback_transit: DiscoveryFallbackTransit,
378
379    // === Periodic Parent Re-evaluation ===
380    /// Timestamp of last periodic parent re-evaluation (for pacing).
381    last_parent_reeval: Option<crate::time::Instant>,
382
383    // === Congestion Logging ===
384    /// Timestamp of last congestion detection log (rate-limited to 5s).
385    last_congestion_log: Option<std::time::Instant>,
386
387    // === Mesh Size Estimate ===
388    /// Cached estimated mesh size (computed once per tick from bloom filters).
389    estimated_mesh_size: Option<u64>,
390    /// Timestamp of last mesh size log emission.
391    last_mesh_size_log: Option<std::time::Instant>,
392
393    // === Bloom Self-Plausibility ===
394    /// Rate-limit state for the self-plausibility WARN. Fires at most
395    /// once per 60s globally when our own outgoing FilterAnnounce has
396    /// an FPR above `node.bloom.max_inbound_fpr`, signalling either
397    /// aggregation drift or an ingress bypass.
398    last_self_warn: Option<std::time::Instant>,
399
400    // === Local Outbound Liveness ===
401    /// Set per peer when a `transport.send` returned a local-side io error
402    /// (`NetworkUnreachable` / `HostUnreachable` / `AddrNotAvailable`),
403    /// cleared on the next successful send to that peer. Used by
404    /// `check_link_heartbeats` to compress only that peer's dead-timeout to
405    /// `fast_link_dead_timeout_secs` while its outbound is observed broken.
406    local_send_failures: LocalSendFailures,
407    /// Set when the rx loop could not complete its 1s maintenance work
408    /// inside the watchdog timeout. Link-dead detection may be valid during
409    /// overload, but traversal cooldown should not punish a path just because
410    /// our own scheduler/worker queue was late.
411    last_rx_loop_maintenance_timeout_at: Option<std::time::Instant>,
412
413    // === Display Names ===
414    /// Human-readable names for configured peers (alias or short npub).
415    /// Populated at startup from peer config.
416    peer_aliases: HashMap<NodeAddr, String>,
417    /// Scheduler weight for explicitly configured peers. Built when config
418    /// changes so the packet hot path only does a NodeAddr hash lookup.
419    configured_peer_send_weights: ConfiguredPeerSendWeights,
420
421    /// Reloadable peer ACL state from standard allow/deny files.
422    peer_acl: acl::PeerAclReloader,
423
424    // === Host Map ===
425    /// Static hostname → npub mapping for DNS resolution.
426    /// Built at construction from peer aliases and /etc/fips/hosts.
427    host_map: Arc<HostMap>,
428}
429
430impl fmt::Debug for Node {
431    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
432        f.debug_struct("Node")
433            .field("node_addr", self.node_addr())
434            .field("state", &self.state)
435            .field("is_leaf_only", &self.is_leaf_only)
436            .field("connections", &self.connection_count())
437            .field("peers", &self.peer_count())
438            .field("links", &self.link_count())
439            .field("transports", &self.transport_count())
440            .finish()
441    }
442}