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    FIPS_ENDPOINT_DIRECT_PACKET_QUEUE_MAX_PACKETS, FIPS_ENDPOINT_DIRECT_PACKET_RUN_MAX_PACKETS,
60    FipsEndpointDirectDeliveryError, FipsEndpointDirectPacketBatch, FipsEndpointDirectPacketRun,
61    FipsEndpointDirectReceiver, FipsEndpointDirectSink,
62};
63pub(in crate::node) use endpoint_service::EndpointServiceRuntime;
64pub(crate) use endpoint_service::{
65    EndpointServiceDatagramDelivery, EndpointServiceEventReceiver, EndpointServiceEventSender,
66    NodeEndpointServiceEvent,
67};
68pub(crate) use endpoint_traffic::{PendingEndpointData, PendingSessionTrafficQueues};
69pub(in crate::node) use identity_cache::IdentityCache;
70pub(in crate::node) use link_registry::{LinkRegistry, PendingConnect, TransportDropTracker};
71pub(in crate::node) use peer_lifecycle::*;
72pub(in crate::node) use peer_runtime::*;
73pub(in crate::node) use session_registry::*;
74pub(in crate::node) use support_state::{
75    BootstrapTransports, DiscoveryFallbackTransit, LocalSendFailures, SessionDirectDegradation,
76};
77
78use self::rate_limit::HandshakeRateLimiter;
79use self::wire::{FLAG_CE, FLAG_KEY_EPOCH};
80use crate::bloom::{BloomFilter, BloomState};
81use crate::cache::CoordCache;
82use crate::config::{NostrDiscoveryPolicy, PeerConfig, RoutingMode};
83use crate::dataplane::{
84    AdmissionConfig, DATAPLANE_TRANSPORT_SEND_BATCH_PACKETS, DataplaneDirectFspSources,
85    DataplaneFastIngressRx, DataplaneLiveNode, DataplaneLiveNodeTurn,
86};
87use crate::node::session::SessionEntry;
88use crate::node::session_wire::{FSP_PHASE_ESTABLISHED, FspCommonPrefix};
89use crate::peer::{ActivePeer, PeerConnection};
90use crate::proto::lookup_limits::{DiscoveryBackoff, DiscoveryForwardRateLimiter};
91use crate::proto::rate_limit::RoutingErrorRateLimiter;
92use crate::proto::routing::{LearnedRouteTable, LearnedRouteTableSnapshot};
93#[cfg(any(target_os = "linux", target_os = "macos"))]
94use crate::transport::ethernet::EthernetTransport;
95use crate::transport::tcp::TcpTransport;
96use crate::transport::tor::TorTransport;
97use crate::transport::udp::UdpTransport;
98#[cfg(feature = "webrtc-transport")]
99use crate::transport::webrtc::WebRtcTransport;
100use crate::transport::{
101    Link, LinkId, PacketRx, PacketTx, TransportAddr, TransportError, TransportHandle, TransportId,
102};
103use crate::tree::TreeState;
104use crate::upper::hosts::HostMap;
105use crate::upper::icmp_rate_limit::IcmpRateLimiter;
106use crate::upper::tun::{TunError, TunOutboundRx, TunState, TunTx};
107use crate::utils::index::{IndexAllocator, SessionIndex};
108use crate::{
109    Config, ConfigError, FipsAddress, Identity, IdentityError, LinkMessageType, NodeAddr,
110    PeerIdentity, encode_npub,
111};
112use rand::Rng;
113use std::collections::{HashMap, HashSet, VecDeque};
114use std::fmt;
115use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
116use std::sync::{Arc, Mutex as StdMutex};
117use std::thread::JoinHandle;
118use thiserror::Error;
119use tracing::{debug, warn};
120
121type DataplaneNode = DataplaneLiveNode;
122
123const LOCAL_SEND_FAILURE_FAST_DEAD_WINDOW: std::time::Duration = std::time::Duration::from_secs(3);
124#[cfg(test)]
125pub(crate) const ENDPOINT_EVENT_TEST_PAYLOAD_LEN: usize = 512;
126const SESSION_DIRECT_DEGRADED_HOLD_MS: u64 = 20_000;
127const SESSION_DIRECT_DEGRADED_MIN_SAMPLE: u64 = 16;
128const SESSION_DIRECT_DEGRADED_LOSS_THRESHOLD: f64 = 0.08;
129const SESSION_DIRECT_RECOVERY_LOSS_THRESHOLD: f64 = 0.02;
130const SESSION_DIRECT_MIN_EXCLUSIVE_TRUST_MS: u64 = 6_500;
131const ROUTING_FALLBACK_MIN_COST_ADVANTAGE: f64 = 0.25;
132const ENDPOINT_EVENT_BACKLOG_HIGH_WATER: usize = 4096;
133
134/// Half-range of the symmetric jitter applied to per-session rekey timers.
135///
136/// Each FMP/FSP session draws an offset uniformly from
137/// `[-REKEY_JITTER_SECS, +REKEY_JITTER_SECS]` seconds at construction and
138/// after each cutover. This preserves the configured mean interval while
139/// reducing dual-initiation bursts in symmetric-start meshes.
140pub(crate) const REKEY_JITTER_SECS: i64 = 15;
141
142/// A running FIPS node instance.
143///
144/// This is the top-level container holding all node state.
145///
146/// ## Peer Lifecycle
147///
148/// Peers go through two phases:
149/// 1. **Connection phase** (`connections`): Handshake in progress, indexed by LinkId
150/// 2. **Active phase** (`peers`): Authenticated, indexed by NodeAddr
151///
152/// The link registry dispatches incoming packets to the right connection before
153/// authentication completes.
154// Discovery lookup constants moved to config: node.discovery.attempt_timeouts_secs, node.discovery.ttl
155pub struct Node {
156    // === Identity ===
157    /// This node's cryptographic identity.
158    identity: Identity,
159
160    /// Random epoch generated at startup for peer restart detection.
161    /// Exchanged inside Noise handshake messages so peers can detect restarts.
162    startup_epoch: [u8; 8],
163
164    /// Instant when the node was created, for uptime reporting.
165    started_at: std::time::Instant,
166
167    // === Configuration ===
168    /// Loaded configuration.
169    config: Config,
170
171    // === State ===
172    /// Node operational state.
173    state: NodeState,
174
175    /// Whether this is a leaf-only node.
176    is_leaf_only: bool,
177
178    // === Spanning Tree ===
179    /// Local spanning tree state.
180    tree_state: TreeState,
181
182    // === Bloom Filter ===
183    /// Local Bloom filter state.
184    bloom_state: BloomState,
185
186    // === Routing ===
187    /// Address -> coordinates cache (from session setup and discovery).
188    coord_cache: CoordCache,
189    /// Locally learned reverse-path next-hop hints.
190    learned_routes: LearnedRouteTable,
191    /// Destinations whose direct first-hop path is temporarily suspect because
192    /// session-layer MMP observed sustained loss while using that direct path.
193    session_direct_degradation: SessionDirectDegradation,
194    /// Recent discovery requests for dedup and reverse-path forwarding.
195    recent_requests: RecentDiscoveryRequests,
196    /// Per-destination path MTU lookup, keyed by FipsAddress (mirrors
197    /// `coord_cache.entries[*].path_mtu`). Sync read-only access from
198    /// the TUN reader/writer threads at TCP MSS clamp time so the
199    /// SYN/SYN-ACK clamp can use the smaller of the local-egress floor
200    /// and the learned per-destination path MTU.
201    path_mtu_lookup: Arc<std::sync::RwLock<HashMap<crate::FipsAddress, u16>>>,
202
203    // === Transports & Links ===
204    /// Active transports (owned by Node).
205    transports: HashMap<TransportId, TransportHandle>,
206    /// Per-transport kernel drop tracking for congestion detection.
207    transport_drops: TransportDropTracker,
208    /// Per-transport wildcard socket-local drop tracking for observability.
209    transport_socket_drops: TransportDropTracker,
210    /// Per-transport Linux namespace receive-buffer error tracking for observability.
211    transport_namespace_drops: TransportDropTracker,
212    /// Active links plus reverse address dispatch index.
213    links: LinkRegistry,
214
215    // === Packet Channel ===
216    /// Packet sender for transports.
217    packet_tx: Option<PacketTx>,
218    /// Packet receiver (for event loop).
219    packet_rx: Option<PacketRx>,
220
221    // === Dataplane ===
222    /// Canonical dataplane state owned by the node.
223    dataplane: DataplaneNode,
224    /// Control ingress surfaced while a synchronous dataplane send is waiting.
225    deferred_dataplane_control_turns: VecDeque<DataplaneLiveNodeTurn>,
226    /// Transit sends admitted to dataplane whose terminal receipts may arrive
227    /// on a later receive-loop turn.
228    deferred_session_forwards: handlers::forwarding::DeferredSessionForwards,
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    /// Configured-peer lookup cache, rebuilt when the peer roster changes.
418    configured_peers: ConfiguredPeerLookup,
419
420    /// Reloadable peer ACL state from standard allow/deny files.
421    peer_acl: acl::PeerAclReloader,
422
423    // === Host Map ===
424    /// Static hostname → npub mapping for DNS resolution.
425    /// Built at construction from peer aliases and /etc/fips/hosts.
426    host_map: Arc<HostMap>,
427}
428
429impl fmt::Debug for Node {
430    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431        f.debug_struct("Node")
432            .field("node_addr", self.node_addr())
433            .field("state", &self.state)
434            .field("is_leaf_only", &self.is_leaf_only)
435            .field("connections", &self.connection_count())
436            .field("peers", &self.peer_count())
437            .field("links", &self.link_count())
438            .field("transports", &self.transport_count())
439            .finish()
440    }
441}