ant_quic/
lib.rs

1// Copyright 2024 Saorsa Labs Ltd.
2//
3// This Saorsa Network Software is licensed under the General Public License (GPL), version 3.
4// Please see the file LICENSE-GPL, or visit <http://www.gnu.org/licenses/> for the full text.
5//
6// Full details available at https://saorsalabs.com/licenses
7
8//! ant-quic: QUIC transport protocol with advanced NAT traversal for P2P networks
9#![allow(elided_lifetimes_in_paths)]
10#![allow(missing_debug_implementations)]
11//!
12//! This library provides a clean, modular implementation of QUIC-native NAT traversal
13//! using raw public keys for authentication. It is designed to be minimal, focused,
14//! and highly testable, with exceptional cross-platform support.
15//!
16//! The library is organized into the following main modules:
17//! - `transport`: Core QUIC transport functionality
18//! - `nat_traversal`: QUIC-native NAT traversal protocol
19//! - `discovery`: Platform-specific network interface discovery
20//! - `crypto`: Raw public key authentication
21//! - `trust`: Trust management with TOFU pinning and channel binding
22
23// Documentation warnings enabled - all public APIs must be documented
24#![cfg_attr(not(fuzzing), warn(missing_docs))]
25#![allow(unreachable_pub)]
26#![allow(clippy::cognitive_complexity)]
27#![allow(clippy::too_many_arguments)]
28#![allow(clippy::use_self)]
29// Dead code warnings enabled - remove unused code
30#![warn(dead_code)]
31#![allow(clippy::field_reassign_with_default)]
32#![allow(clippy::module_inception)]
33#![allow(clippy::useless_vec)]
34#![allow(private_interfaces)]
35#![allow(clippy::upper_case_acronyms)]
36#![allow(clippy::type_complexity)]
37#![allow(clippy::manual_clamp)]
38#![allow(clippy::needless_range_loop)]
39#![allow(clippy::borrowed_box)]
40#![allow(clippy::manual_strip)]
41#![allow(clippy::if_same_then_else)]
42#![allow(clippy::ptr_arg)]
43#![allow(clippy::incompatible_msrv)]
44#![allow(clippy::await_holding_lock)]
45#![allow(clippy::single_match)]
46#![allow(clippy::must_use_candidate)]
47#![allow(clippy::let_underscore_must_use)]
48#![allow(clippy::let_underscore_untyped)]
49#![allow(clippy::large_enum_variant)]
50#![allow(clippy::too_many_lines)]
51#![allow(clippy::result_large_err)]
52#![allow(clippy::enum_glob_use)]
53#![allow(clippy::match_like_matches_macro)]
54#![allow(clippy::struct_field_names)]
55#![allow(clippy::cast_precision_loss)]
56#![allow(clippy::cast_sign_loss)]
57#![allow(clippy::cast_possible_wrap)]
58#![allow(clippy::cast_possible_truncation)]
59#![allow(clippy::unnecessary_wraps)]
60#![allow(clippy::doc_markdown)]
61#![allow(clippy::module_name_repetitions)]
62#![allow(clippy::items_after_statements)]
63#![allow(clippy::missing_panics_doc)]
64#![allow(clippy::missing_errors_doc)]
65#![allow(clippy::similar_names)]
66#![allow(clippy::new_without_default)]
67#![allow(clippy::unwrap_or_default)]
68#![allow(clippy::uninlined_format_args)]
69#![allow(clippy::redundant_field_names)]
70#![allow(clippy::redundant_closure_for_method_calls)]
71#![allow(clippy::redundant_pattern_matching)]
72#![allow(clippy::option_if_let_else)]
73#![allow(clippy::trivially_copy_pass_by_ref)]
74#![allow(clippy::len_without_is_empty)]
75#![allow(clippy::explicit_auto_deref)]
76#![allow(clippy::blocks_in_conditions)]
77#![allow(clippy::collapsible_else_if)]
78#![allow(clippy::collapsible_if)]
79#![allow(clippy::unnecessary_cast)]
80#![allow(clippy::needless_bool)]
81#![allow(clippy::needless_borrow)]
82#![allow(clippy::redundant_static_lifetimes)]
83#![allow(clippy::match_ref_pats)]
84#![allow(clippy::should_implement_trait)]
85#![allow(clippy::wildcard_imports)]
86#![warn(unused_must_use)]
87#![allow(improper_ctypes)]
88#![allow(improper_ctypes_definitions)]
89#![allow(non_upper_case_globals)]
90#![allow(clippy::wrong_self_convention)]
91#![allow(clippy::vec_init_then_push)]
92#![allow(clippy::format_in_format_args)]
93#![allow(clippy::from_over_into)]
94#![allow(clippy::useless_conversion)]
95#![allow(clippy::never_loop)]
96#![allow(dropping_references)]
97#![allow(non_snake_case)]
98#![allow(clippy::unnecessary_literal_unwrap)]
99#![allow(clippy::assertions_on_constants)]
100#![allow(unused_imports)]
101
102use std::{
103    fmt,
104    net::{IpAddr, SocketAddr},
105    ops,
106};
107
108// Core modules
109mod cid_queue;
110pub mod coding;
111mod constant_time;
112mod range_set;
113pub mod transport_parameters;
114mod varint;
115
116pub use varint::{VarInt, VarIntBoundsExceeded};
117
118// Removed optional bloom module
119
120// Core implementation modules
121/// Configuration structures and validation
122pub mod config;
123/// QUIC connection state machine and management
124pub mod connection;
125/// QUIC endpoint for accepting and initiating connections
126pub mod endpoint;
127/// QUIC frame types and encoding/decoding
128pub mod frame;
129/// QUIC packet structures and processing
130pub mod packet;
131/// Shared types and utilities
132pub mod shared;
133/// Transport error types and codes
134pub mod transport_error;
135// Simplified congestion control
136/// Network candidate discovery and management
137pub mod candidate_discovery;
138/// Connection ID generation strategies
139pub mod cid_generator;
140mod congestion;
141mod protocol_violations;
142#[cfg(test)]
143mod protocol_violations_tests;
144
145// Zero-cost tracing system
146/// High-level NAT traversal API
147pub mod nat_traversal_api;
148mod token;
149mod token_memory_cache;
150/// Zero-cost tracing and event logging system
151pub mod tracing;
152
153// Public modules with new structure
154/// Cryptographic operations and raw public key support
155pub mod crypto;
156/// Platform-specific network interface discovery
157pub mod discovery;
158/// NAT traversal protocol implementation
159pub mod nat_traversal;
160/// Transport-level protocol implementation
161pub mod transport;
162
163// Additional modules
164/// Peer authentication system
165pub mod auth;
166/// Secure chat protocol implementation
167pub mod chat;
168// Performance optimization utilities are deprecated; remove module to eliminate dead code
169// pub mod optimization;
170/// High-level QUIC P2P node implementation
171pub mod quic_node;
172/// Real-time statistics dashboard
173pub mod stats_dashboard;
174/// Terminal user interface components
175pub mod terminal_ui;
176
177// Compliance validation framework
178/// IETF compliance validation tools
179pub mod compliance_validator;
180
181// Comprehensive logging system
182/// Structured logging and diagnostics
183pub mod logging;
184
185/// Metrics collection and export system (basic metrics always available)
186pub mod metrics;
187
188/// TURN-style relay protocol for NAT traversal fallback
189pub mod relay;
190
191/// Transport trust module (TOFU, rotations, channel binding surfaces)
192pub mod trust;
193
194/// Address-validation tokens bound to (PeerId||CID||nonce)
195#[cfg(any(feature = "ring", feature = "aws-lc-rs"))]
196pub mod token_v2;
197
198// High-level async API modules (ported from quinn crate)
199pub mod high_level;
200
201// Re-export high-level API types for easier usage
202pub use high_level::{
203    Accept, Connecting, Connection as HighLevelConnection, Endpoint,
204    RecvStream as HighLevelRecvStream, SendStream as HighLevelSendStream,
205};
206
207// Re-export crypto utilities for peer ID management
208pub use crypto::raw_public_keys::key_utils::{
209    derive_peer_id_from_key_bytes, derive_peer_id_from_public_key, generate_ed25519_keypair,
210    public_key_from_bytes, public_key_to_bytes, verify_peer_id,
211};
212
213// Re-export key types for backward compatibility
214pub use candidate_discovery::{
215    CandidateDiscoveryManager, DiscoveryConfig, DiscoveryError, DiscoveryEvent, NetworkInterface,
216    ValidatedCandidate,
217};
218pub use connection::nat_traversal::{CandidateSource, CandidateState, NatTraversalRole};
219pub use connection::{
220    Chunk, Chunks, ClosedStream, Connection, ConnectionError, ConnectionStats, Datagrams, Event,
221    FinishError, ReadError, ReadableError, RecvStream, SendDatagramError, SendStream, StreamEvent,
222    Streams, WriteError, Written,
223};
224pub use endpoint::{
225    AcceptError, ConnectError, ConnectionHandle, DatagramEvent, Endpoint as LowLevelEndpoint,
226    Incoming,
227};
228pub use nat_traversal_api::{
229    BootstrapNode, CandidateAddress, EndpointRole, NatTraversalConfig, NatTraversalEndpoint,
230    NatTraversalError, NatTraversalEvent, NatTraversalStatistics, PeerId,
231};
232pub use quic_node::{NodeStats as QuicNodeStats, QuicNodeConfig, QuicP2PNode};
233pub use relay::{
234    AuthToken, RelayAction, RelayAuthenticator, RelayConnection, RelayConnectionConfig, RelayError,
235    RelayEvent, RelayResult, SessionId, SessionManager, SessionState,
236};
237pub use shared::{ConnectionId, EcnCodepoint, EndpointEvent};
238pub use transport_error::{Code as TransportErrorCode, Error as TransportError};
239
240// #[cfg(fuzzing)]
241// pub mod fuzzing; // Module not implemented yet
242
243/// The QUIC protocol version implemented.
244///
245/// Simplified to include only the essential versions:
246/// - 0x00000001: QUIC v1 (RFC 9000)
247/// - 0xff00_001d: Draft 29
248pub const DEFAULT_SUPPORTED_VERSIONS: &[u32] = &[
249    0x00000001,  // QUIC v1 (RFC 9000)
250    0xff00_001d, // Draft 29
251];
252
253/// Whether an endpoint was the initiator of a connection
254#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
255#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
256pub enum Side {
257    /// The initiator of a connection
258    Client = 0,
259    /// The acceptor of a connection
260    Server = 1,
261}
262
263impl Side {
264    #[inline]
265    /// Shorthand for `self == Side::Client`
266    pub fn is_client(self) -> bool {
267        self == Self::Client
268    }
269
270    #[inline]
271    /// Shorthand for `self == Side::Server`
272    pub fn is_server(self) -> bool {
273        self == Self::Server
274    }
275}
276
277impl ops::Not for Side {
278    type Output = Self;
279    fn not(self) -> Self {
280        match self {
281            Self::Client => Self::Server,
282            Self::Server => Self::Client,
283        }
284    }
285}
286
287/// Whether a stream communicates data in both directions or only from the initiator
288#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
289#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
290pub enum Dir {
291    /// Data flows in both directions
292    Bi = 0,
293    /// Data flows only from the stream's initiator
294    Uni = 1,
295}
296
297impl Dir {
298    fn iter() -> impl Iterator<Item = Self> {
299        [Self::Bi, Self::Uni].iter().cloned()
300    }
301}
302
303impl fmt::Display for Dir {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        use Dir::*;
306        f.pad(match *self {
307            Bi => "bidirectional",
308            Uni => "unidirectional",
309        })
310    }
311}
312
313/// Identifier for a stream within a particular connection
314#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
315#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
316pub struct StreamId(u64);
317
318impl fmt::Display for StreamId {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        let initiator = match self.initiator() {
321            Side::Client => "client",
322            Side::Server => "server",
323        };
324        let dir = match self.dir() {
325            Dir::Uni => "uni",
326            Dir::Bi => "bi",
327        };
328        write!(
329            f,
330            "{} {}directional stream {}",
331            initiator,
332            dir,
333            self.index()
334        )
335    }
336}
337
338impl StreamId {
339    /// Create a new StreamId
340    pub fn new(initiator: Side, dir: Dir, index: u64) -> Self {
341        Self((index << 2) | ((dir as u64) << 1) | initiator as u64)
342    }
343    /// Which side of a connection initiated the stream
344    pub fn initiator(self) -> Side {
345        if self.0 & 0x1 == 0 {
346            Side::Client
347        } else {
348            Side::Server
349        }
350    }
351    /// Which directions data flows in
352    pub fn dir(self) -> Dir {
353        if self.0 & 0x2 == 0 { Dir::Bi } else { Dir::Uni }
354    }
355    /// Distinguishes streams of the same initiator and directionality
356    pub fn index(self) -> u64 {
357        self.0 >> 2
358    }
359}
360
361impl From<StreamId> for VarInt {
362    fn from(x: StreamId) -> Self {
363        unsafe { Self::from_u64_unchecked(x.0) }
364    }
365}
366
367impl From<VarInt> for StreamId {
368    fn from(v: VarInt) -> Self {
369        Self(v.0)
370    }
371}
372
373impl From<StreamId> for u64 {
374    fn from(x: StreamId) -> Self {
375        x.0
376    }
377}
378
379impl coding::Codec for StreamId {
380    fn decode<B: bytes::Buf>(buf: &mut B) -> coding::Result<Self> {
381        VarInt::decode(buf).map(|x| Self(x.into_inner()))
382    }
383    fn encode<B: bytes::BufMut>(&self, buf: &mut B) {
384        // StreamId values should always be valid VarInt values, but handle the error case
385        match VarInt::from_u64(self.0) {
386            Ok(varint) => varint.encode(buf),
387            Err(_) => {
388                // This should never happen for valid StreamIds, but use a safe fallback
389                VarInt::MAX.encode(buf);
390            }
391        }
392    }
393}
394
395/// An outgoing packet
396#[derive(Debug)]
397#[must_use]
398pub struct Transmit {
399    /// The socket this datagram should be sent to
400    pub destination: SocketAddr,
401    /// Explicit congestion notification bits to set on the packet
402    pub ecn: Option<EcnCodepoint>,
403    /// Amount of data written to the caller-supplied buffer
404    pub size: usize,
405    /// The segment size if this transmission contains multiple datagrams.
406    /// This is `None` if the transmit only contains a single datagram
407    pub segment_size: Option<usize>,
408    /// Optional source IP address for the datagram
409    pub src_ip: Option<IpAddr>,
410}
411
412// Deal with time
413#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
414pub(crate) use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
415#[cfg(all(target_family = "wasm", target_os = "unknown"))]
416pub(crate) use web_time::{Duration, Instant, SystemTime, UNIX_EPOCH};
417
418//
419// Useful internal constants
420//
421
422/// The maximum number of CIDs we bother to issue per connection
423pub(crate) const LOC_CID_COUNT: u64 = 8;
424pub(crate) const RESET_TOKEN_SIZE: usize = 16;
425pub(crate) const MAX_CID_SIZE: usize = 20;
426pub(crate) const MIN_INITIAL_SIZE: u16 = 1200;
427/// <https://www.rfc-editor.org/rfc/rfc9000.html#name-datagram-size>
428pub(crate) const INITIAL_MTU: u16 = 1200;
429pub(crate) const MAX_UDP_PAYLOAD: u16 = 65527;
430pub(crate) const TIMER_GRANULARITY: Duration = Duration::from_millis(1);
431/// Maximum number of streams that can be tracked per connection
432pub(crate) const MAX_STREAM_COUNT: u64 = 1 << 60;
433
434// Internal type re-exports for crate modules
435pub use cid_generator::RandomConnectionIdGenerator;
436pub use config::{
437    AckFrequencyConfig, ClientConfig, EndpointConfig, MtuDiscoveryConfig, ServerConfig,
438    TransportConfig,
439};
440
441// Post-Quantum Cryptography (PQC) re-exports - always available
442pub use crypto::pqc::{
443    HybridKem, HybridPreference, HybridSignature, MlDsa65, MlKem768, PqcConfig, PqcConfigBuilder,
444    PqcError, PqcMode, PqcResult,
445};
446pub(crate) use frame::Frame;
447pub use token::TokenStore;
448pub(crate) use token::{NoneTokenLog, ResetToken, TokenLog};
449pub(crate) use token_memory_cache::TokenMemoryCache;