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    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, Condvar, 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    /// Pre-routed established FMP packets accepted directly from UDP receive.
227    dataplane_fast_ingress_rx: Option<DataplaneFastIngressRx>,
228    /// Direct-FSP transport-address classifier published to packet ingress.
229    dataplane_direct_fsp_sources: DataplaneDirectFspSources,
230    /// True when peer path state changed since the classifier was built.
231    dataplane_direct_fsp_sources_dirty: bool,
232    /// Maximum same-destination UDP payloads sent in one dataplane batch.
233    dataplane_transport_send_batch_packets: usize,
234
235    // === Peer Lifecycle ===
236    /// Pending handshake connections plus authenticated peers.
237    peers: PeerLifecycleRegistry,
238
239    // === End-to-End Sessions ===
240    /// Session table for end-to-end encrypted sessions.
241    /// Keyed by remote NodeAddr.
242    sessions: SessionRegistry,
243
244    // === Identity Cache ===
245    /// Maps FipsAddress prefix bytes (bytes 1-15) to cached peer identity data.
246    /// Enables reverse lookup from IPv6 destination to session/routing identity.
247    identity_cache: IdentityCache,
248
249    // === Pending TUN Packets ===
250    /// TUN packets and endpoint payloads queued while waiting for session establishment.
251    pending_session_traffic: PendingSessionTrafficQueues,
252    // === Pending Discovery Lookups ===
253    /// Tracks in-flight discovery lookups and owns dedupe/cap admission.
254    pending_lookups: handlers::discovery::PendingDiscoveryLookups,
255
256    // === Resource Limits ===
257    /// Maximum connections (0 = unlimited).
258    max_connections: usize,
259    /// Maximum peers (0 = unlimited).
260    max_peers: usize,
261    /// Maximum links (0 = unlimited).
262    max_links: usize,
263
264    // === Counters ===
265    /// Next link ID to allocate.
266    next_link_id: u64,
267    /// Next transport ID to allocate.
268    next_transport_id: u32,
269
270    // === Node Statistics ===
271    /// Routing, forwarding, discovery, and error signal counters.
272    stats: stats::NodeStats,
273
274    /// Time-series history of node-level metrics (1s/1m rings).
275    stats_history: stats_history::StatsHistory,
276
277    // === TUN Interface ===
278    /// TUN device state.
279    tun_state: TunState,
280    /// TUN interface name (for cleanup).
281    tun_name: Option<String>,
282    /// TUN packet sender channel.
283    tun_tx: Option<TunTx>,
284    /// Receiver for outbound packets from the TUN reader.
285    tun_outbound_rx: Option<TunOutboundRx>,
286    /// App-owned packet sink used by embedded/no-TUN integrations.
287    external_packet_tx: Option<tokio::sync::mpsc::Sender<NodeDeliveredPacket>>,
288    /// Endpoint control receiver used by embedded/no-daemon integrations.
289    endpoint_control_rx: Option<tokio::sync::mpsc::Receiver<NodeEndpointControlCommand>>,
290    /// Endpoint data batch receiver used by embedded/no-daemon integrations.
291    endpoint_data_rx: Option<EndpointDataBatchRx>,
292    /// Endpoint data event delivery runtime used by embedded/no-daemon integrations.
293    endpoint_events: EndpointEventRuntime,
294    /// Registered FSP DataPacket services and their app delivery queue.
295    endpoint_services: EndpointServiceRuntime,
296    /// TUN reader thread handle.
297    tun_reader_handle: Option<JoinHandle<()>>,
298    /// TUN writer thread handle.
299    tun_writer_handle: Option<JoinHandle<()>>,
300    /// Shutdown pipe: writing to this fd unblocks the TUN reader thread on macOS.
301    /// On Linux, deleting the interface via netlink serves the same purpose.
302    #[cfg(target_os = "macos")]
303    tun_shutdown_fd: Option<std::os::unix::io::RawFd>,
304
305    // === DNS Responder ===
306    /// Receiver for resolved identities from the DNS responder.
307    dns_identity_rx: Option<crate::upper::dns::DnsIdentityRx>,
308    /// DNS responder task handle.
309    dns_task: Option<tokio::task::JoinHandle<()>>,
310
311    // === Index-Based Session Dispatch ===
312    /// Allocator for session indices.
313    index_allocator: IndexAllocator,
314    /// Pending outbound handshakes by our sender_idx.
315    /// Tracks which LinkId corresponds to which session index.
316    pending_outbound: PendingOutboundHandshakes,
317
318    // === Rate Limiting ===
319    /// Rate limiter for msg1 processing (DoS protection).
320    msg1_rate_limiter: HandshakeRateLimiter,
321    /// Rate limiter for ICMP Packet Too Big messages.
322    icmp_rate_limiter: IcmpRateLimiter,
323    /// Rate limiter for routing error signals (CoordsRequired / PathBroken).
324    routing_error_rate_limiter: RoutingErrorRateLimiter,
325    /// Rate limiter for source-side CoordsRequired/PathBroken responses.
326    coords_response_rate_limiter: RoutingErrorRateLimiter,
327    /// Backoff for failed discovery lookups (originator-side).
328    discovery_backoff: DiscoveryBackoff,
329    /// Rate limiter for forwarded discovery requests (transit-side).
330    discovery_forward_limiter: DiscoveryForwardRateLimiter,
331
332    // === Pending Transport Connects ===
333    /// Links waiting for transport-level connection establishment before
334    /// sending handshake msg1. For connection-oriented transports (TCP, Tor),
335    /// the transport connect runs in the background; the tick handler polls
336    /// connection_state() and initiates the handshake when connected.
337    pending_connects: Vec<PendingConnect>,
338
339    // === Connection Retry ===
340    /// Retry state for peers whose outbound connections have failed.
341    /// Keyed by NodeAddr. Entries are created when a handshake times out
342    /// or fails, and removed on successful promotion or when max retries
343    /// are exhausted.
344    retry_pending: retry::PendingRouteRetries,
345
346    /// Optional Nostr/STUN overlay discovery coordinator for `udp:nat` peers.
347    nostr_discovery: Option<Arc<crate::discovery::nostr::NostrDiscovery>>,
348    /// mDNS / DNS-SD responder + browser for local-link peer discovery.
349    /// Identity is unverified at this layer — the Noise XX handshake
350    /// initiated against an mDNS-observed endpoint is what proves the
351    /// peer holds the matching private key.
352    lan_discovery: Option<Arc<crate::discovery::lan::LanDiscovery>>,
353    /// Same-host JSON registry under `~/.fips/instances`. Records are
354    /// loopback routing hints only; peer identity is still verified by the
355    /// Noise handshake.
356    local_instance_registry: Option<crate::discovery::local::LocalInstanceRegistry>,
357    local_instance_started_at_ms: Option<u64>,
358    last_local_instance_publish_ms: Option<u64>,
359    last_local_instance_scan_ms: Option<u64>,
360    /// Wall-clock ms when Nostr discovery successfully started, used to
361    /// schedule the one-shot startup advert sweep after a settle delay.
362    /// `None` until discovery comes up; remains `None` if discovery is
363    /// disabled or failed to start.
364    nostr_discovery_started_at_ms: Option<u64>,
365    /// Whether the one-shot startup advert sweep has run. Set to true
366    /// after the first sweep fires (under `policy: open`); thereafter
367    /// only the per-tick `queue_open_discovery_retries` continues.
368    startup_open_discovery_sweep_done: bool,
369    /// Per-peer UDP transports adopted from NAT traversal handoff plus the
370    /// originating peer npub for protocol-mismatch cooldown bookkeeping.
371    bootstrap_transports: BootstrapTransports,
372    /// Peers that should not be used as reply-learned fallback transit for
373    /// other destinations. Direct lookups to the peer are still permitted.
374    discovery_fallback_transit: DiscoveryFallbackTransit,
375
376    // === Periodic Parent Re-evaluation ===
377    /// Timestamp of last periodic parent re-evaluation (for pacing).
378    last_parent_reeval: Option<crate::time::Instant>,
379
380    // === Congestion Logging ===
381    /// Timestamp of last congestion detection log (rate-limited to 5s).
382    last_congestion_log: Option<std::time::Instant>,
383
384    // === Mesh Size Estimate ===
385    /// Cached estimated mesh size (computed once per tick from bloom filters).
386    estimated_mesh_size: Option<u64>,
387    /// Timestamp of last mesh size log emission.
388    last_mesh_size_log: Option<std::time::Instant>,
389
390    // === Bloom Self-Plausibility ===
391    /// Rate-limit state for the self-plausibility WARN. Fires at most
392    /// once per 60s globally when our own outgoing FilterAnnounce has
393    /// an FPR above `node.bloom.max_inbound_fpr`, signalling either
394    /// aggregation drift or an ingress bypass.
395    last_self_warn: Option<std::time::Instant>,
396
397    // === Local Outbound Liveness ===
398    /// Set per peer when a `transport.send` returned a local-side io error
399    /// (`NetworkUnreachable` / `HostUnreachable` / `AddrNotAvailable`),
400    /// cleared on the next successful send to that peer. Used by
401    /// `check_link_heartbeats` to compress only that peer's dead-timeout to
402    /// `fast_link_dead_timeout_secs` while its outbound is observed broken.
403    local_send_failures: LocalSendFailures,
404    /// Set when the rx loop could not complete its 1s maintenance work
405    /// inside the watchdog timeout. Link-dead detection may be valid during
406    /// overload, but traversal cooldown should not punish a path just because
407    /// our own scheduler/worker queue was late.
408    last_rx_loop_maintenance_timeout_at: Option<std::time::Instant>,
409
410    // === Display Names ===
411    /// Human-readable names for configured peers (alias or short npub).
412    /// Populated at startup from peer config.
413    peer_aliases: HashMap<NodeAddr, String>,
414    /// Scheduler weight for explicitly configured peers. Built when config
415    /// changes so the packet hot path only does a NodeAddr hash lookup.
416    configured_peer_send_weights: ConfiguredPeerSendWeights,
417
418    /// Reloadable peer ACL state from standard allow/deny files.
419    peer_acl: acl::PeerAclReloader,
420
421    // === Host Map ===
422    /// Static hostname → npub mapping for DNS resolution.
423    /// Built at construction from peer aliases and /etc/fips/hosts.
424    host_map: Arc<HostMap>,
425}
426
427impl fmt::Debug for Node {
428    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429        f.debug_struct("Node")
430            .field("node_addr", self.node_addr())
431            .field("state", &self.state)
432            .field("is_leaf_only", &self.is_leaf_only)
433            .field("connections", &self.connection_count())
434            .field("peers", &self.peer_count())
435            .field("links", &self.link_count())
436            .field("transports", &self.transport_count())
437            .finish()
438    }
439}